Skip to content

Commit b5c4fe3

Browse files
zecakehbnjbvr
authored andcommitted
test(sdk): Allow any MockEndpoint to override the expected access token
Signed-off-by: Kévin Commaille <[email protected]>
1 parent 516d066 commit b5c4fe3

File tree

2 files changed

+84
-77
lines changed

2 files changed

+84
-77
lines changed

crates/matrix-sdk/src/test_utils/mocks/mod.rs

Lines changed: 82 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -288,13 +288,12 @@ impl MatrixMockServer {
288288
/// # anyhow::Ok(()) });
289289
/// ```
290290
pub fn mock_sync(&self) -> MockEndpoint<'_, SyncEndpoint> {
291-
let mock = Mock::given(method("GET"))
292-
.and(path("/_matrix/client/v3/sync"))
293-
.and(header("authorization", "Bearer 1234"));
291+
let mock = Mock::given(method("GET")).and(path("/_matrix/client/v3/sync"));
294292
self.mock_endpoint(
295293
mock,
296294
SyncEndpoint { sync_response_builder: self.sync_response_builder.clone() },
297295
)
296+
.expect_default_access_token()
298297
}
299298

300299
/// Creates a prebuilt mock for sending an event in a room.
@@ -336,9 +335,8 @@ impl MatrixMockServer {
336335
/// ```
337336
pub fn mock_room_send(&self) -> MockEndpoint<'_, RoomSendEndpoint> {
338337
let mock = Mock::given(method("PUT"))
339-
.and(header("authorization", "Bearer 1234"))
340338
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/send/.*".to_owned()));
341-
self.mock_endpoint(mock, RoomSendEndpoint)
339+
self.mock_endpoint(mock, RoomSendEndpoint).expect_default_access_token()
342340
}
343341

344342
/// Creates a prebuilt mock for sending a state event in a room.
@@ -385,10 +383,9 @@ impl MatrixMockServer {
385383
/// # anyhow::Ok(()) });
386384
/// ```
387385
pub fn mock_room_send_state(&self) -> MockEndpoint<'_, RoomSendStateEndpoint> {
388-
let mock = Mock::given(method("PUT"))
389-
.and(header("authorization", "Bearer 1234"))
390-
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/.*/.*"));
391-
self.mock_endpoint(mock, RoomSendStateEndpoint::default())
386+
let mock =
387+
Mock::given(method("PUT")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/.*/.*"));
388+
self.mock_endpoint(mock, RoomSendStateEndpoint::default()).expect_default_access_token()
392389
}
393390

394391
/// Creates a prebuilt mock for asking whether *a* room is encrypted or not.
@@ -418,9 +415,8 @@ impl MatrixMockServer {
418415
/// ```
419416
pub fn mock_room_state_encryption(&self) -> MockEndpoint<'_, EncryptionStateEndpoint> {
420417
let mock = Mock::given(method("GET"))
421-
.and(header("authorization", "Bearer 1234"))
422418
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.*room.*encryption.?"));
423-
self.mock_endpoint(mock, EncryptionStateEndpoint)
419+
self.mock_endpoint(mock, EncryptionStateEndpoint).expect_default_access_token()
424420
}
425421

426422
/// Creates a prebuilt mock for setting the room encryption state.
@@ -458,9 +454,8 @@ impl MatrixMockServer {
458454
/// ```
459455
pub fn mock_set_room_state_encryption(&self) -> MockEndpoint<'_, SetEncryptionStateEndpoint> {
460456
let mock = Mock::given(method("PUT"))
461-
.and(header("authorization", "Bearer 1234"))
462457
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.*room.*encryption.?"));
463-
self.mock_endpoint(mock, SetEncryptionStateEndpoint)
458+
self.mock_endpoint(mock, SetEncryptionStateEndpoint).expect_default_access_token()
464459
}
465460

466461
/// Creates a prebuilt mock for the room redact endpoint.
@@ -491,32 +486,29 @@ impl MatrixMockServer {
491486
/// ```
492487
pub fn mock_room_redact(&self) -> MockEndpoint<'_, RoomRedactEndpoint> {
493488
let mock = Mock::given(method("PUT"))
494-
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/redact/.*?/.*?"))
495-
.and(header("authorization", "Bearer 1234"));
496-
self.mock_endpoint(mock, RoomRedactEndpoint)
489+
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/redact/.*?/.*?"));
490+
self.mock_endpoint(mock, RoomRedactEndpoint).expect_default_access_token()
497491
}
498492

499493
/// Creates a prebuilt mock for retrieving an event with /room/.../event.
500494
pub fn mock_room_event(&self) -> MockEndpoint<'_, RoomEventEndpoint> {
501-
let mock = Mock::given(method("GET")).and(header("authorization", "Bearer 1234"));
495+
let mock = Mock::given(method("GET"));
502496
self.mock_endpoint(mock, RoomEventEndpoint { room: None, match_event_id: false })
497+
.expect_default_access_token()
503498
}
504499

505500
/// Create a prebuild mock for paginating room message with the `/messages`
506501
/// endpoint.
507502
pub fn mock_room_messages(&self) -> MockEndpoint<'_, RoomMessagesEndpoint> {
508-
let mock = Mock::given(method("GET"))
509-
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/messages$"))
510-
.and(header("authorization", "Bearer 1234"));
511-
self.mock_endpoint(mock, RoomMessagesEndpoint)
503+
let mock =
504+
Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/v3/rooms/.*/messages$"));
505+
self.mock_endpoint(mock, RoomMessagesEndpoint).expect_default_access_token()
512506
}
513507

514508
/// Create a prebuilt mock for uploading media.
515509
pub fn mock_upload(&self) -> MockEndpoint<'_, UploadEndpoint> {
516-
let mock = Mock::given(method("POST"))
517-
.and(path("/_matrix/media/v3/upload"))
518-
.and(header("authorization", "Bearer 1234"));
519-
self.mock_endpoint(mock, UploadEndpoint)
510+
let mock = Mock::given(method("POST")).and(path("/_matrix/media/v3/upload"));
511+
self.mock_endpoint(mock, UploadEndpoint).expect_default_access_token()
520512
}
521513

522514
/// Create a prebuilt mock for resolving room aliases.
@@ -768,26 +760,23 @@ impl MatrixMockServer {
768760
/// # }
769761
/// ```
770762
pub fn mock_room_keys_version(&self) -> MockEndpoint<'_, RoomKeysVersionEndpoint> {
771-
let mock = Mock::given(method("GET"))
772-
.and(path_regex(r"_matrix/client/v3/room_keys/version"))
773-
.and(header("authorization", "Bearer 1234"));
774-
self.mock_endpoint(mock, RoomKeysVersionEndpoint)
763+
let mock =
764+
Mock::given(method("GET")).and(path_regex(r"_matrix/client/v3/room_keys/version"));
765+
self.mock_endpoint(mock, RoomKeysVersionEndpoint).expect_default_access_token()
775766
}
776767

777768
/// Create a prebuilt mock for adding key storage backups via POST
778769
pub fn mock_add_room_keys_version(&self) -> MockEndpoint<'_, AddRoomKeysVersionEndpoint> {
779-
let mock = Mock::given(method("POST"))
780-
.and(path_regex(r"_matrix/client/v3/room_keys/version"))
781-
.and(header("authorization", "Bearer 1234"));
782-
self.mock_endpoint(mock, AddRoomKeysVersionEndpoint)
770+
let mock =
771+
Mock::given(method("POST")).and(path_regex(r"_matrix/client/v3/room_keys/version"));
772+
self.mock_endpoint(mock, AddRoomKeysVersionEndpoint).expect_default_access_token()
783773
}
784774

785775
/// Create a prebuilt mock for adding key storage backups via POST
786776
pub fn mock_delete_room_keys_version(&self) -> MockEndpoint<'_, DeleteRoomKeysVersionEndpoint> {
787777
let mock = Mock::given(method("DELETE"))
788-
.and(path_regex(r"_matrix/client/v3/room_keys/version/[^/]*"))
789-
.and(header("authorization", "Bearer 1234"));
790-
self.mock_endpoint(mock, DeleteRoomKeysVersionEndpoint)
778+
.and(path_regex(r"_matrix/client/v3/room_keys/version/[^/]*"));
779+
self.mock_endpoint(mock, DeleteRoomKeysVersionEndpoint).expect_default_access_token()
791780
}
792781

793782
/// Create a prebuilt mock for getting the room members in a room.
@@ -945,9 +934,8 @@ impl MatrixMockServer {
945934
/// events.
946935
pub fn mock_set_room_pinned_events(&self) -> MockEndpoint<'_, SetRoomPinnedEventsEndpoint> {
947936
let mock = Mock::given(method("PUT"))
948-
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.room.pinned_events/.*?"))
949-
.and(header("authorization", "Bearer 1234"));
950-
self.mock_endpoint(mock, SetRoomPinnedEventsEndpoint)
937+
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/state/m.room.pinned_events/.*?"));
938+
self.mock_endpoint(mock, SetRoomPinnedEventsEndpoint).expect_default_access_token()
951939
}
952940

953941
/// Creates a prebuilt mock for the endpoint used to get information about
@@ -958,25 +946,21 @@ impl MatrixMockServer {
958946
pub fn mock_who_am_i(&self) -> MockEndpoint<'_, WhoAmIEndpoint> {
959947
let mock =
960948
Mock::given(method("GET")).and(path_regex(r"^/_matrix/client/v3/account/whoami"));
961-
self.mock_endpoint(mock, WhoAmIEndpoint { expected_access_token: "1234" })
949+
self.mock_endpoint(mock, WhoAmIEndpoint).expect_default_access_token()
962950
}
963951

964952
/// Creates a prebuilt mock for the endpoint used to publish end-to-end
965953
/// encryption keys.
966954
pub fn mock_upload_keys(&self) -> MockEndpoint<'_, UploadKeysEndpoint> {
967-
let mock = Mock::given(method("POST"))
968-
.and(path_regex(r"^/_matrix/client/v3/keys/upload"))
969-
.and(header("authorization", "Bearer 1234"));
970-
self.mock_endpoint(mock, UploadKeysEndpoint)
955+
let mock = Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/keys/upload"));
956+
self.mock_endpoint(mock, UploadKeysEndpoint).expect_default_access_token()
971957
}
972958

973959
/// Creates a prebuilt mock for the endpoint used to query end-to-end
974960
/// encryption keys.
975961
pub fn mock_query_keys(&self) -> MockEndpoint<'_, QueryKeysEndpoint> {
976-
let mock = Mock::given(method("POST"))
977-
.and(path_regex(r"^/_matrix/client/v3/keys/query"))
978-
.and(header("authorization", "Bearer 1234"));
979-
self.mock_endpoint(mock, QueryKeysEndpoint)
962+
let mock = Mock::given(method("POST")).and(path_regex(r"^/_matrix/client/v3/keys/query"));
963+
self.mock_endpoint(mock, QueryKeysEndpoint).expect_default_access_token()
980964
}
981965

982966
/// Creates a prebuilt mock for the endpoint used to discover the URL of a
@@ -992,9 +976,8 @@ impl MatrixMockServer {
992976
&self,
993977
) -> MockEndpoint<'_, UploadCrossSigningKeysEndpoint> {
994978
let mock = Mock::given(method("POST"))
995-
.and(path_regex(r"^/_matrix/client/v3/keys/device_signing/upload"))
996-
.and(header("authorization", "Bearer 1234"));
997-
self.mock_endpoint(mock, UploadCrossSigningKeysEndpoint)
979+
.and(path_regex(r"^/_matrix/client/v3/keys/device_signing/upload"));
980+
self.mock_endpoint(mock, UploadCrossSigningKeysEndpoint).expect_default_access_token()
998981
}
999982

1000983
/// Creates a prebuilt mock for the endpoint used to publish cross-signing
@@ -1003,9 +986,8 @@ impl MatrixMockServer {
1003986
&self,
1004987
) -> MockEndpoint<'_, UploadCrossSigningSignaturesEndpoint> {
1005988
let mock = Mock::given(method("POST"))
1006-
.and(path_regex(r"^/_matrix/client/v3/keys/signatures/upload"))
1007-
.and(header("authorization", "Bearer 1234"));
1008-
self.mock_endpoint(mock, UploadCrossSigningSignaturesEndpoint)
989+
.and(path_regex(r"^/_matrix/client/v3/keys/signatures/upload"));
990+
self.mock_endpoint(mock, UploadCrossSigningSignaturesEndpoint).expect_default_access_token()
1009991
}
1010992
}
1011993

@@ -1162,11 +1144,24 @@ pub struct MockEndpoint<'a, T> {
11621144
server: &'a MockServer,
11631145
mock: MockBuilder,
11641146
endpoint: T,
1147+
expected_access_token: ExpectedAccessToken,
11651148
}
11661149

11671150
impl<'a, T> MockEndpoint<'a, T> {
11681151
fn new(server: &'a MockServer, mock: MockBuilder, endpoint: T) -> Self {
1169-
Self { server, mock, endpoint }
1152+
Self { server, mock, endpoint, expected_access_token: ExpectedAccessToken::None }
1153+
}
1154+
1155+
/// Expect authentication with the default access token on this endpoint.
1156+
pub fn expect_default_access_token(mut self) -> Self {
1157+
self.expected_access_token = ExpectedAccessToken::Default;
1158+
self
1159+
}
1160+
1161+
/// Expect authentication with the given access token on this endpoint.
1162+
pub fn expect_access_token(mut self, access_token: &'static str) -> Self {
1163+
self.expected_access_token = ExpectedAccessToken::Custom(access_token);
1164+
self
11701165
}
11711166

11721167
/// Specify how to respond to a query (viz., like
@@ -1211,7 +1206,11 @@ impl<'a, T> MockEndpoint<'a, T> {
12111206
/// # anyhow::Ok(()) });
12121207
/// ```
12131208
pub fn respond_with<R: Respond + 'static>(self, func: R) -> MatrixMock<'a> {
1214-
MatrixMock { mock: self.mock.respond_with(func), server: self.server }
1209+
let mock = self
1210+
.expected_access_token
1211+
.maybe_match_authorization_header(self.mock)
1212+
.respond_with(func);
1213+
MatrixMock { mock, server: self.server }
12151214
}
12161215

12171216
/// Returns a send endpoint that emulates a transient failure, i.e responds
@@ -1292,6 +1291,30 @@ impl<'a, T> MockEndpoint<'a, T> {
12921291
}
12931292
}
12941293

1294+
/// The access token to expect on an endpoint.
1295+
enum ExpectedAccessToken {
1296+
/// We don't expect an access token.
1297+
None,
1298+
1299+
/// We expect the default access token.
1300+
Default,
1301+
1302+
/// We expect the given access token.
1303+
Custom(&'static str),
1304+
}
1305+
1306+
impl ExpectedAccessToken {
1307+
/// Match an `Authorization` header on the given mock if one is expected.
1308+
fn maybe_match_authorization_header(&self, mock: MockBuilder) -> MockBuilder {
1309+
let token = match self {
1310+
Self::None => return mock,
1311+
Self::Default => "1234",
1312+
Self::Custom(token) => token,
1313+
};
1314+
mock.and(header(http::header::AUTHORIZATION, format!("Bearer {token}")))
1315+
}
1316+
}
1317+
12951318
/// A prebuilt mock for sending a message like event in a room.
12961319
pub struct RoomSendEndpoint;
12971320

@@ -2377,35 +2400,19 @@ impl<'a> MockEndpoint<'a, SetRoomPinnedEventsEndpoint> {
23772400
}
23782401

23792402
/// A prebuilt mock for `GET /account/whoami` request.
2380-
pub struct WhoAmIEndpoint {
2381-
expected_access_token: &'static str,
2382-
}
2383-
2384-
impl WhoAmIEndpoint {
2385-
fn add_access_token_matcher(&self, mock: MockBuilder) -> MockBuilder {
2386-
mock.and(header("authorization", format!("Bearer {}", self.expected_access_token)))
2387-
}
2388-
}
2403+
pub struct WhoAmIEndpoint;
23892404

23902405
impl<'a> MockEndpoint<'a, WhoAmIEndpoint> {
2391-
/// Override the access token to expect for this endpoint.
2392-
pub fn expected_access_token(mut self, access_token: &'static str) -> Self {
2393-
self.endpoint.expected_access_token = access_token;
2394-
self
2395-
}
2396-
23972406
/// Returns a successful response with a user ID and device ID.
2398-
pub fn ok(mut self) -> MatrixMock<'a> {
2399-
self.mock = self.endpoint.add_access_token_matcher(self.mock);
2407+
pub fn ok(self) -> MatrixMock<'a> {
24002408
self.respond_with(ResponseTemplate::new(200).set_body_json(json!({
24012409
"user_id": "@joe:example.org",
24022410
"device_id": "D3V1C31D",
24032411
})))
24042412
}
24052413

24062414
/// Returns an error response with an `M_UNKNOWN_TOKEN`.
2407-
pub fn err_unknown_token(mut self) -> MatrixMock<'a> {
2408-
self.mock = self.endpoint.add_access_token_matcher(self.mock);
2415+
pub fn err_unknown_token(self) -> MatrixMock<'a> {
24092416
self.respond_with(ResponseTemplate::new(401).set_body_json(json!({
24102417
"errcode": "M_UNKNOWN_TOKEN",
24112418
"error": "Invalid token"

crates/matrix-sdk/tests/integration/refresh_token.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -567,7 +567,7 @@ async fn test_oauth_refresh_token_handled_success() {
567567
// Return an error first so the token is refreshed.
568568
server
569569
.mock_who_am_i()
570-
.expected_access_token("prev-access-token")
570+
.expect_access_token("prev-access-token")
571571
.err_unknown_token()
572572
.expect(1)
573573
.named("whoami_unknown_token")
@@ -619,7 +619,7 @@ async fn test_oauth_refresh_token_handled_failure() {
619619
// Return an error first so the token is refreshed.
620620
server
621621
.mock_who_am_i()
622-
.expected_access_token("prev-access-token")
622+
.expect_access_token("prev-access-token")
623623
.err_unknown_token()
624624
.expect(1)
625625
.named("whoami_unknown_token")

0 commit comments

Comments
 (0)