matrix_sdk/test_utils/mocks/
oauth.rs1use ruma::{
18 api::client::discovery::get_authorization_server_metadata::v1::AuthorizationServerMetadata,
19 serde::Raw,
20};
21use serde_json::json;
22use url::Url;
23use wiremock::{
24 Mock, MockBuilder,
25 matchers::{method, path_regex},
26};
27
28use super::{MatrixMock, MatrixMockServer, MockEndpoint};
29
30pub struct OAuthMockServer<'a> {
57 server: &'a MatrixMockServer,
58}
59
60impl<'a> OAuthMockServer<'a> {
61 pub(super) fn new(server: &'a MatrixMockServer) -> Self {
62 Self { server }
63 }
64
65 fn mock_endpoint<T>(&self, mock: MockBuilder, endpoint: T) -> MockEndpoint<'a, T> {
67 self.server.mock_endpoint(mock, endpoint)
68 }
69
70 pub fn server_metadata(&self) -> AuthorizationServerMetadata {
72 MockServerMetadataBuilder::new(&self.server.uri())
73 .build()
74 .deserialize()
75 .expect("mock OAuth 2.0 server metadata should deserialize successfully")
76 }
77}
78
79impl OAuthMockServer<'_> {
81 pub fn mock_server_metadata(&self) -> MockEndpoint<'_, ServerMetadataEndpoint> {
91 let mock = Mock::given(method("GET"))
92 .and(path_regex(r"^/_matrix/client/unstable/org.matrix.msc2965/auth_metadata"));
93 self.mock_endpoint(mock, ServerMetadataEndpoint)
94 }
95
96 pub fn mock_registration(&self) -> MockEndpoint<'_, RegistrationEndpoint> {
99 let mock = Mock::given(method("POST")).and(path_regex(r"^/oauth2/registration"));
100 self.mock_endpoint(mock, RegistrationEndpoint)
101 }
102
103 pub fn mock_device_authorization(&self) -> MockEndpoint<'_, DeviceAuthorizationEndpoint> {
106 let mock = Mock::given(method("POST")).and(path_regex(r"^/oauth2/device"));
107 self.mock_endpoint(mock, DeviceAuthorizationEndpoint)
108 }
109
110 pub fn mock_token(&self) -> MockEndpoint<'_, TokenEndpoint> {
113 let mock = Mock::given(method("POST")).and(path_regex(r"^/oauth2/token"));
114 self.mock_endpoint(mock, TokenEndpoint)
115 }
116
117 pub fn mock_revocation(&self) -> MockEndpoint<'_, RevocationEndpoint> {
120 let mock = Mock::given(method("POST")).and(path_regex(r"^/oauth2/revoke"));
121 self.mock_endpoint(mock, RevocationEndpoint)
122 }
123}
124
125#[derive(Default)]
127pub struct ServerMetadataEndpoint;
128
129impl<'a> MockEndpoint<'a, ServerMetadataEndpoint> {
130 fn ok_with_metadata(self, metadata: Raw<AuthorizationServerMetadata>) -> MatrixMock<'a> {
133 self.ok_json(metadata)
134 }
135
136 pub fn ok(self) -> MatrixMock<'a> {
138 let metadata = MockServerMetadataBuilder::new(&self.server.uri()).build();
139 self.ok_with_metadata(metadata)
140 }
141
142 pub fn ok_https(self) -> MatrixMock<'a> {
149 let issuer = self.server.uri().replace("http://", "https://");
150
151 let metadata = MockServerMetadataBuilder::new(&issuer).build();
152 self.ok_with_metadata(metadata)
153 }
154
155 pub fn ok_without_device_authorization(self) -> MatrixMock<'a> {
158 let metadata = MockServerMetadataBuilder::new(&self.server.uri())
159 .without_device_authorization()
160 .build();
161 self.ok_with_metadata(metadata)
162 }
163
164 pub fn ok_without_registration(self) -> MatrixMock<'a> {
167 let metadata =
168 MockServerMetadataBuilder::new(&self.server.uri()).without_registration().build();
169 self.ok_with_metadata(metadata)
170 }
171}
172
173#[derive(Debug, Clone)]
176pub struct MockServerMetadataBuilder {
177 issuer: Url,
178 with_device_authorization: bool,
179 with_registration: bool,
180}
181
182impl MockServerMetadataBuilder {
183 pub fn new(issuer: &str) -> Self {
186 let issuer = Url::parse(issuer).expect("We should be able to parse the issuer");
187
188 Self { issuer, with_device_authorization: true, with_registration: true }
189 }
190
191 fn without_device_authorization(mut self) -> Self {
193 self.with_device_authorization = false;
194 self
195 }
196
197 fn without_registration(mut self) -> Self {
199 self.with_registration = false;
200 self
201 }
202
203 fn authorization_endpoint(&self) -> Url {
205 self.issuer.join("oauth2/authorize").unwrap()
206 }
207
208 fn token_endpoint(&self) -> Url {
210 self.issuer.join("oauth2/token").unwrap()
211 }
212
213 fn jwks_uri(&self) -> Url {
215 self.issuer.join("oauth2/keys.json").unwrap()
216 }
217
218 fn registration_endpoint(&self) -> Url {
220 self.issuer.join("oauth2/registration").unwrap()
221 }
222
223 fn account_management_uri(&self) -> Url {
225 self.issuer.join("account").unwrap()
226 }
227
228 fn device_authorization_endpoint(&self) -> Url {
230 self.issuer.join("oauth2/device").unwrap()
231 }
232
233 fn revocation_endpoint(&self) -> Url {
235 self.issuer.join("oauth2/revoke").unwrap()
236 }
237
238 pub fn build(&self) -> Raw<AuthorizationServerMetadata> {
240 let mut json_metadata = json!({
241 "issuer": self.issuer,
242 "authorization_endpoint": self.authorization_endpoint(),
243 "token_endpoint": self.token_endpoint(),
244 "response_types_supported": ["code"],
245 "response_modes_supported": ["query", "fragment"],
246 "grant_types_supported": ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"],
247 "revocation_endpoint": self.revocation_endpoint(),
248 "code_challenge_methods_supported": ["S256"],
249 "account_management_uri": self.account_management_uri(),
250 "account_management_actions_supported": ["org.matrix.profile", "org.matrix.sessions_list", "org.matrix.session_view", "org.matrix.session_end", "org.matrix.deactivateaccount", "org.matrix.cross_signing_reset"],
251 "prompt_values_supported": ["create"],
252 });
253 let json_metadata_object = json_metadata.as_object_mut().unwrap();
254
255 if self.with_device_authorization {
256 json_metadata_object.insert(
257 "device_authorization_endpoint".to_owned(),
258 self.device_authorization_endpoint().as_str().into(),
259 );
260 }
261
262 if self.with_registration {
263 json_metadata_object.insert(
264 "registration_endpoint".to_owned(),
265 self.registration_endpoint().as_str().into(),
266 );
267 }
268
269 serde_json::from_value(json_metadata).unwrap()
270 }
271}
272
273pub struct RegistrationEndpoint;
275
276impl<'a> MockEndpoint<'a, RegistrationEndpoint> {
277 pub fn ok(self) -> MatrixMock<'a> {
279 self.ok_json(json!({
280 "client_id": "test_client_id",
281 "client_id_issued_at": 1716375696,
282 }))
283 }
284}
285
286pub struct DeviceAuthorizationEndpoint;
288
289impl<'a> MockEndpoint<'a, DeviceAuthorizationEndpoint> {
290 pub fn ok(self) -> MatrixMock<'a> {
292 let issuer_url = Url::parse(&self.server.uri())
293 .expect("We should be able to parse the wiremock server URI");
294 let verification_uri = issuer_url.join("link").unwrap();
295 let mut verification_uri_complete = issuer_url.join("link").unwrap();
296 verification_uri_complete.set_query(Some("code=N32YVC"));
297
298 self.ok_json(json!({
299 "device_code": "N8NAYD9fOhMulpm37mSthx0xSw2p7vdR",
300 "expires_in": 1200,
301 "interval": 5,
302 "user_code": "N32YVC",
303 "verification_uri": verification_uri,
304 "verification_uri_complete": verification_uri_complete,
305 }))
306 }
307}
308
309pub struct TokenEndpoint;
311
312impl<'a> MockEndpoint<'a, TokenEndpoint> {
313 pub fn ok(self) -> MatrixMock<'a> {
315 self.ok_with_tokens("1234", "ZYXWV")
316 }
317
318 pub fn ok_with_tokens(self, access_token: &str, refresh_token: &str) -> MatrixMock<'a> {
320 self.ok_json(json!({
321 "access_token": access_token,
322 "expires_in": 300,
323 "refresh_token": refresh_token,
324 "token_type": "Bearer"
325 }))
326 }
327
328 pub fn access_denied(self) -> MatrixMock<'a> {
330 self.respond_with_code_and_json(
331 400,
332 json!({
333 "error": "access_denied",
334 }),
335 )
336 }
337
338 pub fn expired_token(self) -> MatrixMock<'a> {
340 self.respond_with_code_and_json(
341 400,
342 json!({
343 "error": "expired_token",
344 }),
345 )
346 }
347
348 pub fn invalid_grant(self) -> MatrixMock<'a> {
350 self.respond_with_code_and_json(
351 400,
352 json!({
353 "error": "invalid_grant",
354 }),
355 )
356 }
357}
358
359pub struct RevocationEndpoint;
361
362impl<'a> MockEndpoint<'a, RevocationEndpoint> {
363 pub fn ok(self) -> MatrixMock<'a> {
365 self.ok_empty_json()
366 }
367}