rs_firebase_admin_sdk/credentials/
mod.rs

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
//! OAuth2 credential managers for GCP and Firebase Emulator

pub mod emulator;
pub mod error;
pub mod gcp;

#[cfg(test)]
mod test;

use error::CredentialsError;
use error_stack::{Report, ResultExt};
use headers::{authorization::Bearer, Authorization, HeaderMapExt};
use headers::{Header, HeaderName, HeaderValue};
use http::header::HeaderMap;
use std::future::Future;

static X_GOOG_USER_PROJECT: HeaderName = HeaderName::from_static("x-goog-user-project");

pub struct GoogleUserProject(String);

impl Header for GoogleUserProject {
    fn name() -> &'static HeaderName {
        &X_GOOG_USER_PROJECT
    }

    fn decode<'i, I>(values: &mut I) -> Result<Self, headers::Error>
    where
        I: Iterator<Item = &'i HeaderValue>,
    {
        let value = values
            .next()
            .ok_or_else(headers::Error::invalid)?
            .as_bytes();

        match std::str::from_utf8(value) {
            Ok(v) => Ok(Self(v.into())),
            Err(_) => Err(headers::Error::invalid()),
        }
    }

    fn encode<E>(&self, values: &mut E)
    where
        E: Extend<HeaderValue>,
    {
        let value = HeaderValue::from_str(&self.0).unwrap_or_else(|_| HeaderValue::from_static(""));

        values.extend(std::iter::once(value));
    }
}

pub trait Credentials: Send + Sync + 'static {
    /// Implementation for generation of OAuth2 access token
    fn get_access_token(
        &self,
        scopes: &[&str],
    ) -> impl Future<Output = Result<String, Report<CredentialsError>>> + Send;

    /// Implementation for getting GCP project id
    fn get_project_id(
        &self,
    ) -> impl Future<Output = Result<String, Report<CredentialsError>>> + Send;

    /// Set credentials for a API request, by default use bearer authorization for passing access token
    fn set_credentials(
        &self,
        headers: &mut HeaderMap,
        scopes: &[&str],
    ) -> impl Future<Output = Result<(), Report<CredentialsError>>> + Send {
        async move {
            let token = self.get_access_token(scopes).await?;

            headers.typed_insert(
                Authorization::<Bearer>::bearer(&token)
                    .change_context(CredentialsError::InvalidAccessToken)?,
            );

            headers.typed_insert(GoogleUserProject(self.get_project_id().await?));

            Ok(())
        }
    }
}