src/oauth.rs
176 lines · 6292 bytes
4 symbols in this file
1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use matrix_sdk::authentication::oauth::OAuthAuthorizationData;
4use matrix_sdk::authentication::oauth::registration::{
5 ApplicationType,
6 ClientMetadata,
7 Localized,
8 OAuthGrantType,
9};
10use matrix_sdk::ruma;
11use matrix_sdk::ruma::UserId;
12use matrix_sdk::ruma::serde::Raw;
13use matrix_sdk::utils::UrlOrQuery;
14use matrix_sdk::utils::local_server::{LocalServerBuilder, LocalServerRedirectHandle};
15use tokio::io::AsyncBufReadExt;
16use tokio::task::JoinHandle;
17
18use crate::config::SavedDevice;
19use crate::prelude::*;
20
21enum OAuthRedirectResponse {
22 Server(UrlOrQuery),
23 Stdin(UrlOrQuery),
24}
25
26pub async fn oauth_login(
27 client: Client,
28 user_hint: &UserId,
29 saved_device: Option<SavedDevice>,
30) -> IambResult<()> {
31 let oauth = client.oauth();
32
33 match oauth.server_metadata().await {
34 Ok(server_metadata) => {
35 tracing::info!(
36 "Found OAuth 2.0 server metadata with issuer: {}",
37 server_metadata.issuer
38 );
39
40 let device = if let Some(SavedDevice::OAuth { device_id, client_id, .. }) = saved_device
41 {
42 oauth.restore_registered_client(client_id.clone());
43 Some(device_id)
44 } else {
45 None
46 };
47
48 let (redirect_uri, server_handle) = LocalServerBuilder::new().spawn().await?;
49 let OAuthAuthorizationData { url, .. } = oauth
50 .login(redirect_uri, device, Some(client_metadata().into()), None)
51 .user_id_hint(user_hint)
52 .build()
53 .await
54 .map_err(IambError::from)?;
55
56 let opened =
57 format!("The following URL should have been opened in your browser:\n {url}");
58 tokio::task::spawn_blocking(move || open::that(url.as_str()));
59 println!("{opened}");
60 println!(
61 "\n\n\
62 If the redirect fails to connect (i.e., iamb is not reachable from your browser), \
63 the url (or just the query string) can be pasted here to complete the authorisation flow.\
64 "
65 );
66
67 let url_or_query = wait_auth_code(server_handle).await?;
68 oauth.finish_login(url_or_query).await.map_err(IambError::from)?;
69 Ok(())
70 },
71 Err(error) => {
72 if error.is_not_supported() {
73 tracing::warn!("Homeserver doesn't advertise OAuth 2.0 metadata");
74 } else {
75 tracing::warn!("Error fetching OAuth 2.0 metadata : {error:?}");
76 }
77 Err(UIError::Failure(
78 "Error fetching homeserver OAuth 2.0 metadata. \
79 Homeserver needs to support native OAuth 2.0 for oauth login to work"
80 .to_string(),
81 ))
82 },
83 }
84}
85
86async fn wait_auth_code(server_handle: LocalServerRedirectHandle) -> IambResult<UrlOrQuery> {
87 let (tx, mut rx) = tokio::sync::mpsc::channel(1);
88
89 let server_tx = tx.clone();
90
91 let server = tokio::spawn(async move {
92 let server_resp = server_handle.await;
93 match server_resp {
94 Some(query) => {
95 let _ = server_tx.try_send(OAuthRedirectResponse::Server(query.into()));
96 },
97 None => {
98 println!(
99 "Failed to read query string from browser redirect. \
100 Please paste url in here:\n"
101 );
102 },
103 }
104 });
105
106 let stdin_reader: JoinHandle<Result<(), tokio::io::Error>> = tokio::task::spawn(async move {
107 let stdin = tokio::io::stdin();
108 let mut reader = tokio::io::BufReader::new(stdin);
109 let mut line = String::new();
110
111 loop {
112 reader.read_line(&mut line).await?;
113 if let Ok(url) = Url::parse(&line) {
114 let _ = tx.try_send(OAuthRedirectResponse::Stdin(UrlOrQuery::Url(url)));
115 break;
116 } else if line.starts_with('?') {
117 let strip_qm = line.split_off(0);
118 let _ = tx.try_send(OAuthRedirectResponse::Stdin(UrlOrQuery::Query(strip_qm)));
119 break;
120 } else if line.contains("code=") {
121 let _ = tx.try_send(OAuthRedirectResponse::Stdin(UrlOrQuery::Query(line)));
122 break;
123 } else if !line.contains(char::is_whitespace) {
124 println!("Unrecognised url or query string");
125 } else {
126 break;
127 }
128 }
129 Ok(())
130 });
131
132 let received = rx.recv().await;
133
134 match received {
135 Some(OAuthRedirectResponse::Server(qry)) => {
136 println!("Received authorisation code from browser. Press Enter to continue...");
137 let _ = stdin_reader.await;
138 Ok(qry)
139 },
140 Some(OAuthRedirectResponse::Stdin(url)) => {
141 server.abort();
142 println!("Using redirect from stdin. Localhost listener will be ignored.");
143 Ok(url)
144 },
145 None => {
146 Err(UIError::Failure("Failed to receive redirect from stdin or browser".to_string()))
147 },
148 }
149}
150
151// Taken from the sdk's example
152fn client_metadata() -> Raw<ClientMetadata> {
153 let ipv4_localhost_uri = Url::parse(&format!("http://{}/", Ipv4Addr::LOCALHOST))
154 .expect("Couldn't parse IPv4 redirect URI");
155 let ipv6_localhost_uri = Url::parse(&format!("http://[{}]/", Ipv6Addr::LOCALHOST))
156 .expect("Couldn't parse IPv6 redirect URI");
157 let client_uri =
158 Localized::new(Url::parse("https://iamb.chat").expect("Couldn't parse client URI"), None);
159 let logo_uri = Localized::new(
160 Url::parse("https://iamb.chat/images/iamb.png").expect("Couldn't parse logo uri"),
161 None,
162 );
163
164 let metadata = ruma::assign!(
165 ClientMetadata::new(
166 ApplicationType::Native,
167 vec![OAuthGrantType::AuthorizationCode {
168 redirect_uris: vec![ipv4_localhost_uri, ipv6_localhost_uri],
169 }],
170 client_uri), {
171 client_name: Some(Localized::new("iamb".to_owned(), [])),
172 logo_uri: Some(logo_uri)
173 });
174
175 Raw::new(&metadata).expect("Couldn't serialize client metadata")
176}