fxa_client/token.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//! # Token Management
6//!
7//! A signed-in application will typically hold a number of different *tokens* associated with the
8//! user's account, including:
9//!
10//! - An OAuth `refresh_token`, representing their ongoing connection to the account
11//! and the scopes that have been granted.
12//! - Short-lived OAuth `access_token`s that can be used to access resources on behalf
13//! of the user.
14//! - Optionally, a `session_token` that gives full control over the user's account,
15//! typically managed on behalf of web content that runs within the context
16//! of the application.
17
18use crate::{ApiResult, Error, FirefoxAccount};
19use error_support::handle_error;
20use serde_derive::*;
21use std::convert::TryInto;
22
23impl FirefoxAccount {
24 /// Get a short-lived OAuth access token for the user's account.
25 ///
26 /// **💾 This method alters the persisted account state.**
27 ///
28 /// Applications that need to access resources on behalf of the user must obtain an
29 /// `access_token` in order to do so. For example, an access token is required when
30 /// fetching the user's profile data, or when accessing their data stored in Firefox Sync.
31 ///
32 /// This method will obtain and return an access token bearing the requested scopes, either
33 /// from a local cache of previously-issued tokens, or by creating a new one from the server.
34 ///
35 /// # Arguments
36 ///
37 /// - `scope` - space-separated list of OAuth scopes to be granted by the token.
38 /// - Each scope must have been requested during the signin flow, or be a scope
39 /// which the server might offer automatically in some account-specific cases.
40 /// - Scope order is not significant; `"a b"` and `"b a"` are equivalent.
41 /// - When a single scope is requested and it has an associated scoped key
42 /// (e.g. `https://identity.mozilla.com/apps/oldsync`), the returned
43 /// `AccessTokenInfo::key` will be populated; for multi-scope requests it is `None`.
44 /// - `use_cache` - optionally set to false to force a new token request. The fetched
45 /// token will still be cached for later `get_access_token` calls.
46 ///
47 /// # Notes
48 ///
49 /// - If the application receives an authorization error when trying to use the resulting
50 /// token, it should call [`clear_access_token_cache`](FirefoxAccount::clear_access_token_cache)
51 /// before requesting a fresh token.
52 #[handle_error(Error)]
53 pub fn get_access_token(&self, scope: &str, use_cache: bool) -> ApiResult<AccessTokenInfo> {
54 self.internal
55 .lock()
56 .get_access_token(scope, use_cache)?
57 .try_into()
58 }
59
60 /// Check whether the account has already been granted the given OAuth scope(s).
61 ///
62 /// This checks whether the refresh token has *every* specified scope.
63 ///
64 /// # Arguments
65 /// - `scope` - space-separated list of OAuth scopes. Order is not significant.
66 pub fn has_scope(&self, scope: &str) -> bool {
67 self.internal.lock().has_scope(scope)
68 }
69
70 /// Builds a complete `signedInUser` JSON object for a WebChannel `fxaccounts:fxa_status`
71 /// response, embedding the session token without exposing it to the browser layer. Email and
72 /// uid are read from the cached profile in internal state. Returns `None` if no session token
73 /// is available.
74 pub fn get_signed_in_user_for_web_channel(&self) -> Option<String> {
75 self.internal.lock().get_signed_in_user_for_web_channel()
76 }
77
78 /// Handle a WebChannel password-change notification by exchanging the new session token
79 /// for a new refresh token.
80 ///
81 /// **💾 This method alters the persisted account state.**
82 #[handle_error(Error)]
83 pub fn handle_web_channel_password_change(&self, json_payload: String) -> ApiResult<()> {
84 self.internal
85 .lock()
86 .handle_web_channel_password_change(&json_payload)
87 }
88
89 /// Get the session token for the user's account, if one is available.
90 ///
91 /// **💾 This method alters the persisted account state.**
92 ///
93 /// Applications that function as a web browser may need to hold on to a session token
94 /// on behalf of Firefox Accounts web content. This method exists so that they can retrieve
95 /// it an pass it back to said web content when required.
96 ///
97 /// # Notes
98 ///
99 /// - Please do not attempt to use the resulting token to directly make calls to the
100 /// Firefox Accounts servers! All account management functionality should be performed
101 /// in web content.
102 /// - A session token is only available to applications that have requested the
103 /// `https://identity.mozilla.com/tokens/session` scope.
104 #[handle_error(Error)]
105 pub fn get_session_token(&self) -> ApiResult<String> {
106 self.internal.lock().get_session_token()
107 }
108
109 /// Update the stored session token for the user's account.
110 ///
111 /// **💾 This method alters the persisted account state.**
112 ///
113 /// Applications that function as a web browser may need to hold on to a session token
114 /// on behalf of Firefox Accounts web content. This method exists so that said web content
115 /// signals that it has generated a new session token, the stored value can be updated
116 /// to match.
117 ///
118 /// # Arguments
119 ///
120 /// - `session_token` - the new session token value provided from web content.
121 #[handle_error(Error)]
122 pub fn handle_session_token_change(&self, session_token: &str) -> ApiResult<()> {
123 self.internal
124 .lock()
125 .handle_session_token_change(session_token)
126 }
127
128 /// Create a new OAuth authorization code using the stored session token.
129 ///
130 /// When a signed-in application receives an incoming device pairing request, it can
131 /// use this method to grant the request and generate a corresponding OAuth authorization
132 /// code. This code would then be passed back to the connecting device over the
133 /// pairing channel (a process which is not currently supported by any code in this
134 /// component).
135 ///
136 /// # Arguments
137 ///
138 /// - `params` - the OAuth parameters from the incoming authorization request
139 #[handle_error(Error)]
140 pub fn authorize_code_using_session_token(
141 &self,
142 params: AuthorizationParameters,
143 ) -> ApiResult<String> {
144 self.internal
145 .lock()
146 .authorize_code_using_session_token(params)
147 }
148
149 /// Clear the access token cache in response to an auth failure.
150 ///
151 /// **💾 This method alters the persisted account state.**
152 ///
153 /// Applications that receive an authentication error when trying to use an access token,
154 /// should call this method before creating a new token and retrying the failed operation.
155 /// It ensures that the expired token is removed and a fresh one generated.
156 pub fn clear_access_token_cache(&self) {
157 self.internal.lock().clear_access_token_cache()
158 }
159}
160
161/// An OAuth access token, with its associated keys and metadata.
162///
163/// This struct represents an FxA OAuth access token, which can be used to access a resource
164/// or service on behalf of the user. For example, accessing the user's data in Firefox Sync
165/// an access token for the scope `https://identity.mozilla.com/apps/sync` along with the
166/// associated encryption key.
167#[derive(Debug)]
168pub struct AccessTokenInfo {
169 /// The scope of access granted by token.
170 pub scope: String,
171 /// The access token itself.
172 ///
173 /// This is the value that should be included in the `Authorization` header when
174 /// accessing an OAuth protected resource on behalf of the user.
175 pub token: String,
176 /// The client-side encryption key associated with this scope.
177 ///
178 /// **⚠️ Warning:** the value of this field should never be revealed outside of the
179 /// application. For example, it should never to sent to a server or logged in a log file.
180 pub key: Option<ScopedKey>,
181 /// The expiry time of the token, in seconds.
182 ///
183 /// This is the timestamp at which the token is set to expire, in seconds since
184 /// unix epoch. Note that it is a signed integer, for compatibility with languages
185 /// that do not have an unsigned integer type.
186 ///
187 /// This timestamp is for guidance only. Access tokens are not guaranteed to remain
188 /// value for any particular lengthof time, and consumers should be prepared to handle
189 /// auth failures even if the token has not yet expired.
190 pub expires_at: i64,
191}
192
193/// A cryptographic key associated with an OAuth scope.
194///
195/// Some OAuth scopes have a corresponding client-side encryption key that is required
196/// in order to access protected data. This struct represents such key material in a
197/// format compatible with the common "JWK" standard.
198///
199#[derive(Clone, Serialize, Deserialize)]
200pub struct ScopedKey {
201 /// The type of key.
202 ///
203 /// In practice for FxA, this will always be string string "oct" (short for "octal")
204 /// to represent a raw symmetric key.
205 pub kty: String,
206 /// The OAuth scope with which this key is associated.
207 pub scope: String,
208 /// The key material, as base64-url-encoded bytes.
209 ///
210 /// **⚠️ Warning:** the value of this field should never be revealed outside of the
211 /// application. For example, it should never to sent to a server or logged in a log file.
212 pub k: String,
213 /// An opaque unique identifier for this key.
214 ///
215 /// Unlike the `k` field, this value is not secret and may be revealed to the server.
216 pub kid: String,
217}
218
219/// Parameters provided in an incoming OAuth request.
220///
221/// This struct represents parameters obtained from an incoming OAuth request - that is,
222/// the values that an OAuth client would append to the authorization URL when initiating
223/// an OAuth sign-in flow.
224pub struct AuthorizationParameters {
225 pub client_id: String,
226 pub scope: Vec<String>,
227 pub state: String,
228 pub access_type: String,
229 pub code_challenge: Option<String>,
230 pub code_challenge_method: Option<String>,
231 pub keys_jwk: Option<String>,
232}