1use std::collections::BTreeMap;
17
18use serde::{Deserialize, Serialize};
19
20use super::command::duration_secs;
21
22pub const MAX_GITHUB_REPOSITORIES: usize = 500;
24pub const MIN_AWS_LIFETIME_SECS: u64 = 15 * 60;
26pub const MAX_AWS_LIFETIME_SECS: u64 = 12 * 60 * 60;
28pub const MIN_GCP_LIFETIME_SECS: u64 = 60;
30pub const MAX_GCP_LIFETIME_SECS: u64 = 60 * 60;
33pub const DEFAULT_LIFETIME: &str = "15m";
35pub const AWS_CREDENTIALS: &str = "~/.aws/credentials";
37pub const GCP_CREDENTIALS: &str = "~/.config/gcloud/application_default_credentials.json";
39const GCP_SCOPE_PREFIX: &str = "https://www.googleapis.com/auth/";
41
42#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "kebab-case", deny_unknown_fields)]
45pub enum MintSource {
46 GithubApp(GithubApp),
48 AwsSts(AwsSts),
50 Gcp(Gcp),
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct GithubApp {
58 pub app: String,
60 pub installation: u64,
62 pub key: String,
64 pub repositories: Vec<String>,
66 pub permissions: BTreeMap<String, String>,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub refresh_before: Option<String>,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct AwsSts {
77 pub role: String,
79 pub region: String,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub profile: Option<String>,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub credentials: Option<String>,
87 pub actions: Vec<String>,
89 pub resources: Vec<String>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub lifetime: Option<String>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub refresh_before: Option<String>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Gcp {
103 pub service_account: String,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub credentials: Option<String>,
109 pub scopes: Vec<String>,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub lifetime: Option<String>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub refresh_before: Option<String>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "lowercase", deny_unknown_fields)]
125pub enum Helper {
126 Git {
129 username: String,
131 },
132 Aws,
134}
135
136impl Helper {
137 #[must_use]
139 pub fn tool(&self) -> &'static str {
140 match self {
141 Self::Git { .. } => "git",
142 Self::Aws => "aws",
143 }
144 }
145}
146
147impl std::fmt::Debug for MintSource {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.debug_struct("MintSource")
150 .field("provider", &self.provider())
151 .finish_non_exhaustive()
152 }
153}
154
155impl MintSource {
156 #[must_use]
158 pub fn provider(&self) -> &'static str {
159 match self {
160 Self::GithubApp(_) => "github-app",
161 Self::AwsSts(_) => "aws-sts",
162 Self::Gcp(_) => "gcp",
163 }
164 }
165
166 #[must_use]
169 pub fn files(&self) -> Vec<&str> {
170 match self {
171 Self::GithubApp(g) => vec![g.key.as_str()],
172 Self::AwsSts(a) => vec![a.credentials.as_deref().unwrap_or(AWS_CREDENTIALS)],
173 Self::Gcp(g) => vec![g.credentials.as_deref().unwrap_or(GCP_CREDENTIALS)],
174 }
175 }
176
177 #[must_use]
179 pub fn lifetime_secs(&self) -> u64 {
180 let asked = |l: &Option<String>| {
181 duration_secs(l.as_deref().unwrap_or(DEFAULT_LIFETIME)).unwrap_or(15 * 60)
182 };
183 match self {
184 Self::GithubApp(_) => 60 * 60,
185 Self::AwsSts(a) => asked(&a.lifetime),
186 Self::Gcp(g) => asked(&g.lifetime),
187 }
188 }
189
190 #[must_use]
194 pub fn refresh_before_secs(&self) -> u64 {
195 let (written, default) = match self {
196 Self::GithubApp(g) => (&g.refresh_before, 10 * 60),
197 Self::AwsSts(a) => (&a.refresh_before, self.lifetime_secs() / 5),
198 Self::Gcp(g) => (&g.refresh_before, self.lifetime_secs() / 5),
199 };
200 written
201 .as_deref()
202 .and_then(duration_secs)
203 .unwrap_or(default)
204 .max(10)
205 }
206}
207
208pub(super) fn check(source: &MintSource) -> Result<(), String> {
210 for file in source.files() {
211 if !(crate::paths::is_absolute(file) || file.starts_with("~/")) {
212 return Err(format!(
213 "mint file `{file}` must be absolute or start with `~/`"
214 ));
215 }
216 }
217 match source {
218 MintSource::GithubApp(g) => check_github(g),
219 MintSource::AwsSts(a) => check_aws(a),
220 MintSource::Gcp(g) => check_gcp(g),
221 }?;
222 let lifetime = source.lifetime_secs();
223 let before = source.refresh_before_secs();
224 if before >= lifetime {
225 return Err("mint refresh_before must be shorter than the lifetime".into());
226 }
227 Ok(())
228}
229
230fn check_github(g: &GithubApp) -> Result<(), String> {
231 if g.app.is_empty()
232 || !g
233 .app
234 .bytes()
235 .all(|b| b.is_ascii_alphanumeric() || b == b'.')
236 {
237 return Err("github-app `app` must be the App's client ID or numeric App ID".into());
238 }
239 if g.installation == 0 {
240 return Err("github-app `installation` must be the installation's numeric ID".into());
241 }
242 if g.repositories.is_empty() || g.repositories.len() > MAX_GITHUB_REPOSITORIES {
243 return Err(format!(
244 "github-app `repositories` must name 1 to {MAX_GITHUB_REPOSITORIES} repositories: \
245 without them the token reaches every repository of the installation"
246 ));
247 }
248 let name = |s: &str| {
249 !s.is_empty()
250 && s.len() <= 100
251 && s.bytes()
252 .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
253 };
254 if let Some(bad) = g.repositories.iter().find(|r| !name(r)) {
255 return Err(format!(
256 "github-app repository `{bad}` must be a repository name without its owner"
257 ));
258 }
259 if g.permissions.is_empty() {
260 return Err(
261 "github-app `permissions` must name each permission the token gets: without them \
262 it gets every permission of the App"
263 .into(),
264 );
265 }
266 for (permission, level) in &g.permissions {
267 if permission.is_empty()
268 || !permission
269 .bytes()
270 .all(|b| b.is_ascii_lowercase() || b == b'_')
271 {
272 return Err(format!(
273 "github-app permission `{permission}` is not a permission name"
274 ));
275 }
276 if !matches!(level.as_str(), "read" | "write" | "admin") {
277 return Err(format!(
278 "github-app permission `{permission}` must be `read`, `write` or `admin`"
279 ));
280 }
281 }
282 lifetime_text("github-app", None, g.refresh_before.as_deref(), (1, 1))
283}
284
285fn check_aws(a: &AwsSts) -> Result<(), String> {
286 let role = a.role.split(':').collect::<Vec<_>>();
287 let partition_ok = role.get(1).is_some_and(|p| p.starts_with("aws"));
288 let account_ok = role
289 .get(4)
290 .is_some_and(|n| n.len() == 12 && n.bytes().all(|b| b.is_ascii_digit()));
291 if role.len() != 6
292 || role[0] != "arn"
293 || !partition_ok
294 || role[2] != "iam"
295 || !account_ok
296 || !role[5].starts_with("role/")
297 || a.role.chars().any(char::is_control)
298 {
299 return Err(format!(
300 "aws-sts `role` `{}` must be a role ARN, arn:aws:iam::<account>:role/<name>",
301 a.role
302 ));
303 }
304 if a.region.is_empty()
305 || !a
306 .region
307 .bytes()
308 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
309 {
310 return Err(format!(
311 "aws-sts `region` `{}` is not a region name",
312 a.region
313 ));
314 }
315 if let Some(profile) = &a.profile
316 && (profile.is_empty()
317 || profile.contains([']', '['])
318 || profile.chars().any(char::is_control))
319 {
320 return Err("aws-sts `profile` is not a profile name".into());
321 }
322 if a.actions.is_empty() || a.resources.is_empty() {
323 return Err(
324 "aws-sts needs `actions` and `resources`: the session policy is what narrows the \
325 session below the role's own permissions"
326 .into(),
327 );
328 }
329 for action in &a.actions {
330 let (service, name) = action.split_once(':').unwrap_or(("", ""));
331 let ok = |s: &str, star: bool| {
332 !s.is_empty()
333 && s.bytes()
334 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || (star && b == b'*'))
335 };
336 if !ok(service, false) || !ok(name, true) || name == "*" {
337 return Err(format!(
338 "aws-sts action `{action}` must be `service:Action` and not every action of a \
339 service"
340 ));
341 }
342 }
343 for resource in &a.resources {
344 if !resource.starts_with("arn:")
345 || resource == "arn:*"
346 || resource
347 .chars()
348 .any(|c| c.is_control() || c == '"' || c == '\\')
349 {
350 return Err(format!(
351 "aws-sts resource `{resource}` must be an ARN, not `*`"
352 ));
353 }
354 }
355 lifetime_text(
356 "aws-sts",
357 a.lifetime.as_deref(),
358 a.refresh_before.as_deref(),
359 (MIN_AWS_LIFETIME_SECS, MAX_AWS_LIFETIME_SECS),
360 )
361}
362
363fn check_gcp(g: &Gcp) -> Result<(), String> {
364 let account = &g.service_account;
365 let (name, domain) = account.split_once('@').unwrap_or(("", ""));
366 if name.is_empty()
367 || !domain.ends_with(".gserviceaccount.com")
368 || !account
369 .bytes()
370 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"@.-_".contains(&b))
371 {
372 return Err(format!(
373 "gcp `service_account` `{account}` must be a service account's email"
374 ));
375 }
376 if g.scopes.is_empty() {
377 return Err("gcp `scopes` must name the OAuth scopes the token gets".into());
378 }
379 if let Some(bad) = g.scopes.iter().find(|s| {
380 s.strip_prefix(GCP_SCOPE_PREFIX).is_none_or(|rest| {
381 rest.is_empty()
382 || !rest
383 .bytes()
384 .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
385 })
386 }) {
387 return Err(format!(
388 "gcp scope `{bad}` must be a Google OAuth scope, {GCP_SCOPE_PREFIX}…"
389 ));
390 }
391 lifetime_text(
392 "gcp",
393 g.lifetime.as_deref(),
394 g.refresh_before.as_deref(),
395 (MIN_GCP_LIFETIME_SECS, MAX_GCP_LIFETIME_SECS),
396 )
397}
398
399fn lifetime_text(
401 provider: &str,
402 lifetime: Option<&str>,
403 before: Option<&str>,
404 (min, max): (u64, u64),
405) -> Result<(), String> {
406 if let Some(text) = lifetime {
407 let secs = duration_secs(text).ok_or_else(|| {
408 format!("{provider} lifetime `{text}` is not a duration such as `15m`")
409 })?;
410 if !(min..=max).contains(&secs) {
411 return Err(format!(
412 "{provider} lifetime `{text}` must be from {min}s to {max}s"
413 ));
414 }
415 }
416 if let Some(text) = before
417 && duration_secs(text).is_none_or(|s| s < 10)
418 {
419 return Err(format!(
420 "{provider} refresh_before `{text}` must be a duration of at least 10s"
421 ));
422 }
423 Ok(())
424}
425
426pub(super) fn check_helper(
428 helper: Option<&Helper>,
429 source: &super::Source,
430 host: &str,
431) -> Result<(), String> {
432 let aws_mint = matches!(source, super::Source::Mint(MintSource::AwsSts(_)));
433 match helper {
434 None if aws_mint => Err(
435 "an `aws-sts` mint needs `helper: aws`: AWS requests are signed by the client, so \
436 the proxy cannot put the credentials in a header"
437 .into(),
438 ),
439 Some(Helper::Aws) if !aws_mint => {
440 Err("`helper: aws` hands out credentials an `aws-sts` mint made, nothing else".into())
441 }
442 None | Some(Helper::Aws) => Ok(()),
443 Some(Helper::Git { username }) => {
444 if host.parse::<core::net::Ipv4Addr>().is_ok() {
445 return Err(format!(
446 "`helper: git` needs a DNS name; {host} is an address"
447 ));
448 }
449 if username.is_empty()
450 || !username
451 .bytes()
452 .all(|b| b.is_ascii_alphanumeric() || b"._-@".contains(&b))
453 {
454 return Err(
455 "`helper: git` needs a user name of letters, digits, `.`, `_`, `-` or `@`"
456 .into(),
457 );
458 }
459 Ok(())
460 }
461 }
462}