-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommands.rs
More file actions
263 lines (245 loc) · 9.29 KB
/
Copy pathcommands.rs
File metadata and controls
263 lines (245 loc) · 9.29 KB
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
use clap::{Arg, ArgAction};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::Dispatcher;
use crate::{
CliCoreError, CommandContext, CommandResult, CommandSpec, Credential, GroupSpec, Result,
RuntimeCommandSpec, RuntimeGroupSpec, Tier,
};
/// Data rendered after a successful `auth login`.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthLoginResult {
/// Provider used for login.
pub provider: String,
/// Environment used for login.
pub env: String,
/// Authenticated identity.
pub identity: String,
/// Credential expiration timestamp.
pub expires_at: String,
}
/// Data rendered by `auth status`.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthStatusEntry {
/// Provider name.
pub provider: String,
/// Environment name.
pub env: String,
/// Cached identity, empty when missing or unavailable.
pub identity: String,
/// Credential expiration timestamp, empty when missing or unavailable.
pub expires_at: String,
/// Whether the cached credential is expired or unavailable.
pub expired: bool,
}
/// Builds the built-in runtime `auth` command group.
#[must_use]
pub fn auth_command_group(default_provider: &str, registered_names: &[String]) -> RuntimeGroupSpec {
let effective_default = effective_default_provider(default_provider, registered_names);
RuntimeGroupSpec::new(GroupSpec::new("auth", "Manage authentication credentials"))
.with_command(RuntimeCommandSpec::new_with_context(
CommandSpec::new("login", "Authenticate and cache credentials")
.with_system("auth")
.with_tier(Tier::Mutate)
.mutates(true)
.no_auth(true)
.with_arg(provider_arg(&effective_default, registered_names))
.with_arg(Arg::new("env").long("env").value_name("ENV"))
.with_arg(
Arg::new("scope")
.long("scope")
.short('s')
.value_name("SCOPE")
// One scope per occurrence, repeatable: `--scope a --scope b`.
// `ArgAction::Append` requires a value, so a bare `--scope`
// is rejected rather than silently doing nothing.
.action(ArgAction::Append)
.help("Additional OAuth scope to request (repeatable, one per flag)"),
),
async |context| {
let provider = string_arg(&context.args, "provider");
let env = env_arg(&context)?;
let scopes = string_vec_arg(&context.args, "scope");
serde_json::to_value(
login_and_build_with_scopes(&context.middleware.auth, &provider, &env, &scopes)
.await?,
)
.map(CommandResult::new)
.map_err(Into::into)
},
))
.with_command(RuntimeCommandSpec::new_with_context(
CommandSpec::new("status", "Show cached credential status")
.with_system("auth")
.no_auth(true)
.with_arg(provider_arg(&effective_default, registered_names))
.with_arg(Arg::new("env").long("env").value_name("ENV")),
async |context| {
let provider = string_arg(&context.args, "provider");
let env = string_arg(&context.args, "env");
status_result(&context.middleware.auth, &provider, &env)
.await
.map(CommandResult::new)
},
))
.with_command(RuntimeCommandSpec::new_with_context(
CommandSpec::new("logout", "Clear cached credentials")
.with_system("auth")
.with_tier(Tier::Mutate)
.mutates(true)
.no_auth(true)
.with_arg(provider_arg(&effective_default, registered_names))
.with_arg(Arg::new("env").long("env").value_name("ENV")),
async |context| {
let provider = string_arg(&context.args, "provider");
let env = env_arg(&context)?;
logout_result(&context.middleware.auth, &provider, &env)
.await
.map(CommandResult::new)
},
))
}
fn effective_default_provider(default_provider: &str, registered_names: &[String]) -> String {
if default_provider.is_empty() {
registered_names.first().cloned().unwrap_or_default()
} else {
default_provider.to_owned()
}
}
fn string_arg(args: &serde_json::Map<String, Value>, name: &str) -> String {
args.get(name)
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned()
}
fn env_arg(context: &CommandContext) -> Result<String> {
if let Some(env) = context.user_args.get("env").and_then(Value::as_str) {
if env.is_empty() {
return Err(missing_env_error());
}
return Ok(env.to_owned());
}
if !context.middleware.env.is_empty() {
return Ok(context.middleware.env.clone());
}
Err(missing_env_error())
}
fn missing_env_error() -> CliCoreError {
CliCoreError::message(
"auth: missing environment; pass --env or configure a default environment",
)
}
/// Reads a repeatable string argument as a `Vec<String>`, accepting either a
/// JSON array (multiple values) or a single string.
fn string_vec_arg(args: &serde_json::Map<String, Value>, name: &str) -> Vec<String> {
match args.get(name) {
// Drop empty strings: an empty scope token is never valid and only
// produces confusing auth-server errors.
Some(Value::Array(items)) => items
.iter()
.filter_map(Value::as_str)
.filter(|value| !value.is_empty())
.map(str::to_owned)
.collect(),
Some(Value::String(value)) if !value.is_empty() => vec![value.clone()],
_ => Vec::new(),
}
}
fn provider_arg(default_provider: &str, registered_names: &[String]) -> Arg {
let names = registered_names.join(", ");
let help = format!("Auth provider name (one of: [{names}])");
let mut arg = Arg::new("provider")
.long("provider")
.value_name("NAME")
.help(help);
if !default_provider.is_empty() {
arg = arg.default_value(default_provider.to_owned());
}
arg
}
/// Runs dispatcher login and converts the credential to renderable output.
pub async fn login_and_build(
dispatcher: &Dispatcher,
provider: &str,
env: &str,
) -> Result<AuthLoginResult> {
login_and_build_with_scopes(dispatcher, provider, env, &[]).await
}
/// Like [`login_and_build`], but requests `additional_scopes` on top of the
/// provider's defaults (used by `auth login --scope`).
pub async fn login_and_build_with_scopes(
dispatcher: &Dispatcher,
provider: &str,
env: &str,
additional_scopes: &[String],
) -> Result<AuthLoginResult> {
let credential = dispatcher
.login_with_scopes(provider, env, additional_scopes)
.await?;
Ok(AuthLoginResult {
provider: provider.to_owned(),
env: env.to_owned(),
identity: credential.identity,
expires_at: credential.expires_at,
})
}
/// Builds the JSON value rendered by `auth status`.
pub async fn status_result(dispatcher: &Dispatcher, provider: &str, env: &str) -> Result<Value> {
if !provider.is_empty() && !env.is_empty() {
let credential = dispatcher.status(provider, env).await?;
return serde_json::to_value(to_status_entry(provider, env, Some(&credential)))
.map_err(Into::into);
}
let out = dispatcher
.all_statuses()
.await
.iter()
.map(|entry| {
if entry.error.is_some() {
AuthStatusEntry {
provider: entry.provider.clone(),
env: entry.env.clone(),
identity: String::new(),
expires_at: String::new(),
expired: true,
}
} else {
to_status_entry(&entry.provider, &entry.env, entry.credential.as_ref())
}
})
.collect::<Vec<_>>();
serde_json::to_value(out).map_err(Into::into)
}
/// Runs dispatcher logout and builds the renderable result.
pub async fn logout_result(dispatcher: &Dispatcher, provider: &str, env: &str) -> Result<Value> {
dispatcher.logout(provider, env).await?;
Ok(json!({
"provider": provider,
"env": env,
"status": "logged out",
}))
}
/// Converts an optional credential into an auth status row.
#[must_use]
pub fn to_status_entry(
provider: &str,
env: &str,
credential: Option<&Credential>,
) -> AuthStatusEntry {
credential.map_or_else(
|| AuthStatusEntry {
provider: provider.to_owned(),
env: env.to_owned(),
identity: String::new(),
expires_at: String::new(),
expired: true,
},
|credential| AuthStatusEntry {
provider: provider.to_owned(),
env: env.to_owned(),
identity: credential.identity.clone(),
expires_at: credential.expires_at.clone(),
expired: credential.is_expired(),
},
)
}