diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..fa9034c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + - master + - "codex/**" + +jobs: + rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 + - name: cargo fmt + run: cargo fmt --check + - name: cargo clippy + run: cargo clippy --all-targets --all-features -- -D warnings + - name: cargo test + run: cargo test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1ed3f73 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2034 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "apollo-cli" +version = "0.1.0" +dependencies = [ + "assert_cmd", + "base64", + "clap", + "keyring", + "libc", + "predicates", + "regex", + "reqwest", + "rpassword", + "serde", + "serde_json", + "tempfile", + "toml", + "urlencoding", +] + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "bstr" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" +dependencies = [ + "memchr", + "regex-automata", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be7462df143984c4598a256ef469b251d7d7f9e271135073e78fc535414f3d0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "log", + "zeroize", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "log" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "memchr" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" + +[[package]] +name = "mio" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rpassword" +version = "7.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50a0e551c1e27e1731aba276dbeaeac73f53c7cd34d1bda485d02bd1e0f36844" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.3", +] + +[[package]] +name = "toml_writer" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.122" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3d97871 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "apollo-cli" +version = "0.1.0" +edition = "2024" + +[[bin]] +name = "apollo" +path = "src/main.rs" + +[dependencies] +base64 = "0.22.1" +clap = { version = "4.5.53", features = ["derive"] } +keyring = "3.6.3" +libc = "0.2.178" +regex = "1.12.2" +reqwest = { version = "0.12.26", default-features = false, features = ["blocking", "json", "rustls-tls"] } +rpassword = "7.4.0" +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.150" +toml = "0.9.8" +urlencoding = "2.1.3" + +[dev-dependencies] +assert_cmd = "2.0.17" +predicates = "3.1.3" +serde_json = "1.0.145" +tempfile = "3.23.0" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d9a10c0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md new file mode 100644 index 0000000..a79553a --- /dev/null +++ b/README.md @@ -0,0 +1,326 @@ +# Apollo CLI + +`apollo-cli` is the standalone Rust repository for the `apollo` command-line interface. + +This repository currently covers the first Apollo CLI v0 slices: + +- top-level v0 command routing +- global flag parsing +- output formatting foundation +- non-secret profile configuration +- runtime context resolution +- credential-store abstraction and auth commands +- conservative redaction foundation +- representative Apollo Portal OpenAPI calls under `/openapi/v1/*` +- raw OpenAPI passthrough through `apollo api` +- confirmation protection for mutating commands +- local developer workflow and CI entrypoints + +The package is intentionally self-contained and movable. It lives in this standalone repository for +review, but avoids repo-specific assumptions so the crate can be split, vendored, or republished +without Apollo server-side changes. + +It does not implement generated OpenAPI SDK bindings, agent sessions, MCP, or server-side schema +changes in this slice. + +## Command groups + +- `auth` +- `profile` +- `app` +- `env` +- `namespace` +- `config` +- `release` +- `api` + +Representative v0 commands: + +```bash +apollo init +apollo profile add dev +apollo profile add prod --use +apollo app list +apollo app get sample-app +apollo env list --app sample-app +apollo namespace list --env DEV --app sample-app +apollo namespace get --env DEV --app sample-app --namespace application +apollo namespace create --env DEV --app sample-app application --yes +apollo config list --env DEV --app sample-app +apollo config get --env DEV --app sample-app timeout +apollo config set --env DEV --app sample-app timeout 3000 --yes +apollo config delete --env DEV --app sample-app timeout --yes +apollo config diff --env DEV --app sample-app --target-env FAT +apollo config apply --env DEV --app sample-app --target-env FAT --yes +apollo release list --env DEV --app sample-app +apollo release create --env DEV --app sample-app --title "release title" --yes +apollo release rollback --env DEV 123 --yes +apollo api get /openapi/v1/apps +apollo api post /openapi/v1/apps --body '{"app":{"appId":"sample-app"}}' --yes +``` + +These commands use existing Apollo Portal OpenAPI endpoints only. Deprecated Portal WebAPI +endpoints are intentionally not used. +`apollo namespace create` registers the AppNamespace first and then creates the namespace in the +requested environment and cluster. It creates a private AppNamespace by default. Pass `--public` only +when the namespace should be public. File namespace formats are inferred from `.json`, `.yml`, +`.yaml`, and `.xml` suffixes; other names default to `properties`. + +## Global flags + +The current scaffold parses these global flags before subcommands: + +- `--profile` +- `--server` +- `--output json|table` +- `--yes` + +## Guided setup + +Use `apollo init` for first-time setup. It creates a profile, writes non-secret profile metadata to +`config.toml`, and can store a Consumer token through the credential-store abstraction. + +For local Apollo assembly testing: + +```bash +apollo --output json init --store-token-in-file +apollo profile show +apollo env list --app sample-app +``` + +By default, `apollo init` creates a `local` profile with: + +- `server = "http://127.0.0.1:8070"` +- no persisted `output` unless `--output` is passed +- `operator = "apollo"` +- `active_profile = "local"` + +Use `apollo profile add` to add more environments without hand-editing config: + +```bash +printf '%s\n' "$DEV_TOKEN" | apollo \ + --server https://apollo-dev.example.com \ + --output json \ + profile add dev \ + --operator alice \ + --token-stdin + +apollo profile add prod --server https://apollo-prod.example.com --operator alice --use +``` + +`profile add` does not switch the active profile by default. Pass `--use` when the newly added +profile should become active. Existing profiles are protected from accidental replacement; pass +`--overwrite` to replace one intentionally. + +## Profile config + +The CLI stores non-secret profile metadata in `config.toml` under the OS config directory: + +- macOS: `~/Library/Application Support/apollo/config.toml` +- Linux: `$XDG_CONFIG_HOME/apollo/config.toml` or `~/.config/apollo/config.toml` +- Windows: `%APPDATA%\apollo\config.toml` + +The config file stores: + +- `active_profile` +- profile name +- profile `server` +- profile `output` +- optional `operator` +- optional credential lookup metadata, such as backend/key names + +Tokens are intentionally not part of the supported config schema. Prefer `apollo init`, +`apollo profile add`, and `apollo auth login` over editing this file by hand. + +Example: + +```toml +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +operator = "apollo-bot" + +[profiles.dev.credential] +backend = "native" +key = "dev" +``` + +## Profile commands + +- `apollo init` +- `apollo profile add [name]` +- `apollo profile list` +- `apollo profile show` +- `apollo profile use ` + +Runtime context resolution follows this order: + +1. explicit flags such as `--profile`, `--server`, `--output` +2. environment variables such as `APOLLO_PROFILE`, `APOLLO_SERVER`, `APOLLO_OUTPUT` +3. active profile config +4. command defaults + +## Auth commands + +- `apollo auth login` +- `apollo auth login --token-stdin` +- `apollo auth login --token-stdin --store-token-in-file` +- `apollo auth status` +- `apollo auth logout` + +Credential storage uses an internal store abstraction with these logical providers: + +- `native`: default credential backend, implemented through the OS credential store via the Rust `keyring` crate +- `env`: read-only CI/headless provider through `APOLLO_TOKEN` +- `file`: explicit fallback enabled only with `--store-token-in-file` +- in-memory provider for unit tests + +Native backend selection follows the OS behavior of the underlying credential store: + +- macOS: Keychain Services +- Windows: Credential Manager +- Linux desktop: freedesktop Secret Service compatible providers +- Linux headless/CI: use `APOLLO_TOKEN` or explicitly opt into file fallback + +File fallback writes token material outside `config.toml` under the CLI credentials directory and uses restrictive file permissions on Unix. The profile config stores only non-secret credential lookup metadata. + +OpenAPI commands authenticate with the existing Apollo Consumer token model. The CLI sends the +token as the `Authorization` header value expected by Apollo Portal OpenAPI. + +For local or CI use, `APOLLO_TOKEN` takes precedence and is never written to disk: + +```bash +APOLLO_TOKEN="$TOKEN" apollo --server http://localhost:8070 app list --output json +``` + +`apollo auth logout` removes the credential referenced by the selected profile. It cannot remove +`APOLLO_TOKEN` from the parent shell environment. When `APOLLO_TOKEN` is still set, logout reports +that environment credentials will continue to apply; run `unset APOLLO_TOKEN` to disable that +temporary credential. + +For interactive use, configure a profile and store the token with hidden input: + +```bash +apollo --profile dev auth login +apollo --profile dev app list +``` + +`auth login` stores the token in the OS credential store by default. If the native store is not +available in an interactive terminal, the CLI asks whether to use the local file fallback instead. + +For scripts or manual paste-with-enter workflows, `--token-stdin` reads one token line: + +```bash +printf '%s\n' "$TOKEN" | apollo --profile dev auth login --token-stdin +apollo --profile dev auth login --token-stdin +``` + +## Redaction and Errors + +The output layer applies conservative redaction to human and JSON output before rendering. Token-like fields, `Authorization: Bearer ...` headers, and `consumer token ...` text are rendered as `[REDACTED]`. + +Structured JSON errors include: + +- `code`: stable error code +- `category`: stable category +- `message`: human-readable message +- optional non-sensitive details such as `command`, `profile`, `path`, or `follow_up_issue` + +Current error categories: + +- `authentication_failed` +- `permission_denied` +- `invalid_input` +- `not_found` +- `conflict` +- `precondition_failed` +- `network` +- `server` +- `confirmation_required` +- `unsupported_operation` + +## OpenAPI behavior + +The first v0 implementation uses a small generic HTTP client instead of a generated SDK. This keeps +the CLI independent from the Apollo server repository while still constraining all built-in resource +commands to `/openapi/v1/*`. + +Path and payload mapping follows the current Apollo Portal OpenAPI contract, including: + +- `GET /openapi/v1/apps` +- `GET /openapi/v1/envs` +- `GET /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces` +- `GET|PUT|DELETE /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}` +- `POST /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/diff` +- `POST /openapi/v1/apps/{appId}/appnamespaces` for AppNamespace registration +- `POST /openapi/v1/namespaces` +- `POST /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/synchronize` +- `GET /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases/active` +- `POST /openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases` +- `PUT /openapi/v1/envs/{env}/releases/{releaseId}/rollback` + +Mutating commands require `--yes`. Without it, the CLI returns `confirmation_required` before +opening a network connection. + +## Local development + +Build the CLI: + +```bash +cargo build +``` + +Run the help output: + +```bash +cargo run -- --help +``` + +Run tests: + +```bash +cargo test +``` + +Run focused OpenAPI command integration tests with the local mock HTTP server: + +```bash +cargo test --test openapi +``` + +If you have a local Apollo Portal running, you can also smoke-test against it: + +```bash +APOLLO_TOKEN="$TOKEN" cargo run -- --server http://localhost:8070 --output json env list --app sample-app +APOLLO_TOKEN="$TOKEN" cargo run -- --server http://localhost:8070 --output json app list +``` + +Format the repository: + +```bash +cargo fmt +``` + +Lint the repository: + +```bash +cargo clippy --all-targets --all-features -- -D warnings +``` + +## Repository layout + +- `src/cli.rs`: CLI definition and flag parsing +- `src/config.rs`: profile config loading, saving, and context resolution +- `src/command.rs`: top-level command routing +- `src/credential.rs`: credential-store abstraction and providers +- `src/error.rs`: structured CLI error model +- `src/http.rs`: generic OpenAPI HTTP client and path helpers +- `src/output.rs`: output rendering abstractions +- `src/redaction.rs`: conservative redaction utilities +- `tests/auth.rs`: integration coverage for auth commands and credential behavior +- `tests/cli.rs`: integration coverage for help, flags, and structured errors +- `tests/openapi.rs`: integration coverage for OpenAPI paths, auth headers, and confirmation guards +- `tests/profile.rs`: integration coverage for profile commands and context resolution +- `tests/redaction.rs`: integration coverage for redaction behavior diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..5cb84bf --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,295 @@ +use clap::{Args, Parser, Subcommand, ValueEnum}; +use serde::{Deserialize, Serialize}; + +#[derive(Parser, Debug)] +#[command( + name = "apollo", + bin_name = "apollo", + version, + about = "Standalone Apollo OpenAPI CLI", + long_about = "Standalone Apollo CLI for profile/auth management and Apollo Portal OpenAPI v0 workflows." +)] +pub struct Cli { + #[command(flatten)] + pub global: GlobalOptions, + #[command(subcommand)] + pub command: Commands, +} + +#[derive(Args, Debug)] +pub struct GlobalOptions { + #[arg(long, global = true)] + pub profile: Option, + #[arg(long, global = true)] + pub server: Option, + #[arg(long, value_enum, global = true)] + pub output: Option, + #[arg(long, global = true)] + pub yes: bool, +} + +#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize, ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum OutputFormat { + Json, + Table, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum Commands { + Init(InitArgs), + Auth { + #[command(subcommand)] + command: AuthCommand, + }, + Profile { + #[command(subcommand)] + command: ProfileCommand, + }, + App { + #[command(subcommand)] + command: AppCommand, + }, + Env { + #[command(subcommand)] + command: EnvCommand, + }, + Namespace { + #[command(subcommand)] + command: NamespaceCommand, + }, + Config { + #[command(subcommand)] + command: ConfigCommand, + }, + Release { + #[command(subcommand)] + command: ReleaseCommand, + }, + Api(ApiArgs), +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum ProfileCommand { + Add(ProfileAddArgs), + List, + Show, + Use { name: String }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Args)] +pub struct InitArgs { + #[arg(long)] + pub name: Option, + #[arg(long)] + pub operator: Option, + #[arg(long)] + pub token_stdin: bool, + #[arg(long)] + pub store_token_in_file: bool, + #[arg(long)] + pub overwrite: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq, Args)] +pub struct ProfileAddArgs { + pub name: Option, + #[arg(long)] + pub operator: Option, + #[arg(long)] + pub token_stdin: bool, + #[arg(long)] + pub store_token_in_file: bool, + #[arg(long)] + pub overwrite: bool, + #[arg(long = "use")] + pub use_profile: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum AuthCommand { + Login { + #[arg(long)] + token_stdin: bool, + #[arg(long)] + store_token_in_file: bool, + }, + Status, + Logout, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum AppCommand { + List { + #[arg(long)] + app_ids: Option, + }, + Get { + app_id: String, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum EnvCommand { + List { + #[arg(long)] + app: String, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum NamespaceCommand { + List { + #[command(flatten)] + scope: ClusterScopeArgs, + }, + Get { + #[command(flatten)] + scope: NamespaceScopeArgs, + }, + Create { + #[command(flatten)] + scope: ClusterScopeArgs, + name: String, + #[arg(long)] + operator: Option, + #[arg(long = "public")] + public_namespace: bool, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum ConfigCommand { + List { + #[command(flatten)] + scope: NamespaceScopeArgs, + #[arg(long)] + page: Option, + #[arg(long)] + size: Option, + }, + Get { + #[command(flatten)] + scope: NamespaceScopeArgs, + key: String, + }, + Set { + #[command(flatten)] + scope: NamespaceScopeArgs, + key: String, + value: String, + #[arg(long)] + comment: Option, + #[arg(long)] + operator: Option, + }, + Delete { + #[command(flatten)] + scope: NamespaceScopeArgs, + key: String, + #[arg(long)] + operator: Option, + }, + Diff { + #[command(flatten)] + scope: NamespaceScopeArgs, + #[arg(long)] + target_env: String, + #[arg(long, default_value = "default")] + target_cluster: String, + #[arg(long)] + target_namespace: Option, + }, + Apply { + #[command(flatten)] + scope: NamespaceScopeArgs, + #[arg(long)] + target_env: String, + #[arg(long, default_value = "default")] + target_cluster: String, + #[arg(long)] + target_namespace: Option, + #[arg(long)] + operator: Option, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum ReleaseCommand { + List { + #[command(flatten)] + scope: NamespaceScopeArgs, + #[arg(long)] + page: Option, + #[arg(long)] + size: Option, + }, + Create { + #[command(flatten)] + scope: NamespaceScopeArgs, + #[arg(long)] + title: String, + #[arg(long)] + comment: Option, + #[arg(long)] + emergency: bool, + #[arg(long)] + operator: Option, + }, + Rollback { + #[arg(long)] + env: String, + release_id: i64, + #[arg(long)] + to_release_id: Option, + #[arg(long)] + operator: Option, + }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Args)] +pub struct ApiArgs { + pub method: HttpMethod, + pub path: String, + #[arg(long)] + pub body: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq, Args)] +pub struct ClusterScopeArgs { + #[arg(long)] + pub env: String, + #[arg(long)] + pub app: String, + #[arg(long, default_value = "default")] + pub cluster: String, +} + +#[derive(Clone, Debug, Eq, PartialEq, Args)] +pub struct NamespaceScopeArgs { + #[command(flatten)] + pub cluster_scope: ClusterScopeArgs, + #[arg(long, default_value = "application")] + pub namespace: String, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)] +pub enum HttpMethod { + Get, + Post, + Put, + Patch, + Delete, +} + +impl HttpMethod { + pub fn as_str(self) -> &'static str { + match self { + Self::Get => "GET", + Self::Post => "POST", + Self::Put => "PUT", + Self::Patch => "PATCH", + Self::Delete => "DELETE", + } + } +} diff --git a/src/command.rs b/src/command.rs new file mode 100644 index 0000000..f4c7cb0 --- /dev/null +++ b/src/command.rs @@ -0,0 +1,1558 @@ +use std::io::{self, BufRead, IsTerminal, Write}; + +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::cli::{ + ApiArgs, AppCommand, AuthCommand, Cli, Commands, ConfigCommand, EnvCommand, InitArgs, + NamespaceCommand, NamespaceScopeArgs, OutputFormat, ProfileCommand, ReleaseCommand, +}; +use crate::config::{ + CredentialRef, LoadedConfig, ProfileConfig, RuntimeContext, load_config, read_env_output, + resolve_context, resolve_output, save_config, +}; +use crate::credential; +use crate::error::CliError; +use crate::http::{OpenApiClient, OpenApiResponse, append_query, encode_path_segment}; +use crate::output::{OutputWriter, RenderedOutput}; +use crate::redaction::Sensitive; + +const DEFAULT_PAGE: u32 = 0; +const DEFAULT_PAGE_SIZE: u32 = 20; +const SYNC_ITEMS_PAGE_SIZE: u32 = 500; +const DEFAULT_INIT_PROFILE: &str = "local"; +const DEFAULT_INIT_SERVER: &str = "http://127.0.0.1:8070"; +const DEFAULT_INIT_OPERATOR: &str = "apollo"; + +pub fn execute(cli: Cli) -> Result { + let output = output_from_flags_or_env(&cli).unwrap_or(OutputFormat::Table); + + match &cli.command { + Commands::Init(args) => execute_init(args.clone(), &cli, output), + Commands::Auth { command } => execute_auth(command.clone(), &cli, output), + Commands::Profile { command } => execute_profile(command.clone(), &cli, output), + Commands::App { command } => execute_app(command.clone(), &cli, output), + Commands::Env { command } => execute_env(command.clone(), &cli, output), + Commands::Namespace { command } => execute_namespace(command.clone(), &cli, output), + Commands::Config { command } => execute_config(command.clone(), &cli, output), + Commands::Release { command } => execute_release(command.clone(), &cli, output), + Commands::Api(args) => execute_api(args.clone(), &cli, output), + } +} + +fn output_from_flags_or_env(cli: &Cli) -> Option { + cli.global.output.or_else(read_env_output) +} + +fn non_blank(value: String) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) +} + +fn execute_init( + args: InitArgs, + cli: &Cli, + output: OutputFormat, +) -> Result { + let options = ProfileSetupOptions { + mode: ProfileSetupMode::Init, + name: args.name, + operator: args.operator, + token_stdin: args.token_stdin, + store_token_in_file: args.store_token_in_file, + overwrite: args.overwrite, + use_profile: true, + }; + execute_profile_setup(options, cli, output) +} + +fn execute_auth( + command: AuthCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + match command { + AuthCommand::Status => { + if env_token_is_set() { + let loaded = load_config(output).ok(); + let writer_output = loaded + .as_ref() + .and_then(|loaded| resolve_output(cli, loaded, output).ok()) + .unwrap_or_else(|| output_from_flags_or_env(cli).unwrap_or(output)); + let writer = OutputWriter::new(writer_output); + let profile = cli + .global + .profile + .clone() + .and_then(non_blank) + .or_else(|| std::env::var("APOLLO_PROFILE").ok().and_then(non_blank)) + .or_else(|| { + loaded + .as_ref() + .and_then(|loaded| loaded.config.active_profile.clone()) + .and_then(non_blank) + }); + let response = AuthStatusResponse { + authenticated: true, + source: "env".to_owned(), + profile, + backend: Some("env".to_owned()), + key: Some("APOLLO_TOKEN".to_owned()), + }; + return Ok(writer.render_success(&response, response.render_table())); + } + + let loaded = load_config(output)?; + let writer_output = resolve_output(cli, &loaded, output)?; + let writer = OutputWriter::new(writer_output); + let context = resolve_context(cli, &loaded, output)?; + let profile = required_profile(&context, writer_output)?; + let status = credential::status(&loaded.path, &profile, context.credential.as_ref()); + let response = AuthStatusResponse { + authenticated: status.authenticated, + source: status.source.as_str().to_owned(), + profile: Some(profile), + backend: status.backend, + key: status.key, + }; + Ok(writer.render_success(&response, response.render_table())) + } + AuthCommand::Login { + token_stdin, + store_token_in_file, + } => { + let loaded = load_config(output)?; + let writer_output = resolve_output(cli, &loaded, output)?; + let writer = OutputWriter::new(writer_output); + let context = resolve_context(cli, &loaded, output)?; + let profile = required_profile(&context, writer_output)?; + if !loaded.config.profiles.contains_key(&profile) { + return Err(CliError::profile_not_found(&profile, writer_output)); + } + let token = credential::token_from_login_input(token_stdin, writer_output)?; + + let credential_ref = store_setup_token( + &loaded.path, + &profile, + &token, + store_token_in_file, + is_interactive_terminal(), + writer_output, + )?; + + let mut config = loaded.config.clone(); + let profile_config = config + .profiles + .get_mut(&profile) + .ok_or_else(|| CliError::profile_not_found(&profile, writer_output))?; + profile_config.credential = Some(credential_ref.clone()); + save_config(&loaded.path, &config, writer_output)?; + + let response = AuthLoginResponse { + stored: true, + profile: profile.clone(), + backend: credential_ref.backend, + key: credential_ref.key, + }; + Ok(writer.render_success(&response, response.render_table())) + } + AuthCommand::Logout => { + let loaded = load_config(output)?; + let writer_output = resolve_output(cli, &loaded, output)?; + let writer = OutputWriter::new(writer_output); + let context = resolve_context(cli, &loaded, output)?; + let profile = required_profile(&context, output)?; + let environment_token_still_active = std::env::var("APOLLO_TOKEN") + .ok() + .is_some_and(|token| !token.trim().is_empty()); + let credential_ref = context.credential.clone().unwrap_or_else(|| CredentialRef { + backend: "native".to_owned(), + key: profile.clone(), + }); + credential::delete(&loaded.path, &credential_ref) + .map_err(|error| CliError::credential_store_unavailable(&error, writer_output))?; + let message = if environment_token_still_active { + Some( + "Local credential was removed, but APOLLO_TOKEN is still set and will continue to authenticate commands in this shell. Run `unset APOLLO_TOKEN` to disable it." + .to_owned(), + ) + } else { + None + }; + let response = AuthLogoutResponse { + logged_out: true, + profile, + backend: credential_ref.backend, + key: credential_ref.key, + environment_token_still_active, + message, + }; + Ok(writer.render_success(&response, response.render_table())) + } + } +} + +fn execute_profile( + command: ProfileCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + let loaded = load_config(output)?; + + match command { + ProfileCommand::Add(args) => { + let options = ProfileSetupOptions { + mode: ProfileSetupMode::Add, + name: args.name, + operator: args.operator, + token_stdin: args.token_stdin, + store_token_in_file: args.store_token_in_file, + overwrite: args.overwrite, + use_profile: args.use_profile, + }; + execute_profile_setup(options, cli, output) + } + ProfileCommand::List => { + let writer_output = resolve_output(cli, &loaded, output) + .unwrap_or_else(|_| output_from_flags_or_env(cli).unwrap_or(output)); + let writer = OutputWriter::new(writer_output); + let response = ProfileListResponse::from_loaded_config(&loaded); + Ok(writer.render_success(&response, response.render_table())) + } + ProfileCommand::Show => { + let writer = OutputWriter::new(resolve_output(cli, &loaded, output)?); + let context = resolve_context(cli, &loaded, output)?; + let response = ProfileShowResponse::from_context(&loaded, context); + Ok(writer.render_success(&response, response.render_table())) + } + ProfileCommand::Use { name } => { + let writer_output = resolve_output(cli, &loaded, output) + .unwrap_or_else(|_| output_from_flags_or_env(cli).unwrap_or(output)); + let writer = OutputWriter::new(writer_output); + if !loaded.config.profiles.contains_key(&name) { + return Err(CliError::profile_not_found(&name, writer_output)); + } + + let mut config = loaded.config.clone(); + config.active_profile = Some(name.clone()); + save_config(&loaded.path, &config, writer_output)?; + + let response = ProfileUseResponse { + active_profile: name.clone(), + config_path: loaded.path.display().to_string(), + }; + Ok(writer.render_success( + &response, + format!( + "Active profile set to '{}'.\nConfig path: {}", + name, + loaded.path.display() + ), + )) + } + } +} + +#[derive(Copy, Clone)] +enum ProfileSetupMode { + Init, + Add, +} + +impl ProfileSetupMode { + fn command_name(self) -> &'static str { + match self { + Self::Init => "init", + Self::Add => "profile add", + } + } +} + +struct ProfileSetupOptions { + mode: ProfileSetupMode, + name: Option, + operator: Option, + token_stdin: bool, + store_token_in_file: bool, + overwrite: bool, + use_profile: bool, +} + +fn execute_profile_setup( + options: ProfileSetupOptions, + cli: &Cli, + output: OutputFormat, +) -> Result { + let loaded = load_config(output)?; + let writer_output = resolve_output(cli, &loaded, output) + .unwrap_or_else(|_| output_from_flags_or_env(cli).unwrap_or(output)); + let writer = OutputWriter::new(writer_output); + let interactive = is_interactive_terminal(); + + let profile_name = resolve_setup_profile_name(&options, cli, interactive, writer_output)?; + if loaded.config.profiles.contains_key(&profile_name) && !options.overwrite { + return Err(CliError::profile_already_exists( + &profile_name, + options.mode.command_name(), + writer_output, + )); + } + + let server = resolve_setup_server(&options, cli, interactive, writer_output)?; + let profile_output = cli.global.output; + let response_output = profile_output.unwrap_or(OutputFormat::Table); + let operator = resolve_setup_operator(&options, interactive, writer_output)?; + let existing_profile = loaded.config.profiles.get(&profile_name); + + let mut profile_config = ProfileConfig { + server: Some(server.clone()), + output: profile_output, + operator: operator.clone(), + credential: existing_profile.and_then(|profile| profile.credential.clone()), + }; + + let credential = resolve_setup_token(&options, interactive, writer_output)? + .map(|token| { + store_setup_token( + &loaded.path, + &profile_name, + &token, + options.store_token_in_file, + interactive, + writer_output, + ) + }) + .transpose()?; + if let Some(credential) = credential.clone() { + profile_config.credential = Some(credential); + } + + let mut config = loaded.config.clone(); + config.profiles.insert(profile_name.clone(), profile_config); + let should_set_active = options.use_profile || config.active_profile.is_none(); + if should_set_active { + config.active_profile = Some(profile_name.clone()); + } + save_config(&loaded.path, &config, writer_output)?; + let response_credential = config + .profiles + .get(&profile_name) + .and_then(|profile| profile.credential.clone()); + + let response = ProfileSetupResponse { + profile: profile_name, + active_profile: config.active_profile.clone(), + server, + output: response_output.to_string(), + operator, + credential: response_credential, + config_path: loaded.path.display().to_string(), + next_steps: vec![ + "apollo profile show".to_owned(), + "apollo app list".to_owned(), + "apollo env list --app ".to_owned(), + ], + }; + Ok(writer.render_success(&response, response.render_table())) +} + +fn execute_app( + command: AppCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + let openapi = openapi_context(cli, output)?; + let path = match command { + AppCommand::List { app_ids } => { + let path = "/openapi/v1/apps".to_owned(); + if let Some(app_ids) = app_ids { + append_query(path, "appIds", &app_ids) + } else { + path + } + } + AppCommand::Get { app_id } => { + format!("/openapi/v1/apps/{}", encode_path_segment(&app_id)) + } + }; + openapi.request("GET", &path, None) +} + +fn execute_env( + command: EnvCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + let openapi = openapi_context(cli, output)?; + match command { + EnvCommand::List { app } => { + let path = format!("/openapi/v1/apps/{}/envclusters", encode_path_segment(&app)); + openapi.request("GET", &path, None) + } + } +} + +fn execute_namespace( + command: NamespaceCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + if matches!(command, NamespaceCommand::Create { .. }) { + require_yes_for_openapi(cli, output)?; + } + let openapi = openapi_context(cli, output)?; + match command { + NamespaceCommand::List { scope } => { + let path = cluster_namespaces_path(&scope.env, &scope.app, &scope.cluster); + openapi.request("GET", &path, None) + } + NamespaceCommand::Get { scope } => { + let path = namespace_path(&scope); + openapi.request("GET", &path, None) + } + NamespaceCommand::Create { + scope, + name, + operator, + public_namespace, + } => { + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + let app_namespace_name = + register_app_namespace(&openapi, &scope.app, &name, public_namespace, &operator)?; + let path = append_query("/openapi/v1/namespaces".to_owned(), "operator", &operator); + let body = json!([{ + "appId": scope.app, + "env": scope.env, + "clusterName": scope.cluster, + "appNamespaceName": app_namespace_name, + }]); + openapi.request("POST", &path, Some(body)) + } + } +} + +struct AppNamespaceRegistration { + name: String, + format: &'static str, +} + +fn register_app_namespace( + openapi: &OpenApiCommandContext, + app_id: &str, + namespace_name: &str, + public_namespace: bool, + operator: &str, +) -> Result { + if let Some(existing_name) = find_app_namespace(openapi, app_id, namespace_name)? { + return Ok(existing_name); + } + + let registration = app_namespace_registration(namespace_name); + let path = format!( + "/openapi/v1/apps/{}/appnamespaces", + encode_path_segment(app_id) + ); + let body = json!({ + "appId": app_id, + "name": registration.name, + "format": registration.format, + "isPublic": public_namespace, + "dataChangeCreatedBy": operator, + }); + let response = openapi.client.request("POST", &path, Some(body))?; + Ok(response + .data + .get("name") + .and_then(Value::as_str) + .unwrap_or(namespace_name) + .to_owned()) +} + +fn find_app_namespace( + openapi: &OpenApiCommandContext, + app_id: &str, + namespace_name: &str, +) -> Result, CliError> { + let path = format!( + "/openapi/v1/apps/{}/appnamespaces/{}", + encode_path_segment(app_id), + encode_path_segment(namespace_name) + ); + match openapi.client.request("GET", &path, None) { + Ok(response) => Ok(Some( + response + .data + .get("name") + .and_then(Value::as_str) + .unwrap_or(namespace_name) + .to_owned(), + )), + Err(error) if error.http_status_code() == Some(404) => Ok(None), + Err(error) => Err(error), + } +} + +fn app_namespace_registration(namespace_name: &str) -> AppNamespaceRegistration { + let lowercase_name = namespace_name.to_ascii_lowercase(); + for format in ["yaml", "yml", "json", "xml"] { + let suffix = format!(".{format}"); + if lowercase_name.ends_with(&suffix) && namespace_name.len() > suffix.len() { + return AppNamespaceRegistration { + name: namespace_name[..namespace_name.len() - suffix.len()].to_owned(), + format, + }; + } + } + + AppNamespaceRegistration { + name: namespace_name.to_owned(), + format: "properties", + } +} + +fn execute_config( + command: ConfigCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + if config_command_requires_confirmation(&command) { + require_yes_for_openapi(cli, output)?; + } + let openapi = openapi_context(cli, output)?; + match command { + ConfigCommand::List { scope, page, size } => { + let mut path = format!("{}/items", namespace_path(&scope)); + path = append_query(path, "page", &page.unwrap_or(DEFAULT_PAGE).to_string()); + path = append_query(path, "size", &size.unwrap_or(DEFAULT_PAGE_SIZE).to_string()); + openapi.request("GET", &path, None) + } + ConfigCommand::Get { scope, key } => { + let path = item_path(&scope, &key); + openapi.request("GET", &path, None) + } + ConfigCommand::Set { + scope, + key, + value, + comment, + operator, + } => { + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + let update_path = append_query(item_path(&scope, &key), "createIfNotExists", "true"); + let create_path = append_query( + format!("{}/items", namespace_path(&scope)), + "operator", + &operator, + ); + let body = json!({ + "key": key, + "value": value, + "dataChangeCreatedBy": operator, + "dataChangeLastModifiedBy": operator, + }); + let mut body = body; + if let Some(comment) = comment { + body["comment"] = json!(comment); + } + match openapi + .client + .request("PUT", &update_path, Some(body.clone())) + { + Ok(response) => Ok(render_openapi_response(&openapi.writer, &response)), + Err(error) if error.http_status_code() == Some(404) => { + let response = openapi.client.request("POST", &create_path, Some(body))?; + Ok(render_openapi_response(&openapi.writer, &response)) + } + Err(error) => Err(error), + } + } + ConfigCommand::Delete { + scope, + key, + operator, + } => { + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + let path = append_query(item_path(&scope, &key), "operator", &operator); + openapi.request("DELETE", &path, None) + } + ConfigCommand::Diff { + scope, + target_env, + target_cluster, + target_namespace, + } => { + let sync_items = source_sync_items(&openapi, &scope)?; + let body = sync_body( + &scope, + target_env, + target_cluster, + target_namespace, + sync_items, + ); + let path = format!("{}/items/diff", namespace_path(&scope)); + openapi.request("POST", &path, Some(body)) + } + ConfigCommand::Apply { + scope, + target_env, + target_cluster, + target_namespace, + operator, + } => { + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + if let Some(namespace) = &target_namespace + && namespace != &scope.namespace + { + return Err(CliError::invalid_input( + "config apply does not support --target-namespace different from the source namespace because Apollo synchronize requires matching namespace names", + openapi.context.output, + )); + } + let sync_items = source_sync_items(&openapi, &scope)?; + let body = sync_body( + &scope, + target_env, + target_cluster, + target_namespace, + sync_items, + ); + let path = append_query( + format!("{}/items/synchronize", namespace_path(&scope)), + "operator", + &operator, + ); + openapi.request("POST", &path, Some(body)) + } + } +} + +fn execute_release( + command: ReleaseCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + if release_command_requires_confirmation(&command) { + require_yes_for_openapi(cli, output)?; + } + let openapi = openapi_context(cli, output)?; + match command { + ReleaseCommand::List { scope, page, size } => { + let mut path = format!("{}/releases/active", namespace_path(&scope)); + path = append_query(path, "page", &page.unwrap_or(DEFAULT_PAGE).to_string()); + path = append_query(path, "size", &size.unwrap_or(DEFAULT_PAGE_SIZE).to_string()); + openapi.request("GET", &path, None) + } + ReleaseCommand::Create { + scope, + title, + comment, + emergency, + operator, + } => { + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + let path = format!("{}/releases", namespace_path(&scope)); + let body = json!({ + "releaseTitle": title, + "releaseComment": comment.unwrap_or_default(), + "releasedBy": operator, + "isEmergencyPublish": emergency, + }); + openapi.request("POST", &path, Some(body)) + } + ReleaseCommand::Rollback { + env, + release_id, + to_release_id, + operator, + } => { + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + let mut path = append_query( + format!( + "/openapi/v1/envs/{}/releases/{}/rollback", + encode_path_segment(&env), + release_id + ), + "operator", + &operator, + ); + if let Some(to_release_id) = to_release_id { + path = append_query(path, "toReleaseId", &to_release_id.to_string()); + } + openapi.request("PUT", &path, None) + } + } +} + +fn execute_api(args: ApiArgs, cli: &Cli, output: OutputFormat) -> Result { + if http_method_requires_confirmation(args.method) { + require_yes_for_openapi(cli, output)?; + } + let openapi = openapi_context(cli, output)?; + let body = match args.body { + Some(body) => Some(serde_json::from_str::(&body).map_err(|error| { + CliError::invalid_input(&error.to_string(), openapi.context.output) + })?), + None => None, + }; + openapi.request(args.method.as_str(), &args.path, body) +} + +struct OpenApiCommandContext { + context: RuntimeContext, + writer: OutputWriter, + client: OpenApiClient, +} + +impl OpenApiCommandContext { + fn request( + &self, + method: &str, + path: &str, + body: Option, + ) -> Result { + let response = self.client.request(method, path, body)?; + Ok(render_openapi_response(&self.writer, &response)) + } +} + +fn openapi_context(cli: &Cli, output: OutputFormat) -> Result { + if env_token_is_set() && explicit_server(cli).is_some() { + if let Ok(loaded) = load_config(output) + && let Some(context) = env_openapi_context(cli, &loaded, output)? + { + return Ok(context); + } + return env_only_openapi_context(cli, output); + } + + let loaded = load_config(output)?; + if let Some(context) = env_openapi_context(cli, &loaded, output)? { + return Ok(context); + } + + let writer_output = resolve_output(cli, &loaded, output)?; + let context = resolve_context(cli, &loaded, writer_output)?; + let server = required_server(&context, writer_output)?; + let token = credential::resolve_token( + &loaded.path, + context.profile.as_deref(), + context.credential.as_ref(), + ) + .map_err(|error| CliError::credential_store_unavailable(&error, writer_output))? + .ok_or_else(|| { + CliError::authentication_required( + "Authenticate with APOLLO_TOKEN or `apollo auth login` before calling OpenAPI.", + writer_output, + ) + })?; + Ok(OpenApiCommandContext { + context, + writer: OutputWriter::new(writer_output), + client: OpenApiClient::new(server, token, writer_output), + }) +} + +fn env_openapi_context( + cli: &Cli, + loaded: &LoadedConfig, + output: OutputFormat, +) -> Result, CliError> { + if !env_token_is_set() { + return Ok(None); + } + let Some(server) = explicit_server(cli) else { + return Ok(None); + }; + + let writer_output = resolve_output(cli, loaded, output) + .unwrap_or_else(|_| output_from_flags_or_env(cli).unwrap_or(output)); + let token = credential::resolve_token(&loaded.path, None, None) + .map_err(|error| CliError::credential_store_unavailable(&error, writer_output))? + .ok_or_else(|| { + CliError::authentication_required( + "Authenticate with APOLLO_TOKEN or `apollo auth login` before calling OpenAPI.", + writer_output, + ) + })?; + let selected_profile = cli + .global + .profile + .clone() + .and_then(non_blank) + .or_else(|| std::env::var("APOLLO_PROFILE").ok().and_then(non_blank)) + .or_else(|| loaded.config.active_profile.clone().and_then(non_blank)); + let operator = selected_profile + .as_ref() + .and_then(|profile| loaded.config.profiles.get(profile)) + .and_then(|profile| profile.operator.clone().and_then(non_blank)); + + let context = RuntimeContext { + profile: selected_profile, + server: Some(server.clone()), + output: writer_output, + operator, + credential: None, + }; + + Ok(Some(OpenApiCommandContext { + context, + writer: OutputWriter::new(writer_output), + client: OpenApiClient::new(server, token, writer_output), + })) +} + +fn env_only_openapi_context( + cli: &Cli, + output: OutputFormat, +) -> Result { + let server = explicit_server(cli).ok_or_else(|| { + CliError::authentication_required( + "Provide --server or APOLLO_SERVER when using APOLLO_TOKEN without a profile.", + output, + ) + })?; + let writer_output = output_from_flags_or_env(cli).unwrap_or(output); + let token = credential::resolve_token(std::path::Path::new(""), None, None) + .map_err(|error| CliError::credential_store_unavailable(&error, writer_output))? + .ok_or_else(|| { + CliError::authentication_required( + "Authenticate with APOLLO_TOKEN or `apollo auth login` before calling OpenAPI.", + writer_output, + ) + })?; + let selected_profile = cli + .global + .profile + .clone() + .and_then(non_blank) + .or_else(|| std::env::var("APOLLO_PROFILE").ok().and_then(non_blank)); + let context = RuntimeContext { + profile: selected_profile, + server: Some(server.clone()), + output: writer_output, + operator: None, + credential: None, + }; + Ok(OpenApiCommandContext { + context, + writer: OutputWriter::new(writer_output), + client: OpenApiClient::new(server, token, writer_output), + }) +} + +fn render_openapi_response(writer: &OutputWriter, response: &OpenApiResponse) -> RenderedOutput { + writer.render_success(response, response.render_table()) +} + +fn config_command_requires_confirmation(command: &ConfigCommand) -> bool { + matches!( + command, + ConfigCommand::Set { .. } | ConfigCommand::Delete { .. } | ConfigCommand::Apply { .. } + ) +} + +fn release_command_requires_confirmation(command: &ReleaseCommand) -> bool { + matches!( + command, + ReleaseCommand::Create { .. } | ReleaseCommand::Rollback { .. } + ) +} + +fn http_method_requires_confirmation(method: crate::cli::HttpMethod) -> bool { + matches!( + method, + crate::cli::HttpMethod::Post + | crate::cli::HttpMethod::Put + | crate::cli::HttpMethod::Patch + | crate::cli::HttpMethod::Delete + ) +} + +fn require_yes_for_openapi(cli: &Cli, output: OutputFormat) -> Result<(), CliError> { + require_yes(cli, output_for_confirmation(cli, output)) +} + +fn output_for_confirmation(cli: &Cli, output: OutputFormat) -> OutputFormat { + if let Some(output) = output_from_flags_or_env(cli) { + return output; + } + + load_config(output) + .ok() + .and_then(|loaded| resolve_output(cli, &loaded, output).ok()) + .unwrap_or(output) +} + +fn explicit_server(cli: &Cli) -> Option { + cli.global + .server + .clone() + .and_then(non_blank) + .or_else(|| std::env::var("APOLLO_SERVER").ok().and_then(non_blank)) +} + +fn env_token_is_set() -> bool { + std::env::var("APOLLO_TOKEN") + .ok() + .is_some_and(|token| !token.trim().is_empty()) +} + +fn required_server(context: &RuntimeContext, output: OutputFormat) -> Result { + context + .server + .clone() + .filter(|server| !server.trim().is_empty()) + .ok_or_else(|| { + CliError::invalid_input( + "provide a server with --server, APOLLO_SERVER, or profile config", + output, + ) + }) +} + +fn required_operator( + command_operator: Option<&str>, + context: &RuntimeContext, + output: OutputFormat, +) -> Result { + command_operator + .map(ToOwned::to_owned) + .filter(|operator| !operator.trim().is_empty()) + .or_else(|| { + context + .operator + .clone() + .filter(|operator| !operator.trim().is_empty()) + }) + .ok_or_else(|| { + CliError::invalid_input( + "provide an operator with --operator or profile config", + output, + ) + }) +} + +fn require_yes(cli: &Cli, output: OutputFormat) -> Result<(), CliError> { + if cli.global.yes { + Ok(()) + } else { + Err(CliError::confirmation_required( + "This command mutates Apollo state. Re-run with --yes to confirm.", + output, + )) + } +} + +fn cluster_namespaces_path(env: &str, app: &str, cluster: &str) -> String { + format!( + "/openapi/v1/envs/{}/apps/{}/clusters/{}/namespaces", + encode_path_segment(env), + encode_path_segment(app), + encode_path_segment(cluster), + ) +} + +fn namespace_path(scope: &NamespaceScopeArgs) -> String { + format!( + "{}/{}", + cluster_namespaces_path( + &scope.cluster_scope.env, + &scope.cluster_scope.app, + &scope.cluster_scope.cluster + ), + encode_path_segment(&scope.namespace), + ) +} + +fn item_path(scope: &NamespaceScopeArgs, key: &str) -> String { + if key.contains('/') || key.contains('\\') { + format!( + "{}/encodedItems/{}", + namespace_path(scope), + encode_path_segment(&URL_SAFE_NO_PAD.encode(key.as_bytes())) + ) + } else { + format!( + "{}/items/{}", + namespace_path(scope), + encode_path_segment(key) + ) + } +} + +fn source_sync_items( + openapi: &OpenApiCommandContext, + scope: &NamespaceScopeArgs, +) -> Result, CliError> { + let mut items = Vec::new(); + let mut page = DEFAULT_PAGE; + + loop { + let mut path = format!("{}/items", namespace_path(scope)); + path = append_query(path, "page", &page.to_string()); + path = append_query(path, "size", &SYNC_ITEMS_PAGE_SIZE.to_string()); + let response = openapi.client.request("GET", &path, None)?; + let content = item_page_content(&response.data, openapi.context.output)?; + let content_len = content.len(); + items.extend(content); + + let total = response.data.get("total").and_then(Value::as_u64); + if total.is_some_and(|total| items.len() as u64 >= total) + || content_len < SYNC_ITEMS_PAGE_SIZE as usize + { + break; + } + page += 1; + } + + Ok(items) +} + +fn item_page_content(data: &Value, output: OutputFormat) -> Result, CliError> { + data.get("content") + .and_then(Value::as_array) + .or_else(|| data.as_array()) + .cloned() + .ok_or_else(|| { + CliError::invalid_input( + "OpenAPI item list response did not contain a content array", + output, + ) + }) +} + +fn sync_body( + scope: &NamespaceScopeArgs, + target_env: String, + target_cluster: String, + target_namespace: Option, + sync_items: Vec, +) -> Value { + json!({ + "syncToNamespaces": [{ + "appId": scope.cluster_scope.app.clone(), + "env": target_env, + "clusterName": target_cluster, + "namespaceName": target_namespace.unwrap_or_else(|| scope.namespace.clone()), + }], + "syncItems": sync_items, + }) +} + +fn resolve_setup_profile_name( + options: &ProfileSetupOptions, + cli: &Cli, + interactive: bool, + output: OutputFormat, +) -> Result { + options + .name + .clone() + .and_then(non_blank) + .or_else(|| cli.global.profile.clone().and_then(non_blank)) + .or_else(|| match options.mode { + ProfileSetupMode::Init => Some(DEFAULT_INIT_PROFILE.to_owned()), + ProfileSetupMode::Add => None, + }) + .map(Ok) + .unwrap_or_else(|| { + if interactive { + prompt_required("Profile name", None, output) + } else { + Err(CliError::invalid_input( + "provide a profile name, for example `apollo profile add dev --server ...`", + output, + )) + } + }) +} + +fn resolve_setup_server( + options: &ProfileSetupOptions, + cli: &Cli, + interactive: bool, + output: OutputFormat, +) -> Result { + cli.global + .server + .clone() + .and_then(non_blank) + .or_else(|| match options.mode { + ProfileSetupMode::Init => Some(DEFAULT_INIT_SERVER.to_owned()), + ProfileSetupMode::Add => None, + }) + .map(Ok) + .unwrap_or_else(|| { + if interactive { + prompt_required("Apollo Portal server URL", None, output) + } else { + Err(CliError::invalid_input( + "provide a server with --server when adding a profile non-interactively", + output, + )) + } + }) +} + +fn resolve_setup_operator( + options: &ProfileSetupOptions, + interactive: bool, + output: OutputFormat, +) -> Result, CliError> { + if let Some(operator) = options.operator.clone().and_then(non_blank) { + return Ok(Some(operator)); + } + if matches!(options.mode, ProfileSetupMode::Init) { + return Ok(Some(DEFAULT_INIT_OPERATOR.to_owned())); + } + if interactive { + prompt_optional("Default operator", output) + } else { + Ok(None) + } +} + +fn resolve_setup_token( + options: &ProfileSetupOptions, + interactive: bool, + output: OutputFormat, +) -> Result, CliError> { + if options.token_stdin { + return credential::token_from_env_or_stdin(true, output).map(Some); + } + if interactive && prompt_yes_no("Store a Consumer token now?", false, output)? { + credential::prompt_token(output).map(Some) + } else { + Ok(None) + } +} + +fn store_setup_token( + config_path: &std::path::Path, + profile: &str, + token: &Sensitive, + store_token_in_file: bool, + interactive: bool, + output: OutputFormat, +) -> Result { + if store_token_in_file { + return credential::store_file(config_path, profile, token) + .map_err(|error| CliError::credential_store_unavailable(&error, output)); + } + + match credential::store_native(profile, token) { + Ok(credential) => Ok(credential), + Err(error) => { + if interactive + && prompt_yes_no( + "Native credential storage is unavailable. Store token in a local file instead?", + false, + output, + )? + { + credential::store_file(config_path, profile, token) + .map_err(|error| CliError::credential_store_unavailable(&error, output)) + } else { + Err(CliError::confirmation_required( + &format!( + "Native credential storage is unavailable: {}. Re-run with --store-token-in-file to use the explicit file fallback.", + error + ), + output, + )) + } + } + } +} + +fn is_interactive_terminal() -> bool { + io::stdin().is_terminal() && io::stderr().is_terminal() +} + +fn prompt_required( + label: &str, + default: Option<&str>, + output: OutputFormat, +) -> Result { + loop { + let value = prompt_line(label, default, output)?; + if !value.trim().is_empty() { + return Ok(value.trim().to_owned()); + } + eprintln!("{} is required.", label); + } +} + +fn prompt_optional(label: &str, output: OutputFormat) -> Result, CliError> { + let value = prompt_line(label, None, output)?; + let value = value.trim().to_owned(); + Ok((!value.is_empty()).then_some(value)) +} + +fn prompt_yes_no(label: &str, default: bool, output: OutputFormat) -> Result { + let suffix = if default { "[Y/n]" } else { "[y/N]" }; + loop { + eprint!("{} {} ", label, suffix); + io::stderr() + .flush() + .map_err(|error| CliError::invalid_input(&error.to_string(), output))?; + let line = read_prompt_line(&mut io::stdin().lock(), output)?; + let value = line.trim().to_ascii_lowercase(); + if value.is_empty() { + return Ok(default); + } + match value.as_str() { + "y" | "yes" => return Ok(true), + "n" | "no" => return Ok(false), + _ => eprintln!("Please answer y or n."), + } + } +} + +fn prompt_line( + label: &str, + default: Option<&str>, + output: OutputFormat, +) -> Result { + if let Some(default) = default { + eprint!("{} [{}]: ", label, default); + } else { + eprint!("{}: ", label); + } + io::stderr() + .flush() + .map_err(|error| CliError::invalid_input(&error.to_string(), output))?; + + let line = read_prompt_line(&mut io::stdin().lock(), output)?; + let value = line.trim(); + if value.is_empty() { + Ok(default.unwrap_or_default().to_owned()) + } else { + Ok(value.to_owned()) + } +} + +fn read_prompt_line(reader: &mut R, output: OutputFormat) -> Result { + let mut line = String::new(); + let bytes_read = reader + .read_line(&mut line) + .map_err(|error| CliError::invalid_input(&error.to_string(), output))?; + if bytes_read == 0 { + return Err(CliError::invalid_input("input aborted", output)); + } + Ok(line) +} + +#[derive(Serialize)] +struct ProfileListResponse { + #[serde(rename = "activeProfile")] + active_profile: Option, + #[serde(rename = "configPath")] + config_path: String, + profiles: Vec, +} + +impl ProfileListResponse { + fn from_loaded_config(loaded: &LoadedConfig) -> Self { + let active_profile = loaded.config.active_profile.clone(); + let profiles = loaded + .config + .profiles + .iter() + .map(|(name, profile)| ProfileSummaryRow::from_profile(name, profile, &active_profile)) + .collect(); + + Self { + active_profile, + config_path: loaded.path.display().to_string(), + profiles, + } + } + + fn render_table(&self) -> String { + if self.profiles.is_empty() { + return format!("No profiles configured.\nConfig path: {}", self.config_path); + } + + let mut lines = vec![format!("Config path: {}", self.config_path)]; + for profile in &self.profiles { + let marker = if profile.active { "*" } else { "-" }; + let output = profile.output.as_deref().unwrap_or("table"); + lines.push(format!( + "{} {} {} {}", + marker, profile.name, profile.server, output + )); + } + lines.join("\n") + } +} + +#[derive(Serialize)] +struct ProfileSummaryRow { + active: bool, + name: String, + server: String, + #[serde(skip_serializing_if = "Option::is_none")] + output: Option, + #[serde(skip_serializing_if = "Option::is_none")] + operator: Option, + #[serde(skip_serializing_if = "Option::is_none")] + credential: Option, +} + +impl ProfileSummaryRow { + fn from_profile(name: &str, profile: &ProfileConfig, active_profile: &Option) -> Self { + Self { + active: active_profile.as_deref() == Some(name), + name: name.to_owned(), + server: profile + .server + .clone() + .unwrap_or_else(|| "".to_owned()), + output: profile.output.map(|output| output.to_string()), + operator: profile.operator.clone(), + credential: profile.credential.clone(), + } + } +} + +#[derive(Serialize)] +struct ProfileShowResponse { + #[serde(rename = "activeProfile")] + active_profile: Option, + #[serde(rename = "configPath")] + config_path: String, + context: RuntimeContextRow, +} + +impl ProfileShowResponse { + fn from_context(loaded: &LoadedConfig, context: RuntimeContext) -> Self { + Self { + active_profile: loaded.config.active_profile.clone(), + config_path: loaded.path.display().to_string(), + context: RuntimeContextRow::from_runtime_context(context), + } + } + + fn render_table(&self) -> String { + let mut lines = vec![format!("Config path: {}", self.config_path)]; + if let Some(active_profile) = &self.active_profile { + lines.push(format!("Active profile: {}", active_profile)); + } + lines.push(format!( + "Resolved profile: {}", + self.context.profile.as_deref().unwrap_or("") + )); + lines.push(format!( + "Server: {}", + self.context.server.as_deref().unwrap_or("") + )); + lines.push(format!("Output: {}", self.context.output)); + if let Some(operator) = &self.context.operator { + lines.push(format!("Operator: {}", operator)); + } + if let Some(credential) = &self.context.credential { + lines.push(format!("Credential backend: {}", credential.backend)); + lines.push(format!("Credential key: {}", credential.key)); + } + lines.join("\n") + } +} + +#[derive(Serialize)] +struct RuntimeContextRow { + #[serde(skip_serializing_if = "Option::is_none")] + profile: Option, + #[serde(skip_serializing_if = "Option::is_none")] + server: Option, + output: String, + #[serde(skip_serializing_if = "Option::is_none")] + operator: Option, + #[serde(skip_serializing_if = "Option::is_none")] + credential: Option, +} + +impl RuntimeContextRow { + fn from_runtime_context(context: RuntimeContext) -> Self { + Self { + profile: context.profile, + server: context.server, + output: context.output.to_string(), + operator: context.operator, + credential: context.credential, + } + } +} + +#[derive(Serialize)] +struct ProfileUseResponse { + #[serde(rename = "activeProfile")] + active_profile: String, + #[serde(rename = "configPath")] + config_path: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ProfileSetupResponse { + profile: String, + active_profile: Option, + server: String, + output: String, + #[serde(skip_serializing_if = "Option::is_none")] + operator: Option, + #[serde(skip_serializing_if = "Option::is_none")] + credential: Option, + config_path: String, + next_steps: Vec, +} + +impl ProfileSetupResponse { + fn render_table(&self) -> String { + let mut lines = vec![ + format!("Profile '{}' configured.", self.profile), + format!("Config path: {}", self.config_path), + format!("Server: {}", self.server), + format!("Output: {}", self.output), + ]; + if self.active_profile.as_deref() == Some(self.profile.as_str()) { + lines.push("Active profile: yes".to_owned()); + } + if let Some(operator) = &self.operator { + lines.push(format!("Operator: {}", operator)); + } + if let Some(credential) = &self.credential { + lines.push(format!("Credential backend: {}", credential.backend)); + lines.push(format!("Credential key: {}", credential.key)); + } else { + lines.push("Credential: not configured".to_owned()); + lines.push( + "Run `apollo auth login --token-stdin` when you have a Consumer token.".to_owned(), + ); + } + if !self.next_steps.is_empty() { + lines.push("Next steps:".to_owned()); + lines.extend(self.next_steps.iter().map(|step| format!(" {}", step))); + } + lines.join("\n") + } +} + +#[derive(Serialize)] +struct AuthStatusResponse { + authenticated: bool, + source: String, + #[serde(skip_serializing_if = "Option::is_none")] + profile: Option, + #[serde(skip_serializing_if = "Option::is_none")] + backend: Option, + #[serde(skip_serializing_if = "Option::is_none")] + key: Option, +} + +impl AuthStatusResponse { + fn render_table(&self) -> String { + let state = if self.authenticated { + "authenticated" + } else { + "not authenticated" + }; + format!( + "Profile: {}\nStatus: {}\nSource: {}", + self.profile.as_deref().unwrap_or(""), + state, + self.source + ) + } +} + +#[derive(Serialize)] +struct AuthLoginResponse { + stored: bool, + profile: String, + backend: String, + key: String, +} + +impl AuthLoginResponse { + fn render_table(&self) -> String { + format!( + "Credential stored for profile '{}'.\nBackend: {}\nKey: {}", + self.profile, self.backend, self.key + ) + } +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use crate::cli::OutputFormat; + + #[test] + fn read_prompt_line_reports_eof_as_aborted_input() { + let mut reader = Cursor::new(Vec::::new()); + let error = + super::read_prompt_line(&mut reader, OutputFormat::Json).expect_err("EOF should fail"); + + assert_eq!(error.exit_code(), 1); + } +} + +#[derive(Serialize)] +struct AuthLogoutResponse { + #[serde(rename = "loggedOut")] + logged_out: bool, + profile: String, + backend: String, + key: String, + #[serde(rename = "environmentCredentialStillActive")] + environment_token_still_active: bool, + #[serde(skip_serializing_if = "Option::is_none")] + message: Option, +} + +impl AuthLogoutResponse { + fn render_table(&self) -> String { + let mut body = format!( + "Credential removed for profile '{}'.\nBackend: {}\nKey: {}", + self.profile, self.backend, self.key + ); + if let Some(message) = &self.message { + body.push('\n'); + body.push_str(message); + } + body + } +} + +fn required_profile(context: &RuntimeContext, output: OutputFormat) -> Result { + context.profile.clone().ok_or_else(|| { + CliError::invalid_input("select a profile with --profile or active_profile", output) + }) +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..340cba7 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,349 @@ +use std::collections::{BTreeMap, HashMap}; +use std::env; +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::cli::{Cli, OutputFormat}; +use crate::error::CliError; + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct AppConfig { + pub active_profile: Option, + #[serde(default)] + pub profiles: BTreeMap, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct ProfileConfig { + pub server: Option, + pub output: Option, + pub operator: Option, + pub credential: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CredentialRef { + pub backend: String, + pub key: String, +} + +#[derive(Clone, Debug)] +pub struct LoadedConfig { + pub path: PathBuf, + pub config: AppConfig, +} + +#[derive(Clone, Debug)] +pub struct RuntimeContext { + pub profile: Option, + pub server: Option, + pub output: OutputFormat, + pub operator: Option, + pub credential: Option, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +enum Platform { + MacOs, + Linux, + Windows, +} + +impl Platform { + fn current() -> Self { + if cfg!(target_os = "macos") { + Self::MacOs + } else if cfg!(target_os = "windows") { + Self::Windows + } else { + Self::Linux + } + } +} + +pub fn load_config(format: OutputFormat) -> Result { + let path = config_path(format)?; + if !path.exists() { + return Ok(LoadedConfig { + path, + config: AppConfig::default(), + }); + } + + let body = fs::read_to_string(&path) + .map_err(|error| CliError::invalid_config(&path, &error.to_string(), format))?; + let config: AppConfig = toml::from_str(&body) + .map_err(|error| CliError::invalid_config(&path, &error.to_string(), format))?; + + Ok(LoadedConfig { path, config }) +} + +pub fn save_config(path: &Path, config: &AppConfig, format: OutputFormat) -> Result<(), CliError> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .map_err(|error| CliError::invalid_config(path, &error.to_string(), format))?; + } + + let body = toml::to_string_pretty(config) + .map_err(|error| CliError::invalid_config(path, &error.to_string(), format))?; + fs::write(path, body) + .map_err(|error| CliError::invalid_config(path, &error.to_string(), format))?; + Ok(()) +} + +pub fn resolve_context( + cli: &Cli, + loaded: &LoadedConfig, + format: OutputFormat, +) -> Result { + let (selected_profile, profile_config) = selected_profile_and_config(cli, loaded, format)?; + let output = resolve_output(cli, loaded, format)?; + + Ok(RuntimeContext { + profile: selected_profile, + server: cli + .global + .server + .clone() + .and_then(non_blank) + .or_else(|| env_var_non_blank("APOLLO_SERVER")) + .or_else(|| { + profile_config + .as_ref() + .and_then(|profile| profile.server.clone().and_then(non_blank)) + }), + output, + operator: profile_config + .as_ref() + .and_then(|profile| profile.operator.clone().and_then(non_blank)), + credential: profile_config.and_then(|profile| profile.credential), + }) +} + +pub fn resolve_output( + cli: &Cli, + loaded: &LoadedConfig, + format: OutputFormat, +) -> Result { + let (_, profile_config) = selected_profile_and_config(cli, loaded, format)?; + + Ok(cli + .global + .output + .or_else(read_env_output) + .or_else(|| profile_config.as_ref().and_then(|profile| profile.output)) + .unwrap_or(OutputFormat::Table)) +} + +fn config_path(format: OutputFormat) -> Result { + let vars = collect_env_vars(); + config_path_for_platform(Platform::current(), &vars) + .map_err(|message| CliError::missing_config_base(&message, format)) +} + +fn config_path_for_platform( + platform: Platform, + vars: &HashMap, +) -> Result { + let home = || { + vars.get("HOME") + .filter(|value| !value.is_empty()) + .cloned() + .map(PathBuf::from) + .ok_or_else(|| "HOME is not set".to_owned()) + }; + + match platform { + Platform::MacOs => Ok(home()? + .join("Library") + .join("Application Support") + .join("apollo") + .join("config.toml")), + Platform::Linux => { + if let Some(xdg_config_home) = vars + .get("XDG_CONFIG_HOME") + .filter(|value| !value.is_empty()) + .cloned() + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + { + Ok(xdg_config_home.join("apollo").join("config.toml")) + } else { + Ok(home()?.join(".config").join("apollo").join("config.toml")) + } + } + Platform::Windows => vars + .get("APPDATA") + .filter(|value| !value.is_empty()) + .cloned() + .map(PathBuf::from) + .ok_or_else(|| "APPDATA is not set".to_owned()) + .map(|path| path.join("apollo").join("config.toml")), + } +} + +fn collect_env_vars() -> HashMap { + env::vars_os() + .filter_map(|(key, value)| key.into_string().ok().map(|key| (key, value))) + .collect() +} + +pub(crate) fn read_env_output() -> Option { + env::var("APOLLO_OUTPUT") + .ok() + .and_then(|value| OutputFormat::parse(&value)) +} + +fn selected_profile_and_config( + cli: &Cli, + loaded: &LoadedConfig, + format: OutputFormat, +) -> Result<(Option, Option), CliError> { + let selected_profile = cli + .global + .profile + .clone() + .and_then(non_blank) + .or_else(|| env_var_non_blank("APOLLO_PROFILE")) + .or_else(|| loaded.config.active_profile.clone().and_then(non_blank)); + + let profile_config = match &selected_profile { + Some(profile_name) => Some( + loaded + .config + .profiles + .get(profile_name) + .cloned() + .ok_or_else(|| CliError::profile_not_found(profile_name, format))?, + ), + None => None, + }; + + Ok((selected_profile, profile_config)) +} + +fn env_var_non_blank(name: &str) -> Option { + env::var(name).ok().and_then(non_blank) +} + +fn non_blank(value: String) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) +} + +impl OutputFormat { + pub fn parse(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "json" => Some(Self::Json), + "table" => Some(Self::Table), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Json => "json", + Self::Table => "table", + } + } +} + +impl std::fmt::Display for OutputFormat { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.as_str()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::ffi::OsString; + use std::path::PathBuf; + + use super::{Platform, config_path_for_platform}; + + #[test] + fn config_path_uses_macos_convention() { + let vars = HashMap::from([(String::from("HOME"), OsString::from("/Users/tester"))]); + let path = config_path_for_platform(Platform::MacOs, &vars).expect("macos path"); + assert_eq!( + path, + PathBuf::from("/Users/tester/Library/Application Support/apollo/config.toml") + ); + } + + #[test] + fn config_path_uses_linux_xdg_when_present() { + let vars = HashMap::from([( + String::from("XDG_CONFIG_HOME"), + OsString::from("/tmp/config-home"), + )]); + let path = config_path_for_platform(Platform::Linux, &vars).expect("linux xdg path"); + assert_eq!(path, PathBuf::from("/tmp/config-home/apollo/config.toml")); + } + + #[test] + fn config_path_treats_empty_linux_xdg_as_unset() { + let vars = HashMap::from([ + (String::from("HOME"), OsString::from("/home/tester")), + (String::from("XDG_CONFIG_HOME"), OsString::from("")), + ]); + let path = config_path_for_platform(Platform::Linux, &vars).expect("linux xdg path"); + assert_eq!( + path, + PathBuf::from("/home/tester/.config/apollo/config.toml") + ); + } + + #[test] + fn config_path_treats_relative_linux_xdg_as_unset() { + let vars = HashMap::from([ + (String::from("HOME"), OsString::from("/home/tester")), + (String::from("XDG_CONFIG_HOME"), OsString::from(".config")), + ]); + let path = config_path_for_platform(Platform::Linux, &vars).expect("linux xdg path"); + assert_eq!( + path, + PathBuf::from("/home/tester/.config/apollo/config.toml") + ); + } + + #[test] + fn config_path_treats_empty_home_as_unset() { + let vars = HashMap::from([(String::from("HOME"), OsString::from(""))]); + let error = config_path_for_platform(Platform::MacOs, &vars).expect_err("missing home"); + assert_eq!(error, "HOME is not set"); + + let vars = HashMap::from([ + (String::from("HOME"), OsString::from("")), + (String::from("XDG_CONFIG_HOME"), OsString::from("")), + ]); + let error = config_path_for_platform(Platform::Linux, &vars).expect_err("missing home"); + assert_eq!(error, "HOME is not set"); + } + + #[test] + fn config_path_uses_windows_appdata_convention() { + let vars = HashMap::from([( + String::from("APPDATA"), + OsString::from(r"C:\Users\tester\AppData\Roaming"), + )]); + let path = config_path_for_platform(Platform::Windows, &vars).expect("windows path"); + assert_eq!( + path, + PathBuf::from(r"C:\Users\tester\AppData\Roaming") + .join("apollo") + .join("config.toml") + ); + } + + #[test] + fn config_path_treats_empty_windows_appdata_as_unset() { + let vars = HashMap::from([(String::from("APPDATA"), OsString::from(""))]); + let error = config_path_for_platform(Platform::Windows, &vars).expect_err("appdata"); + assert_eq!(error, "APPDATA is not set"); + } +} diff --git a/src/credential.rs b/src/credential.rs new file mode 100644 index 0000000..83f54b8 --- /dev/null +++ b/src/credential.rs @@ -0,0 +1,507 @@ +use std::env; +use std::fs; +use std::io::{BufRead, IsTerminal, Write}; +use std::path::{Path, PathBuf}; + +#[cfg(unix)] +use std::fs::OpenOptions; +#[cfg(unix)] +use std::mem; +#[cfg(unix)] +use std::os::fd::AsRawFd; + +#[cfg(unix)] +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + +use keyring::Entry; + +use crate::config::CredentialRef; +use crate::error::CliError; +use crate::redaction::Sensitive; + +const SERVICE_NAME: &str = "apollo-cli"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum CredentialSource { + Env, + File, + Native, + None, +} + +impl CredentialSource { + pub fn as_str(&self) -> &'static str { + match self { + Self::Env => "env", + Self::File => "file", + Self::Native => "native", + Self::None => "none", + } + } +} + +#[derive(Clone, Debug)] +pub struct CredentialStatus { + pub authenticated: bool, + pub source: CredentialSource, + pub backend: Option, + pub key: Option, +} + +pub trait CredentialStore { + fn get(&self, key: &str) -> Result, String>; + fn set(&self, key: &str, token: &Sensitive) -> Result<(), String>; + fn delete(&self, key: &str) -> Result<(), String>; +} + +pub struct NativeCredentialStore; + +impl CredentialStore for NativeCredentialStore { + fn get(&self, key: &str) -> Result, String> { + if native_disabled_for_tests() { + return Err("native credential store disabled".to_owned()); + } + let entry = Entry::new(SERVICE_NAME, key).map_err(|error| error.to_string())?; + match entry.get_password() { + Ok(token) => Ok(Some(Sensitive::new(token))), + Err(keyring::Error::NoEntry) => Ok(None), + Err(error) => Err(error.to_string()), + } + } + + fn set(&self, key: &str, token: &Sensitive) -> Result<(), String> { + if native_disabled_for_tests() { + return Err("native credential store disabled".to_owned()); + } + let entry = Entry::new(SERVICE_NAME, key).map_err(|error| error.to_string())?; + entry + .set_password(token.expose_secret()) + .map_err(|error| error.to_string()) + } + + fn delete(&self, key: &str) -> Result<(), String> { + if native_disabled_for_tests() { + return Err("native credential store disabled".to_owned()); + } + let entry = Entry::new(SERVICE_NAME, key).map_err(|error| error.to_string())?; + match entry.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(error) => Err(error.to_string()), + } + } +} + +pub struct FileCredentialStore { + base_dir: PathBuf, +} + +impl FileCredentialStore { + pub fn new(config_path: &Path) -> Self { + Self { + base_dir: config_path + .parent() + .unwrap_or_else(|| Path::new(".")) + .join("credentials"), + } + } + + pub fn path_for_key(&self, key: &str) -> Result { + validate_file_credential_key(key)?; + Ok(self.base_dir.join(format!("{}.token", key))) + } +} + +impl CredentialStore for FileCredentialStore { + fn get(&self, key: &str) -> Result, String> { + let path = self.path_for_key(key)?; + if !path.exists() { + return Ok(None); + } + let token = fs::read_to_string(path).map_err(|error| error.to_string())?; + Ok(Some(Sensitive::new(token.trim().to_owned()))) + } + + fn set(&self, key: &str, token: &Sensitive) -> Result<(), String> { + let path = self.path_for_key(key)?; + fs::create_dir_all(&self.base_dir).map_err(|error| error.to_string())?; + write_token_file(&path, token.expose_secret())?; + Ok(()) + } + + fn delete(&self, key: &str) -> Result<(), String> { + let path = self.path_for_key(key)?; + if path.exists() { + fs::remove_file(path).map_err(|error| error.to_string())?; + } + Ok(()) + } +} + +fn validate_file_credential_key(key: &str) -> Result<(), String> { + if key.trim().is_empty() { + return Err("credential key must not be empty".to_owned()); + } + if key.contains('/') || key.contains('\\') { + return Err("credential key must not contain path separators".to_owned()); + } + Ok(()) +} + +#[cfg(unix)] +fn write_token_file(path: &Path, token: &str) -> Result<(), String> { + use std::io::Write as _; + + let mut file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(path) + .map_err(|error| error.to_string())?; + fs::set_permissions(path, fs::Permissions::from_mode(0o600)) + .map_err(|error| error.to_string())?; + file.write_all(token.as_bytes()) + .map_err(|error| error.to_string()) +} + +#[cfg(windows)] +fn write_token_file(_path: &Path, _token: &str) -> Result<(), String> { + Err( + "file credential fallback is not available on Windows because ACL restriction is not implemented; use native credential storage" + .to_owned(), + ) +} + +#[cfg(all(not(unix), not(windows)))] +fn write_token_file(path: &Path, token: &str) -> Result<(), String> { + fs::write(path, token).map_err(|error| error.to_string()) +} + +pub fn status( + config_path: &Path, + profile: &str, + credential: Option<&CredentialRef>, +) -> CredentialStatus { + if env_token().is_some() { + return CredentialStatus { + authenticated: true, + source: CredentialSource::Env, + backend: Some("env".to_owned()), + key: Some("APOLLO_TOKEN".to_owned()), + }; + } + + let credential = credential_for_profile(profile, credential); + let store_result = token_from_store(config_path, &credential); + + CredentialStatus { + authenticated: store_result.ok().flatten().is_some(), + source: source_from_backend(&credential.backend), + backend: Some(credential.backend), + key: Some(credential.key), + } +} + +pub fn resolve_token( + config_path: &Path, + profile: Option<&str>, + credential: Option<&CredentialRef>, +) -> Result, String> { + if let Some(token) = env_token() { + return Ok(Some(token)); + } + + let Some(profile) = profile else { + return Ok(None); + }; + let credential = credential_for_profile(profile, credential); + token_from_store(config_path, &credential) +} + +pub fn store_file( + config_path: &Path, + key: &str, + token: &Sensitive, +) -> Result { + FileCredentialStore::new(config_path).set(key, token)?; + Ok(CredentialRef { + backend: "file".to_owned(), + key: key.to_owned(), + }) +} + +pub fn store_native(key: &str, token: &Sensitive) -> Result { + NativeCredentialStore.set(key, token)?; + Ok(CredentialRef { + backend: "native".to_owned(), + key: key.to_owned(), + }) +} + +pub fn delete(config_path: &Path, credential: &CredentialRef) -> Result<(), String> { + match credential.backend.as_str() { + "file" => FileCredentialStore::new(config_path).delete(&credential.key), + "native" => NativeCredentialStore.delete(&credential.key), + "env" => { + Err("APOLLO_TOKEN is provided by the environment and cannot be removed".to_owned()) + } + _ => Ok(()), + } +} + +pub fn token_from_env_or_stdin( + token_stdin: bool, + format: crate::cli::OutputFormat, +) -> Result { + if token_stdin { + let stdin = std::io::stdin(); + return token_from_reader(stdin.lock(), format); + } + + if let Some(token) = env_token() { + return Ok(token); + } + + if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() { + return prompt_token(format); + } + + Err(CliError::invalid_input( + "provide a token with interactive prompt, --token-stdin, or APOLLO_TOKEN", + format, + )) +} + +pub fn token_from_login_input( + token_stdin: bool, + format: crate::cli::OutputFormat, +) -> Result { + if token_stdin { + let stdin = std::io::stdin(); + return token_from_reader(stdin.lock(), format); + } + + if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() { + return prompt_token(format); + } + + Err(CliError::invalid_input( + "provide a token with interactive prompt or --token-stdin; APOLLO_TOKEN is read-only and is not persisted by auth login", + format, + )) +} + +pub fn prompt_token(format: crate::cli::OutputFormat) -> Result { + let token = prompt_hidden("Consumer token: ", format)?; + token_from_value(token, format) +} + +#[cfg(unix)] +fn prompt_hidden(prompt: &str, format: crate::cli::OutputFormat) -> Result { + let stdin = std::io::stdin(); + let fd = stdin.as_raw_fd(); + let mut stderr = std::io::stderr().lock(); + + stderr + .write_all(prompt.as_bytes()) + .and_then(|()| stderr.flush()) + .map_err(|error| CliError::invalid_input(&error.to_string(), format))?; + + let mut echo_guard = TerminalEchoGuard::disable(fd, format)?; + let mut token = String::new(); + let read_result = stdin.lock().read_line(&mut token); + echo_guard.restore(); + writeln!(stderr).map_err(|error| CliError::invalid_input(&error.to_string(), format))?; + + read_result.map_err(|error| CliError::invalid_input(&error.to_string(), format))?; + Ok(token) +} + +#[cfg(unix)] +struct TerminalEchoGuard { + fd: libc::c_int, + original: libc::termios, + active: bool, +} + +#[cfg(unix)] +impl TerminalEchoGuard { + fn disable(fd: libc::c_int, format: crate::cli::OutputFormat) -> Result { + let original = unsafe { + let mut term = mem::MaybeUninit::::uninit(); + if libc::tcgetattr(fd, term.as_mut_ptr()) != 0 { + return Err(CliError::invalid_input( + &std::io::Error::last_os_error().to_string(), + format, + )); + } + term.assume_init() + }; + let mut hidden = original; + hidden.c_lflag &= !libc::ECHO; + if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &hidden) } != 0 { + return Err(CliError::invalid_input( + &std::io::Error::last_os_error().to_string(), + format, + )); + } + Ok(Self { + fd, + original, + active: true, + }) + } + + fn restore(&mut self) { + if self.active { + unsafe { + libc::tcsetattr(self.fd, libc::TCSANOW, &self.original); + } + self.active = false; + } + } +} + +#[cfg(unix)] +impl Drop for TerminalEchoGuard { + fn drop(&mut self) { + self.restore(); + } +} + +#[cfg(not(unix))] +fn prompt_hidden(prompt: &str, format: crate::cli::OutputFormat) -> Result { + rpassword::prompt_password(prompt) + .map_err(|error| CliError::invalid_input(&error.to_string(), format)) +} + +fn token_from_reader( + mut reader: R, + format: crate::cli::OutputFormat, +) -> Result { + let mut token = String::new(); + reader + .read_line(&mut token) + .map_err(|error| CliError::invalid_input(&error.to_string(), format))?; + token_from_value(token, format) +} + +fn token_from_value( + token: String, + format: crate::cli::OutputFormat, +) -> Result { + let token = token.trim().to_owned(); + if token.is_empty() { + return Err(CliError::invalid_input("token input was empty", format)); + } + Ok(Sensitive::new(token)) +} + +fn source_from_backend(backend: &str) -> CredentialSource { + match backend { + "file" => CredentialSource::File, + "native" => CredentialSource::Native, + _ => CredentialSource::None, + } +} + +fn credential_for_profile(profile: &str, credential: Option<&CredentialRef>) -> CredentialRef { + credential.cloned().unwrap_or_else(|| CredentialRef { + backend: "native".to_owned(), + key: profile.to_owned(), + }) +} + +fn token_from_store( + config_path: &Path, + credential: &CredentialRef, +) -> Result, String> { + match credential.backend.as_str() { + "file" => FileCredentialStore::new(config_path).get(&credential.key), + "native" => NativeCredentialStore.get(&credential.key), + _ => Ok(None), + } +} + +fn env_token() -> Option { + env::var("APOLLO_TOKEN") + .ok() + .map(|token| token.trim().to_owned()) + .filter(|token| !token.is_empty()) + .map(Sensitive::new) +} + +fn native_disabled_for_tests() -> bool { + env::var("APOLLO_CLI_TEST_DISABLE_NATIVE").is_ok() +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::collections::BTreeMap; + use std::io::Cursor; + + use super::CredentialStore; + use crate::cli::OutputFormat; + use crate::redaction::Sensitive; + + #[derive(Default)] + struct InMemoryCredentialStore { + credentials: RefCell>, + } + + impl CredentialStore for InMemoryCredentialStore { + fn get(&self, key: &str) -> Result, String> { + Ok(self + .credentials + .borrow() + .get(key) + .cloned() + .map(Sensitive::new)) + } + + fn set(&self, key: &str, token: &Sensitive) -> Result<(), String> { + self.credentials + .borrow_mut() + .insert(key.to_owned(), token.expose_secret().to_owned()); + Ok(()) + } + + fn delete(&self, key: &str) -> Result<(), String> { + self.credentials.borrow_mut().remove(key); + Ok(()) + } + } + + #[test] + fn in_memory_store_supports_set_get_delete() { + let store = InMemoryCredentialStore::default(); + let token = Sensitive::new("secret-token"); + + store.set("dev", &token).expect("set token"); + let stored = store.get("dev").expect("get token").expect("stored token"); + assert_eq!(stored.expose_secret(), "secret-token"); + + store.delete("dev").expect("delete token"); + assert!(store.get("dev").expect("get after delete").is_none()); + } + + #[test] + fn token_from_reader_accepts_enter_terminated_token() { + let token = super::token_from_reader( + Cursor::new("secret-from-stdin\nignored-second-line\n"), + OutputFormat::Json, + ) + .expect("token"); + + assert_eq!(token.expose_secret(), "secret-from-stdin"); + } + + #[test] + fn token_from_reader_rejects_empty_token() { + let error = super::token_from_reader(Cursor::new("\n"), OutputFormat::Json) + .expect_err("empty token should fail"); + + assert_eq!(error.exit_code(), 1); + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..116504b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,320 @@ +use crate::cli::OutputFormat; +use crate::output::{OutputStream, OutputWriter, RenderedOutput, StructuredError}; + +#[derive(Debug)] +pub enum CliErrorKind { + Parse { + message: String, + }, + InvalidConfig { + path: String, + message: String, + }, + MissingConfigBase { + message: String, + }, + ConfirmationRequired { + message: String, + }, + CredentialStoreUnavailable { + message: String, + }, + InvalidInput { + message: String, + }, + AuthenticationRequired { + message: String, + }, + Network { + path: String, + message: String, + }, + HttpStatus { + status: u16, + path: String, + message: String, + }, + ProfileNotFound { + profile: String, + }, + ProfileAlreadyExists { + profile: String, + command: String, + }, +} + +#[derive(Debug)] +pub struct CliError { + kind: CliErrorKind, + format: OutputFormat, +} + +impl CliError { + pub fn parse(message: String) -> Self { + Self { + kind: CliErrorKind::Parse { message }, + format: OutputFormat::Table, + } + } + + pub fn invalid_config(path: &std::path::Path, message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::InvalidConfig { + path: path.display().to_string(), + message: message.to_owned(), + }, + format, + } + } + + pub fn missing_config_base(message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::MissingConfigBase { + message: message.to_owned(), + }, + format, + } + } + + pub fn profile_not_found(profile: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::ProfileNotFound { + profile: profile.to_owned(), + }, + format, + } + } + + pub fn profile_already_exists(profile: &str, command: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::ProfileAlreadyExists { + profile: profile.to_owned(), + command: command.to_owned(), + }, + format, + } + } + + pub fn confirmation_required(message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::ConfirmationRequired { + message: message.to_owned(), + }, + format, + } + } + + pub fn credential_store_unavailable(message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::CredentialStoreUnavailable { + message: message.to_owned(), + }, + format, + } + } + + pub fn invalid_input(message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::InvalidInput { + message: message.to_owned(), + }, + format, + } + } + + pub fn authentication_required(message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::AuthenticationRequired { + message: message.to_owned(), + }, + format, + } + } + + pub fn network(path: &str, message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::Network { + path: path.to_owned(), + message: message.to_owned(), + }, + format, + } + } + + pub fn http_status(status: u16, path: &str, message: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::HttpStatus { + status, + path: path.to_owned(), + message: message.to_owned(), + }, + format, + } + } + + pub fn exit_code(&self) -> u8 { + match self.kind { + CliErrorKind::Parse { .. } => 2, + CliErrorKind::InvalidConfig { .. } + | CliErrorKind::MissingConfigBase { .. } + | CliErrorKind::ConfirmationRequired { .. } + | CliErrorKind::CredentialStoreUnavailable { .. } + | CliErrorKind::InvalidInput { .. } + | CliErrorKind::AuthenticationRequired { .. } + | CliErrorKind::Network { .. } + | CliErrorKind::HttpStatus { .. } + | CliErrorKind::ProfileNotFound { .. } + | CliErrorKind::ProfileAlreadyExists { .. } => 1, + } + } + + pub fn http_status_code(&self) -> Option { + match self.kind { + CliErrorKind::HttpStatus { status, .. } => Some(status), + _ => None, + } + } + + pub fn render(&self) -> RenderedOutput { + match &self.kind { + CliErrorKind::Parse { message } => RenderedOutput { + stream: OutputStream::Stderr, + body: ensure_trailing_newline(message.clone()), + }, + CliErrorKind::InvalidConfig { path, message } => OutputWriter::new(self.format) + .render_error(&StructuredError { + code: "invalid_config", + category: "invalid_input", + message: format!("Invalid Apollo CLI config at {}: {}", path, message), + command: None, + follow_up_issue: None, + path: Some(path.clone()), + profile: None, + }), + CliErrorKind::MissingConfigBase { message } => OutputWriter::new(self.format) + .render_error(&StructuredError { + code: "missing_config_base", + category: "invalid_input", + message: format!("Cannot resolve Apollo CLI config path: {}", message), + command: None, + follow_up_issue: None, + path: None, + profile: None, + }), + CliErrorKind::ConfirmationRequired { message } => OutputWriter::new(self.format) + .render_error(&StructuredError { + code: "confirmation_required", + category: "confirmation_required", + message: message.clone(), + command: None, + follow_up_issue: Some(5626), + path: None, + profile: None, + }), + CliErrorKind::CredentialStoreUnavailable { message } => OutputWriter::new(self.format) + .render_error(&StructuredError { + code: "credential_store_unavailable", + category: "unsupported_operation", + message: message.clone(), + command: Some("auth".to_owned()), + follow_up_issue: Some(5630), + path: None, + profile: None, + }), + CliErrorKind::InvalidInput { message } => { + OutputWriter::new(self.format).render_error(&StructuredError { + code: "invalid_input", + category: "invalid_input", + message: message.clone(), + command: None, + follow_up_issue: None, + path: None, + profile: None, + }) + } + CliErrorKind::AuthenticationRequired { message } => OutputWriter::new(self.format) + .render_error(&StructuredError { + code: "authentication_failed", + category: "authentication_failed", + message: message.clone(), + command: Some("auth".to_owned()), + follow_up_issue: Some(5630), + path: None, + profile: None, + }), + CliErrorKind::Network { path, message } => { + OutputWriter::new(self.format).render_error(&StructuredError { + code: "network_error", + category: "network", + message: format!("OpenAPI request to {} failed: {}", path, message), + command: None, + follow_up_issue: None, + path: Some(path.clone()), + profile: None, + }) + } + CliErrorKind::HttpStatus { + status, + path, + message, + } => { + let (code, category) = http_status_code_and_category(*status); + OutputWriter::new(self.format).render_error(&StructuredError { + code, + category, + message: format!( + "OpenAPI request to {} returned HTTP {}: {}", + path, status, message + ), + command: None, + follow_up_issue: None, + path: Some(path.clone()), + profile: None, + }) + } + CliErrorKind::ProfileNotFound { profile } => OutputWriter::new(self.format) + .render_error(&StructuredError { + code: "profile_not_found", + category: "not_found", + message: format!("Profile '{}' was not found.", profile), + command: Some("profile".to_owned()), + follow_up_issue: Some(5629), + path: None, + profile: Some(profile.clone()), + }), + CliErrorKind::ProfileAlreadyExists { profile, command } => { + OutputWriter::new(self.format).render_error(&StructuredError { + code: "profile_already_exists", + category: "invalid_input", + message: format!( + "Profile '{}' already exists. Re-run with --overwrite to replace it.", + profile + ), + command: Some(command.clone()), + follow_up_issue: None, + path: None, + profile: Some(profile.clone()), + }) + } + } + } +} + +fn http_status_code_and_category(status: u16) -> (&'static str, &'static str) { + match status { + 401 => ("authentication_failed", "authentication_failed"), + 403 => ("permission_denied", "permission_denied"), + 404 => ("not_found", "not_found"), + 409 => ("conflict", "conflict"), + 412 => ("precondition_failed", "precondition_failed"), + 400..=499 => ("invalid_input", "invalid_input"), + _ => ("server_error", "server"), + } +} + +fn ensure_trailing_newline(mut body: String) -> String { + if !body.ends_with('\n') { + body.push('\n'); + } + body +} diff --git a/src/http.rs b/src/http.rs new file mode 100644 index 0000000..6ed22bc --- /dev/null +++ b/src/http.rs @@ -0,0 +1,213 @@ +use serde::{Serialize, Serializer, ser::SerializeStruct}; +use serde_json::Value; +use std::fmt; +use std::time::Duration; + +use crate::cli::OutputFormat; +use crate::error::CliError; +use crate::redaction::{Redactor, Sensitive}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_ERROR_BODY_CHARS: usize = 4096; + +#[derive(Clone)] +pub struct OpenApiResponse { + pub status: u16, + pub data: Value, + redaction_token: Sensitive, +} + +impl OpenApiResponse { + pub fn render_table(&self) -> String { + serde_json::to_string_pretty(&self.redacted_data()).expect("openapi response table json") + } + + fn redacted_data(&self) -> Value { + redact_exact_token_value(self.data.clone(), self.redaction_token.expose_secret()) + } +} + +impl fmt::Debug for OpenApiResponse { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("OpenApiResponse") + .field("status", &self.status) + .field("data", &self.redacted_data()) + .finish() + } +} + +impl Serialize for OpenApiResponse { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut state = serializer.serialize_struct("OpenApiResponse", 2)?; + state.serialize_field("status", &self.status)?; + state.serialize_field("data", &self.redacted_data())?; + state.end() + } +} + +pub struct OpenApiClient { + server: String, + token: Sensitive, + format: OutputFormat, + client: reqwest::blocking::Client, +} + +impl OpenApiClient { + pub fn new(server: String, token: Sensitive, format: OutputFormat) -> Self { + Self { + server: server.trim_end_matches('/').to_owned(), + token, + format, + client: reqwest::blocking::Client::new(), + } + } + + pub fn request( + &self, + method: &str, + path: &str, + body: Option, + ) -> Result { + let path = normalize_openapi_path(path, self.format)?; + let url = format!("{}{}", self.server, path); + let method = reqwest::Method::from_bytes(method.as_bytes()) + .map_err(|_| CliError::invalid_input("unsupported HTTP method", self.format))?; + let mut request = self + .client + .request(method, &url) + .header(reqwest::header::AUTHORIZATION, self.token.expose_secret()) + .header(reqwest::header::ACCEPT, "application/json"); + if let Some(body) = body { + request = request.json(&body); + } + + let response = request + .timeout(REQUEST_TIMEOUT) + .send() + .map_err(|error| CliError::network(&path, &error.to_string(), self.format))?; + let status = response.status(); + let body = response + .text() + .map_err(|error| CliError::network(&path, &error.to_string(), self.format))?; + + if !status.is_success() { + let body = sanitize_error_body(&body, self.token.expose_secret()); + return Err(CliError::http_status( + status.as_u16(), + &path, + &body, + self.format, + )); + } + + let data = if body.trim().is_empty() { + Value::Null + } else { + serde_json::from_str(&body).unwrap_or(Value::String(body)) + }; + + Ok(OpenApiResponse { + status: status.as_u16(), + data, + redaction_token: self.token.clone(), + }) + } +} + +fn sanitize_error_body(body: &str, token: &str) -> String { + let redactor = Redactor; + let redacted = serde_json::from_str::(body) + .ok() + .map(|value| redactor.redact_json(value).to_string()) + .unwrap_or_else(|| redactor.redact_text(body)); + let redacted = redact_exact_token(redacted, token); + truncate_chars(redacted, MAX_ERROR_BODY_CHARS) +} + +fn redact_exact_token(value: String, token: &str) -> String { + let token = token.trim(); + if token.is_empty() { + value + } else { + value.replace(token, "[REDACTED]") + } +} + +fn redact_exact_token_value(value: Value, token: &str) -> Value { + let token = token.trim(); + if token.is_empty() { + return value; + } + + match value { + Value::String(value) => Value::String(value.replace(token, "[REDACTED]")), + Value::Array(values) => Value::Array( + values + .into_iter() + .map(|value| redact_exact_token_value(value, token)) + .collect(), + ), + Value::Object(map) => Value::Object( + map.into_iter() + .map(|(key, value)| { + ( + key.replace(token, "[REDACTED]"), + redact_exact_token_value(value, token), + ) + }) + .collect(), + ), + value => value, + } +} + +fn truncate_chars(value: String, max_chars: usize) -> String { + let mut chars = value.chars(); + let truncated: String = chars.by_ref().take(max_chars).collect(); + if chars.next().is_some() { + format!("{}...", truncated) + } else { + truncated + } +} + +pub fn encode_path_segment(value: &str) -> String { + urlencoding::encode(value).into_owned() +} + +pub fn append_query(path: String, key: &str, value: &str) -> String { + let separator = if path.contains('?') { '&' } else { '?' }; + format!( + "{}{}{}={}", + path, + separator, + urlencoding::encode(key), + urlencoding::encode(value) + ) +} + +fn normalize_openapi_path(path: &str, format: OutputFormat) -> Result { + if path.starts_with("http://") || path.starts_with("https://") { + return Err(CliError::invalid_input( + "OpenAPI path must be relative, for example /openapi/v1/apps", + format, + )); + } + let path = if path.starts_with('/') { + path.to_owned() + } else { + format!("/{}", path) + }; + if path == "/openapi/v1" || path.starts_with("/openapi/v1/") { + Ok(path) + } else { + Err(CliError::invalid_input( + "OpenAPI path must start with /openapi/v1", + format, + )) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..b7508bd --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,96 @@ +mod cli; +mod command; +mod config; +mod credential; +mod error; +mod http; +mod output; +pub mod redaction; + +use std::ffi::OsString; +use std::process::ExitCode; + +use clap::Parser; + +use crate::cli::Cli; +use crate::command::execute; +use crate::error::CliError; +use crate::output::OutputStream; + +pub fn main_entry(args: I) -> ExitCode +where + I: IntoIterator, + T: Into + Clone, +{ + match run(args) { + Ok(rendered) => { + match rendered.stream { + OutputStream::Stdout => print!("{}", rendered.body), + OutputStream::Stderr => eprint!("{}", rendered.body), + } + ExitCode::SUCCESS + } + Err(error) => { + let rendered = error.render(); + match rendered.stream { + OutputStream::Stdout => print!("{}", rendered.body), + OutputStream::Stderr => eprint!("{}", rendered.body), + } + ExitCode::from(error.exit_code()) + } + } +} + +fn run(args: I) -> Result +where + I: IntoIterator, + T: Into + Clone, +{ + match Cli::try_parse_from(args) { + Ok(cli) => execute(cli), + Err(error) => { + if error.use_stderr() { + Err(CliError::parse(error.to_string())) + } else { + Ok(output::RenderedOutput::stdout(error.to_string())) + } + } + } +} + +#[cfg(test)] +mod tests { + use clap::Parser; + + use crate::cli::{Cli, Commands, OutputFormat, ProfileCommand}; + + #[test] + fn parse_global_flags_before_subcommand() { + let cli = Cli::parse_from([ + "apollo", + "--profile", + "dev", + "--server", + "https://apollo.example.com", + "--output", + "json", + "--yes", + "profile", + "show", + ]); + + assert_eq!(cli.global.profile.as_deref(), Some("dev")); + assert_eq!( + cli.global.server.as_deref(), + Some("https://apollo.example.com") + ); + assert_eq!(cli.global.output, Some(OutputFormat::Json)); + assert!(cli.global.yes); + assert_eq!( + cli.command, + Commands::Profile { + command: ProfileCommand::Show, + } + ); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..726350e --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +use std::process::ExitCode; + +fn main() -> ExitCode { + apollo_cli::main_entry(std::env::args_os()) +} diff --git a/src/output.rs b/src/output.rs new file mode 100644 index 0000000..5a0044a --- /dev/null +++ b/src/output.rs @@ -0,0 +1,103 @@ +use serde::Serialize; +use serde_json::json; + +use crate::cli::OutputFormat; +use crate::redaction::Redactor; + +#[derive(Debug, Eq, PartialEq)] +pub enum OutputStream { + Stdout, + Stderr, +} + +#[derive(Debug, Eq, PartialEq)] +pub struct RenderedOutput { + pub stream: OutputStream, + pub body: String, +} + +impl RenderedOutput { + pub fn stdout(body: String) -> Self { + Self { + stream: OutputStream::Stdout, + body: ensure_trailing_newline(body), + } + } +} + +pub struct OutputWriter { + format: OutputFormat, +} + +impl OutputWriter { + pub fn new(format: OutputFormat) -> Self { + Self { format } + } + + pub fn render_error(&self, error: &StructuredError) -> RenderedOutput { + let redactor = Redactor; + match self.format { + OutputFormat::Json => { + let value = redactor.redact_json(json!({ "error": error })); + RenderedOutput { + stream: OutputStream::Stderr, + body: ensure_trailing_newline( + serde_json::to_string_pretty(&value) + .expect("structured error json serialization"), + ), + } + } + OutputFormat::Table => { + let mut lines = vec![redactor.redact_text(&error.message)]; + if let Some(command) = &error.command { + lines.push(format!("Command: {}", command)); + } + if let Some(issue) = error.follow_up_issue { + lines.push(format!("Follow-up issue: #{}", issue)); + } + RenderedOutput { + stream: OutputStream::Stderr, + body: ensure_trailing_newline(lines.join("\n")), + } + } + } + } + + pub fn render_success(&self, value: &T, table_body: String) -> RenderedOutput { + let redactor = Redactor; + match self.format { + OutputFormat::Json => { + let value = + serde_json::to_value(value).expect("structured success json serialization"); + let value = redactor.redact_json(value); + RenderedOutput::stdout( + serde_json::to_string_pretty(&value) + .expect("structured success json serialization"), + ) + } + OutputFormat::Table => RenderedOutput::stdout(redactor.redact_text(&table_body)), + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct StructuredError { + pub code: &'static str, + pub category: &'static str, + pub message: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub follow_up_issue: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, +} + +fn ensure_trailing_newline(mut body: String) -> String { + if !body.ends_with('\n') { + body.push('\n'); + } + body +} diff --git a/src/redaction.rs b/src/redaction.rs new file mode 100644 index 0000000..28070ed --- /dev/null +++ b/src/redaction.rs @@ -0,0 +1,84 @@ +use std::fmt; +use std::sync::LazyLock; + +use regex::Regex; +use serde_json::{Map, Value}; + +const REDACTED: &str = "[REDACTED]"; + +static AUTHORIZATION_RE: LazyLock = + LazyLock::new(|| Regex::new("(?i)(authorization\\s*:\\s*(?:bearer\\s+)?)[^\\s]+").unwrap()); +static CONSUMER_TOKEN_RE: LazyLock = + LazyLock::new(|| Regex::new("(?i)(consumer\\s+token\\s+)[^\\s]+").unwrap()); +static JSON_SENSITIVE_FIELD_RE: LazyLock = LazyLock::new(|| { + Regex::new("(?i)(\"[^\"]*(?:authorization|token|password|secret)[^\"]*\"\\s*:\\s*\")[^\"]*(\")") + .unwrap() +}); + +#[derive(Default)] +pub struct Redactor; + +impl Redactor { + pub fn redact_text(&self, value: &str) -> String { + let value = AUTHORIZATION_RE.replace_all(value, format!("${{1}}{}", REDACTED)); + let value = CONSUMER_TOKEN_RE + .replace_all(&value, format!("${{1}}{}", REDACTED)) + .to_string(); + JSON_SENSITIVE_FIELD_RE + .replace_all(&value, format!("${{1}}{}${{2}}", REDACTED)) + .to_string() + } + + pub fn redact_json(&self, value: Value) -> Value { + match value { + Value::Object(map) => Value::Object(self.redact_object(map)), + Value::Array(values) => Value::Array( + values + .into_iter() + .map(|value| self.redact_json(value)) + .collect(), + ), + Value::String(value) => Value::String(self.redact_text(&value)), + value => value, + } + } + + fn redact_object(&self, map: Map) -> Map { + map.into_iter() + .map(|(key, value)| { + if is_sensitive_key(&key) { + (key, Value::String(REDACTED.to_owned())) + } else { + (key, self.redact_json(value)) + } + }) + .collect() + } +} + +#[derive(Clone)] +pub struct Sensitive(String); + +impl Sensitive { + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } + + pub fn expose_secret(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for Sensitive { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(REDACTED) + } +} + +fn is_sensitive_key(key: &str) -> bool { + let key = key.to_ascii_lowercase(); + key.contains("token") + || key.contains("authorization") + || key.contains("password") + || key.contains("secret") +} diff --git a/tests/auth.rs b/tests/auth.rs new file mode 100644 index 0000000..9f2f6f7 --- /dev/null +++ b/tests/auth.rs @@ -0,0 +1,519 @@ +use std::fs; +use std::path::PathBuf; + +#[cfg(unix)] +use std::os::unix::fs::PermissionsExt; + +use assert_cmd::Command; +use serde_json::Value; +use tempfile::TempDir; + +#[test] +fn auth_status_uses_apollo_token_without_writing_credentials() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "secret-from-env") + .args(["--output", "json", "auth", "status"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["authenticated"], true); + assert_eq!(json["source"], "env"); + assert_eq!(json["profile"], "dev"); + assert!(!stdout.contains("secret-from-env")); + assert!(!credential_file_path(&home, "dev").exists()); +} + +#[test] +fn auth_status_reports_environment_token_without_profile() { + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "secret-from-env") + .args([ + "--server", + "https://apollo-dev.example.com", + "--output", + "json", + "auth", + "status", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["authenticated"], true); + assert_eq!(json["source"], "env"); + assert_eq!(json["backend"], "env"); + assert_eq!(json["key"], "APOLLO_TOKEN"); + assert!(json["profile"].is_null()); + assert!(!stdout.contains("secret-from-env")); +} + +#[test] +fn auth_status_reports_environment_token_without_config_home() { + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "secret-from-env") + .env_remove("HOME") + .env_remove("XDG_CONFIG_HOME") + .env_remove("APPDATA") + .args(["--output", "json", "auth", "status"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["authenticated"], true); + assert_eq!(json["source"], "env"); + assert_eq!(json["backend"], "env"); + assert_eq!(json["key"], "APOLLO_TOKEN"); + assert!(json["profile"].is_null()); + assert!(!stdout.contains("secret-from-env")); +} + +#[test] +fn auth_status_reports_environment_token_with_stale_active_profile() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "missing" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "secret-from-env") + .args(["--output", "json", "auth", "status"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["authenticated"], true); + assert_eq!(json["source"], "env"); + assert_eq!(json["profile"], "missing"); + assert!(!stdout.contains("secret-from-env")); +} + +#[test] +fn auth_login_file_fallback_requires_explicit_opt_in() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +"#, + ); + + let assert = base_command(&home) + .write_stdin("secret-from-stdin\n") + .args(["--output", "json", "auth", "login", "--token-stdin"]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "confirmation_required"); + assert!(!stderr.contains("secret-from-stdin")); + assert!(!credential_file_path(&home, "dev").exists()); +} + +#[test] +fn auth_login_does_not_persist_apollo_token_from_environment() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "secret-from-env") + .args(["--output", "json", "auth", "login", "--store-token-in-file"]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "invalid_input"); + assert!(stderr.contains("APOLLO_TOKEN is read-only")); + assert!(!stderr.contains("secret-from-env")); + assert!(!credential_file_path(&home, "dev").exists()); +} + +#[test] +fn auth_login_can_store_file_fallback_token_without_printing_it() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +"#, + ); + + let assert = base_command(&home) + .write_stdin("secret-from-stdin\n") + .args([ + "--output", + "json", + "auth", + "login", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["stored"], true); + assert_eq!(json["backend"], "file"); + assert_eq!(json["profile"], "dev"); + assert!(credential_file_path(&home, "dev").exists()); + assert!(!stdout.contains("secret-from-stdin")); + + #[cfg(unix)] + assert_eq!( + fs::metadata(credential_file_path(&home, "dev")) + .expect("credential metadata") + .permissions() + .mode() + & 0o777, + 0o600 + ); + + let config = fs::read_to_string(config_path(&home)).expect("config"); + assert!(config.contains("backend = \"file\"")); + assert!(!config.contains("secret-from-stdin")); +} + +#[cfg(unix)] +#[test] +fn auth_login_tightens_existing_file_credential_permissions() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" + +[profiles.dev.credential] +backend = "file" +key = "dev" +"#, + ); + fs::create_dir_all(credential_file_path(&home, "dev").parent().expect("parent")) + .expect("credential dir"); + fs::write(credential_file_path(&home, "dev"), "old-secret\n").expect("credential file"); + fs::set_permissions( + credential_file_path(&home, "dev"), + fs::Permissions::from_mode(0o644), + ) + .expect("set permissive mode"); + + base_command(&home) + .write_stdin("new-secret\n") + .args([ + "--output", + "json", + "auth", + "login", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .success(); + + assert_eq!( + fs::metadata(credential_file_path(&home, "dev")) + .expect("credential metadata") + .permissions() + .mode() + & 0o777, + 0o600 + ); + assert_eq!( + fs::read_to_string(credential_file_path(&home, "dev")).expect("credential"), + "new-secret" + ); +} + +#[test] +fn auth_status_detects_file_fallback_without_printing_token() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" + +[profiles.dev.credential] +backend = "file" +key = "dev" +"#, + ); + fs::create_dir_all(credential_file_path(&home, "dev").parent().expect("parent")) + .expect("credential dir"); + fs::write(credential_file_path(&home, "dev"), "secret-from-file\n").expect("credential file"); + + let assert = base_command(&home) + .args(["--output", "json", "auth", "status"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["authenticated"], true); + assert_eq!(json["source"], "file"); + assert!(!stdout.contains("secret-from-file")); +} + +#[test] +fn auth_login_rejects_file_credential_keys_with_path_separators() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "../dev" + +[profiles."../dev"] +server = "https://apollo-dev.example.com" +"#, + ); + + let assert = base_command(&home) + .write_stdin("secret-from-stdin\n") + .args([ + "--output", + "json", + "auth", + "login", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "credential_store_unavailable"); + assert!(!stderr.contains("secret-from-stdin")); + assert!( + !config_root(&home) + .join("apollo") + .join("credentials") + .exists() + ); +} + +#[test] +fn auth_login_rejects_missing_profile_before_storing_token() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "missing" +"#, + ); + + let assert = base_command(&home) + .write_stdin("secret-from-stdin\n") + .args([ + "--output", + "json", + "auth", + "login", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "profile_not_found"); + assert!(!stderr.contains("secret-from-stdin")); + assert!( + !config_root(&home) + .join("apollo") + .join("credentials") + .exists() + ); +} + +#[test] +fn auth_logout_removes_file_credential_and_keeps_profile_config() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" + +[profiles.dev.credential] +backend = "file" +key = "dev" +"#, + ); + fs::create_dir_all(credential_file_path(&home, "dev").parent().expect("parent")) + .expect("credential dir"); + fs::write(credential_file_path(&home, "dev"), "secret-from-file\n").expect("credential file"); + + base_command(&home) + .args(["auth", "logout"]) + .assert() + .success(); + + assert!(!credential_file_path(&home, "dev").exists()); + let config = fs::read_to_string(config_path(&home)).expect("config"); + assert!(config.contains("[profiles.dev]")); + assert!(!config.contains("secret-from-file")); +} + +#[test] +fn auth_logout_warns_when_apollo_token_environment_still_applies() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" + +[profiles.dev.credential] +backend = "file" +key = "dev" +"#, + ); + fs::create_dir_all(credential_file_path(&home, "dev").parent().expect("parent")) + .expect("credential dir"); + fs::write(credential_file_path(&home, "dev"), "secret-from-file\n").expect("credential file"); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "secret-from-env") + .args(["--output", "json", "auth", "logout"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["loggedOut"], true); + assert_eq!(json["environmentCredentialStillActive"], true); + assert!( + json["message"] + .as_str() + .expect("message") + .contains("APOLLO_TOKEN") + ); + assert!(!stdout.contains("secret-from-env")); + assert!(!stdout.contains("secret-from-file")); + assert!(!credential_file_path(&home, "dev").exists()); +} + +fn base_command(home: &TempDir) -> Command { + let mut command = Command::cargo_bin("apollo").expect("apollo binary"); + command.env_remove("APOLLO_PROFILE"); + command.env_remove("APOLLO_SERVER"); + command.env_remove("APOLLO_OUTPUT"); + command.env_remove("APOLLO_TOKEN"); + command.env_remove("XDG_CONFIG_HOME"); + command.env_remove("APPDATA"); + command.env("APOLLO_CLI_TEST_DISABLE_NATIVE", "1"); + command.env("HOME", home.path()); + if cfg!(target_os = "linux") { + command.env("XDG_CONFIG_HOME", home.path().join(".config")); + } + if cfg!(target_os = "windows") { + command.env("APPDATA", home.path().join("AppData").join("Roaming")); + } + command +} + +fn temp_home() -> TempDir { + tempfile::tempdir().expect("temp home") +} + +fn config_path(home: &TempDir) -> PathBuf { + config_root(home).join("apollo").join("config.toml") +} + +fn credential_file_path(home: &TempDir, key: &str) -> PathBuf { + config_root(home) + .join("apollo") + .join("credentials") + .join(format!("{}.token", key)) +} + +fn config_root(home: &TempDir) -> PathBuf { + if cfg!(target_os = "macos") { + home.path().join("Library").join("Application Support") + } else if cfg!(target_os = "windows") { + home.path().join("AppData").join("Roaming") + } else { + home.path().join(".config") + } +} + +fn write_config(home: &TempDir, body: &str) { + let config_path = config_path(home); + fs::create_dir_all(config_path.parent().expect("config parent")).expect("create config dir"); + fs::write(config_path, normalize_toml(body)).expect("write config"); +} + +fn normalize_toml(body: &str) -> String { + body.lines() + .map(str::trim_end) + .collect::>() + .join("\n") + .trim() + .to_owned() + + "\n" +} diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..b928f5f --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,154 @@ +use assert_cmd::Command; +use predicates::prelude::predicate; +use serde_json::Value; +use tempfile::TempDir; + +#[test] +fn help_lists_v0_command_groups_and_global_flags() { + Command::cargo_bin("apollo") + .expect("apollo binary") + .arg("--help") + .assert() + .success() + .stdout(predicate::str::contains("init")) + .stdout(predicate::str::contains("auth")) + .stdout(predicate::str::contains("profile")) + .stdout(predicate::str::contains("app")) + .stdout(predicate::str::contains("env")) + .stdout(predicate::str::contains("namespace")) + .stdout(predicate::str::contains("config")) + .stdout(predicate::str::contains("release")) + .stdout(predicate::str::contains("api")) + .stdout(predicate::str::contains("--profile")) + .stdout(predicate::str::contains("--server")) + .stdout(predicate::str::contains("--output")) + .stdout(predicate::str::contains("--yes")); +} + +#[test] +fn openapi_command_without_token_returns_structured_json_error() { + let assert = Command::cargo_bin("apollo") + .expect("apollo binary") + .env_remove("APOLLO_TOKEN") + .args([ + "--server", + "http://127.0.0.1:9", + "--output", + "json", + "app", + "list", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let output = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 output"); + let json: Value = serde_json::from_str(&output).expect("valid json output"); + + assert_eq!(json["error"]["code"], "authentication_failed"); + assert_eq!(json["error"]["category"], "authentication_failed"); + assert_eq!(json["error"]["command"], "auth"); +} + +#[test] +fn global_flags_are_accepted_before_subcommands() { + Command::cargo_bin("apollo") + .expect("apollo binary") + .args([ + "--profile", + "dev", + "--server", + "https://apollo.example.com", + "--output", + "table", + "--yes", + "config", + ]) + .assert() + .failure() + .stderr(predicate::str::contains("config")); +} + +#[test] +fn apollo_output_controls_early_config_errors() { + let home = temp_home(); + write_config(&home, "active_profile = [not valid toml\n"); + + let assert = base_command(&home) + .env("APOLLO_OUTPUT", "json") + .args(["profile", "list"]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "invalid_config"); +} + +#[test] +fn auth_help_lists_v0_auth_commands() { + Command::cargo_bin("apollo") + .expect("apollo binary") + .args(["auth", "--help"]) + .assert() + .success() + .stdout(predicate::str::contains("login")) + .stdout(predicate::str::contains("status")) + .stdout(predicate::str::contains("logout")); +} + +#[test] +fn profile_help_lists_add_command() { + Command::cargo_bin("apollo") + .expect("apollo binary") + .args(["profile", "--help"]) + .assert() + .success() + .stdout(predicate::str::contains("add")) + .stdout(predicate::str::contains("use")); +} + +fn base_command(home: &TempDir) -> Command { + let mut command = Command::cargo_bin("apollo").expect("apollo binary"); + command.env_remove("APOLLO_PROFILE"); + command.env_remove("APOLLO_SERVER"); + command.env_remove("APOLLO_OUTPUT"); + command.env_remove("APOLLO_TOKEN"); + command.env_remove("XDG_CONFIG_HOME"); + command.env_remove("APPDATA"); + command.env("HOME", home.path()); + if cfg!(target_os = "linux") { + command.env("XDG_CONFIG_HOME", home.path().join(".config")); + } + if cfg!(target_os = "windows") { + command.env("APPDATA", home.path().join("AppData").join("Roaming")); + } + command +} + +fn temp_home() -> TempDir { + tempfile::tempdir().expect("temp home") +} + +fn config_path(home: &TempDir) -> std::path::PathBuf { + config_root(home).join("apollo").join("config.toml") +} + +fn config_root(home: &TempDir) -> std::path::PathBuf { + if cfg!(target_os = "macos") { + home.path().join("Library").join("Application Support") + } else if cfg!(target_os = "windows") { + home.path().join("AppData").join("Roaming") + } else { + home.path().join(".config") + } +} + +fn write_config(home: &TempDir, body: &str) { + let config_path = config_path(home); + std::fs::create_dir_all(config_path.parent().expect("config parent")) + .expect("create config dir"); + std::fs::write(config_path, body).expect("write config"); +} diff --git a/tests/openapi.rs b/tests/openapi.rs new file mode 100644 index 0000000..4f2f43a --- /dev/null +++ b/tests/openapi.rs @@ -0,0 +1,1020 @@ +use std::fs; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::path::PathBuf; +use std::sync::mpsc::{self, Receiver}; +use std::thread; +use std::time::Duration; + +use assert_cmd::Command; +use predicates::prelude::predicate; +use serde_json::Value; +use tempfile::TempDir; + +#[test] +fn api_get_calls_openapi_with_consumer_token() { + let server = TestServer::json(r#"[{"appId":"demo"}]"#); + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--server", + &server.url(), + "--output", + "json", + "api", + "get", + "/openapi/v1/apps", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + assert_eq!(json["data"][0]["appId"], "demo"); + assert!(!stdout.contains("consumer-token")); + + let request = server.request(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/openapi/v1/apps"); + assert!( + request + .headers + .iter() + .any(|header| header.eq_ignore_ascii_case("authorization: consumer-token")) + ); +} + +#[test] +fn openapi_env_auth_with_explicit_server_ignores_stale_active_profile() { + let server = TestServer::json(r#"[{"appId":"demo"}]"#); + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "missing" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args(["--server", &server.url(), "--output", "json", "app", "list"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["data"][0]["appId"], "demo"); + assert_eq!(server.request().path, "/openapi/v1/apps"); +} + +#[test] +fn openapi_env_auth_with_explicit_server_does_not_require_config_home() { + let server = TestServer::json(r#"[{"appId":"demo"}]"#); + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .env_remove("HOME") + .env_remove("XDG_CONFIG_HOME") + .env_remove("APPDATA") + .args([ + "--server", + &server.url(), + "--output", + "json", + "api", + "get", + "/openapi/v1/apps", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + assert_eq!(json["data"][0]["appId"], "demo"); + assert_eq!(server.request().path, "/openapi/v1/apps"); +} + +#[test] +fn app_and_env_commands_call_openapi_endpoints() { + let app_server = TestServer::json(r#"[{"appId":"demo"}]"#); + let home = temp_home(); + write_config(&home, &profile_config(&app_server.url())); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args(["--output", "json", "app", "list"]) + .assert() + .success() + .stdout(predicate::str::contains(r#""appId": "demo""#)); + assert_eq!(app_server.request().path, "/openapi/v1/apps"); + + let app_get_server = TestServer::json(r#"{"appId":"demo"}"#); + write_config(&home, &profile_config(&app_get_server.url())); + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args(["--output", "json", "app", "get", "demo"]) + .assert() + .success() + .stdout(predicate::str::contains(r#""appId": "demo""#)); + assert_eq!(app_get_server.request().path, "/openapi/v1/apps/demo"); + + let env_server = TestServer::json(r#"["DEV","FAT"]"#); + write_config(&home, &profile_config(&env_server.url())); + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args(["--output", "json", "env", "list", "--app", "demo"]) + .assert() + .success() + .stdout(predicate::str::contains("DEV")); + assert_eq!( + env_server.request().path, + "/openapi/v1/apps/demo/envclusters" + ); +} + +#[test] +fn namespace_config_and_release_commands_map_to_openapi_paths() { + let namespace_server = TestServer::json(r#"[{"namespaceName":"application"}]"#); + let home = temp_home(); + write_config(&home, &profile_config(&namespace_server.url())); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", + "json", + "namespace", + "list", + "--env", + "DEV", + "--app", + "demo", + ]) + .assert() + .success(); + assert_eq!( + namespace_server.request().path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces" + ); + + let config_server = TestServer::json(r#"{"key":"timeout","value":"3000"}"#); + write_config(&home, &profile_config(&config_server.url())); + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", "json", "config", "get", "--env", "DEV", "--app", "demo", "timeout", + ]) + .assert() + .success(); + assert_eq!( + config_server.request().path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/timeout" + ); + + let config_list_server = TestServer::json(r#"{"content":[],"page":0,"size":20,"total":0}"#); + write_config(&home, &profile_config(&config_list_server.url())); + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", "json", "config", "list", "--env", "DEV", "--app", "demo", + ]) + .assert() + .success(); + assert_eq!( + config_list_server.request().path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items?page=0&size=20" + ); + + let release_server = TestServer::json(r#"[{"id":1,"name":"release-1"}]"#); + write_config(&home, &profile_config(&release_server.url())); + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", "json", "release", "list", "--env", "DEV", "--app", "demo", + ]) + .assert() + .success(); + assert_eq!( + release_server.request().path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/active?page=0&size=20" + ); +} + +#[test] +fn mutating_commands_require_yes_before_network_call() { + let home = temp_home(); + write_config(&home, &profile_config("http://127.0.0.1:9")); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", "json", "config", "set", "--env", "DEV", "--app", "demo", "timeout", "3000", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + assert_eq!(json["error"]["code"], "confirmation_required"); +} + +#[test] +fn mutating_confirmation_uses_profile_output_before_resolving_credentials() { + let home = temp_home(); + write_config( + &home, + &profile_config_with_output("http://127.0.0.1:9", "json"), + ); + + let assert = base_command(&home) + .args([ + "config", "set", "--env", "DEV", "--app", "demo", "timeout", "3000", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + assert_eq!(json["error"]["code"], "confirmation_required"); +} + +#[test] +fn openapi_error_redacts_sensitive_response_body_to_stderr() { + let server = TestServer::new(500, "application/json", r#"{"message":"consumer-token"}"#); + let home = temp_home(); + write_config(&home, &profile_config(&server.url())); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args(["--output", "json", "app", "list"]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "server_error"); + assert!(!stderr.contains("consumer-token")); + assert!(stderr.contains("[REDACTED]")); +} + +#[test] +fn openapi_success_redacts_exact_token_from_response_body() { + let server = TestServer::json(r#"{"message":"consumer-token","consumer-token":"value"}"#); + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--server", + &server.url(), + "--output", + "json", + "api", + "get", + "/openapi/v1/apps", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["data"]["message"], "[REDACTED]"); + assert_eq!(json["data"]["[REDACTED]"], "value"); + assert!(!stdout.contains("consumer-token")); +} + +#[test] +fn config_set_with_yes_sends_update_payload() { + let server = TestServer::empty(); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", "--output", "json", "config", "set", "--env", "DEV", "--app", "demo", + "timeout", "3000", + ]) + .assert() + .success(); + + let request = server.request(); + assert_eq!(request.method, "PUT"); + assert_eq!( + request.path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/timeout?createIfNotExists=true" + ); + let body: Value = serde_json::from_str(&request.body).expect("json body"); + assert_eq!(body["key"], "timeout"); + assert_eq!(body["value"], "3000"); + assert_eq!(body["dataChangeLastModifiedBy"], "apollo-bot"); + assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); + assert!(body.get("comment").is_none()); +} + +#[test] +fn config_set_with_yes_sends_comment_when_provided() { + let server = TestServer::empty(); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "config", + "set", + "--env", + "DEV", + "--app", + "demo", + "--comment", + "update timeout", + "timeout", + "3000", + ]) + .assert() + .success(); + + let request = server.request(); + let body: Value = serde_json::from_str(&request.body).expect("json body"); + assert_eq!(body["comment"], "update timeout"); +} + +#[test] +fn config_item_commands_use_encoded_items_for_path_sensitive_keys() { + let get_server = TestServer::json(r#"{"key":"logging/level","value":"debug"}"#); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&get_server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", + "json", + "config", + "get", + "--env", + "DEV", + "--app", + "demo", + "logging/level", + ]) + .assert() + .success(); + assert_eq!( + get_server.request().path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/encodedItems/bG9nZ2luZy9sZXZlbA" + ); + + let set_server = TestServer::empty(); + write_config( + &home, + &profile_config_with_operator(&set_server.url(), "apollo-bot"), + ); + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "config", + "set", + "--env", + "DEV", + "--app", + "demo", + "logging/level", + "debug", + ]) + .assert() + .success(); + assert_eq!( + set_server.request().path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/encodedItems/bG9nZ2luZy9sZXZlbA?createIfNotExists=true" + ); +} + +#[test] +fn config_set_falls_back_to_create_when_update_reports_missing_item() { + let server = TestServer::sequence(vec![ + (404, "application/json", r#"{"message":"item not found"}"#), + ( + 200, + "application/json", + r#"{"key":"timeout","value":"3000"}"#, + ), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", "--output", "json", "config", "set", "--env", "DEV", "--app", "demo", + "timeout", "3000", + ]) + .assert() + .success() + .stdout(predicate::str::contains(r#""key": "timeout""#)); + + let requests = server.requests(2); + assert_eq!(requests[0].method, "PUT"); + assert_eq!( + requests[0].path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/timeout?createIfNotExists=true" + ); + assert_eq!(requests[1].method, "POST"); + assert_eq!( + requests[1].path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items?operator=apollo-bot" + ); + let body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(body["key"], "timeout"); + assert_eq!(body["value"], "3000"); + assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); +} + +#[test] +fn namespace_create_with_yes_sends_namespace_instance_payload() { + let server = TestServer::sequence(vec![ + (404, "application/json", r#"{"message":"not found"}"#), + (200, "application/json", r#"{"name":"settings.json"}"#), + (200, "application/json", "{}"), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "namespace", + "create", + "--env", + "DEV", + "--app", + "demo", + "settings.json", + ]) + .assert() + .success(); + + let requests = server.requests(3); + assert_eq!(requests[0].method, "GET"); + assert_eq!( + requests[0].path, + "/openapi/v1/apps/demo/appnamespaces/settings.json" + ); + + assert_eq!(requests[1].method, "POST"); + assert_eq!(requests[1].path, "/openapi/v1/apps/demo/appnamespaces"); + let app_namespace_body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(app_namespace_body["appId"], "demo"); + assert_eq!(app_namespace_body["name"], "settings"); + assert_eq!(app_namespace_body["format"], "json"); + assert_eq!(app_namespace_body["isPublic"], false); + assert_eq!(app_namespace_body["dataChangeCreatedBy"], "apollo-bot"); + + assert_eq!(requests[2].method, "POST"); + assert_eq!( + requests[2].path, + "/openapi/v1/namespaces?operator=apollo-bot" + ); + let namespace_body: Value = serde_json::from_str(&requests[2].body).expect("json body"); + assert_eq!(namespace_body[0]["appId"], "demo"); + assert_eq!(namespace_body[0]["env"], "DEV"); + assert_eq!(namespace_body[0]["clusterName"], "default"); + assert_eq!(namespace_body[0]["appNamespaceName"], "settings.json"); +} + +#[test] +fn namespace_create_reuses_existing_appnamespace() { + let server = TestServer::sequence(vec![ + (200, "application/json", r#"{"name":"application"}"#), + (200, "application/json", "{}"), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "namespace", + "create", + "--env", + "DEV", + "--app", + "demo", + "application", + ]) + .assert() + .success(); + + let requests = server.requests(2); + assert_eq!(requests[0].method, "GET"); + assert_eq!( + requests[0].path, + "/openapi/v1/apps/demo/appnamespaces/application" + ); + assert_eq!(requests[1].method, "POST"); + assert_eq!( + requests[1].path, + "/openapi/v1/namespaces?operator=apollo-bot" + ); + let namespace_body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(namespace_body[0]["appNamespaceName"], "application"); +} + +#[test] +fn namespace_create_with_public_flag_sends_public_namespace_payload() { + let server = TestServer::sequence(vec![ + (404, "application/json", r#"{"message":"not found"}"#), + ( + 200, + "application/json", + r#"{"name":"public.application.yml"}"#, + ), + (200, "application/json", "{}"), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "namespace", + "create", + "--env", + "DEV", + "--app", + "demo", + "--public", + "application.yml", + ]) + .assert() + .success(); + + let requests = server.requests(3); + assert_eq!(requests[0].method, "GET"); + assert_eq!( + requests[0].path, + "/openapi/v1/apps/demo/appnamespaces/application.yml" + ); + + assert_eq!(requests[1].method, "POST"); + assert_eq!(requests[1].path, "/openapi/v1/apps/demo/appnamespaces"); + let app_namespace_body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(app_namespace_body["appId"], "demo"); + assert_eq!(app_namespace_body["name"], "application"); + assert_eq!(app_namespace_body["format"], "yml"); + assert_eq!(app_namespace_body["isPublic"], true); + assert_eq!(app_namespace_body["dataChangeCreatedBy"], "apollo-bot"); + + assert_eq!(requests[2].method, "POST"); + assert_eq!( + requests[2].path, + "/openapi/v1/namespaces?operator=apollo-bot" + ); + let namespace_body: Value = serde_json::from_str(&requests[2].body).expect("json body"); + assert_eq!(namespace_body[0]["appId"], "demo"); + assert_eq!(namespace_body[0]["env"], "DEV"); + assert_eq!(namespace_body[0]["clusterName"], "default"); + assert_eq!( + namespace_body[0]["appNamespaceName"], + "public.application.yml" + ); +} + +#[test] +fn config_apply_with_yes_uses_synchronize_endpoint() { + let server = TestServer::sequence(vec![ + ( + 200, + "application/json", + r#"{"content":[{"key":"timeout","value":"3000"}],"page":0,"size":500,"total":1}"#, + ), + (200, "application/json", "{}"), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "config", + "apply", + "--env", + "DEV", + "--app", + "demo", + "--target-env", + "FAT", + ]) + .assert() + .success(); + + let requests = server.requests(2); + assert_eq!(requests[0].method, "GET"); + assert_eq!( + requests[0].path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items?page=0&size=500" + ); + assert_eq!(requests[1].method, "POST"); + assert_eq!( + requests[1].path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/synchronize?operator=apollo-bot" + ); + let body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(body["syncToNamespaces"][0]["appId"], "demo"); + assert_eq!(body["syncToNamespaces"][0]["env"], "FAT"); + assert_eq!(body["syncToNamespaces"][0]["clusterName"], "default"); + assert_eq!(body["syncToNamespaces"][0]["namespaceName"], "application"); + assert_eq!(body["syncItems"][0]["key"], "timeout"); + assert_eq!(body["syncItems"][0]["value"], "3000"); +} + +#[test] +fn config_apply_rejects_cross_namespace_target_before_syncing() { + let server = TestServer::empty(); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--yes", + "--output", + "json", + "config", + "apply", + "--env", + "DEV", + "--app", + "demo", + "--target-env", + "FAT", + "--target-namespace", + "other", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + assert_eq!(json["error"]["code"], "invalid_input"); + assert!(stderr.contains("--target-namespace")); +} + +#[test] +fn config_diff_populates_sync_items_from_source_namespace() { + let server = TestServer::sequence(vec![ + ( + 200, + "application/json", + r#"{"content":[{"key":"timeout","value":"3000"}],"page":0,"size":500,"total":1}"#, + ), + (200, "application/json", "{}"), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", + "json", + "config", + "diff", + "--env", + "DEV", + "--app", + "demo", + "--target-env", + "FAT", + ]) + .assert() + .success(); + + let requests = server.requests(2); + assert_eq!(requests[0].method, "GET"); + assert_eq!( + requests[0].path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items?page=0&size=500" + ); + assert_eq!(requests[1].method, "POST"); + assert_eq!( + requests[1].path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/diff" + ); + let body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(body["syncItems"][0]["key"], "timeout"); + assert_eq!(body["syncItems"][0]["value"], "3000"); +} + +#[test] +fn config_diff_keeps_source_sync_items_unredacted_while_redacting_output() { + let server = TestServer::sequence(vec![ + ( + 200, + "application/json", + r#"{"content":[{"key":"token-value","value":"consumer-token"}],"page":0,"size":500,"total":1}"#, + ), + (200, "application/json", r#"{"message":"consumer-token"}"#), + ]); + let home = temp_home(); + write_config( + &home, + &profile_config_with_operator(&server.url(), "apollo-bot"), + ); + + let assert = base_command(&home) + .env("APOLLO_TOKEN", "consumer-token") + .args([ + "--output", + "json", + "config", + "diff", + "--env", + "DEV", + "--app", + "demo", + "--target-env", + "FAT", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + assert_eq!(json["data"]["message"], "[REDACTED]"); + assert!(!stdout.contains("consumer-token")); + + let requests = server.requests(2); + let body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + assert_eq!(body["syncItems"][0]["key"], "token-value"); + assert_eq!(body["syncItems"][0]["value"], "consumer-token"); +} + +#[derive(Debug)] +struct CapturedRequest { + method: String, + path: String, + headers: Vec, + body: String, +} + +struct TestServer { + addr: SocketAddr, + request_rx: Receiver, +} + +impl TestServer { + fn json(body: &'static str) -> Self { + Self::new(200, "application/json", body) + } + + fn empty() -> Self { + Self::new(200, "application/json", "{}") + } + + fn new(status: u16, content_type: &'static str, body: &'static str) -> Self { + Self::sequence(vec![(status, content_type, body)]) + } + + fn sequence(responses: Vec<(u16, &'static str, &'static str)>) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server"); + let addr = listener.local_addr().expect("local addr"); + let (request_tx, request_rx) = mpsc::channel(); + thread::spawn(move || { + for (status, content_type, body) in responses { + let (stream, _) = listener.accept().expect("accept request"); + let request = read_request(stream, status, content_type, body); + request_tx.send(request).expect("send captured request"); + } + }); + Self { addr, request_rx } + } + + fn url(&self) -> String { + format!("http://{}", self.addr) + } + + fn request(self) -> CapturedRequest { + self.request_rx + .recv_timeout(Duration::from_secs(5)) + .expect("timed out waiting for captured request") + } + + fn requests(self, count: usize) -> Vec { + (0..count) + .map(|_| { + self.request_rx + .recv_timeout(Duration::from_secs(5)) + .expect("timed out waiting for captured request") + }) + .collect() + } +} + +fn read_request( + mut stream: TcpStream, + status: u16, + content_type: &str, + response_body: &str, +) -> CapturedRequest { + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 1024]; + loop { + let read = stream.read(&mut chunk).expect("read request"); + if read == 0 { + break; + } + buffer.extend_from_slice(&chunk[..read]); + if request_complete(&buffer) { + break; + } + } + + let request = String::from_utf8_lossy(&buffer).to_string(); + let (head, body) = request.split_once("\r\n\r\n").unwrap_or((&request, "")); + let mut lines = head.lines(); + let request_line = lines.next().expect("request line"); + let mut parts = request_line.split_whitespace(); + let method = parts.next().expect("method").to_owned(); + let path = parts.next().expect("path").to_owned(); + let headers = lines.map(ToOwned::to_owned).collect(); + + let response = format!( + "HTTP/1.1 {} OK\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + status, + content_type, + response_body.len(), + response_body + ); + stream + .write_all(response.as_bytes()) + .expect("write response"); + + CapturedRequest { + method, + path, + headers, + body: body.to_owned(), + } +} + +fn request_complete(buffer: &[u8]) -> bool { + let request = String::from_utf8_lossy(buffer); + let Some((head, body)) = request.split_once("\r\n\r\n") else { + return false; + }; + let content_length = head.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok()) + .flatten() + }); + match content_length { + Some(length) => body.len() >= length, + None => true, + } +} + +fn base_command(home: &TempDir) -> Command { + let mut command = Command::cargo_bin("apollo").expect("apollo binary"); + command.env_remove("APOLLO_PROFILE"); + command.env_remove("APOLLO_SERVER"); + command.env_remove("APOLLO_OUTPUT"); + command.env_remove("APOLLO_TOKEN"); + command.env_remove("XDG_CONFIG_HOME"); + command.env_remove("APPDATA"); + command.env("APOLLO_CLI_TEST_DISABLE_NATIVE", "1"); + command.env("HOME", home.path()); + if cfg!(target_os = "linux") { + command.env("XDG_CONFIG_HOME", home.path().join(".config")); + } + if cfg!(target_os = "windows") { + command.env("APPDATA", home.path().join("AppData").join("Roaming")); + } + command +} + +fn temp_home() -> TempDir { + tempfile::tempdir().expect("temp home") +} + +fn config_path(home: &TempDir) -> PathBuf { + config_root(home).join("apollo").join("config.toml") +} + +fn config_root(home: &TempDir) -> PathBuf { + if cfg!(target_os = "macos") { + home.path().join("Library").join("Application Support") + } else if cfg!(target_os = "windows") { + home.path().join("AppData").join("Roaming") + } else { + home.path().join(".config") + } +} + +fn write_config(home: &TempDir, body: &str) { + let config_path = config_path(home); + fs::create_dir_all(config_path.parent().expect("config parent")).expect("create config dir"); + fs::write(config_path, normalize_toml(body)).expect("write config"); +} + +fn profile_config(server: &str) -> String { + profile_config_with_operator(server, "apollo-bot") +} + +fn profile_config_with_output(server: &str, output: &str) -> String { + format!( + r#" +active_profile = "dev" + +[profiles.dev] +server = "{}" +output = "{}" +operator = "apollo-bot" +"#, + server, output + ) +} + +fn profile_config_with_operator(server: &str, operator: &str) -> String { + format!( + r#" +active_profile = "dev" + +[profiles.dev] +server = "{}" +output = "table" +operator = "{}" +"#, + server, operator + ) +} + +fn normalize_toml(body: &str) -> String { + body.lines() + .map(str::trim_end) + .collect::>() + .join("\n") + .trim() + .to_owned() + + "\n" +} diff --git a/tests/profile.rs b/tests/profile.rs new file mode 100644 index 0000000..5a01dc3 --- /dev/null +++ b/tests/profile.rs @@ -0,0 +1,784 @@ +use std::fs; +use std::path::PathBuf; + +use assert_cmd::Command; +use predicates::prelude::predicate; +use serde_json::Value; +use tempfile::TempDir; + +#[test] +fn profile_show_uses_active_profile_config_and_redacts_unknown_token_fields() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +operator = "dev-operator" +token = "super-secret-token" + +[profiles.dev.credential] +backend = "keychain" +key = "apollo/dev" +"#, + ); + + let assert = base_command(&home) + .args(["--output", "json", "profile", "show"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["context"]["profile"], "dev"); + assert_eq!(json["context"]["server"], "https://apollo-dev.example.com"); + assert_eq!(json["context"]["operator"], "dev-operator"); + assert_eq!(json["context"]["credential"]["backend"], "keychain"); + assert_eq!(json["context"]["credential"]["key"], "apollo/dev"); + assert!(!stdout.contains("super-secret-token")); +} + +#[test] +fn profile_show_prefers_env_over_active_profile_config() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_SERVER", "https://apollo-env.example.com") + .args(["--output", "json", "profile", "show"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["context"]["server"], "https://apollo-env.example.com"); +} + +#[test] +fn profile_show_ignores_blank_environment_overrides() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_PROFILE", "") + .env("APOLLO_SERVER", " ") + .args(["--output", "json", "profile", "show"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["context"]["profile"], "dev"); + assert_eq!(json["context"]["server"], "https://apollo-dev.example.com"); +} + +#[test] +fn profile_show_uses_apollo_output_for_json_rendering() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_OUTPUT", "json") + .args(["profile", "show"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["context"]["profile"], "dev"); + assert_eq!(json["context"]["output"], "json"); +} + +#[test] +fn profile_list_uses_active_profile_output_for_rendering() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "json" +"#, + ); + + let assert = base_command(&home) + .args(["profile", "list"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["activeProfile"], "dev"); + assert_eq!(json["profiles"][0]["name"], "dev"); +} + +#[test] +fn profile_show_prefers_flags_over_environment() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" + +[profiles.prod] +server = "https://apollo-prod.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .env("APOLLO_PROFILE", "dev") + .env("APOLLO_SERVER", "https://apollo-env.example.com") + .args([ + "--profile", + "prod", + "--server", + "https://apollo-flag.example.com", + "--output", + "json", + "profile", + "show", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["context"]["profile"], "prod"); + assert_eq!(json["context"]["server"], "https://apollo-flag.example.com"); +} + +#[test] +fn profile_list_returns_profiles_with_active_marker() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" + +[profiles.prod] +server = "https://apollo-prod.example.com" +output = "json" +"#, + ); + + let assert = base_command(&home) + .args(["--output", "json", "profile", "list"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + let profiles = json["profiles"].as_array().expect("profiles array"); + + assert_eq!(profiles.len(), 2); + assert!( + profiles + .iter() + .any(|profile| profile["name"] == "dev" && profile["active"] == true) + ); + assert!( + profiles + .iter() + .any(|profile| profile["name"] == "prod" && profile["active"] == false) + ); +} + +#[test] +fn profile_list_recovers_when_active_profile_is_stale() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "deleted" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .args(["--output", "json", "profile", "list"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["activeProfile"], "deleted"); + assert_eq!(json["profiles"][0]["name"], "dev"); +} + +#[test] +fn profile_use_updates_active_profile() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" + +[profiles.prod] +server = "https://apollo-prod.example.com" +output = "json" +"#, + ); + + base_command(&home) + .args(["profile", "use", "prod"]) + .assert() + .success(); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("active_profile = \"prod\"")); +} + +#[test] +fn profile_use_honors_active_profile_output_config() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "json" + +[profiles.prod] +server = "https://apollo-prod.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .args(["profile", "use", "prod"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + assert_eq!(json["activeProfile"], "prod"); +} + +#[test] +fn profile_use_recovers_when_active_profile_is_stale() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "deleted" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + base_command(&home) + .args(["profile", "use", "dev"]) + .assert() + .success(); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("active_profile = \"dev\"")); +} + +#[test] +fn profile_use_returns_structured_error_for_unknown_profile() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "table" +"#, + ); + + let assert = base_command(&home) + .args(["--output", "json", "profile", "use", "prod"]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + + assert_eq!(json["error"]["code"], "profile_not_found"); + assert_eq!(json["error"]["profile"], "prod"); +} + +#[test] +fn init_creates_local_profile_and_file_credential_without_printing_token() { + let home = temp_home(); + + let assert = base_command(&home) + .write_stdin("secret-from-stdin\n") + .args([ + "--output", + "json", + "init", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["profile"], "local"); + assert_eq!(json["activeProfile"], "local"); + assert_eq!(json["server"], "http://127.0.0.1:8070"); + assert_eq!(json["credential"]["backend"], "file"); + assert!(!stdout.contains("secret-from-stdin")); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("active_profile = \"local\"")); + assert!(config.contains("[profiles.local]")); + assert!(config.contains("server = \"http://127.0.0.1:8070\"")); + assert!(config.contains("output = \"json\"")); + assert!(config.contains("operator = \"apollo\"")); + assert!(config.contains("backend = \"file\"")); + assert!(!config.contains("secret-from-stdin")); + assert!(credential_file_path(&home, "local").exists()); +} + +#[test] +fn init_with_apollo_output_json_does_not_persist_implicit_output() { + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_OUTPUT", "json") + .write_stdin("secret-from-stdin\n") + .args(["init", "--token-stdin", "--store-token-in-file"]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["activeProfile"], "local"); + assert_eq!(json["output"], "table"); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(!config.contains("output = \"json\"")); +} + +#[test] +fn init_ignores_blank_setup_values_and_uses_defaults() { + let home = temp_home(); + + let assert = base_command(&home) + .env("APOLLO_OUTPUT", "json") + .write_stdin("secret-from-stdin\n") + .args([ + "--profile", + "", + "--server", + "", + "init", + "--name", + "", + "--operator", + "", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["profile"], "local"); + assert_eq!(json["server"], "http://127.0.0.1:8070"); + assert_eq!(json["operator"], "apollo"); + assert_eq!(json["output"], "table"); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("[profiles.local]")); + assert!(config.contains("server = \"http://127.0.0.1:8070\"")); + assert!(config.contains("operator = \"apollo\"")); + assert!(!config.contains("[profiles.\"\"]")); + assert!(!config.contains("output = \"json\"")); +} + +#[test] +fn profile_add_trims_setup_values_before_persisting() { + let home = temp_home(); + + let assert = base_command(&home) + .args([ + "--output", + "json", + "--server", + " https://apollo-dev.example.com/ ", + "profile", + "add", + " dev ", + "--operator", + " alice ", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["profile"], "dev"); + assert_eq!(json["server"], "https://apollo-dev.example.com/"); + assert_eq!(json["operator"], "alice"); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("[profiles.dev]")); + assert!(config.contains("server = \"https://apollo-dev.example.com/\"")); + assert!(config.contains("operator = \"alice\"")); + assert!(!config.contains(" dev ")); + assert!(!config.contains(" alice ")); +} + +#[test] +fn profile_add_creates_profile_without_switching_active_profile() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "local" + +[profiles.local] +server = "http://127.0.0.1:8070" +output = "json" +"#, + ); + + let assert = base_command(&home) + .write_stdin("secret-from-stdin\n") + .args([ + "--server", + "https://apollo-dev.example.com", + "--output", + "json", + "profile", + "add", + "dev", + "--operator", + "dev-operator", + "--token-stdin", + "--store-token-in-file", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + + assert_eq!(json["profile"], "dev"); + assert_eq!(json["activeProfile"], "local"); + assert_eq!(json["server"], "https://apollo-dev.example.com"); + assert_eq!(json["operator"], "dev-operator"); + assert_eq!(json["credential"]["backend"], "file"); + assert!(!stdout.contains("secret-from-stdin")); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("active_profile = \"local\"")); + assert!(config.contains("[profiles.local]")); + assert!(config.contains("[profiles.dev]")); + assert!(config.contains("server = \"https://apollo-dev.example.com\"")); + assert!(config.contains("operator = \"dev-operator\"")); + assert!(!config.contains("secret-from-stdin")); + assert!(credential_file_path(&home, "dev").exists()); +} + +#[test] +fn profile_add_honors_active_profile_output_config() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "local" + +[profiles.local] +server = "http://127.0.0.1:8070" +output = "json" +"#, + ); + + let assert = base_command(&home) + .args([ + "--server", + "https://apollo-prod.example.com", + "profile", + "add", + "prod", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + let json: Value = serde_json::from_str(&stdout).expect("json stdout"); + assert_eq!(json["profile"], "prod"); + assert_eq!(json["activeProfile"], "local"); +} + +#[test] +fn profile_add_with_use_sets_active_profile() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "local" + +[profiles.local] +server = "http://127.0.0.1:8070" +output = "json" +"#, + ); + + base_command(&home) + .args([ + "--server", + "https://apollo-prod.example.com", + "profile", + "add", + "prod", + "--use", + ]) + .assert() + .success(); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("active_profile = \"prod\"")); + assert!(config.contains("[profiles.prod]")); +} + +#[test] +fn profile_add_overwrite_preserves_existing_credential_without_new_token() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-old.example.com" +output = "table" + +[profiles.dev.credential] +backend = "file" +key = "dev" +"#, + ); + fs::create_dir_all(credential_file_path(&home, "dev").parent().expect("parent")) + .expect("credential dir"); + fs::write(credential_file_path(&home, "dev"), "secret-from-file\n").expect("credential file"); + + let assert = base_command(&home) + .args([ + "--server", + "https://apollo-new.example.com", + "profile", + "add", + "dev", + "--overwrite", + ]) + .assert() + .success(); + + let stdout = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 stdout"); + assert!(stdout.contains("Credential backend: file")); + assert!(stdout.contains("Credential key: dev")); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(config.contains("server = \"https://apollo-new.example.com\"")); + assert!(config.contains("backend = \"file\"")); + assert!(config.contains("key = \"dev\"")); + assert!(credential_file_path(&home, "dev").exists()); +} + +#[test] +fn profile_add_refuses_existing_profile_without_overwrite() { + let home = temp_home(); + write_config( + &home, + r#" +active_profile = "dev" + +[profiles.dev] +server = "https://apollo-dev.example.com" +output = "json" +"#, + ); + + base_command(&home) + .args([ + "--output", + "json", + "--server", + "https://apollo-new.example.com", + "profile", + "add", + "dev", + ]) + .assert() + .failure() + .stderr(predicate::str::contains("profile_already_exists")); +} + +#[test] +fn profile_add_rejects_blank_profile_name_non_interactively() { + let home = temp_home(); + + let assert = base_command(&home) + .args([ + "--output", + "json", + "--server", + "https://apollo-dev.example.com", + "profile", + "add", + "", + ]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + assert_eq!(json["error"]["code"], "invalid_input"); + assert!(stderr.contains("provide a profile name")); +} + +#[test] +fn profile_add_rejects_blank_server_non_interactively() { + let home = temp_home(); + + let assert = base_command(&home) + .args(["--output", "json", "--server", "", "profile", "add", "dev"]) + .assert() + .failure(); + + assert!(assert.get_output().stdout.is_empty()); + let stderr = String::from_utf8(assert.get_output().stderr.clone()).expect("utf8 stderr"); + let json: Value = serde_json::from_str(&stderr).expect("json stderr"); + assert_eq!(json["error"]["code"], "invalid_input"); + assert!(stderr.contains("provide a server")); +} + +fn base_command(home: &TempDir) -> Command { + let mut command = Command::cargo_bin("apollo").expect("apollo binary"); + command.env_remove("APOLLO_PROFILE"); + command.env_remove("APOLLO_SERVER"); + command.env_remove("APOLLO_OUTPUT"); + command.env_remove("APOLLO_TOKEN"); + command.env_remove("XDG_CONFIG_HOME"); + command.env_remove("APPDATA"); + command.env("APOLLO_CLI_TEST_DISABLE_NATIVE", "1"); + command.env("HOME", home.path()); + if cfg!(target_os = "linux") { + command.env("XDG_CONFIG_HOME", home.path().join(".config")); + } + if cfg!(target_os = "windows") { + command.env("APPDATA", home.path().join("AppData").join("Roaming")); + } + command +} + +fn temp_home() -> TempDir { + tempfile::tempdir().expect("temp home") +} + +fn config_path(home: &TempDir) -> PathBuf { + config_root(home).join("apollo").join("config.toml") +} + +fn credential_file_path(home: &TempDir, key: &str) -> PathBuf { + config_root(home) + .join("apollo") + .join("credentials") + .join(format!("{}.token", key)) +} + +fn config_root(home: &TempDir) -> PathBuf { + if cfg!(target_os = "macos") { + home.path().join("Library").join("Application Support") + } else if cfg!(target_os = "windows") { + home.path().join("AppData").join("Roaming") + } else { + home.path().join(".config") + } +} + +fn write_config(home: &TempDir, body: &str) { + let config_path = config_path(home); + fs::create_dir_all( + config_path + .parent() + .expect("config path parent should exist"), + ) + .expect("create config dir"); + fs::write(config_path, normalize_toml(body)).expect("write config"); +} + +fn normalize_toml(body: &str) -> String { + body.lines() + .map(str::trim_end) + .collect::>() + .join("\n") + .trim() + .to_owned() + + "\n" +} diff --git a/tests/redaction.rs b/tests/redaction.rs new file mode 100644 index 0000000..dcdcfbe --- /dev/null +++ b/tests/redaction.rs @@ -0,0 +1,48 @@ +use apollo_cli::redaction::{Redactor, Sensitive}; +use serde_json::json; + +#[test] +fn redacts_token_like_text_and_authorization_headers() { + let redactor = Redactor; + + assert_eq!( + redactor.redact_text("Authorization: Bearer secret-token"), + "Authorization: Bearer [REDACTED]" + ); + assert_eq!( + redactor.redact_text("Authorization: secret-token"), + "Authorization: [REDACTED]" + ); + assert_eq!( + redactor.redact_text("consumer token secret-token"), + "consumer token [REDACTED]" + ); + assert_eq!( + redactor.redact_text(r#"{"token":"secret-token","message":"visible"}"#), + r#"{"token":"[REDACTED]","message":"visible"}"# + ); +} + +#[test] +fn redacts_nested_token_like_json_fields() { + let redactor = Redactor; + let redacted = redactor.redact_json(json!({ + "profile": "dev", + "token": "secret-token", + "nested": { + "authorization": "Bearer secret-token", + "value": "visible" + } + })); + + assert_eq!(redacted["profile"], "dev"); + assert_eq!(redacted["token"], "[REDACTED]"); + assert_eq!(redacted["nested"]["authorization"], "[REDACTED]"); + assert_eq!(redacted["nested"]["value"], "visible"); +} + +#[test] +fn debug_output_for_sensitive_values_is_redacted() { + let token = Sensitive::new("secret-token"); + assert_eq!(format!("{:?}", token), "[REDACTED]"); +}