-
Notifications
You must be signed in to change notification settings - Fork 248
/
default_credentials.rs
288 lines (249 loc) · 9.67 KB
/
default_credentials.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
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
use super::{
AzureCliCredential, EnvironmentCredential, ImdsManagedIdentityCredential, TokenCredential,
};
use azure_core::TokenResponse;
#[derive(Debug)]
/// Provides a mechanism of selectively disabling credentials used for a `DefaultAzureCredential` instance
pub struct DefaultAzureCredentialBuilder {
include_environment_credential: bool,
include_managed_identity_credential: bool,
include_cli_credential: bool,
}
impl Default for DefaultAzureCredentialBuilder {
fn default() -> Self {
Self {
include_environment_credential: true,
include_managed_identity_credential: true,
include_cli_credential: true,
}
}
}
impl DefaultAzureCredentialBuilder {
/// Create a new `DefaultAzureCredentialBuilder`
pub fn new() -> Self {
Self::default()
}
/// Exclude using credentials from the environment
pub fn exclude_environment_credential(&mut self) -> &mut Self {
self.include_environment_credential = false;
self
}
/// Exclude using credentials from the cli
pub fn exclude_cli_credential(&mut self) -> &mut Self {
self.include_cli_credential = false;
self
}
/// Exclude using managed identity credentials
pub fn exclude_managed_identity_credential(&mut self) -> &mut Self {
self.include_managed_identity_credential = false;
self
}
pub fn build(&self) -> DefaultAzureCredential {
let source_count = self.include_cli_credential as usize
+ self.include_cli_credential as usize
+ self.include_managed_identity_credential as usize;
let mut sources = Vec::<DefaultAzureCredentialEnum>::with_capacity(source_count);
if self.include_environment_credential {
sources.push(DefaultAzureCredentialEnum::Environment(
EnvironmentCredential::default(),
));
}
if self.include_managed_identity_credential {
sources.push(DefaultAzureCredentialEnum::ManagedIdentity(
ImdsManagedIdentityCredential {},
))
}
if self.include_cli_credential {
sources.push(DefaultAzureCredentialEnum::AzureCli(AzureCliCredential {}));
}
DefaultAzureCredential::with_sources(sources)
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum DefaultAzureCredentialError {
#[error("Error getting token credential from Azure CLI: {0}")]
AzureCliCredentialError(#[from] super::AzureCliCredentialError),
#[error("Error getting environment credential: {0}")]
EnvironmentCredentialError(#[from] super::EnvironmentCredentialError),
#[error("Error getting managed identity credential: {0}")]
ManagedIdentityCredentialError(#[from] super::ManagedIdentityCredentialError),
#[error(
"Multiple errors were encountered while attempting to authenticate:\n{}",
format_aggregate_error(.0)
)]
CredentialUnavailable(Vec<DefaultAzureCredentialError>),
}
/// Types of TokenCredential supported by DefaultAzureCredential
pub enum DefaultAzureCredentialEnum {
Environment(EnvironmentCredential),
ManagedIdentity(ImdsManagedIdentityCredential),
AzureCli(AzureCliCredential),
}
#[async_trait::async_trait]
impl TokenCredential for DefaultAzureCredentialEnum {
type Error = DefaultAzureCredentialError;
async fn get_token(&self, resource: &str) -> Result<TokenResponse, Self::Error> {
match self {
DefaultAzureCredentialEnum::Environment(credential) => credential
.get_token(resource)
.await
.map_err(DefaultAzureCredentialError::EnvironmentCredentialError),
DefaultAzureCredentialEnum::ManagedIdentity(credential) => credential
.get_token(resource)
.await
.map_err(DefaultAzureCredentialError::ManagedIdentityCredentialError),
DefaultAzureCredentialEnum::AzureCli(credential) => credential
.get_token(resource)
.await
.map_err(DefaultAzureCredentialError::AzureCliCredentialError),
}
}
}
/// Provides a default `TokenCredential` authentication flow for applications that will be deployed to Azure.
///
/// The following credential types if enabled will be tried, in order:
/// - EnvironmentCredential
/// - ManagedIdentityCredential
/// - AzureCliCredential
/// Consult the documentation of these credential types for more information on how they attempt authentication.
pub struct DefaultAzureCredential {
sources: Vec<DefaultAzureCredentialEnum>,
}
impl DefaultAzureCredential {
pub fn with_sources(sources: Vec<DefaultAzureCredentialEnum>) -> Self {
DefaultAzureCredential { sources }
}
}
impl Default for DefaultAzureCredential {
fn default() -> Self {
DefaultAzureCredential {
sources: vec![
DefaultAzureCredentialEnum::Environment(EnvironmentCredential::default()),
DefaultAzureCredentialEnum::ManagedIdentity(ImdsManagedIdentityCredential {}),
DefaultAzureCredentialEnum::AzureCli(AzureCliCredential {}),
],
}
}
}
#[async_trait::async_trait]
impl TokenCredential for DefaultAzureCredential {
type Error = DefaultAzureCredentialError;
/// Try to fetch a token using each of the credential sources until one succeeds
async fn get_token(&self, resource: &str) -> Result<TokenResponse, Self::Error> {
let mut errors = Vec::new();
for source in &self.sources {
let token_res = source.get_token(resource).await;
match token_res {
Ok(token) => return Ok(token),
Err(error) => errors.push(error),
}
}
Err(DefaultAzureCredentialError::CredentialUnavailable(errors))
}
}
#[async_trait::async_trait]
impl azure_core::TokenCredential for DefaultAzureCredential {
async fn get_token(
&self,
resource: &str,
) -> Result<azure_core::TokenResponse, azure_core::Error> {
TokenCredential::get_token(self, resource)
.await
.map_err(|error| azure_core::Error::GetTokenError(Box::new(error)))
}
}
fn format_aggregate_error(errors: &[DefaultAzureCredentialError]) -> String {
errors
.iter()
.map(|error| error.to_string())
.collect::<Vec<String>>()
.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
use std::matches;
#[test]
fn test_builder_included_credential_flags() {
let builder = DefaultAzureCredentialBuilder::new();
assert_eq!(builder.include_cli_credential, true);
assert_eq!(builder.include_environment_credential, true);
assert_eq!(builder.include_managed_identity_credential, true);
let mut builder = DefaultAzureCredentialBuilder::new();
builder.exclude_cli_credential();
assert_eq!(builder.include_cli_credential, false);
assert_eq!(builder.include_environment_credential, true);
assert_eq!(builder.include_managed_identity_credential, true);
let mut builder = DefaultAzureCredentialBuilder::new();
builder.exclude_environment_credential();
assert_eq!(builder.include_cli_credential, true);
assert_eq!(builder.include_environment_credential, false);
assert_eq!(builder.include_managed_identity_credential, true);
let mut builder = DefaultAzureCredentialBuilder::new();
builder.exclude_managed_identity_credential();
assert_eq!(builder.include_cli_credential, true);
assert_eq!(builder.include_environment_credential, true);
assert_eq!(builder.include_managed_identity_credential, false);
}
macro_rules! contains_credential {
($creds:expr, $p:pat) => {
$creds.sources.iter().any(|x| matches!(x, $p))
};
}
#[test]
fn test_credential_sources() {
let mut builder = DefaultAzureCredentialBuilder::new();
// test with all sources
let credential = builder.build();
assert_eq!(credential.sources.len(), 3);
assert!(contains_credential!(
credential,
DefaultAzureCredentialEnum::Environment(_)
));
assert!(contains_credential!(
credential,
DefaultAzureCredentialEnum::AzureCli(_)
));
assert!(contains_credential!(
credential,
DefaultAzureCredentialEnum::ManagedIdentity(_)
));
// remove environment source
builder.exclude_environment_credential();
let credential = builder.build();
assert_eq!(credential.sources.len(), 2);
assert!(!contains_credential!(
credential,
DefaultAzureCredentialEnum::Environment(_)
));
assert!(contains_credential!(
credential,
DefaultAzureCredentialEnum::AzureCli(_)
));
assert!(contains_credential!(
credential,
DefaultAzureCredentialEnum::ManagedIdentity(_)
));
// remove cli source
builder.exclude_cli_credential();
let credential = builder.build();
assert_eq!(credential.sources.len(), 1);
assert!(!contains_credential!(
credential,
DefaultAzureCredentialEnum::Environment(_)
));
assert!(!contains_credential!(
credential,
DefaultAzureCredentialEnum::AzureCli(_)
));
assert!(contains_credential!(
credential,
DefaultAzureCredentialEnum::ManagedIdentity(_)
));
// remove managed identity source
builder.exclude_managed_identity_credential();
let credential = builder.build();
assert_eq!(credential.sources.len(), 0);
}
}