firebase-admin-sdk 0.2.4

Firebase Admin SDK for Rust, enabling interaction with Firebase services (Auth, FCM, Firestore, Storage, etc.) from a Rust backend.
Documentation
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
//! Firebase Authentication module.
//!
//! This module provides functionality for managing users (create, update, delete, list, get)
//! and generating OOB (Out-of-Band) codes for email actions like password resets and email verification.
//! It also includes ID token verification.

pub mod keys;
pub mod models;
pub mod project_config;
pub mod project_config_impl;
pub mod tenant_mgt;
pub mod verifier;

use crate::auth::models::{
    ActionCodeSettings, CreateSessionCookieRequest, CreateSessionCookieResponse, CreateUserRequest,
    DeleteAccountRequest, EmailLinkRequest, EmailLinkResponse, GetAccountInfoRequest,
    GetAccountInfoResponse, ImportUsersRequest, ImportUsersResponse, ListUsersResponse,
    UpdateUserRequest, UserRecord,
};
use crate::auth::project_config_impl::ProjectConfig;
use crate::auth::tenant_mgt::TenantAwareness;
use crate::auth::verifier::{FirebaseTokenClaims, IdTokenVerifier, TokenVerificationError};
use crate::core::middleware::AuthMiddleware;
use crate::core::parse_error_response;
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use reqwest::header;
use reqwest::Client;
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
use serde::Serialize;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;
use url::Url;

const AUTH_V1_API: &str = "https://identitytoolkit.googleapis.com/v1/projects/{project_id}";
const AUTH_V1_TENANT_API: &str =
    "https://identitytoolkit.googleapis.com/v1/projects/{project_id}/tenants/{tenant_id}";

/// Errors that can occur during Authentication operations.
#[derive(Error, Debug)]
pub enum AuthError {
    /// Wrapper for `reqwest::Error`.
    #[error("HTTP Request failed: {0}")]
    RequestError(#[from] reqwest::Error),
    /// Wrapper for `reqwest_middleware::Error`.
    #[error("Middleware error: {0}")]
    MiddlewareError(#[from] reqwest_middleware::Error),
    /// Errors returned by the Identity Toolkit API.
    #[error("API error: {0}")]
    ApiError(String),
    /// The requested user was not found.
    #[error("User not found")]
    UserNotFound,
    /// Wrapper for `serde_json::Error`.
    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),
    /// Error during ID token verification.
    #[error("Token verification error: {0}")]
    TokenVerificationError(#[from] TokenVerificationError),
    /// Wrapper for `jsonwebtoken::errors::Error`.
    #[error("JWT error: {0}")]
    JwtError(#[from] jsonwebtoken::errors::Error),
    /// The private key provided in the service account is invalid.
    #[error("Invalid private key")]
    InvalidPrivateKey,
    /// A service account key is required for this operation (e.g., custom token signing) but was not provided.
    #[error("Service account key required for this operation")]
    ServiceAccountKeyRequired,
    /// Errors occurred during a bulk import operation.
    #[error("Import users error: {0:?}")]
    ImportUsersError(Vec<models::ImportUserError>),
}

/// Claims used for generating custom tokens.
#[derive(Debug, Serialize)]
struct CustomTokenClaims {
    iss: String,
    sub: String,
    aud: String,
    iat: usize,
    exp: usize,
    uid: String,
    #[serde(flatten)]
    claims: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Client for interacting with Firebase Authentication.
#[derive(Clone)]
pub struct FirebaseAuth {
    client: ClientWithMiddleware,
    base_url: String,
    verifier: Arc<IdTokenVerifier>,
    middleware: AuthMiddleware,
    tenant_id: Option<String>,
}

impl FirebaseAuth {
    /// Creates a new `FirebaseAuth` instance.
    ///
    /// This is typically called via `FirebaseApp::auth()`.
    pub fn new(middleware: AuthMiddleware) -> Self {
        let retry_policy = ExponentialBackoff::builder().build_with_max_retries(3);

        let client = ClientBuilder::new(Client::new())
            .with(RetryTransientMiddleware::new_with_policy(retry_policy))
            .with(middleware.clone())
            .build();

        let key = &middleware.key;
        let project_id = key.project_id.clone().unwrap_or_default();
        let verifier = Arc::new(IdTokenVerifier::new(project_id.clone()));

        let tenant_id = middleware.tenant_id();

        let base_url = if let Some(tid) = &tenant_id {
            AUTH_V1_TENANT_API
                .replace("{project_id}", &project_id)
                .replace("{tenant_id}", tid)
        } else {
            AUTH_V1_API.replace("{project_id}", &project_id)
        };

        Self {
            client,
            base_url,
            verifier,
            middleware,
            tenant_id,
        }
    }

    #[cfg(test)]
    pub(crate) fn new_with_client(client: ClientWithMiddleware, base_url: String) -> Self {
        // We need a dummy middleware and verifier for the struct, but we won't use them for this test
        // Ideally we'd have a builder or optionals, but for now we construct dummies.
        let key = yup_oauth2::ServiceAccountKey {
            key_type: Some("service_account".to_string()),
            client_email: "test@example.com".to_string(),
            private_key: "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6\n-----END PRIVATE KEY-----".to_string(),
            project_id: Some("test-project".to_string()),
            private_key_id: None,
            client_id: None,
            auth_uri: None,
            token_uri: "https://oauth2.googleapis.com/token".to_string(),
            auth_provider_x509_cert_url: None,
            client_x509_cert_url: None,
        };
        let middleware = AuthMiddleware::new(key);
        let verifier = Arc::new(IdTokenVerifier::new("test-project".to_string()));

        Self {
            client,
            base_url,
            verifier,
            middleware,
            tenant_id: None,
        }
    }

    /// Returns the tenant awareness interface.
    pub fn tenant_manager(&self) -> TenantAwareness {
        TenantAwareness::new(self.middleware.clone())
    }

    /// Returns the project config interface.
    pub fn project_config_manager(&self) -> ProjectConfig {
        ProjectConfig::new(self.middleware.clone())
    }

    /// Verifies a Firebase ID token.
    ///
    /// This method fetches Google's public keys (caching them respecting Cache-Control)
    /// and verifies the signature, audience, issuer, and expiration of the token.
    ///
    /// # Arguments
    ///
    /// * `token` - The JWT ID token string.
    pub async fn verify_id_token(&self, token: &str) -> Result<FirebaseTokenClaims, AuthError> {
        Ok(self.verifier.verify_id_token(token).await?)
    }

    /// Creates a session cookie from an ID token.
    ///
    /// # Arguments
    ///
    /// * `id_token` - The ID token to exchange for a session cookie.
    /// * `valid_duration` - The duration for which the session cookie is valid.
    pub async fn create_session_cookie(
        &self,
        id_token: &str,
        valid_duration: std::time::Duration,
    ) -> Result<String, AuthError> {
        let url = format!("{}:createSessionCookie", self.base_url);

        let request = CreateSessionCookieRequest {
            id_token: id_token.to_string(),
            valid_duration_seconds: valid_duration.as_secs(),
        };

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Create session cookie failed").await,
            ));
        }

        let result: CreateSessionCookieResponse = response.json().await?;
        Ok(result.session_cookie)
    }

    /// Verifies a Firebase session cookie.
    ///
    /// # Arguments
    ///
    /// * `session_cookie` - The session cookie string.
    pub async fn verify_session_cookie(
        &self,
        session_cookie: &str,
    ) -> Result<FirebaseTokenClaims, AuthError> {
        Ok(self.verifier.verify_session_cookie(session_cookie).await?)
    }

    /// Creates a custom token for the given UID with optional custom claims.
    ///
    /// This token can be sent to a client application to sign in with `signInWithCustomToken`.
    ///
    /// # Arguments
    ///
    /// * `uid` - The unique identifier for the user.
    /// * `custom_claims` - Optional JSON object containing custom claims.
    pub fn create_custom_token(
        &self,
        uid: &str,
        custom_claims: Option<serde_json::Map<String, serde_json::Value>>,
    ) -> Result<String, AuthError> {
        let key = &self.middleware.key;
        let client_email = key.client_email.clone();
        let private_key = key.private_key.clone();

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as usize;

        let mut final_claims = custom_claims.unwrap_or_default();
        if let Some(tid) = &self.tenant_id {
            final_claims.insert(
                "tenant_id".to_string(),
                serde_json::Value::String(tid.clone()),
            );
        }

        let claims = CustomTokenClaims {
            iss: client_email.clone(),
            sub: client_email,
            aud: "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit".to_string(),
            iat: now,
            exp: now + 3600, // 1 hour expiration
            uid: uid.to_string(),
            claims: Some(final_claims),
        };

        let encoding_key = EncodingKey::from_rsa_pem(private_key.as_bytes())
            .map_err(|_| AuthError::InvalidPrivateKey)?;

        let header = Header::new(Algorithm::RS256);
        let token = encode(&header, &claims, &encoding_key)?;

        Ok(token)
    }

    /// Internal helper to generate OOB (Out-of-Band) email links.
    async fn generate_email_link(
        &self,
        request_type: &str,
        email: &str,
        settings: Option<ActionCodeSettings>,
    ) -> Result<String, AuthError> {
        let url = format!("{}/accounts:sendOobCode", self.base_url,);

        let mut request = EmailLinkRequest {
            request_type: request_type.to_string(),
            email: Some(email.to_string()),
            ..Default::default()
        };

        if let Some(s) = settings {
            request.continue_url = Some(s.url);
            request.can_handle_code_in_app = s.handle_code_in_app;
            request.dynamic_link_domain = s.dynamic_link_domain;

            if let Some(ios) = s.ios {
                request.ios_bundle_id = Some(ios.bundle_id);
            }

            if let Some(android) = s.android {
                request.android_package_name = Some(android.package_name);
                request.android_install_app = android.install_app;
                request.android_minimum_version = android.minimum_version;
            }
        }

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Generate email link failed").await,
            ));
        }

        let result: EmailLinkResponse = response.json().await?;
        Ok(result.oob_link)
    }

    /// Generates a link for password reset.
    pub async fn generate_password_reset_link(
        &self,
        email: &str,
        settings: Option<ActionCodeSettings>,
    ) -> Result<String, AuthError> {
        self.generate_email_link("PASSWORD_RESET", email, settings)
            .await
    }

    /// Generates a link for email verification.
    pub async fn generate_email_verification_link(
        &self,
        email: &str,
        settings: Option<ActionCodeSettings>,
    ) -> Result<String, AuthError> {
        self.generate_email_link("VERIFY_EMAIL", email, settings)
            .await
    }

    /// Generates a link for sign-in with email.
    pub async fn generate_sign_in_with_email_link(
        &self,
        email: &str,
        settings: Option<ActionCodeSettings>,
    ) -> Result<String, AuthError> {
        self.generate_email_link("EMAIL_SIGNIN", email, settings)
            .await
    }

    /// Imports users in bulk.
    ///
    /// # Arguments
    ///
    /// * `request` - An `ImportUsersRequest` containing the list of users and hashing algorithm configuration.
    pub async fn import_users(
        &self,
        request: ImportUsersRequest,
    ) -> Result<ImportUsersResponse, AuthError> {
        let url = format!("{}/accounts:batchCreate", self.base_url,);

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Import users failed").await,
            ));
        }

        let result: ImportUsersResponse = response.json().await?;

        if let Some(errors) = &result.error {
            if !errors.is_empty() {
                // Partial failure or full failure reporting depending on API behavior
                // Usually batchCreate returns 200 with errors list for partials.
                // We can return the response or error out.
                // Let's return the response but user should check it.
                // Or we can define that if errors exist, we return Err(AuthError::ImportUsersError(errors))
                return Err(AuthError::ImportUsersError(
                    errors
                        .iter()
                        .map(|e| models::ImportUserError {
                            index: e.index,
                            message: e.message.clone(),
                        })
                        .collect(),
                ));
            }
        }

        Ok(result)
    }

    /// Creates a new user.
    pub async fn create_user(&self, request: CreateUserRequest) -> Result<UserRecord, AuthError> {
        let url = format!("{}/accounts", self.base_url);

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Create user failed").await,
            ));
        }

        let user: UserRecord = response.json().await?;
        Ok(user)
    }

    /// Updates an existing user.
    pub async fn update_user(&self, request: UpdateUserRequest) -> Result<UserRecord, AuthError> {
        let url = format!("{}/accounts:update", self.base_url);

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Update user failed").await,
            ));
        }

        let user: UserRecord = response.json().await?;
        Ok(user)
    }

    /// Deletes a user by UID.
    pub async fn delete_user(&self, uid: &str) -> Result<(), AuthError> {
        let url = format!("{}/accounts:delete", self.base_url);
        let request = DeleteAccountRequest {
            local_id: uid.to_string(),
        };

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Delete user failed").await,
            ));
        }

        Ok(())
    }

    /// Internal helper to get account info.
    async fn get_account_info(
        &self,
        request: GetAccountInfoRequest,
    ) -> Result<UserRecord, AuthError> {
        let url = format!("{}/accounts:lookup", self.base_url);

        let response = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .body(serde_json::to_vec(&request)?)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "Get user failed").await,
            ));
        }

        let result: GetAccountInfoResponse = response.json().await?;

        result
            .users
            .and_then(|mut users| users.pop())
            .ok_or(AuthError::UserNotFound)
    }

    /// Retrieves a user by their UID.
    pub async fn get_user(&self, uid: &str) -> Result<UserRecord, AuthError> {
        let request = GetAccountInfoRequest {
            local_id: Some(vec![uid.to_string()]),
            email: None,
            phone_number: None,
        };
        self.get_account_info(request).await
    }

    /// Retrieves a user by their email.
    pub async fn get_user_by_email(&self, email: &str) -> Result<UserRecord, AuthError> {
        let request = GetAccountInfoRequest {
            local_id: None,
            email: Some(vec![email.to_string()]),
            phone_number: None,
        };
        self.get_account_info(request).await
    }

    /// Retrieves a user by their phone number.
    pub async fn get_user_by_phone_number(&self, phone: &str) -> Result<UserRecord, AuthError> {
        let request = GetAccountInfoRequest {
            local_id: None,
            email: None,
            phone_number: Some(vec![phone.to_string()]),
        };
        self.get_account_info(request).await
    }

    /// Lists users.
    ///
    /// # Arguments
    ///
    /// * `max_results` - The maximum number of users to return.
    /// * `page_token` - The next page token from a previous response.
    pub async fn list_users(
        &self,
        max_results: u32,
        page_token: Option<&str>,
    ) -> Result<ListUsersResponse, AuthError> {
        let url = format!("{}/accounts", self.base_url);
        let mut url_obj = Url::parse(&url).map_err(|e| AuthError::ApiError(e.to_string()))?;

        {
            let mut query_pairs = url_obj.query_pairs_mut();
            query_pairs.append_pair("maxResults", &max_results.to_string());
            if let Some(token) = page_token {
                query_pairs.append_pair("nextPageToken", token);
            }
        }

        let response = self.client.get(url_obj).send().await?;

        if !response.status().is_success() {
            return Err(AuthError::ApiError(
                parse_error_response(response, "List users failed").await,
            ));
        }

        let result: ListUsersResponse = response.json().await?;
        Ok(result)
    }
}

#[cfg(test)]
mod tests;