Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OAuth open URL in default browser, set success message and throw desc… #1396

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] - YYYY-MM-DD

### Changed
- [oauth] Open authorization URL in default browser
- [oauth] Allow optionally passing success message to display on browser return page
- [oauth] Throw specific errors on failure states

### Added

Expand Down
37 changes: 37 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions oauth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ log = "0.4"
oauth2 = "4.4"
thiserror = "1.0"
url = "2.2"
open = "5.3.1"

[dev-dependencies]
env_logger = { version = "0.11.2", default-features = false, features = ["color", "humantime", "auto-color"] }
2 changes: 1 addition & 1 deletion oauth/examples/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn main() {
return;
};

match get_access_token(client_id, redirect_uri, scopes) {
match get_access_token(client_id, redirect_uri, scopes, None) {
Ok(token) => println!("Success: {token:#?}"),
Err(e) => println!("Failed: {e}"),
};
Expand Down
161 changes: 144 additions & 17 deletions oauth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ pub enum OAuthError {
#[error("Auth code param not found in URI {uri}")]
AuthCodeNotFound { uri: String },

#[error("CSRF token param not found in URI {uri}")]
CsrfTokenNotFound { uri: String },

#[error("Failed to read redirect URI from stdin")]
AuthCodeStdinRead,

Expand Down Expand Up @@ -63,6 +66,12 @@ pub enum OAuthError {

#[error("Failed to exchange code for access token ({e})")]
ExchangeCode { e: String },

#[error("Spotify did not provide a refresh token")]
NoRefreshToken,

#[error("Spotify did not return the token scopes")]
NoTokenScopes,
}

#[derive(Debug)]
Expand All @@ -74,20 +83,38 @@ pub struct OAuthToken {
pub scopes: Vec<String>,
}

/// Return code query-string parameter from the redirect URI.
fn get_code(redirect_url: &str) -> Result<AuthorizationCode, OAuthError> {
/// Return URL from the redirect URI &str.
fn get_url(redirect_url: &str) -> Result<Url, OAuthError> {
let url = Url::parse(redirect_url).map_err(|e| OAuthError::AuthCodeBadUri {
uri: redirect_url.to_string(),
e,
})?;
let code = url
.query_pairs()
.find(|(key, _)| key == "code")
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
Ok(url)
}

/// Return a query-string parameter from the redirect URI.
fn get_query_string_parameter(url: &Url, query_string_parameter_key: &str) -> Option<String> {
url.query_pairs()
.find(|(key, _)| key == query_string_parameter_key)
.map(|(_, query_string_parameter)| query_string_parameter.into_owned())
}

/// Return state query-string parameter from the redirect URI (CSRF token).
fn get_state(url: &Url) -> Result<String, OAuthError> {
let state = get_query_string_parameter(url, "state").ok_or(OAuthError::CsrfTokenNotFound {
uri: url.to_string(),
})?;

Ok(state)
}

/// Return code query-string parameter from the redirect URI.
fn get_code(url: &Url) -> Result<AuthorizationCode, OAuthError> {
let code = get_query_string_parameter(url, "code")
.map(AuthorizationCode::new)
.ok_or(OAuthError::AuthCodeNotFound {
uri: redirect_url.to_string(),
uri: url.to_string(),
})?;

Ok(code)
}

Expand All @@ -100,11 +127,16 @@ fn get_authcode_stdin() -> Result<AuthorizationCode, OAuthError> {
.read_line(&mut buffer)
.map_err(|_| OAuthError::AuthCodeStdinRead)?;

get_code(buffer.trim())
let url = get_url(buffer.trim())?;
get_code(&url)
}

/// Spawn HTTP server at provided socket address to accept OAuth callback and return auth code.
fn get_authcode_listener(socket_address: SocketAddr) -> Result<AuthorizationCode, OAuthError> {
fn get_authcode_listener(
socket_address: SocketAddr,
csrf_token: CsrfToken,
success_message: Option<String>,
) -> Result<AuthorizationCode, OAuthError> {
let listener =
TcpListener::bind(socket_address).map_err(|e| OAuthError::AuthCodeListenerBind {
addr: socket_address,
Expand All @@ -128,19 +160,28 @@ fn get_authcode_listener(socket_address: SocketAddr) -> Result<AuthorizationCode
.split_whitespace()
.nth(1)
.ok_or(OAuthError::AuthCodeListenerParse)?;
let code = get_code(&("http://localhost".to_string() + redirect_url));

let url = get_url(&("http://localhost".to_string() + redirect_url))?;

let token = get_state(&url)?;
if !token.eq(csrf_token.secret()) {
return Err(OAuthError::CsrfTokenNotFound {
uri: redirect_url.to_string(),
});
}
let code = get_code(&url)?;

let message = "Go back to your terminal :)";
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
message.len(),
message
success_message.unwrap_or(message.to_owned())
);
stream
.write_all(response.as_bytes())
.map_err(|_| OAuthError::AuthCodeListenerWrite)?;

code
Ok(code)
}

// If the specified `redirect_uri` is HTTP, loopback, and contains a port,
Expand Down Expand Up @@ -168,6 +209,7 @@ pub fn get_access_token(
client_id: &str,
redirect_uri: &str,
scopes: Vec<&str>,
success_message: Option<String>,
) -> Result<OAuthToken, OAuthError> {
let auth_url = AuthUrl::new("https://accounts.spotify.com/authorize".to_string())
.map_err(|_| OAuthError::InvalidSpotifyUri)?;
Expand Down Expand Up @@ -195,16 +237,19 @@ pub fn get_access_token(
.into_iter()
.map(|s| Scope::new(s.into()))
.collect();
let (auth_url, _) = client
let (auth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
.add_scopes(request_scopes)
.set_pkce_challenge(pkce_challenge)
.url();

println!("Browse to: {}", auth_url);
if let Err(err) = open::that(auth_url.to_string()) {
eprintln!("An error occurred when opening '{}': {}", auth_url, err)
}

let code = match get_socket_address(redirect_uri) {
Some(addr) => get_authcode_listener(addr),
Some(addr) => get_authcode_listener(addr, csrf_token, success_message),
_ => get_authcode_stdin(),
}?;
trace!("Exchange {code:?} for access token");
Expand All @@ -226,11 +271,17 @@ pub fn get_access_token(

let token_scopes: Vec<String> = match token.scopes() {
Some(s) => s.iter().map(|s| s.to_string()).collect(),
_ => scopes.into_iter().map(|s| s.to_string()).collect(),
None => {
error!("Spotify did not return the token scopes.");
return Err(OAuthError::NoTokenScopes);
}
};
let refresh_token = match token.refresh_token() {
Some(t) => t.secret().to_string(),
_ => "".to_string(), // Spotify always provides a refresh token.
None => {
error!("Spotify did not provide a refresh token.");
return Err(OAuthError::NoRefreshToken);
}
};
Ok(OAuthToken {
access_token: token.access_token().secret().to_string(),
Expand Down Expand Up @@ -284,4 +335,80 @@ mod test {
Some(localhost_v6)
);
}
#[test]
fn test_get_url_valid() {
let redirect_url = "https://example.com/callback?code=1234&state=abcd";
let result = get_url(redirect_url);
assert!(result.is_ok());
let url = result.unwrap();
assert_eq!(url.as_str(), redirect_url);
}

#[test]
fn test_get_url_invalid() {
let redirect_url = "invalid_url";
let result = get_url(redirect_url);
assert!(result.is_err());
if let Err(OAuthError::AuthCodeBadUri { uri, .. }) = result {
assert_eq!(uri, redirect_url.to_string());
} else {
panic!("Expected OAuthError::AuthCodeBadUri");
}
}

#[test]
fn test_get_query_string_parameter_found() {
let url = Url::parse("https://example.com/callback?code=1234&state=abcd").unwrap();
let key = "code";
let result = get_query_string_parameter(&url, key);
assert_eq!(result, Some("1234".to_string()));
}

#[test]
fn test_get_query_string_parameter_not_found() {
let url = Url::parse("https://example.com/callback?code=1234&state=abcd").unwrap();
let key = "missing_key";
let result = get_query_string_parameter(&url, key);
assert!(result.is_none());
}

#[test]
fn test_get_state_valid() {
let url = Url::parse("https://example.com/callback?state=abcd").unwrap();
let result = get_state(&url);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "abcd");
}

#[test]
fn test_get_state_missing() {
let url = Url::parse("https://example.com/callback").unwrap();
let result = get_state(&url);
assert!(result.is_err());
if let Err(OAuthError::CsrfTokenNotFound { uri }) = result {
assert_eq!(uri, url.to_string());
} else {
panic!("Expected OAuthError::CsrfTokenNotFound");
}
}

#[test]
fn test_get_code_valid() {
let url = Url::parse("https://example.com/callback?code=1234").unwrap();
let result = get_code(&url);
assert!(result.is_ok());
assert_eq!(result.unwrap().secret(), "1234");
}

#[test]
fn test_get_code_missing() {
let url = Url::parse("https://example.com/callback").unwrap();
let result = get_code(&url);
assert!(result.is_err());
if let Err(OAuthError::AuthCodeNotFound { uri }) = result {
assert_eq!(uri, url.to_string());
} else {
panic!("Expected OAuthError::AuthCodeNotFound");
}
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1896,6 +1896,7 @@ async fn main() {
&setup.session_config.client_id,
&format!("http://127.0.0.1{port_str}/login"),
OAUTH_SCOPES.to_vec(),
None,
) {
Ok(token) => token.access_token,
Err(e) => {
Expand Down