day_part_auth/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-part-auth: sign-in for Day apps, through the platform's own doors.
5//!
6//! ```no_run
7//! use day_part_auth::{Client, Provider};
8//!
9//! let client = Client::new(Provider::google(), "1234.apps.googleusercontent.com")
10//! .scopes(["openid", "email", "profile"]);
11//! # async fn run(client: Client) {
12//! match client.sign_in().await {
13//! Ok(tokens) => println!("signed in as {:?}", tokens.subject()),
14//! Err(e) => println!("not signed in: {e}"),
15//! }
16//! # }
17//! ```
18//!
19//! Three layers, each usable on its own:
20//!
21//! 1. [`session`]: the system's sign-in browser (`ASWebAuthenticationSession`, a Custom Tab,
22//! a same-origin popup, the default browser with a loopback listener), which returns the URL
23//! the provider redirected to.
24//! 2. The OAuth 2.0 / OpenID Connect client: [`Provider`] (discovered or given),
25//! [`Client`] and [`Redirect`], the authorization request with PKCE, `state` and `nonce`
26//! ([`authorize`]), and the token requests ([`tokens`]) whose ID tokens are verified against
27//! the provider's keys ([`jwt`]). [`Client::sign_in`] runs the whole flow.
28//! 3. The native credentials: [`apple`] (Sign in with Apple), [`google`] (Credential Manager on
29//! Android), and [`passkeys`] (WebAuthn JSON in, credential JSON out).
30//!
31//! Every future here is `Send` and resolves on the UI thread when awaited under `day::task`;
32//! the calls that show a browser or a sheet start on the UI thread, which is where an action
33//! runs. Nothing here posts to a main loop, so the crate works in a plain `main` and under
34//! `cargo test`.
35//!
36//! The crate keeps no tokens. A [`TokenSet`] is the app's to store, and
37//! [day-part-keychain](https://daybrite.dev/docs/reference/keychain) is where a refresh token
38//! belongs.
39
40use std::fmt;
41
42pub use day_bridge::Support;
43
44pub mod apple;
45pub mod authorize;
46pub mod crypto;
47#[cfg(all(feature = "demo-provider", not(target_arch = "wasm32")))]
48pub mod demo_provider;
49mod flow;
50pub mod google;
51mod http;
52pub mod jwt;
53mod native;
54pub mod passkeys;
55pub mod provider;
56pub mod session;
57pub mod tokens;
58mod urls;
59
60pub use authorize::{Authorization, Client, Redirect};
61pub use provider::Provider;
62pub use session::SessionOptions;
63pub use tokens::{IdToken, TokenSet};
64
65/// Why a sign-in, a token request or a credential request did not succeed.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum AuthError {
68 /// This platform has no implementation of what was asked.
69 Unsupported,
70 /// The person dismissed the browser or the dialog.
71 Cancelled,
72 /// The callback never arrived within the time allowed.
73 Timeout,
74 /// The request could not be built: a missing endpoint, an unusable redirect URI, a
75 /// malformed URL. The text says which.
76 InvalidRequest(String),
77 /// The provider answered an authorization or token request with an error (`error`, and
78 /// `error_description` when it gave one).
79 Provider {
80 error: String,
81 description: Option<String>,
82 },
83 /// The callback's `state` did not match the request's, or arrived without one.
84 StateMismatch,
85 /// A token or a provider document failed validation. The text says what.
86 InvalidToken(String),
87 /// A network request failed before the provider answered.
88 Network(String),
89 /// A platform error outside the vocabulary above, with the platform's message.
90 Platform(String),
91}
92
93impl fmt::Display for AuthError {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 match self {
96 AuthError::Unsupported => write!(f, "not supported on this platform"),
97 AuthError::Cancelled => write!(f, "cancelled"),
98 AuthError::Timeout => write!(f, "the callback did not arrive in time"),
99 AuthError::InvalidRequest(why) => write!(f, "invalid request: {why}"),
100 AuthError::Provider { error, description } => match description {
101 Some(d) => write!(f, "{error}: {d}"),
102 None => write!(f, "{error}"),
103 },
104 AuthError::StateMismatch => write!(f, "the callback's state does not match"),
105 AuthError::InvalidToken(why) => write!(f, "invalid token: {why}"),
106 AuthError::Network(why) => write!(f, "network: {why}"),
107 AuthError::Platform(why) => write!(f, "platform error: {why}"),
108 }
109 }
110}
111
112impl std::error::Error for AuthError {}
113
114impl From<day_bridge::Error> for AuthError {
115 fn from(e: day_bridge::Error) -> Self {
116 match e {
117 day_bridge::Error::Unsupported => AuthError::Unsupported,
118 day_bridge::Error::Foreign(message) => match message.as_str() {
119 "cancelled" => AuthError::Cancelled,
120 "unsupported" => AuthError::Unsupported,
121 _ => AuthError::Platform(message),
122 },
123 day_bridge::Error::Encoding => AuthError::Platform("bridge encoding error".into()),
124 day_bridge::Error::Runtime => {
125 AuthError::Platform("platform runtime unavailable".into())
126 }
127 }
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 #[test]
136 fn errors_display_and_convert() {
137 for e in [
138 AuthError::Unsupported,
139 AuthError::Cancelled,
140 AuthError::Timeout,
141 AuthError::InvalidRequest("x".into()),
142 AuthError::Provider {
143 error: "e".into(),
144 description: None,
145 },
146 AuthError::Provider {
147 error: "e".into(),
148 description: Some("d".into()),
149 },
150 AuthError::StateMismatch,
151 AuthError::InvalidToken("x".into()),
152 AuthError::Network("x".into()),
153 AuthError::Platform("x".into()),
154 ] {
155 assert_ne!(e.to_string(), "");
156 }
157 assert_eq!(
158 AuthError::from(day_bridge::Error::Foreign("cancelled".into())),
159 AuthError::Cancelled
160 );
161 assert_eq!(
162 AuthError::from(day_bridge::Error::Unsupported),
163 AuthError::Unsupported
164 );
165 }
166}