azure_identity/token_credentials/
app_service_managed_identity_credential.rs

1use crate::{ImdsId, ImdsManagedIdentityCredential, TokenCredentialOptions};
2use azure_core::auth::{AccessToken, TokenCredential};
3use azure_core::error::{ErrorKind, ResultExt};
4use azure_core::headers::HeaderName;
5use azure_core::Url;
6
7const ENDPOINT_ENV: &str = "IDENTITY_ENDPOINT";
8const API_VERSION: &str = "2019-08-01";
9const SECRET_HEADER: HeaderName = HeaderName::from_static("x-identity-header");
10const SECRET_ENV: &str = "IDENTITY_HEADER";
11
12#[derive(Debug)]
13pub struct AppServiceManagedIdentityCredential {
14    credential: ImdsManagedIdentityCredential,
15}
16
17impl AppServiceManagedIdentityCredential {
18    pub fn create(options: impl Into<TokenCredentialOptions>) -> azure_core::Result<Self> {
19        let options = options.into();
20        let env = options.env();
21        let endpoint = &env
22            .var(ENDPOINT_ENV)
23            .with_context(ErrorKind::Credential, || {
24                format!(
25                    "app service credential requires {} environment variable",
26                    ENDPOINT_ENV
27                )
28            })?;
29        let endpoint = Url::parse(endpoint).with_context(ErrorKind::Credential, || {
30            format!(
31                "app service credential {} environment variable must be a valid URL, but is '{endpoint}'",
32                ENDPOINT_ENV
33            )
34        })?;
35        Ok(Self {
36            credential: ImdsManagedIdentityCredential::new(
37                options,
38                endpoint,
39                API_VERSION,
40                SECRET_HEADER,
41                SECRET_ENV,
42                ImdsId::SystemAssigned,
43            ),
44        })
45    }
46}
47
48#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
49#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
50impl TokenCredential for AppServiceManagedIdentityCredential {
51    async fn get_token(&self, scopes: &[&str]) -> azure_core::Result<AccessToken> {
52        self.credential.get_token(scopes).await
53    }
54
55    async fn clear_cache(&self) -> azure_core::Result<()> {
56        self.credential.clear_cache().await
57    }
58}