-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlogin.rs
More file actions
768 lines (690 loc) · 26.9 KB
/
login.rs
File metadata and controls
768 lines (690 loc) · 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use crate::{
JsonValue, login::url_discovery::is_local_dev_environment_url, parsed_url::ParsedUrl,
plugins::PluginSlug, uuid::WpUuid,
};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, str, sync::Arc};
use wp_localization::{MessageBundle, WpMessages, WpSupportsLocalization};
use wp_localization_macro::WpDeriveLocalizable;
use wp_serde_helper::{
deserialize_empty_array_or_hashmap, deserialize_false_or_string, deserialize_offset,
deserialize_string_vec_or_string_as_option,
};
const KEY_APPLICATION_PASSWORDS: &str = "application-passwords";
const KEY_OAUTH2: &str = "oauth2";
pub mod login_client;
pub mod nonce;
pub mod url_discovery;
#[derive(Debug, uniffi::Record)]
pub struct WpRestApiUrls {
api_details: Arc<WpApiDetails>,
api_root_url: String,
}
// After a successful login, the system will receive an OAuth callback with the login details
// embedded as query params. This function parses that URL and extracts the login details as an object.
#[uniffi::export]
pub fn extract_login_details_from_url(
url: String,
) -> Result<WpApiApplicationPasswordDetails, OAuthResponseUrlError> {
let url = ParsedUrl::parse(&url).map_err(|_| OAuthResponseUrlError::InvalidUrl)?;
extract_login_details_from_parsed_url(url)
}
pub fn extract_login_details_from_parsed_url(
url: ParsedUrl,
) -> Result<WpApiApplicationPasswordDetails, OAuthResponseUrlError> {
let f = |key| {
url.inner
.query_pairs()
.find_map(|(k, v)| (k == key).then_some(v.to_string()))
};
if let Some(is_success) = f("success")
&& is_success == "false"
{
return Err(OAuthResponseUrlError::UnsuccessfulLogin);
}
let site_url = f("site_url").ok_or(OAuthResponseUrlError::MissingSiteUrl)?;
let user_login = f("user_login").ok_or(OAuthResponseUrlError::MissingUsername)?;
let password = f("password").ok_or(OAuthResponseUrlError::MissingPassword)?;
Ok(WpApiApplicationPasswordDetails {
site_url,
user_login,
password,
})
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Object)]
pub struct WpApiDetails {
pub name: String,
pub description: String,
pub url: String,
pub home: String,
#[serde(default, deserialize_with = "deserialize_offset")]
pub gmt_offset: Option<f64>,
pub timezone_string: Option<String>,
pub namespaces: Vec<String>,
pub authentication: WpApiDetailsAuthenticationMap,
#[serde(default, deserialize_with = "deserialize_false_or_string")]
pub site_icon_url: Option<String>,
pub routes: HashMap<String, WpRoute>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct WpRoute {
pub namespace: String,
pub methods: Vec<String>,
pub endpoints: Vec<WpEndpoint>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct WpEndpoint {
pub methods: Vec<String>,
pub args: Arc<WpEndpointArgs>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Object)]
#[serde(transparent)]
pub struct WpEndpointArgs(serde_json::Value);
impl WpEndpointArgs {
pub fn get(&self, arg: &str) -> Option<WpEndpointArg> {
let obj = self.0.as_object()?;
let value = obj.get(arg)?;
serde_json::from_value(value.clone()).ok()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct WpEndpointArg {
pub required: bool,
pub default: Option<JsonValue>,
pub description: Option<String>,
#[serde(deserialize_with = "deserialize_string_vec_or_string_as_option")]
#[serde(default)]
pub r#type: Option<Vec<String>>,
pub r#enum: Option<Vec<JsonValue>>,
// There are many other fields that are specific to the type of argument. These are not currently supported because
// they're likely to be of limited value to library users. We're open to adding them if there's a demand for them.
}
impl TryFrom<&[u8]> for WpApiDetails {
type Error = serde_json::Error;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
// If the body starts with the UTF-8 BOM, remove it
if value.starts_with(&[0xEF, 0xBB, 0xBF]) {
serde_json::from_slice::<WpApiDetails>(&value[3..])
} else {
serde_json::from_slice::<WpApiDetails>(value)
}
}
}
#[uniffi::export]
impl WpApiDetails {
/// Does the site have application passwords enabled?
pub fn has_application_passwords_authentication_url(&self) -> bool {
self.authentication
.has_application_passwords_authentication_url()
}
/// Returns the URL to be used in application password authentication.
///
/// See the "Authorization Flow" section for details:
/// <https://github.com/WordPress/wordpress-develop/blob/530493396b324f5bed518a494e2843e7fdb020f1/src/wp-includes/rest-api.php#L1099-L1119>
pub fn find_application_passwords_authentication_url(&self) -> Option<String> {
self.authentication
.find_application_passwords_authentication_url()
}
/// Does the site use OAuth2?
pub fn has_oauth2(&self) -> bool {
self.authentication.has_oauth2()
}
pub fn find_oauth2_endpoints(&self) -> Option<OAuth2Endpoints> {
self.authentication.find_oauth2_endpoints()
}
/// Does the site URL (as defined by the site itself, not by user input) use HTTPS?
pub fn uses_https(&self) -> bool {
self.url.starts_with("https://")
}
/// Does the site use a plugin that disables application passwords?
pub fn has_application_password_blocking_plugin(&self) -> bool {
KnownAuthenticationBlockingPlugin::application_passwords()
.iter()
.any(|plugin| {
plugin
.namespace
.as_ref()
.is_some_and(|ns| self.namespaces.contains(ns))
})
}
/// Returns a list of plugins that might be responsible for disabling application passwords.
pub fn application_password_blocking_plugins(&self) -> Vec<KnownAuthenticationBlockingPlugin> {
KnownAuthenticationBlockingPlugin::application_passwords()
.iter()
.filter(|plugin| {
plugin
.namespace
.as_ref()
.is_some_and(|ns| self.namespaces.contains(ns))
})
.cloned()
.collect()
}
/// Returns a list of plugins that might be responsible for disabling XML-RPC.
pub fn xmlrpc_blocking_plugins(&self) -> Vec<KnownAuthenticationBlockingPlugin> {
KnownAuthenticationBlockingPlugin::xmlrpc()
.iter()
.filter(|plugin| {
plugin
.namespace
.as_ref()
.is_some_and(|ns| self.namespaces.contains(ns))
})
.cloned()
.collect()
}
/// Returns the site URL (as defined by the site itself, not by user input) as a string.
pub fn site_url_string(&self) -> String {
self.url.clone()
}
/// Returns `true` if the site URL looks like a local development environment URL.
pub fn site_url_is_local_development_environment(&self) -> bool {
ParsedUrl::parse(self.url.as_str())
.is_ok_and(|parsed_url| is_local_dev_environment_url(&parsed_url))
}
/// Returns `true` if the site has routes matching the given namespace.
pub fn has_namespace(&self, namespace: String) -> bool {
self.namespaces.contains(&namespace)
}
/// Returns `true` if the site has the given route.
pub fn has_route(&self, route: String) -> bool {
self.routes.contains_key(&route)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct KnownAuthenticationBlockingPlugin {
/// The name of the plugin.
pub name: String,
/// The plugin's slug. For example: "wordfence/wordfence"
pub slug: PluginSlug,
/// The plugin's REST API namespace.
pub namespace: Option<String>,
/// A URL to the plugin's support page, where users can find help.
pub support_url: String,
}
impl KnownAuthenticationBlockingPlugin {
fn all() -> Vec<Self> {
vec![
Self {
name: "Wordfence".to_string(),
slug: PluginSlug::from("wordfence/wordfence"),
namespace: Some("wordfence/v1".to_string()),
// TODO: Ensure this is correct with the WordFence folks
support_url: "https://www.wordfence.com/support/".to_string(),
},
Self {
name: "Hostinger Tools".to_string(),
slug: PluginSlug::from("hostinger-tools/hostinger-tools"),
namespace: Some("hostinger-tools-plugin/v1".to_string()),
// TODO: Ensure this is correct with the Hostinger folks
support_url: "https://wordpress.org/support/plugin/hostinger/".to_string(),
},
Self {
name: "FluentAuth".to_string(),
slug: PluginSlug::from("fluent-security/fluent-security"),
namespace: Some("fluent-auth".to_string()),
// TODO: Ensure this is correct with the FluentAuth folks
support_url: "https://wordpress.org/support/plugin/fluent-security/".to_string(),
},
Self {
name: "Disable XML-RPC".to_string(),
slug: PluginSlug::from("disable-xml-rpc/disable-xml-rpc"),
namespace: None,
support_url: "https://wordpress.org/plugins/disable-xml-rpc/".to_string(),
},
Self {
name: "Disable XML-RPC-API".to_string(),
slug: PluginSlug::from("disable-xml-rpc-api/disable-xml-rpc-api"),
namespace: None,
support_url: "https://wordpress.org/plugins/disable-xml-rpc-api/".to_string(),
},
Self {
name: "Loginizer".to_string(),
slug: PluginSlug::from("loginizer/loginizer"),
namespace: None,
support_url: "https://wordpress.org/support/plugin/loginizer/".to_string(),
},
Self {
name: "Really Simple Security".to_string(),
slug: PluginSlug::from("really-simple-ssl/rlrsssl-really-simple-ssl"),
namespace: None,
support_url: "https://wordpress.org/support/plugin/really-simple-ssl/".to_string(),
},
]
}
fn application_passwords() -> Vec<Self> {
let names = ["Wordfence", "Hostinger Tools", "FluentAuth"];
Self::all()
.into_iter()
.filter(|plugin| names.contains(&plugin.name.as_str()))
.collect()
}
fn xmlrpc() -> Vec<Self> {
Self::all()
}
}
#[uniffi::export]
fn xmlrpc_blocking_plugins() -> Vec<KnownAuthenticationBlockingPlugin> {
KnownAuthenticationBlockingPlugin::xmlrpc()
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum WpRestApiAuthenticationScheme {
ApplicationPassword(WpRestApiApplicationPasswordAuthenticationScheme),
OAuth2(WpRestApiOAuth2AuthenticationScheme),
/// Catch-all for unknown authentication schemes (e.g., oauth1)
Unknown(serde_json::Value),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct WpRestApiApplicationPasswordAuthenticationScheme {
pub endpoints: WpRestApiAuthorizationEndpoint,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct WpRestApiAuthorizationEndpoint {
pub authorization: String,
}
/// OAuth2 authentication scheme with authorization and token endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]
pub struct WpRestApiOAuth2AuthenticationScheme {
pub authorize: String,
pub token: String,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, uniffi::Record)]
pub struct WpApiApplicationPasswordDetails {
pub site_url: String,
pub user_login: String,
pub password: String,
}
#[derive(
Debug, PartialEq, Eq, PartialOrd, Ord, thiserror::Error, uniffi::Error, WpDeriveLocalizable,
)]
pub enum OAuthResponseUrlError {
InvalidUrl,
MissingSiteUrl,
MissingUsername,
MissingPassword,
UnsuccessfulLogin,
}
impl WpSupportsLocalization for OAuthResponseUrlError {
fn message_bundle(&self) -> MessageBundle<'_> {
match self {
OAuthResponseUrlError::MissingSiteUrl
| OAuthResponseUrlError::MissingUsername
| OAuthResponseUrlError::MissingPassword => {
WpMessages::oauth_response_url_error_url_invalid()
}
OAuthResponseUrlError::UnsuccessfulLogin => {
WpMessages::oauth_response_url_error_unsuccessful_login()
}
OAuthResponseUrlError::InvalidUrl => WpMessages::oauth_response_url_error_url_invalid(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WpApiDetailsAuthenticationMap(
#[serde(deserialize_with = "deserialize_empty_array_or_hashmap")]
HashMap<String, WpRestApiAuthenticationScheme>,
);
impl WpApiDetailsAuthenticationMap {
pub fn has_application_passwords_authentication_url(&self) -> bool {
self.0.contains_key(KEY_APPLICATION_PASSWORDS)
}
pub fn find_application_passwords_authentication_url(&self) -> Option<String> {
self.0
.get(KEY_APPLICATION_PASSWORDS)
.and_then(|auth_scheme| match auth_scheme {
WpRestApiAuthenticationScheme::ApplicationPassword(auth_scheme) => {
Some(auth_scheme.endpoints.authorization.clone())
}
_ => None,
})
}
pub fn has_oauth2(&self) -> bool {
self.0.contains_key(KEY_OAUTH2)
}
pub fn find_oauth2_endpoints(&self) -> Option<OAuth2Endpoints> {
self.0
.get(KEY_OAUTH2)
.and_then(|auth_scheme| match auth_scheme {
WpRestApiAuthenticationScheme::OAuth2(auth_scheme) => Some(OAuth2Endpoints {
authorization_url: auth_scheme.authorize.clone(),
token_url: auth_scheme.token.clone(),
}),
_ => None,
})
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, uniffi::Record)]
pub struct OAuth2Endpoints {
pub authorization_url: String,
pub token_url: String,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, uniffi::Record)]
pub struct OAuth2Client {
pub client_id: String,
pub client_secret: String,
#[serde(rename = "redirectUri")]
pub redirect_uri: String,
pub scope: String,
pub state: Option<String>,
}
/// Return a URL to be used in application password authentication.
///
/// See the "Authorization Flow" section for details:
/// <https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/>
#[uniffi::export]
pub fn create_application_password_authentication_url(
login_url: Arc<ParsedUrl>,
app_name: String,
app_id: Option<Arc<WpUuid>>,
success_url: Option<String>,
reject_url: Option<String>,
) -> ParsedUrl {
let mut auth_url = login_url.inner.clone();
auth_url
.query_pairs_mut()
.append_pair("app_name", app_name.as_str());
if let Some(app_id) = app_id {
auth_url
.query_pairs_mut()
.append_pair("app_id", app_id.uuid_string().as_str());
}
if let Some(success_url) = success_url {
auth_url
.query_pairs_mut()
.append_pair("success_url", success_url.as_str());
}
if let Some(reject_url) = reject_url {
auth_url
.query_pairs_mut()
.append_pair("reject_url", reject_url.as_str());
}
ParsedUrl::new(auth_url)
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
use std::io::Read;
#[rstest]
#[case(
"exampleauth://login?site_url=http://example.com&user_login=test&password=1234",
Ok(())
)]
#[case(
"exampleauth://login?site_url=http://example.com&user_login=test&password=1234&foo=bar",
Ok(())
)]
#[case(
"exampleauth://login?user_login=test&password=1234",
Err(OAuthResponseUrlError::MissingSiteUrl)
)]
#[case(
"exampleauth://login?site_url=http://example.com&password=1234",
Err(OAuthResponseUrlError::MissingUsername)
)]
#[case(
"exampleauth://login?site_url=http://example.com&user_login=test",
Err(OAuthResponseUrlError::MissingPassword)
)]
#[case(
"exampleauth://login?success=false",
Err(OAuthResponseUrlError::UnsuccessfulLogin)
)]
#[case(
"exampleauth://login?success=true",
Err(OAuthResponseUrlError::MissingSiteUrl)
)]
fn test_extract_login_details_from_url(
#[case] input: &str,
#[case] expected_result: Result<(), OAuthResponseUrlError>,
) {
assert_eq!(
extract_login_details_from_url(ParsedUrl::try_from(input).unwrap().into()),
expected_result.map(|_| WpApiApplicationPasswordDetails {
site_url: "http://example.com".to_string(),
user_login: "test".to_string(),
password: "1234".to_string(),
})
);
}
#[rstest]
fn test_auth_url() {
let app_id = WpUuid::new();
let app_id_str = app_id.uuid_string();
let login_url = ParsedUrl::parse("https://example.com/wp-login.php").unwrap();
let auth_url = create_application_password_authentication_url(
login_url.into(),
"AppName".to_string(),
Some(app_id.into()),
Some("https://example.com/success".to_string()),
Some("https://example.com/reject".to_string()),
);
let expected_url = format!(
"https://example.com/wp-login.php?app_name=AppName&app_id={app_id_str}&success_url=https%3A%2F%2Fexample.com%2Fsuccess&reject_url=https%3A%2F%2Fexample.com%2Freject"
);
assert_eq!(auth_url, ParsedUrl::parse(expected_url.as_str()).unwrap());
}
#[test]
fn test_parse_wp_api_details_authentication_map_only_application_passwords() {
let json = r#"{
"authentication": {
"application-passwords": {
"endpoints": {
"authorization": "http://localhost/wp-admin/authorize-application.php"
}
}
}
}"#;
test_parse_wp_api_details_authentication_map_helper(json);
}
#[test]
fn test_parse_wp_api_details_authentication_map_application_passwords_and_oauth() {
let json = r#"{
"authentication": {
"oauth1": {
"request": "http://localhost/oauth1/request",
"authorize": "http://localhost/oauth1/authorize",
"access": "http://localhost/oauth1/access",
"version": "0.1"
},
"application-passwords": {
"endpoints": {
"authorization": "http://localhost/wp-admin/authorize-application.php"
}
}
}
}"#;
test_parse_wp_api_details_authentication_map_helper(json);
}
#[test]
fn test_parse_wp_api_details_authentication_map_application_passwords_and_oauth2() {
let json = r#"{
"authentication": {
"oauth2": {
"authorize": "http://localhost/oauth/authorize",
"token": "http://localhost/oauth/token",
"me": "http://localhost/oauth/me",
"version": "2.0",
"software": "WP OAuth Server"
},
"application-passwords": {
"endpoints": {
"authorization": "http://localhost/wp-admin/authorize-application.php"
}
}
}
}"#;
let result = serde_json::from_str::<WpApiDetailsAuthenticationMapWrapper>(json);
assert!(
result.is_ok(),
"Failed to parse json as `WpApiDetailsAuthenticationMap`"
);
let auth_map = result
.expect("Already verified result is Ok")
.authentication;
// Verify application passwords URL
assert_eq!(
auth_map.find_application_passwords_authentication_url(),
Some("http://localhost/wp-admin/authorize-application.php".to_string())
);
// Verify OAuth2 endpoints
assert!(auth_map.has_oauth2());
let oauth2_endpoints = auth_map.find_oauth2_endpoints();
assert!(oauth2_endpoints.is_some());
let endpoints = oauth2_endpoints.unwrap();
assert_eq!(
endpoints.authorization_url,
"http://localhost/oauth/authorize"
);
assert_eq!(endpoints.token_url, "http://localhost/oauth/token");
}
#[test]
fn test_find_oauth2_endpoints_returns_none_when_missing() {
let json = r#"{
"authentication": {
"application-passwords": {
"endpoints": {
"authorization": "http://localhost/wp-admin/authorize-application.php"
}
}
}
}"#;
let result = serde_json::from_str::<WpApiDetailsAuthenticationMapWrapper>(json)
.expect("Failed to parse json");
assert!(!result.authentication.has_oauth2());
assert!(result.authentication.find_oauth2_endpoints().is_none());
}
#[test]
fn test_find_oauth2_endpoints_only() {
let json = r#"{
"authentication": {
"oauth2": {
"authorize": "https://example.com/oauth/authorize",
"token": "https://example.com/oauth/token"
}
}
}"#;
let result = serde_json::from_str::<WpApiDetailsAuthenticationMapWrapper>(json)
.expect("Failed to parse json");
assert!(result.authentication.has_oauth2());
let endpoints = result.authentication.find_oauth2_endpoints().unwrap();
assert_eq!(
endpoints.authorization_url,
"https://example.com/oauth/authorize"
);
assert_eq!(endpoints.token_url, "https://example.com/oauth/token");
}
fn test_parse_wp_api_details_authentication_map_helper(json: &str) {
let result = serde_json::from_str::<WpApiDetailsAuthenticationMapWrapper>(json);
assert!(
result.is_ok(),
"Failed to parse json as `WpApiDetailsAuthenticationMap`"
);
assert_eq!(
result
.expect("Already verified result is Ok")
.authentication
.find_application_passwords_authentication_url(),
Some("http://localhost/wp-admin/authorize-application.php".to_string())
);
}
#[test]
fn test_parse_empty_vec_as_wp_api_details_authentication_map() {
let json = r#"{"authentication": []}"#;
let result = serde_json::from_str::<WpApiDetailsAuthenticationMapWrapper>(json);
assert!(
result.is_ok(),
"Failed to parse '[]' as `WpApiDetailsAuthenticationMap`"
);
assert!(
result
.expect("Already verified result is Ok")
.authentication
.0
.is_empty()
);
}
#[rstest]
#[case("api-details/test-case-01.json")]
#[case("api-details/test-case-02.json")]
#[case("api-details/test-case-03.json")]
#[case("api-details/test-case-04.json")]
#[case("api-details/test-case-05.json")]
#[case("api-details/test-case-06.json")]
#[case("api-details/test-case-07.json")]
fn test_api_details_json(#[case] input: &str) {
let json = test_json(input).expect("Failed to read test resource");
let result = WpApiDetails::try_from(json.as_slice());
assert!(
result.is_ok(),
"Failed to parse json as `WpApiDetails`: {result:#?}"
);
}
#[test]
fn test_has_namespace() {
let json: Vec<u8> =
test_json("api-details/test-case-03.json").expect("Failed to read test resource");
let result = WpApiDetails::try_from(json.as_slice());
assert!(
result.is_ok(),
"Failed to parse json as `WpApiDetails`: {result:#?}"
);
let unwrapped_result = result.unwrap();
assert!(unwrapped_result.has_namespace("jetpack/v4".to_string()));
assert!(!unwrapped_result.has_namespace("jetpack/v2".to_string()));
}
#[rstest]
#[case("context", Some(JsonValue::String("edit".to_string())))]
#[case("jetpack_blocks_disabled", Some(JsonValue::Bool(false)))]
#[case("jetpack_portfolio_posts_per_page", Some(JsonValue::Int(10)))]
#[case("show", Some(JsonValue::Array(vec![JsonValue::String("post".to_string())])))]
#[case("sharing_services", Some(JsonValue::Object(HashMap::from([("visible".to_string(), JsonValue::Array(vec![JsonValue::String("facebook".to_string()), JsonValue::String("x".to_string())])), ("hidden".to_string(), JsonValue::Array(vec![]))]))))]
fn test_route_args(#[case] argument_name: &str, #[case] expected_result: Option<JsonValue>) {
let json: Vec<u8> =
test_json("api-details/test-case-03.json").expect("Failed to read test resource");
let result = WpApiDetails::try_from(json.as_slice());
assert!(
result.is_ok(),
"Failed to parse json as `WpApiDetails`: {result:#?}"
);
let unwrapped_result = result.unwrap();
assert!(unwrapped_result.has_route("/jetpack/v4/settings".to_string()));
let route = unwrapped_result.routes.get("/jetpack/v4/settings").unwrap();
let argument = route
.endpoints
.first()
.unwrap()
.args
.get(argument_name)
.unwrap();
assert_eq!(argument.default, expected_result);
}
#[test]
fn test_has_route() {
let json: Vec<u8> =
test_json("api-details/test-case-03.json").expect("Failed to read test resource");
let result = WpApiDetails::try_from(json.as_slice());
assert!(
result.is_ok(),
"Failed to parse json as `WpApiDetails`: {result:#?}"
);
let unwrapped_result = result.unwrap();
assert!(unwrapped_result.has_route("/jetpack/v4/backup-helper-script".to_string()));
assert!(!unwrapped_result.has_route("/jetpack/v4/fake-endpoint".to_string()));
}
fn test_json(input: &str) -> Result<Vec<u8>, std::io::Error> {
let mut file_path = std::path::PathBuf::from(env!("CARGO_WORKSPACE_DIR"));
file_path.push("test-data");
file_path.push(input);
let mut f = std::fs::File::open(file_path)?;
let mut buffer = Vec::new();
// read the whole file
f.read_to_end(&mut buffer)?;
Ok(buffer)
}
#[derive(Debug, Deserialize)]
struct WpApiDetailsAuthenticationMapWrapper {
authentication: WpApiDetailsAuthenticationMap,
}
}