Skip to main content

isothrum_machine/cloud/
oci.rs

1//! Oracle Cloud, through the OCI CLI (`oci`) and the config file it and Terraform's provider sign
2//! in with (`~/.oci/config`, an API key): whether that sign-in holds, a compartment's name, and the
3//! config file's default profile.
4
5use std::path::Path;
6
7use super::{ask, line, says};
8use crate::context::Context;
9use crate::failure::{Failure, Refusal};
10
11/// The OCI CLI.
12pub const CLI: &str = "oci";
13
14/// The variable that moves the config file from `~/.oci/config`.
15pub const CONFIG_FILE_VAR: &str = "OCI_CLI_CONFIG_FILE";
16
17/// How the OCI CLI refused, read from what it said: a sign-in run out or missing, or the config
18/// file's key rejected (the runner's reading, `NotAuthenticated`, a config or private key
19/// problem, a 401), or a compartment it can't see (`NotAuthorizedOrNotFound`).
20#[must_use]
21pub fn refusal(said: &str) -> Refusal {
22    if isothrum_runner::sign_in_expired(said) || says(said, &["NotAuthenticated", "config", "private key", "401"]) {
23        Refusal::CredentialsExpired
24    } else if says(said, &["NotAuthorizedOrNotFound"]) {
25        Refusal::Denied
26    } else {
27        Refusal::Other
28    }
29}
30
31/// Whether the config file's sign-in still holds: the regions it can list
32/// (`oci iam region list`).
33///
34/// # Errors
35///
36/// [`Failure`]: the CLI isn't installed, or Oracle refused ([`Refusal::CredentialsExpired`]).
37pub async fn signed_in(cx: &Context) -> Result<(), Failure> {
38    ask(cx, CLI, &["iam", "region", "list", "--output", "json"], refusal).await.map(drop)
39}
40
41/// Compartment `id`'s name (`oci iam compartment get`): the config file signs in and can reach it.
42///
43/// # Errors
44///
45/// [`Failure`]: the CLI isn't installed, or Oracle refused ([`Refusal::CredentialsExpired`]: the
46/// config file's key; [`Refusal::Denied`]: not this account's to see).
47pub async fn compartment_name(cx: &Context, id: &str) -> Result<String, Failure> {
48    ask(
49        cx,
50        CLI,
51        &["iam", "compartment", "get", "--compartment-id", id, "--query", "data.name", "--raw-output"],
52        refusal,
53    )
54    .await
55    .map(|out| line(&out))
56}
57
58/// The default profile of an OCI config file.
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct Config {
62    /// Its tenancy's OCID, empty when it has none.
63    pub tenancy: String,
64    /// Its region, empty when it has none.
65    pub region: String,
66}
67
68/// The config file at `path`'s default profile; None when it can't be read (there is none).
69#[must_use]
70pub fn config(path: &Path) -> Option<Config> {
71    std::fs::read_to_string(path).ok().map(|text| parse_config(&text))
72}
73
74/// The `[DEFAULT]` profile's tenancy and region in a config file's text (the section matched in
75/// any case; a later one of the same name overrides; a value may hold `=`).
76#[must_use]
77pub fn parse_config(text: &str) -> Config {
78    let mut config = Config::default();
79    let mut in_default = false;
80    for line in text.lines() {
81        let l = line.trim();
82        if l.starts_with('[') {
83            in_default = l.eq_ignore_ascii_case("[DEFAULT]");
84            continue;
85        }
86        if !in_default {
87            continue;
88        }
89        if let Some((k, v)) = l.split_once('=') {
90            match k.trim() {
91                "tenancy" => v.trim().clone_into(&mut config.tenancy),
92                "region" => v.trim().clone_into(&mut config.region),
93                _ => {}
94            }
95        }
96    }
97    config
98}
99
100#[cfg(test)]
101mod tests;