hws 0.1.1

Client library and kubectl-shaped CLI for the app-lb admin API
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! The heyctl config file: named contexts, kubeconfig-style.
//!
//! One file, `~/.config/heyctl/config.json`, holding a set of named contexts
//! (server + credentials) and which one is current. Written `0600` because it
//! can hold a password — app-lb's admin API authenticates with HTTP Basic, and
//! there is no token endpoint to trade it for something shorter-lived.

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_context: Option<String>,
    #[serde(default)]
    pub contexts: BTreeMap<String, ContextEntry>,
    /// Artifact stores, kept apart from `contexts` on purpose.
    ///
    /// A store is not an app-lb: it is a different service, on a different host
    /// more often than not, authenticated by a shared key rather than by a
    /// username and password. Folding it into `ContextEntry` would mean every
    /// context carrying four fields most of them never use, and `--server`
    /// silently pointing the registry commands at a load balancer.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub registries: BTreeMap<String, RegistryEntry>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_registry: Option<String>,
}

/// One artifact store: where it is and how to prove you may write to it.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RegistryEntry {
    pub url: String,
    /// `ART_API_KEY`, presented as `Authorization: Bearer`. Stored in the clear
    /// in a `0600` file, exactly as a context's password is; `api_key_command`
    /// is here for anyone who would rather it live in a keychain.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// A shell command whose stdout is the key. Takes precedence over a stored
    /// `api_key`; run via `sh -c` on every request that needs one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key_command: Option<String>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub insecure_skip_tls_verify: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ContextEntry {
    pub server: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// Stored in the clear. `password_command` exists for anyone who would
    /// rather keep it in a keychain and shell out for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,
    /// A shell command whose stdout is the password. Takes precedence over a
    /// stored `password`; run via `sh -c` on every request that needs auth.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub password_command: Option<String>,
    /// A bearer token — an app-lb app-token (`applb_…`) or a Heyo API key
    /// (`heyo_api_…`, which is how a namespace-scoped credential reaches
    /// Cloud's `/namespaces/{ns}/lb` door). When set, it is the credential:
    /// a user/password on the same context is ignored.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    /// A shell command whose stdout is the token; takes precedence over a
    /// stored `token`, like `password_command` does for a password.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_command: Option<String>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub insecure_skip_tls_verify: bool,
}

fn is_false(b: &bool) -> bool {
    !*b
}

/// Where the credentials for the current invocation came from — reported by
/// `whoami` so "why am I getting a 401" has an answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PasswordSource {
    None,
    Flag,
    Command,
    Stored,
}

impl PasswordSource {
    pub fn describe(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Flag => "--password / HEYCTL_PASSWORD",
            Self::Command => "password_command",
            Self::Stored => "stored in the config file",
        }
    }

    /// The same question for an artifact store's key, which arrives by different
    /// flags. Two methods rather than a format argument because the answer is
    /// what somebody reads when a `401` surprises them, and naming the wrong
    /// flag there sends them to edit something that was never in play.
    pub fn describe_api_key(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Flag => "--api-key / HEYCTL_ART_API_KEY",
            Self::Command => "api_key_command",
            Self::Stored => "stored in the config file",
        }
    }

    /// The same question for a bearer token.
    pub fn describe_token(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Flag => "--token / HEYCTL_TOKEN",
            Self::Command => "token_command",
            Self::Stored => "stored in the config file",
        }
    }
}

/// A context resolved against the command line: what this invocation will use.
#[derive(Debug, Clone)]
pub struct Endpoint {
    /// The context name, or `"(none)"` when nothing is configured and the
    /// built-in default server is in play.
    pub name: String,
    pub server: String,
    pub user: Option<String>,
    pub password: Option<String>,
    pub password_source: PasswordSource,
    /// A bearer, which outranks the Basic pair when both are present.
    pub token: Option<String>,
    pub token_source: PasswordSource,
    pub insecure_skip_tls_verify: bool,
}

impl Config {
    pub fn path(explicit: Option<&Path>) -> Result<PathBuf> {
        if let Some(p) = explicit {
            return Ok(p.to_path_buf());
        }
        if let Some(dir) = dirs::config_dir() {
            return Ok(dir.join("heyctl").join("config.json"));
        }
        // No XDG config dir (an unusual container, say) — fall back to $HOME.
        let home = dirs::home_dir().context("no config directory and no home directory")?;
        Ok(home.join(".heyctl").join("config.json"))
    }

    pub fn load(path: &Path) -> Result<Self> {
        match std::fs::read_to_string(path) {
            // An empty file is the same as no file: a half-finished write, or
            // /dev/null passed deliberately to ignore the stored contexts.
            Ok(text) if text.trim().is_empty() => Ok(Self::default()),
            Ok(text) => serde_json::from_str(&text)
                .with_context(|| format!("parsing the config file {}", path.display())),
            // A missing config is the normal first-run state, not an error: the
            // built-in default server makes `heyctl get deployments` work
            // against a local app-lb with no setup at all.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
        }
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
            restrict(parent, 0o700)?;
        }
        let mut text = serde_json::to_string_pretty(self)?;
        text.push('\n');
        std::fs::write(path, text).with_context(|| format!("writing {}", path.display()))?;
        // Written after the fact rather than with `OpenOptions::mode`, so an
        // existing file that was too permissive gets tightened too.
        restrict(path, 0o600)?;
        Ok(())
    }

    /// The context this invocation should use: `--context`, else
    /// `current_context`, else the only context if there is exactly one.
    pub fn resolve(&self, requested: Option<&str>) -> Result<Option<(String, ContextEntry)>> {
        if let Some(name) = requested {
            let entry = self
                .contexts
                .get(name)
                .with_context(|| format!("no context named {name:?} — `heyctl config get-contexts` lists them"))?;
            return Ok(Some((name.to_string(), entry.clone())));
        }
        if let Some(name) = &self.current_context
            && let Some(entry) = self.contexts.get(name)
        {
            return Ok(Some((name.clone(), entry.clone())));
        }
        if self.contexts.len() == 1 {
            let (name, entry) = self.contexts.iter().next().expect("len == 1");
            return Ok(Some((name.clone(), entry.clone())));
        }
        if self.current_context.is_some() {
            bail!(
                "current context {:?} is not in the config file — pick one with \
                 `heyctl config use-context`",
                self.current_context.as_deref().unwrap_or_default()
            );
        }
        Ok(None)
    }

    /// The artifact store this invocation should use, by the same rules as
    /// [`resolve`](Self::resolve): `--registry`, else `current_registry`, else
    /// the only one if there is exactly one.
    ///
    /// Unlike a context there is no built-in default. An app-lb answers on a
    /// known loopback port; a store does not, and guessing one would mean
    /// `artifact push` could upload a rootfs to whatever happens to be
    /// listening.
    pub fn resolve_registry(&self, requested: Option<&str>) -> Result<Option<(String, RegistryEntry)>> {
        if let Some(name) = requested {
            let entry = self.registries.get(name).with_context(|| {
                format!("no registry named {name:?} — `heyctl artifact registries` lists them")
            })?;
            return Ok(Some((name.to_string(), entry.clone())));
        }
        if let Some(name) = &self.current_registry
            && let Some(entry) = self.registries.get(name)
        {
            return Ok(Some((name.clone(), entry.clone())));
        }
        if self.registries.len() == 1 {
            let (name, entry) = self.registries.iter().next().expect("len == 1");
            return Ok(Some((name.clone(), entry.clone())));
        }
        if self.current_registry.is_some() {
            bail!(
                "current registry {:?} is not in the config file — pick one with \
                 `heyctl artifact use`",
                self.current_registry.as_deref().unwrap_or_default()
            );
        }
        Ok(None)
    }
}

/// A registry resolved against the command line: what this invocation will use.
#[derive(Debug, Clone)]
pub struct RegistryEndpoint {
    pub name: String,
    pub url: String,
    pub api_key: Option<String>,
    pub api_key_source: PasswordSource,
    pub insecure_skip_tls_verify: bool,
}

/// Merge a stored registry with the command-line/env overrides.
///
/// Errors rather than defaulting when nothing names a store: see
/// [`Config::resolve_registry`] for why there is no fallback URL.
pub fn resolve_registry_endpoint(
    config: &Config,
    registry: Option<&str>,
    url: Option<&str>,
    api_key: Option<&str>,
    insecure: bool,
) -> Result<RegistryEndpoint> {
    let resolved = config.resolve_registry(registry)?;
    let (name, entry) = match resolved {
        Some((n, e)) => (n, e),
        None if url.is_some() => ("(none)".to_string(), RegistryEntry::default()),
        None => bail!(
            "no artifact store configured — run `heyctl artifact login <url>` first, \
             or pass --registry-url"
        ),
    };

    let (api_key, api_key_source) = match api_key {
        Some(k) => (Some(k.to_string()), PasswordSource::Flag),
        None => match &entry.api_key_command {
            Some(cmd) => (Some(run_password_command(cmd)?), PasswordSource::Command),
            None => match &entry.api_key {
                Some(k) => (Some(k.clone()), PasswordSource::Stored),
                None => (None, PasswordSource::None),
            },
        },
    };

    Ok(RegistryEndpoint {
        name,
        url: url
            .map(str::to_string)
            .or_else(|| (!entry.url.is_empty()).then(|| entry.url.clone()))
            .ok_or_else(|| anyhow::anyhow!("the stored registry has no url"))?,
        api_key,
        api_key_source,
        insecure_skip_tls_verify: insecure || entry.insecure_skip_tls_verify,
    })
}

/// Merge a stored context with the command-line/env overrides.
pub fn resolve_endpoint(
    config: &Config,
    context: Option<&str>,
    server: Option<&str>,
    user: Option<&str>,
    password: Option<&str>,
    token: Option<&str>,
    insecure: bool,
) -> Result<Endpoint> {
    let resolved = config.resolve(context)?;
    let (name, entry) = match resolved {
        Some((n, e)) => (n, e),
        None => ("(none)".to_string(), ContextEntry::default()),
    };

    // Precedence, highest first: an explicit flag (which clap has already
    // merged the HEYCTL_* env vars into), then the context, then the
    // built-in default.
    let (password, password_source) = match password {
        Some(p) => (Some(p.to_string()), PasswordSource::Flag),
        None => match &entry.password_command {
            Some(cmd) => (Some(run_password_command(cmd)?), PasswordSource::Command),
            None => match &entry.password {
                Some(p) => (Some(p.clone()), PasswordSource::Stored),
                None => (None, PasswordSource::None),
            },
        },
    };

    // The same ladder for a bearer. Resolved independently of the password so
    // `whoami` can say which of the two the next request will actually send.
    let (token, token_source) = match token {
        Some(t) => (Some(t.to_string()), PasswordSource::Flag),
        None => match &entry.token_command {
            Some(cmd) => (Some(run_password_command(cmd)?), PasswordSource::Command),
            None => match &entry.token {
                Some(t) => (Some(t.clone()), PasswordSource::Stored),
                None => (None, PasswordSource::None),
            },
        },
    };

    Ok(Endpoint {
        name,
        server: server
            .map(str::to_string)
            .or_else(|| (!entry.server.is_empty()).then(|| entry.server.clone()))
            .unwrap_or_else(|| crate::cmd::DEFAULT_SERVER.to_string()),
        user: user.map(str::to_string).or(entry.user),
        password,
        password_source,
        token,
        token_source,
        insecure_skip_tls_verify: insecure || entry.insecure_skip_tls_verify,
    })
}

fn run_password_command(cmd: &str) -> Result<String> {
    let out = std::process::Command::new("sh")
        .arg("-c")
        .arg(cmd)
        .output()
        .with_context(|| format!("running password_command: {cmd}"))?;
    if !out.status.success() {
        bail!(
            "password_command failed ({}): {}",
            out.status,
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let password = String::from_utf8(out.stdout)
        .context("password_command produced output that is not UTF-8")?;
    Ok(password.trim_end_matches(['\n', '\r']).to_string())
}

#[cfg(unix)]
fn restrict(path: &Path, mode: u32) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
        .with_context(|| format!("setting {mode:o} on {}", path.display()))
}

#[cfg(not(unix))]
fn restrict(_path: &Path, _mode: u32) -> Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg_with(names: &[&str], current: Option<&str>) -> Config {
        Config {
            current_context: current.map(str::to_string),
            contexts: names
                .iter()
                .map(|n| {
                    (
                        n.to_string(),
                        ContextEntry {
                            server: format!("http://{n}:9090"),
                            user: Some("admin".into()),
                            password: Some("pw".into()),
                            ..Default::default()
                        },
                    )
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn a_token_outranks_the_pair_and_follows_the_same_ladder() {
        let mut cfg = cfg_with(&["lb"], None);
        cfg.contexts.get_mut("lb").unwrap().token = Some("heyo_api_stored".into());
        let ep = resolve_endpoint(&cfg, None, None, None, None, None, false).unwrap();
        assert_eq!(ep.token.as_deref(), Some("heyo_api_stored"));
        assert_eq!(ep.token_source, PasswordSource::Stored);
        // The pair is still resolved — whoami reports both — but the token wins.
        assert_eq!(ep.password.as_deref(), Some("pw"));

        let ep = resolve_endpoint(&cfg, None, None, None, None, Some("heyo_api_flag"), false).unwrap();
        assert_eq!(ep.token.as_deref(), Some("heyo_api_flag"));
        assert_eq!(ep.token_source, PasswordSource::Flag);

        cfg.contexts.get_mut("lb").unwrap().token_command = Some("printf heyo_api_cmd".into());
        let ep = resolve_endpoint(&cfg, None, None, None, None, None, false).unwrap();
        assert_eq!(ep.token.as_deref(), Some("heyo_api_cmd"));
        assert_eq!(ep.token_source, PasswordSource::Command);

        let ep = resolve_endpoint(&Config::default(), None, None, None, None, None, false).unwrap();
        assert!(ep.token.is_none());
        assert_eq!(ep.token_source, PasswordSource::None);
    }

    fn cfg_with_registries(names: &[&str], current: Option<&str>) -> Config {
        Config {
            current_registry: current.map(str::to_string),
            registries: names
                .iter()
                .map(|n| {
                    (
                        n.to_string(),
                        RegistryEntry {
                            url: format!("http://{n}:8080"),
                            api_key: Some("k".into()),
                            ..Default::default()
                        },
                    )
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn a_lone_registry_is_used_without_being_selected() {
        let cfg = cfg_with_registries(&["store"], None);
        let ep = resolve_registry_endpoint(&cfg, None, None, None, false).unwrap();
        assert_eq!(ep.name, "store");
        assert_eq!(ep.url, "http://store:8080");
        assert_eq!(ep.api_key_source, PasswordSource::Stored);
    }

    #[test]
    fn no_registry_is_an_error_rather_than_a_guessed_url() {
        // A push has to go somewhere deliberate: there is no conventional port
        // for an artifact store the way there is for an app-lb admin listener.
        assert!(resolve_registry_endpoint(&Config::default(), None, None, None, false).is_err());
        // ...unless the URL is given outright, which is deliberate enough.
        let ep = resolve_registry_endpoint(
            &Config::default(),
            None,
            Some("http://art:8080"),
            Some("key"),
            false,
        )
        .unwrap();
        assert_eq!(ep.url, "http://art:8080");
        assert_eq!(ep.api_key_source, PasswordSource::Flag);
    }

    #[test]
    fn an_unknown_registry_is_an_error() {
        assert!(cfg_with_registries(&["prod"], None).resolve_registry(Some("dev")).is_err());
    }

    #[test]
    fn registries_and_contexts_are_stored_side_by_side_without_colliding() {
        let mut cfg = cfg_with(&["prod"], Some("prod"));
        cfg.registries = cfg_with_registries(&["store"], None).registries;
        let json = serde_json::to_string(&cfg).unwrap();
        let back: Config = serde_json::from_str(&json).unwrap();
        assert_eq!(back.contexts["prod"].server, "http://prod:9090");
        assert_eq!(back.registries["store"].url, "http://store:8080");
    }

    #[test]
    fn a_config_written_before_registries_existed_still_parses() {
        let old = r#"{"current_context":"prod","contexts":{"prod":{"server":"http://prod:9090"}}}"#;
        let cfg: Config = serde_json::from_str(old).unwrap();
        assert!(cfg.registries.is_empty());
        assert!(cfg.current_registry.is_none());
    }

    #[test]
    fn a_lone_context_is_used_without_being_selected() {
        let cfg = cfg_with(&["prod"], None);
        let (name, _) = cfg.resolve(None).unwrap().unwrap();
        assert_eq!(name, "prod");
    }

    #[test]
    fn an_empty_config_resolves_to_nothing_rather_than_failing() {
        assert!(Config::default().resolve(None).unwrap().is_none());
    }

    #[test]
    fn flags_outrank_the_stored_context() {
        let cfg = cfg_with(&["prod"], Some("prod"));
        let ep = resolve_endpoint(&cfg, None, Some("http://other:1"), None, Some("flag"), None, false)
            .unwrap();
        assert_eq!(ep.server, "http://other:1");
        assert_eq!(ep.password.as_deref(), Some("flag"));
        assert_eq!(ep.password_source, PasswordSource::Flag);
        assert_eq!(ep.user.as_deref(), Some("admin"), "not overridden, so kept");
    }

    #[test]
    fn no_config_at_all_still_points_at_a_local_app_lb() {
        let ep = resolve_endpoint(&Config::default(), None, None, None, None, None, false).unwrap();
        assert_eq!(ep.server, crate::cmd::DEFAULT_SERVER);
        assert_eq!(ep.password_source, PasswordSource::None);
    }

    #[test]
    fn an_unknown_context_is_an_error() {
        assert!(cfg_with(&["prod"], None).resolve(Some("staging")).is_err());
    }
}