From 67df365ccd5d5277323d5c5d5d85ac76b1541916 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 11:15:22 +0800 Subject: [PATCH 01/18] feat: scaffold Apollo CLI v0 --- .github/workflows/ci.yml | 23 ++ .gitignore | 1 + Cargo.lock | 798 +++++++++++++++++++++++++++++++++++++++ Cargo.toml | 22 ++ LICENSE | 176 +++++++++ README.md | 179 +++++++++ src/cli.rs | 73 ++++ src/command.rs | 363 ++++++++++++++++++ src/config.rs | 285 ++++++++++++++ src/credential.rs | 290 ++++++++++++++ src/error.rs | 221 +++++++++++ src/lib.rs | 95 +++++ src/main.rs | 5 + src/output.rs | 100 +++++ src/redaction.rs | 75 ++++ tests/auth.rs | 230 +++++++++++ tests/cli.rs | 71 ++++ tests/profile.rs | 273 ++++++++++++++ tests/redaction.rs | 40 ++ 19 files changed, 3320 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/cli.rs create mode 100644 src/command.rs create mode 100644 src/config.rs create mode 100644 src/credential.rs create mode 100644 src/error.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/output.rs create mode 100644 src/redaction.rs create mode 100644 tests/auth.rs create mode 100644 tests/cli.rs create mode 100644 tests/profile.rs create mode 100644 tests/redaction.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..71daccc --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + - master + - "codex/**" + +jobs: + rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - 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..ba6903a --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,798 @@ +# 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", +] + +[[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", +] + +[[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", + "clap", + "keyring", + "predicates", + "regex", + "serde", + "serde_json", + "tempfile", + "toml", +] + +[[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 = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[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 = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[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 = "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", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[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 = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "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 = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[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 = "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 = "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 = "log" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" + +[[package]] +name = "memchr" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" + +[[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 = "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 = "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 = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[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 = "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", +] + +[[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 = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[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 = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[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 = "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 = "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 = "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-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 = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[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 = "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 = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[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..cd231bc --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "apollo-cli" +version = "0.1.0" +edition = "2024" + +[[bin]] +name = "apollo" +path = "src/main.rs" + +[dependencies] +clap = { version = "4.5.53", features = ["derive"] } +keyring = "3.6.3" +regex = "1.12.2" +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.150" +toml = "0.9.8" + +[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..3dae8dc --- /dev/null +++ b/README.md @@ -0,0 +1,179 @@ +# 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 +- structured placeholder errors +- output formatting foundation +- non-secret profile configuration +- runtime context resolution +- credential-store abstraction and auth commands +- conservative redaction foundation +- local developer workflow and CI entrypoints + +It does not yet implement Apollo OpenAPI calls or agent-oriented flows. + +## Command groups + +The current scaffold exposes the planned v0 top-level groups: + +- `auth` +- `profile` +- `app` +- `env` +- `namespace` +- `config` +- `release` +- `api` + +## Global flags + +The current scaffold parses these global flags before subcommands: + +- `--profile` +- `--server` +- `--output json|table` +- `--yes` + +## 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. + +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 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 --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. + +## 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` + +## Local development + +Build the CLI: + +```bash +cargo build +``` + +Run the help output: + +```bash +cargo run -- --help +``` + +Run tests: + +```bash +cargo test +``` + +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/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 placeholder errors +- `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..3f7f35b --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,73 @@ +use clap::{Args, Parser, Subcommand, ValueEnum}; +use serde::{Deserialize, Serialize}; + +#[derive(Parser, Debug)] +#[command( + name = "apollo", + bin_name = "apollo", + version, + about = "Apollo CLI v0 scaffold", + long_about = "Standalone Apollo CLI scaffold for v0 command routing, global flags, and structured output/error handling." +)] +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 { + Auth { + #[command(subcommand)] + command: AuthCommand, + }, + Profile { + #[command(subcommand)] + command: ProfileCommand, + }, + App, + Env, + Namespace, + Config, + Release, + Api, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum ProfileCommand { + List, + Show, + Use { name: String }, +} + +#[derive(Clone, Debug, Eq, PartialEq, Subcommand)] +pub enum AuthCommand { + Login { + #[arg(long)] + token_stdin: bool, + #[arg(long)] + store_token_in_file: bool, + }, + Status, + Logout, +} diff --git a/src/command.rs b/src/command.rs new file mode 100644 index 0000000..939c10b --- /dev/null +++ b/src/command.rs @@ -0,0 +1,363 @@ +use serde::Serialize; + +use crate::cli::{AuthCommand, Cli, Commands, OutputFormat, ProfileCommand}; +use crate::config::{ + CredentialRef, LoadedConfig, ProfileConfig, RuntimeContext, load_config, resolve_context, + resolve_output, save_config, +}; +use crate::credential; +use crate::error::CliError; +use crate::output::{OutputWriter, RenderedOutput}; + +pub fn execute(cli: Cli) -> Result { + let output = cli.global.output.unwrap_or(OutputFormat::Table); + + match &cli.command { + Commands::Auth { command } => execute_auth(command.clone(), &cli, output), + Commands::Profile { command } => execute_profile(command.clone(), &cli, output), + Commands::App => Err(CliError::not_implemented("app", None, output)), + Commands::Env => Err(CliError::not_implemented("env", None, output)), + Commands::Namespace => Err(CliError::not_implemented("namespace", None, output)), + Commands::Config => Err(CliError::not_implemented("config", Some(5631), output)), + Commands::Release => Err(CliError::not_implemented("release", None, output)), + Commands::Api => Err(CliError::not_implemented("api", None, output)), + } +} + +fn execute_auth( + command: AuthCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + let loaded = load_config(output)?; + let writer_output = resolve_output(cli, &loaded, output)?; + let writer = OutputWriter::new(writer_output); + + match command { + AuthCommand::Status => { + let context = resolve_context(cli, &loaded, output)?; + let profile = required_profile(&context, 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, + backend: status.backend, + key: status.key, + }; + Ok(writer.render_success(&response, response.render_table())) + } + AuthCommand::Login { + token_stdin, + store_token_in_file, + } => { + let context = resolve_context(cli, &loaded, output)?; + let profile = required_profile(&context, output)?; + let token = credential::token_from_env_or_stdin(token_stdin, writer_output)?; + + let credential_ref = if store_token_in_file { + credential::store_file(&loaded.path, &profile, &token).map_err(|error| { + CliError::credential_store_unavailable(&error, writer_output) + })? + } else { + credential::store_native(&profile, &token).map_err(|error| { + CliError::confirmation_required( + &format!( + "Native credential storage is unavailable: {}. Re-run with --store-token-in-file to use the explicit file fallback.", + error + ), + 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 context = resolve_context(cli, &loaded, output)?; + let profile = required_profile(&context, output)?; + 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 response = AuthLogoutResponse { + logged_out: true, + profile, + backend: credential_ref.backend, + key: credential_ref.key, + }; + Ok(writer.render_success(&response, response.render_table())) + } + } +} + +fn execute_profile( + command: ProfileCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + let loaded = load_config(output)?; + let writer = OutputWriter::new(resolve_output(cli, &loaded, output)?); + + match command { + ProfileCommand::List => { + let response = ProfileListResponse::from_loaded_config(&loaded); + Ok(writer.render_success(&response, response.render_table())) + } + ProfileCommand::Show => { + 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 } => { + if !loaded.config.profiles.contains_key(&name) { + return Err(CliError::profile_not_found(&name, output)); + } + + let mut config = loaded.config.clone(); + config.active_profile = Some(name.clone()); + save_config(&loaded.path, &config, 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(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_default(), + 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)] +struct AuthStatusResponse { + authenticated: bool, + source: String, + profile: String, + #[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, 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 + ) + } +} + +#[derive(Serialize)] +struct AuthLogoutResponse { + #[serde(rename = "loggedOut")] + logged_out: bool, + profile: String, + backend: String, + key: String, +} + +impl AuthLogoutResponse { + fn render_table(&self) -> String { + format!( + "Credential removed for profile '{}'.\nBackend: {}\nKey: {}", + self.profile, self.backend, self.key + ) + } +} + +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..f5f6405 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,285 @@ +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() + .or_else(|| env::var("APOLLO_SERVER").ok()) + .or_else(|| { + profile_config + .as_ref() + .and_then(|profile| profile.server.clone()) + }), + output, + operator: profile_config + .as_ref() + .and_then(|profile| profile.operator.clone()), + 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") + .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").cloned() { + Ok(PathBuf::from(xdg_config_home) + .join("apollo") + .join("config.toml")) + } else { + Ok(home()?.join(".config").join("apollo").join("config.toml")) + } + } + Platform::Windows => vars + .get("APPDATA") + .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() +} + +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() + .or_else(|| env::var("APOLLO_PROFILE").ok()) + .or_else(|| loaded.config.active_profile.clone()); + + 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)) +} + +impl OutputFormat { + pub fn parse(value: &str) -> Option { + match value.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_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") + ); + } +} diff --git a/src/credential.rs b/src/credential.rs new file mode 100644 index 0000000..3c82cb0 --- /dev/null +++ b/src/credential.rs @@ -0,0 +1,290 @@ +use std::env; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +#[cfg(unix)] +use std::os::unix::fs::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) -> PathBuf { + 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> { + fs::create_dir_all(&self.base_dir).map_err(|error| error.to_string())?; + let path = self.path_for_key(key); + fs::write(&path, token.expose_secret()).map_err(|error| error.to_string())?; + #[cfg(unix)] + { + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)) + .map_err(|error| error.to_string())?; + } + 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(()) + } +} + +pub fn status( + config_path: &Path, + profile: &str, + credential: Option<&CredentialRef>, +) -> CredentialStatus { + if env::var("APOLLO_TOKEN") + .map(|token| !token.trim().is_empty()) + .unwrap_or(false) + { + return CredentialStatus { + authenticated: true, + source: CredentialSource::Env, + backend: Some("env".to_owned()), + key: Some("APOLLO_TOKEN".to_owned()), + }; + } + + let credential = credential.cloned().unwrap_or_else(|| CredentialRef { + backend: "native".to_owned(), + key: profile.to_owned(), + }); + + let store_result = match credential.backend.as_str() { + "file" => FileCredentialStore::new(config_path).get(&credential.key), + "native" => NativeCredentialStore.get(&credential.key), + _ => Ok(None), + }; + + CredentialStatus { + authenticated: store_result.ok().flatten().is_some(), + source: source_from_backend(&credential.backend), + backend: Some(credential.backend), + key: Some(credential.key), + } +} + +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 mut token = String::new(); + let mut stdin = std::io::stdin(); + stdin + .read_to_string(&mut token) + .map_err(|error| CliError::invalid_input(&error.to_string(), format))?; + let token = token.trim().to_owned(); + if token.is_empty() { + return Err(CliError::invalid_input("token input was empty", format)); + } + return Ok(Sensitive::new(token)); + } + + env::var("APOLLO_TOKEN") + .ok() + .filter(|token| !token.trim().is_empty()) + .map(Sensitive::new) + .ok_or_else(|| { + CliError::invalid_input("provide a token with --token-stdin or APOLLO_TOKEN", format) + }) +} + +fn source_from_backend(backend: &str) -> CredentialSource { + match backend { + "file" => CredentialSource::File, + "native" => CredentialSource::Native, + _ => CredentialSource::None, + } +} + +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 super::CredentialStore; + 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()); + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..3443791 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,221 @@ +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, + }, + NotImplemented { + command: String, + follow_up_issue: Option, + }, + ProfileNotFound { + profile: 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 not_implemented( + command: &str, + follow_up_issue: Option, + format: OutputFormat, + ) -> Self { + Self { + kind: CliErrorKind::NotImplemented { + command: command.to_owned(), + follow_up_issue, + }, + format, + } + } + + 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 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 exit_code(&self) -> u8 { + match self.kind { + CliErrorKind::Parse { .. } => 2, + CliErrorKind::InvalidConfig { .. } + | CliErrorKind::MissingConfigBase { .. } + | CliErrorKind::ConfirmationRequired { .. } + | CliErrorKind::CredentialStoreUnavailable { .. } + | CliErrorKind::InvalidInput { .. } + | CliErrorKind::NotImplemented { .. } + | CliErrorKind::ProfileNotFound { .. } => 1, + } + } + + pub fn render(&self) -> RenderedOutput { + match &self.kind { + CliErrorKind::Parse { message } => RenderedOutput { + stream: OutputStream::Stderr, + body: ensure_trailing_newline(message.clone()), + }, + CliErrorKind::NotImplemented { + command, + follow_up_issue, + } => OutputWriter::new(self.format).render_error(&StructuredError { + code: "not_implemented", + category: "unsupported_operation", + message: format!( + "The '{}' command group is scaffolded but not implemented yet.", + command + ), + command: Some(command.clone()), + follow_up_issue: *follow_up_issue, + path: None, + profile: None, + }), + 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::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()), + }), + } + } +} + +fn ensure_trailing_newline(mut body: String) -> String { + if !body.ends_with('\n') { + body.push('\n'); + } + body +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..1a93029 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,95 @@ +mod cli; +mod command; +mod config; +mod credential; +mod error; +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..5d2e263 --- /dev/null +++ b/src/output.rs @@ -0,0 +1,100 @@ +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::stdout( + 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..c7cd67c --- /dev/null +++ b/src/redaction.rs @@ -0,0 +1,75 @@ +use std::fmt; + +use regex::Regex; +use serde_json::{Map, Value}; + +const REDACTED: &str = "[REDACTED]"; + +#[derive(Default)] +pub struct Redactor; + +impl Redactor { + pub fn redact_text(&self, value: &str) -> String { + let authorization = Regex::new("(?i)(authorization\\s*:\\s*bearer\\s+)[^\\s]+") + .expect("authorization regex"); + let consumer_token = + Regex::new("(?i)(consumer\\s+token\\s+)[^\\s]+").expect("consumer token regex"); + + let value = authorization.replace_all(value, format!("${{1}}{}", REDACTED)); + consumer_token + .replace_all(&value, format!("${{1}}{}", 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() + } +} + +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..8613e3c --- /dev/null +++ b/tests/auth.rs @@ -0,0 +1,230 @@ +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_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(); + + 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["error"]["code"], "confirmation_required"); + assert!(!stdout.contains("secret-from-stdin")); + 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")); +} + +#[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_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")); +} + +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()); + command +} + +fn temp_home() -> TempDir { + tempfile::tempdir().expect("temp home") +} + +fn config_path(home: &TempDir) -> PathBuf { + home.path() + .join("Library") + .join("Application Support") + .join("apollo") + .join("config.toml") +} + +fn credential_file_path(home: &TempDir, key: &str) -> PathBuf { + home.path() + .join("Library") + .join("Application Support") + .join("apollo") + .join("credentials") + .join(format!("{}.token", key)) +} + +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..7b51c8e --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,71 @@ +use assert_cmd::Command; +use predicates::prelude::predicate; +use serde_json::Value; + +#[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("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 placeholder_command_returns_structured_json_error() { + let assert = Command::cargo_bin("apollo") + .expect("apollo binary") + .args(["--output", "json", "app"]) + .assert() + .failure(); + + let output = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 output"); + let json: Value = serde_json::from_str(&output).expect("valid json output"); + + assert_eq!(json["error"]["code"], "not_implemented"); + assert_eq!(json["error"]["category"], "unsupported_operation"); + assert_eq!(json["error"]["command"], "app"); +} + +#[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 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")); +} diff --git a/tests/profile.rs b/tests/profile.rs new file mode 100644 index 0000000..bf95b2c --- /dev/null +++ b/tests/profile.rs @@ -0,0 +1,273 @@ +use std::fs; +use std::path::PathBuf; + +use assert_cmd::Command; +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_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_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_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_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(); + + 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["error"]["code"], "profile_not_found"); + assert_eq!(json["error"]["profile"], "prod"); +} + +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("XDG_CONFIG_HOME"); + command.env_remove("APPDATA"); + command.env("HOME", home.path()); + command +} + +fn temp_home() -> TempDir { + tempfile::tempdir().expect("temp home") +} + +fn config_path(home: &TempDir) -> PathBuf { + home.path() + .join("Library") + .join("Application Support") + .join("apollo") + .join("config.toml") +} + +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..29e0f46 --- /dev/null +++ b/tests/redaction.rs @@ -0,0 +1,40 @@ +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("consumer token secret-token"), + "consumer token [REDACTED]" + ); +} + +#[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]"); +} From 6c9adeb876b92cba5e4f0103a167459283f2e838 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 11:20:14 +0800 Subject: [PATCH 02/18] test: make auth profile fixtures cross-platform --- tests/auth.rs | 26 ++++++++++++++++++-------- tests/profile.rs | 22 +++++++++++++++++----- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/tests/auth.rs b/tests/auth.rs index 8613e3c..2724d22 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -189,6 +189,12 @@ fn base_command(home: &TempDir) -> Command { 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 } @@ -197,22 +203,26 @@ fn temp_home() -> TempDir { } fn config_path(home: &TempDir) -> PathBuf { - home.path() - .join("Library") - .join("Application Support") - .join("apollo") - .join("config.toml") + config_root(home).join("apollo").join("config.toml") } fn credential_file_path(home: &TempDir, key: &str) -> PathBuf { - home.path() - .join("Library") - .join("Application Support") + 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"); diff --git a/tests/profile.rs b/tests/profile.rs index bf95b2c..03e6ca1 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -236,6 +236,12 @@ fn base_command(home: &TempDir) -> Command { 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 } @@ -244,11 +250,17 @@ fn temp_home() -> TempDir { } fn config_path(home: &TempDir) -> PathBuf { - home.path() - .join("Library") - .join("Application Support") - .join("apollo") - .join("config.toml") + 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) { From 266455ece1f0f35ad07c99b03015069e4065f34d Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 11:39:44 +0800 Subject: [PATCH 03/18] feat: implement Apollo CLI OpenAPI commands --- Cargo.lock | 1223 ++++++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 2 + README.md | 93 +++- src/cli.rs | 202 +++++++- src/command.rs | 384 +++++++++++++- src/credential.rs | 59 ++- src/error.rs | 129 +++-- src/http.rs | 121 +++++ src/lib.rs | 1 + tests/cli.rs | 18 +- tests/openapi.rs | 428 ++++++++++++++++ 11 files changed, 2578 insertions(+), 82 deletions(-) create mode 100644 src/http.rs create mode 100644 tests/openapi.rs diff --git a/Cargo.lock b/Cargo.lock index ba6903a..c6e8079 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,7 +47,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -58,7 +58,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -76,10 +76,12 @@ dependencies = [ "keyring", "predicates", "regex", + "reqwest", "serde", "serde_json", "tempfile", "toml", + "urlencoding", ] [[package]] @@ -97,12 +99,24 @@ dependencies = [ "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" @@ -120,12 +134,40 @@ dependencies = [ "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" @@ -178,6 +220,17 @@ 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" @@ -191,7 +244,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -200,6 +253,12 @@ 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" @@ -215,6 +274,91 @@ 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" @@ -223,7 +367,7 @@ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", "wasip2", "wasip3", ] @@ -249,12 +393,213 @@ 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" @@ -267,6 +612,12 @@ dependencies = [ "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" @@ -279,6 +630,18 @@ 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" @@ -307,18 +670,41 @@ 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" @@ -346,6 +732,36 @@ 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" @@ -395,6 +811,61 @@ 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" @@ -404,12 +875,47 @@ 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" @@ -439,6 +945,66 @@ 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 = "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" @@ -449,14 +1015,61 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] -name = "semver" -version = "1.0.28" +name = "rustls" +version = "0.23.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +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" @@ -510,12 +1123,64 @@ 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" @@ -527,6 +1192,26 @@ dependencies = [ "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" @@ -534,10 +1219,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -546,6 +1231,75 @@ 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" @@ -585,6 +1339,76 @@ 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" @@ -597,6 +1421,36 @@ 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" @@ -612,6 +1466,21 @@ 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" @@ -630,6 +1499,61 @@ 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" @@ -664,12 +1588,59 @@ dependencies = [ "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.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" @@ -679,6 +1650,135 @@ 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" @@ -785,12 +1885,115 @@ dependencies = [ "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" diff --git a/Cargo.toml b/Cargo.toml index cd231bc..b230266 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,9 +11,11 @@ path = "src/main.rs" clap = { version = "4.5.53", features = ["derive"] } keyring = "3.6.3" regex = "1.12.2" +reqwest = { version = "0.12.26", default-features = false, features = ["blocking", "json", "rustls-tls"] } 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" diff --git a/README.md b/README.md index 3dae8dc..447ecb0 100644 --- a/README.md +++ b/README.md @@ -6,19 +6,24 @@ This repository currently covers the first Apollo CLI v0 slices: - top-level v0 command routing - global flag parsing -- structured placeholder errors - 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 -It does not yet implement Apollo OpenAPI calls or agent-oriented flows. +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. -## Command groups +It does not implement generated OpenAPI SDK bindings, agent sessions, MCP, or server-side schema +changes in this slice. -The current scaffold exposes the planned v0 top-level groups: +## Command groups - `auth` - `profile` @@ -29,6 +34,31 @@ The current scaffold exposes the planned v0 top-level groups: - `release` - `api` +Representative v0 commands: + +```bash +apollo app list +apollo app get sample-app +apollo env list +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. + ## Global flags The current scaffold parses these global flags before subcommands: @@ -108,6 +138,22 @@ Native backend selection follows the OS behavior of the underlying credential st 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 +``` + +For interactive use, configure a profile and store the token: + +```bash +printf '%s\n' "$TOKEN" | apollo --profile dev auth login --token-stdin +apollo --profile dev app list +``` + ## 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]`. @@ -132,6 +178,28 @@ Current error categories: - `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/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: @@ -152,6 +220,19 @@ Run tests: 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 +APOLLO_TOKEN="$TOKEN" cargo run -- --server http://localhost:8070 --output json app list +``` + Format the repository: ```bash @@ -171,9 +252,11 @@ cargo clippy --all-targets --all-features -- -D warnings - `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 placeholder errors +- `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 index 3f7f35b..a8a3ce9 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize}; name = "apollo", bin_name = "apollo", version, - about = "Apollo CLI v0 scaffold", - long_about = "Standalone Apollo CLI scaffold for v0 command routing, global flags, and structured output/error handling." + 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)] @@ -45,12 +45,27 @@ pub enum Commands { #[command(subcommand)] command: ProfileCommand, }, - App, - Env, - Namespace, - Config, - Release, - Api, + 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)] @@ -71,3 +86,174 @@ pub enum AuthCommand { 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, +} + +#[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, + }, +} + +#[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 index 939c10b..291713d 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,12 +1,17 @@ use serde::Serialize; +use serde_json::{Value, json}; -use crate::cli::{AuthCommand, Cli, Commands, OutputFormat, ProfileCommand}; +use crate::cli::{ + ApiArgs, AppCommand, AuthCommand, Cli, Commands, ConfigCommand, EnvCommand, NamespaceCommand, + NamespaceScopeArgs, OutputFormat, ProfileCommand, ReleaseCommand, +}; use crate::config::{ CredentialRef, LoadedConfig, ProfileConfig, RuntimeContext, load_config, 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}; pub fn execute(cli: Cli) -> Result { @@ -15,12 +20,12 @@ pub fn execute(cli: Cli) -> Result { match &cli.command { Commands::Auth { command } => execute_auth(command.clone(), &cli, output), Commands::Profile { command } => execute_profile(command.clone(), &cli, output), - Commands::App => Err(CliError::not_implemented("app", None, output)), - Commands::Env => Err(CliError::not_implemented("env", None, output)), - Commands::Namespace => Err(CliError::not_implemented("namespace", None, output)), - Commands::Config => Err(CliError::not_implemented("config", Some(5631), output)), - Commands::Release => Err(CliError::not_implemented("release", None, output)), - Commands::Api => Err(CliError::not_implemented("api", None, 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), } } @@ -150,6 +155,371 @@ fn execute_profile( } } +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 => openapi.request("GET", "/openapi/v1/envs", None), + } +} + +fn execute_namespace( + command: NamespaceCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + 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, + } => { + require_yes(cli, output)?; + let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let path = append_query("/openapi/v1/namespaces".to_owned(), "operator", &operator); + let body = json!([{ + "appId": scope.app, + "env": scope.env, + "clusterName": scope.cluster, + "appNamespaceName": name, + }]); + openapi.request("POST", &path, Some(body)) + } + } +} + +fn execute_config( + command: ConfigCommand, + cli: &Cli, + output: OutputFormat, +) -> Result { + let openapi = openapi_context(cli, output)?; + match command { + ConfigCommand::List { scope, page, size } => { + let mut path = format!("{}/items", namespace_path(&scope)); + if let Some(page) = page { + path = append_query(path, "page", &page.to_string()); + } + if let Some(size) = size { + path = append_query(path, "size", &size.to_string()); + } + openapi.request("GET", &path, None) + } + ConfigCommand::Get { scope, key } => { + let path = format!( + "{}/items/{}", + namespace_path(&scope), + encode_path_segment(&key) + ); + openapi.request("GET", &path, None) + } + ConfigCommand::Set { + scope, + key, + value, + comment, + operator, + } => { + require_yes(cli, output)?; + let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let path = append_query( + format!( + "{}/items/{}", + namespace_path(&scope), + encode_path_segment(&key) + ), + "createIfNotExists", + "true", + ); + let body = json!({ + "key": key, + "value": value, + "comment": comment.unwrap_or_default(), + "dataChangeCreatedBy": operator, + "dataChangeLastModifiedBy": operator, + }); + openapi.request("PUT", &path, Some(body)) + } + ConfigCommand::Delete { + scope, + key, + operator, + } => { + require_yes(cli, output)?; + let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let path = append_query( + format!( + "{}/items/{}", + namespace_path(&scope), + encode_path_segment(&key) + ), + "operator", + &operator, + ); + openapi.request("DELETE", &path, None) + } + ConfigCommand::Diff { + scope, + target_env, + target_cluster, + target_namespace, + } => { + let body = sync_body(&scope, target_env, target_cluster, target_namespace); + let path = format!("{}/items/diff", namespace_path(&scope)); + openapi.request("POST", &path, Some(body)) + } + ConfigCommand::Apply { + scope, + target_env, + target_cluster, + target_namespace, + operator, + } => { + require_yes(cli, output)?; + let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let body = sync_body(&scope, target_env, target_cluster, target_namespace); + 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 { + let openapi = openapi_context(cli, output)?; + match command { + ReleaseCommand::List { scope, page, size } => { + let mut path = format!("{}/releases/active", namespace_path(&scope)); + if let Some(page) = page { + path = append_query(path, "page", &page.to_string()); + } + if let Some(size) = size { + path = append_query(path, "size", &size.to_string()); + } + openapi.request("GET", &path, None) + } + ReleaseCommand::Create { + scope, + title, + comment, + emergency, + operator, + } => { + require_yes(cli, output)?; + let operator = required_operator(operator.as_deref(), &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, + } => { + require_yes(cli, output)?; + let operator = required_operator(operator.as_deref(), &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 { + 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(), output))?, + ), + None => None, + }; + if matches!( + args.method, + crate::cli::HttpMethod::Post + | crate::cli::HttpMethod::Put + | crate::cli::HttpMethod::Patch + | crate::cli::HttpMethod::Delete + ) { + require_yes(cli, output)?; + } + 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 { + let loaded = load_config(output)?; + 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 render_openapi_response(writer: &OutputWriter, response: &OpenApiResponse) -> RenderedOutput { + writer.render_success(response, response.render_table()) +} + +fn required_server(context: &RuntimeContext, output: OutputFormat) -> Result { + context.server.clone().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) + .or_else(|| context.operator.clone()) + .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 sync_body( + scope: &NamespaceScopeArgs, + target_env: String, + target_cluster: String, + target_namespace: Option, +) -> Value { + json!({ + "syncToNamespaces": [{ + "appId": scope.cluster_scope.app.clone(), + "env": target_env, + "clusterName": target_cluster, + "namespaceName": target_namespace.unwrap_or_else(|| scope.namespace.clone()), + }], + }) +} + #[derive(Serialize)] struct ProfileListResponse { #[serde(rename = "activeProfile")] diff --git a/src/credential.rs b/src/credential.rs index 3c82cb0..b90ef15 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -139,10 +139,7 @@ pub fn status( profile: &str, credential: Option<&CredentialRef>, ) -> CredentialStatus { - if env::var("APOLLO_TOKEN") - .map(|token| !token.trim().is_empty()) - .unwrap_or(false) - { + if env_token().is_some() { return CredentialStatus { authenticated: true, source: CredentialSource::Env, @@ -151,16 +148,8 @@ pub fn status( }; } - let credential = credential.cloned().unwrap_or_else(|| CredentialRef { - backend: "native".to_owned(), - key: profile.to_owned(), - }); - - let store_result = match credential.backend.as_str() { - "file" => FileCredentialStore::new(config_path).get(&credential.key), - "native" => NativeCredentialStore.get(&credential.key), - _ => Ok(None), - }; + let credential = credential_for_profile(profile, credential); + let store_result = token_from_store(config_path, &credential); CredentialStatus { authenticated: store_result.ok().flatten().is_some(), @@ -170,6 +159,22 @@ pub fn status( } } +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, @@ -235,6 +240,32 @@ fn source_from_backend(backend: &str) -> CredentialSource { } } +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() } diff --git a/src/error.rs b/src/error.rs index 3443791..12d8394 100644 --- a/src/error.rs +++ b/src/error.rs @@ -22,9 +22,17 @@ pub enum CliErrorKind { InvalidInput { message: String, }, - NotImplemented { - command: String, - follow_up_issue: Option, + AuthenticationRequired { + message: String, + }, + Network { + path: String, + message: String, + }, + HttpStatus { + status: u16, + path: String, + message: String, }, ProfileNotFound { profile: String, @@ -45,20 +53,6 @@ impl CliError { } } - pub fn not_implemented( - command: &str, - follow_up_issue: Option, - format: OutputFormat, - ) -> Self { - Self { - kind: CliErrorKind::NotImplemented { - command: command.to_owned(), - follow_up_issue, - }, - format, - } - } - pub fn invalid_config(path: &std::path::Path, message: &str, format: OutputFormat) -> Self { Self { kind: CliErrorKind::InvalidConfig { @@ -114,6 +108,36 @@ impl CliError { } } + 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, @@ -122,7 +146,9 @@ impl CliError { | CliErrorKind::ConfirmationRequired { .. } | CliErrorKind::CredentialStoreUnavailable { .. } | CliErrorKind::InvalidInput { .. } - | CliErrorKind::NotImplemented { .. } + | CliErrorKind::AuthenticationRequired { .. } + | CliErrorKind::Network { .. } + | CliErrorKind::HttpStatus { .. } | CliErrorKind::ProfileNotFound { .. } => 1, } } @@ -133,21 +159,6 @@ impl CliError { stream: OutputStream::Stderr, body: ensure_trailing_newline(message.clone()), }, - CliErrorKind::NotImplemented { - command, - follow_up_issue, - } => OutputWriter::new(self.format).render_error(&StructuredError { - code: "not_implemented", - category: "unsupported_operation", - message: format!( - "The '{}' command group is scaffolded but not implemented yet.", - command - ), - command: Some(command.clone()), - follow_up_issue: *follow_up_issue, - path: None, - profile: None, - }), CliErrorKind::InvalidConfig { path, message } => OutputWriter::new(self.format) .render_error(&StructuredError { code: "invalid_config", @@ -199,6 +210,46 @@ impl CliError { 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", @@ -213,6 +264,18 @@ impl CliError { } } +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'); diff --git a/src/http.rs b/src/http.rs new file mode 100644 index 0000000..db491ce --- /dev/null +++ b/src/http.rs @@ -0,0 +1,121 @@ +use serde::Serialize; +use serde_json::Value; + +use crate::cli::OutputFormat; +use crate::error::CliError; +use crate::redaction::Sensitive; + +#[derive(Clone, Debug, Serialize)] +pub struct OpenApiResponse { + pub status: u16, + pub data: Value, +} + +impl OpenApiResponse { + pub fn render_table(&self) -> String { + serde_json::to_string_pretty(&self.data).expect("openapi response table json") + } +} + +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 + .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() { + 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, + }) + } +} + +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 index 1a93029..b7508bd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ mod command; mod config; mod credential; mod error; +mod http; mod output; pub mod redaction; diff --git a/tests/cli.rs b/tests/cli.rs index 7b51c8e..558bd60 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -24,19 +24,27 @@ fn help_lists_v0_command_groups_and_global_flags() { } #[test] -fn placeholder_command_returns_structured_json_error() { +fn openapi_command_without_token_returns_structured_json_error() { let assert = Command::cargo_bin("apollo") .expect("apollo binary") - .args(["--output", "json", "app"]) + .env_remove("APOLLO_TOKEN") + .args([ + "--server", + "http://127.0.0.1:9", + "--output", + "json", + "app", + "list", + ]) .assert() .failure(); let output = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 output"); let json: Value = serde_json::from_str(&output).expect("valid json output"); - assert_eq!(json["error"]["code"], "not_implemented"); - assert_eq!(json["error"]["category"], "unsupported_operation"); - assert_eq!(json["error"]["command"], "app"); + assert_eq!(json["error"]["code"], "authentication_failed"); + assert_eq!(json["error"]["category"], "authentication_failed"); + assert_eq!(json["error"]["command"], "auth"); } #[test] diff --git a/tests/openapi.rs b/tests/openapi.rs new file mode 100644 index 0000000..c32350e --- /dev/null +++ b/tests/openapi.rs @@ -0,0 +1,428 @@ +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 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 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 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"]) + .assert() + .success() + .stdout(predicate::str::contains("DEV")); + assert_eq!(env_server.request().path, "/openapi/v1/envs"); +} + +#[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 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" + ); +} + +#[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(); + + 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["error"]["code"], "confirmation_required"); +} + +#[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"); +} + +#[test] +fn namespace_create_with_yes_sends_namespace_instance_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", + "namespace", + "create", + "--env", + "DEV", + "--app", + "demo", + "application", + ]) + .assert() + .success(); + + let request = server.request(); + assert_eq!(request.method, "POST"); + assert_eq!(request.path, "/openapi/v1/namespaces?operator=apollo-bot"); + let body: Value = serde_json::from_str(&request.body).expect("json body"); + assert_eq!(body[0]["appId"], "demo"); + assert_eq!(body[0]["env"], "DEV"); + assert_eq!(body[0]["clusterName"], "default"); + assert_eq!(body[0]["appNamespaceName"], "application"); +} + +#[test] +fn config_apply_with_yes_uses_synchronize_endpoint() { + 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", + "apply", + "--env", + "DEV", + "--app", + "demo", + "--target-env", + "FAT", + ]) + .assert() + .success(); + + let request = server.request(); + assert_eq!(request.method, "POST"); + assert_eq!( + request.path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/synchronize?operator=apollo-bot" + ); + let body: Value = serde_json::from_str(&request.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"); +} + +#[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 { + 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 || { + 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().expect("captured request") + } +} + +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_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" +} From 084f6a9741ed4c11f488a65f5d3f3adce8b91171 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 13:52:55 +0800 Subject: [PATCH 04/18] fix: align OpenAPI commands with Apollo assembly --- src/command.rs | 38 +++++++++++++++--------- src/error.rs | 7 +++++ tests/openapi.rs | 77 +++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 104 insertions(+), 18 deletions(-) diff --git a/src/command.rs b/src/command.rs index 291713d..474d3f1 100644 --- a/src/command.rs +++ b/src/command.rs @@ -14,6 +14,9 @@ use crate::error::CliError; use crate::http::{OpenApiClient, OpenApiResponse, append_query, encode_path_segment}; use crate::output::{OutputWriter, RenderedOutput}; +const DEFAULT_PAGE: u32 = 0; +const DEFAULT_PAGE_SIZE: u32 = 20; + pub fn execute(cli: Cli) -> Result { let output = cli.global.output.unwrap_or(OutputFormat::Table); @@ -229,12 +232,8 @@ fn execute_config( match command { ConfigCommand::List { scope, page, size } => { let mut path = format!("{}/items", namespace_path(&scope)); - if let Some(page) = page { - path = append_query(path, "page", &page.to_string()); - } - if let Some(size) = size { - path = append_query(path, "size", &size.to_string()); - } + 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 } => { @@ -254,7 +253,7 @@ fn execute_config( } => { require_yes(cli, output)?; let operator = required_operator(operator.as_deref(), &openapi.context, output)?; - let path = append_query( + let update_path = append_query( format!( "{}/items/{}", namespace_path(&scope), @@ -263,6 +262,11 @@ fn execute_config( "createIfNotExists", "true", ); + let create_path = append_query( + format!("{}/items", namespace_path(&scope)), + "operator", + &operator, + ); let body = json!({ "key": key, "value": value, @@ -270,7 +274,17 @@ fn execute_config( "dataChangeCreatedBy": operator, "dataChangeLastModifiedBy": operator, }); - openapi.request("PUT", &path, Some(body)) + 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, @@ -329,12 +343,8 @@ fn execute_release( match command { ReleaseCommand::List { scope, page, size } => { let mut path = format!("{}/releases/active", namespace_path(&scope)); - if let Some(page) = page { - path = append_query(path, "page", &page.to_string()); - } - if let Some(size) = size { - path = append_query(path, "size", &size.to_string()); - } + 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 { diff --git a/src/error.rs b/src/error.rs index 12d8394..0336383 100644 --- a/src/error.rs +++ b/src/error.rs @@ -153,6 +153,13 @@ impl CliError { } } + 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 { diff --git a/tests/openapi.rs b/tests/openapi.rs index c32350e..6fe2275 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -109,6 +109,20 @@ fn namespace_config_and_release_commands_map_to_openapi_paths() { "/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) @@ -120,7 +134,7 @@ fn namespace_config_and_release_commands_map_to_openapi_paths() { .success(); assert_eq!( release_server.request().path, - "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/active" + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/active?page=0&size=20" ); } @@ -173,6 +187,49 @@ fn config_set_with_yes_sends_update_payload() { assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); } +#[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::empty(); @@ -272,13 +329,19 @@ impl TestServer { } 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 || { - let (stream, _) = listener.accept().expect("accept request"); - let request = read_request(stream, status, content_type, body); - request_tx.send(request).expect("send captured request"); + 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 } } @@ -290,6 +353,12 @@ impl TestServer { fn request(self) -> CapturedRequest { self.request_rx.recv().expect("captured request") } + + fn requests(self, count: usize) -> Vec { + (0..count) + .map(|_| self.request_rx.recv().expect("captured request")) + .collect() + } } fn read_request( From a2323474ed0accbf3824100e0ff59b58820d2582 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 15:41:49 +0800 Subject: [PATCH 05/18] feat: add guided profile setup --- Cargo.lock | 31 ++++ Cargo.toml | 1 + README.md | 45 +++++- src/cli.rs | 31 ++++ src/command.rs | 372 ++++++++++++++++++++++++++++++++++++++++++++++- src/error.rs | 28 +++- tests/cli.rs | 12 ++ tests/profile.rs | 158 ++++++++++++++++++++ 8 files changed, 674 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6e8079..04dd8e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -77,6 +77,7 @@ dependencies = [ "predicates", "regex", "reqwest", + "rpassword", "serde", "serde_json", "tempfile", @@ -999,6 +1000,27 @@ dependencies = [ "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" @@ -1632,6 +1654,15 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index b230266..b7127a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ clap = { version = "4.5.53", features = ["derive"] } keyring = "3.6.3" 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" diff --git a/README.md b/README.md index 447ecb0..0ee10a9 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,9 @@ changes in this slice. 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 @@ -68,6 +71,43 @@ The current scaffold parses these global flags before subcommands: - `--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 +printf '%s\n' "$TOKEN" | apollo --output json init --token-stdin --store-token-in-file +apollo profile show +apollo env list +``` + +By default, `apollo init` creates a `local` profile with: + +- `server = "http://127.0.0.1:8070"` +- `output = "json"` +- `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: @@ -85,7 +125,8 @@ The config file stores: - optional `operator` - optional credential lookup metadata, such as backend/key names -Tokens are intentionally not part of the supported config schema. +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: @@ -104,6 +145,8 @@ key = "dev" ## Profile commands +- `apollo init` +- `apollo profile add [name]` - `apollo profile list` - `apollo profile show` - `apollo profile use ` diff --git a/src/cli.rs b/src/cli.rs index a8a3ce9..b119d07 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -37,6 +37,7 @@ pub enum OutputFormat { #[derive(Clone, Debug, Eq, PartialEq, Subcommand)] pub enum Commands { + Init(InitArgs), Auth { #[command(subcommand)] command: AuthCommand, @@ -70,11 +71,41 @@ pub enum Commands { #[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 { diff --git a/src/command.rs b/src/command.rs index 474d3f1..2d7e357 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,9 +1,11 @@ +use std::io::{self, IsTerminal, Write}; + use serde::Serialize; use serde_json::{Value, json}; use crate::cli::{ - ApiArgs, AppCommand, AuthCommand, Cli, Commands, ConfigCommand, EnvCommand, NamespaceCommand, - NamespaceScopeArgs, OutputFormat, ProfileCommand, ReleaseCommand, + ApiArgs, AppCommand, AuthCommand, Cli, Commands, ConfigCommand, EnvCommand, InitArgs, + NamespaceCommand, NamespaceScopeArgs, OutputFormat, ProfileCommand, ReleaseCommand, }; use crate::config::{ CredentialRef, LoadedConfig, ProfileConfig, RuntimeContext, load_config, resolve_context, @@ -13,14 +15,19 @@ 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 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 = cli.global.output.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), @@ -32,6 +39,23 @@ pub fn execute(cli: Cli) -> Result { } } +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, @@ -124,6 +148,18 @@ fn execute_profile( let writer = OutputWriter::new(resolve_output(cli, &loaded, 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 response = ProfileListResponse::from_loaded_config(&loaded); Ok(writer.render_success(&response, response.render_table())) @@ -158,6 +194,89 @@ fn execute_profile( } } +#[derive(Copy, Clone)] +enum ProfileSetupMode { + Init, + 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)?; + 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, + writer_output, + )); + } + + let server = resolve_setup_server(&options, cli, interactive, writer_output)?; + let profile_output = cli.global.output.unwrap_or(OutputFormat::Json); + let operator = resolve_setup_operator(&options, interactive, writer_output)?; + + let mut profile_config = ProfileConfig { + server: Some(server.clone()), + output: Some(profile_output), + operator: operator.clone(), + credential: None, + }; + + 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()?; + profile_config.credential = credential.clone(); + + 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 = ProfileSetupResponse { + profile: profile_name, + active_profile: config.active_profile.clone(), + server, + output: profile_output.to_string(), + operator, + credential, + config_path: loaded.path.display().to_string(), + next_steps: vec![ + "apollo profile show".to_owned(), + "apollo env list".to_owned(), + ], + }; + Ok(writer.render_success(&response, response.render_table())) +} + fn execute_app( command: AppCommand, cli: &Cli, @@ -530,6 +649,210 @@ fn sync_body( }) } +fn resolve_setup_profile_name( + options: &ProfileSetupOptions, + cli: &Cli, + interactive: bool, + output: OutputFormat, +) -> Result { + options + .name + .clone() + .or_else(|| cli.global.profile.clone()) + .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() + .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 { + return Ok(Some(operator.clone())); + } + 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)? { + let token = rpassword::prompt_password("Consumer token: ") + .map_err(|error| CliError::invalid_input(&error.to_string(), output))?; + let token = token.trim().to_owned(); + if token.is_empty() { + Ok(None) + } else { + Ok(Some(Sensitive::new(token))) + } + } 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 mut line = String::new(); + io::stdin() + .read_line(&mut line) + .map_err(|error| CliError::invalid_input(&error.to_string(), 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 mut line = String::new(); + io::stdin() + .read_line(&mut line) + .map_err(|error| CliError::invalid_input(&error.to_string(), output))?; + let value = line.trim(); + if value.is_empty() { + Ok(default.unwrap_or_default().to_owned()) + } else { + Ok(value.to_owned()) + } +} + #[derive(Serialize)] struct ProfileListResponse { #[serde(rename = "activeProfile")] @@ -676,6 +999,51 @@ struct ProfileUseResponse { config_path: String, } +#[derive(Serialize)] +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, diff --git a/src/error.rs b/src/error.rs index 0336383..9e2c779 100644 --- a/src/error.rs +++ b/src/error.rs @@ -37,6 +37,9 @@ pub enum CliErrorKind { ProfileNotFound { profile: String, }, + ProfileAlreadyExists { + profile: String, + }, } #[derive(Debug)] @@ -81,6 +84,15 @@ impl CliError { } } + pub fn profile_already_exists(profile: &str, format: OutputFormat) -> Self { + Self { + kind: CliErrorKind::ProfileAlreadyExists { + profile: profile.to_owned(), + }, + format, + } + } + pub fn confirmation_required(message: &str, format: OutputFormat) -> Self { Self { kind: CliErrorKind::ConfirmationRequired { @@ -149,7 +161,8 @@ impl CliError { | CliErrorKind::AuthenticationRequired { .. } | CliErrorKind::Network { .. } | CliErrorKind::HttpStatus { .. } - | CliErrorKind::ProfileNotFound { .. } => 1, + | CliErrorKind::ProfileNotFound { .. } + | CliErrorKind::ProfileAlreadyExists { .. } => 1, } } @@ -267,6 +280,19 @@ impl CliError { path: None, profile: Some(profile.clone()), }), + CliErrorKind::ProfileAlreadyExists { profile } => 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("profile add".to_owned()), + follow_up_issue: None, + path: None, + profile: Some(profile.clone()), + }), } } } diff --git a/tests/cli.rs b/tests/cli.rs index 558bd60..58494ba 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -9,6 +9,7 @@ fn help_lists_v0_command_groups_and_global_flags() { .arg("--help") .assert() .success() + .stdout(predicate::str::contains("init")) .stdout(predicate::str::contains("auth")) .stdout(predicate::str::contains("profile")) .stdout(predicate::str::contains("app")) @@ -77,3 +78,14 @@ fn auth_help_lists_v0_auth_commands() { .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")); +} diff --git a/tests/profile.rs b/tests/profile.rs index 03e6ca1..3779294 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -2,6 +2,7 @@ use std::fs; use std::path::PathBuf; use assert_cmd::Command; +use predicates::prelude::predicate; use serde_json::Value; use tempfile::TempDir; @@ -228,13 +229,163 @@ output = "table" 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["active_profile"], "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 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["active_profile"], "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_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_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() + .stdout(predicate::str::contains("profile_already_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")); @@ -253,6 +404,13 @@ 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") From ec9370fc82a02413650da5c127cdb11035ba853f Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 15:52:37 +0800 Subject: [PATCH 06/18] fix: clarify logout with environment token --- README.md | 5 +++++ src/command.rs | 26 ++++++++++++++++++++++++-- tests/auth.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0ee10a9..8b99b00 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,11 @@ For local or CI use, `APOLLO_TOKEN` takes precedence and is never written to dis 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: ```bash diff --git a/src/command.rs b/src/command.rs index 2d7e357..013d08e 100644 --- a/src/command.rs +++ b/src/command.rs @@ -122,17 +122,30 @@ fn execute_auth( AuthCommand::Logout => { 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())) } @@ -1093,14 +1106,23 @@ struct AuthLogoutResponse { 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 { - format!( + 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 } } diff --git a/tests/auth.rs b/tests/auth.rs index 2724d22..8da5068 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -179,6 +179,48 @@ key = "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"); From 03f993b672605f003e051c9457740c2a47866c42 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 16:01:49 +0800 Subject: [PATCH 07/18] fix: make auth login token input interactive --- README.md | 14 +++++++-- src/credential.rs | 76 ++++++++++++++++++++++++++++++++++++----------- 2 files changed, 70 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 8b99b00..9672144 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Use `apollo init` for first-time setup. It creates a profile, writes non-secret For local Apollo assembly testing: ```bash -printf '%s\n' "$TOKEN" | apollo --output json init --token-stdin --store-token-in-file +apollo --output json init --store-token-in-file apollo profile show apollo env list ``` @@ -160,6 +160,7 @@ Runtime context resolution follows this order: ## Auth commands +- `apollo auth login` - `apollo auth login --token-stdin` - `apollo auth login --token-stdin --store-token-in-file` - `apollo auth status` @@ -195,13 +196,20 @@ APOLLO_TOKEN="$TOKEN" apollo --server http://localhost:8070 app list --output js 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: +For interactive use, configure a profile and store the token with hidden input: ```bash -printf '%s\n' "$TOKEN" | apollo --profile dev auth login --token-stdin +apollo --profile dev auth login apollo --profile dev app list ``` +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]`. diff --git a/src/credential.rs b/src/credential.rs index b90ef15..bb82171 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -1,6 +1,6 @@ use std::env; use std::fs; -use std::io::Read; +use std::io::{BufRead, IsTerminal}; use std::path::{Path, PathBuf}; #[cfg(unix)] @@ -211,25 +211,46 @@ pub fn token_from_env_or_stdin( format: crate::cli::OutputFormat, ) -> Result { if token_stdin { - let mut token = String::new(); - let mut stdin = std::io::stdin(); - stdin - .read_to_string(&mut token) + 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() { + let token = rpassword::prompt_password("Consumer token: ") .map_err(|error| CliError::invalid_input(&error.to_string(), format))?; - let token = token.trim().to_owned(); - if token.is_empty() { - return Err(CliError::invalid_input("token input was empty", format)); - } - return Ok(Sensitive::new(token)); + return token_from_value(token, format); } - env::var("APOLLO_TOKEN") - .ok() - .filter(|token| !token.trim().is_empty()) - .map(Sensitive::new) - .ok_or_else(|| { - CliError::invalid_input("provide a token with --token-stdin or APOLLO_TOKEN", format) - }) + Err(CliError::invalid_input( + "provide a token with interactive prompt, --token-stdin, or APOLLO_TOKEN", + 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 { @@ -274,8 +295,10 @@ fn native_disabled_for_tests() -> bool { 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)] @@ -318,4 +341,23 @@ mod tests { 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); + } } From f19ecbaee5c8ff8dd2686e5da6feabc6fdd27891 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 7 Jun 2026 16:13:12 +0800 Subject: [PATCH 08/18] fix: harden interactive auth login --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 3 ++ src/command.rs | 32 +++++----------- src/credential.rs | 95 +++++++++++++++++++++++++++++++++++++++++++++-- 5 files changed, 105 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 04dd8e4..7d3fd8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -74,6 +74,7 @@ dependencies = [ "assert_cmd", "clap", "keyring", + "libc", "predicates", "regex", "reqwest", diff --git a/Cargo.toml b/Cargo.toml index b7127a8..d53d020 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ path = "src/main.rs" [dependencies] 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" diff --git a/README.md b/README.md index 9672144..4407a22 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,9 @@ 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 diff --git a/src/command.rs b/src/command.rs index 013d08e..fc1c932 100644 --- a/src/command.rs +++ b/src/command.rs @@ -87,21 +87,14 @@ fn execute_auth( let profile = required_profile(&context, output)?; let token = credential::token_from_env_or_stdin(token_stdin, writer_output)?; - let credential_ref = if store_token_in_file { - credential::store_file(&loaded.path, &profile, &token).map_err(|error| { - CliError::credential_store_unavailable(&error, writer_output) - })? - } else { - credential::store_native(&profile, &token).map_err(|error| { - CliError::confirmation_required( - &format!( - "Native credential storage is unavailable: {}. Re-run with --store-token-in-file to use the explicit file fallback.", - error - ), - 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 @@ -742,14 +735,7 @@ fn resolve_setup_token( return credential::token_from_env_or_stdin(true, output).map(Some); } if interactive && prompt_yes_no("Store a Consumer token now?", false, output)? { - let token = rpassword::prompt_password("Consumer token: ") - .map_err(|error| CliError::invalid_input(&error.to_string(), output))?; - let token = token.trim().to_owned(); - if token.is_empty() { - Ok(None) - } else { - Ok(Some(Sensitive::new(token))) - } + credential::prompt_token(output).map(Some) } else { Ok(None) } diff --git a/src/credential.rs b/src/credential.rs index bb82171..18cecaf 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -1,8 +1,13 @@ use std::env; use std::fs; -use std::io::{BufRead, IsTerminal}; +use std::io::{BufRead, IsTerminal, Write}; use std::path::{Path, PathBuf}; +#[cfg(unix)] +use std::mem; +#[cfg(unix)] +use std::os::fd::AsRawFd; + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; @@ -220,9 +225,7 @@ pub fn token_from_env_or_stdin( } if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() { - let token = rpassword::prompt_password("Consumer token: ") - .map_err(|error| CliError::invalid_input(&error.to_string(), format))?; - return token_from_value(token, format); + return prompt_token(format); } Err(CliError::invalid_input( @@ -231,6 +234,90 @@ pub fn token_from_env_or_stdin( )) } +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, From 40d13ddbae8f6480e4d5f1c0483c716636c01c50 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 12:04:33 +0800 Subject: [PATCH 09/18] fix: address cli review feedback --- .github/workflows/ci.yml | 2 + src/command.rs | 109 +++++++++++++++++++++------- src/config.rs | 43 ++++++++--- src/credential.rs | 52 ++++++++++---- src/error.rs | 13 ++-- src/http.rs | 27 ++++++- src/output.rs | 11 +-- src/redaction.rs | 22 ++++-- tests/auth.rs | 42 ++++++++++- tests/cli.rs | 65 ++++++++++++++++- tests/openapi.rs | 41 +++++++++-- tests/profile.rs | 149 +++++++++++++++++++++++++++++++++++++-- tests/redaction.rs | 8 +++ 13 files changed, 506 insertions(+), 78 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71daccc..3e84f24 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - name: cargo fmt diff --git a/src/command.rs b/src/command.rs index fc1c932..66da308 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,4 +1,4 @@ -use std::io::{self, IsTerminal, Write}; +use std::io::{self, BufRead, IsTerminal, Write}; use serde::Serialize; use serde_json::{Value, json}; @@ -8,8 +8,8 @@ use crate::cli::{ NamespaceCommand, NamespaceScopeArgs, OutputFormat, ProfileCommand, ReleaseCommand, }; use crate::config::{ - CredentialRef, LoadedConfig, ProfileConfig, RuntimeContext, load_config, resolve_context, - resolve_output, save_config, + CredentialRef, LoadedConfig, ProfileConfig, RuntimeContext, load_config, read_env_output, + resolve_context, resolve_output, save_config, }; use crate::credential; use crate::error::CliError; @@ -24,7 +24,7 @@ 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 = cli.global.output.unwrap_or(OutputFormat::Table); + let output = output_from_flags_or_env(&cli).unwrap_or(OutputFormat::Table); match &cli.command { Commands::Init(args) => execute_init(args.clone(), &cli, output), @@ -39,6 +39,10 @@ pub fn execute(cli: Cli) -> Result { } } +fn output_from_flags_or_env(cli: &Cli) -> Option { + cli.global.output.or_else(read_env_output) +} + fn execute_init( args: InitArgs, cli: &Cli, @@ -151,7 +155,6 @@ fn execute_profile( output: OutputFormat, ) -> Result { let loaded = load_config(output)?; - let writer = OutputWriter::new(resolve_output(cli, &loaded, output)?); match command { ProfileCommand::Add(args) => { @@ -167,22 +170,26 @@ fn execute_profile( execute_profile_setup(options, cli, output) } ProfileCommand::List => { + let writer = OutputWriter::new(output_from_flags_or_env(cli).unwrap_or(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 = 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, output)); + 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, output)?; + save_config(&loaded.path, &config, writer_output)?; let response = ProfileUseResponse { active_profile: name.clone(), @@ -206,6 +213,15 @@ enum ProfileSetupMode { Add, } +impl ProfileSetupMode { + fn command_name(self) -> &'static str { + match self { + Self::Init => "init", + Self::Add => "profile add", + } + } +} + struct ProfileSetupOptions { mode: ProfileSetupMode, name: Option, @@ -222,7 +238,7 @@ fn execute_profile_setup( output: OutputFormat, ) -> Result { let loaded = load_config(output)?; - let writer_output = resolve_output(cli, &loaded, output)?; + let writer_output = output_from_flags_or_env(cli).unwrap_or(output); let writer = OutputWriter::new(writer_output); let interactive = is_interactive_terminal(); @@ -230,6 +246,7 @@ fn execute_profile_setup( if loaded.config.profiles.contains_key(&profile_name) && !options.overwrite { return Err(CliError::profile_already_exists( &profile_name, + options.mode.command_name(), writer_output, )); } @@ -237,12 +254,13 @@ fn execute_profile_setup( let server = resolve_setup_server(&options, cli, interactive, writer_output)?; let profile_output = cli.global.output.unwrap_or(OutputFormat::Json); 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: Some(profile_output), + output: cli.global.output, operator: operator.clone(), - credential: None, + credential: existing_profile.and_then(|profile| profile.credential.clone()), }; let credential = resolve_setup_token(&options, interactive, writer_output)? @@ -257,7 +275,9 @@ fn execute_profile_setup( ) }) .transpose()?; - profile_config.credential = credential.clone(); + 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); @@ -583,12 +603,16 @@ fn render_openapi_response(writer: &OutputWriter, response: &OpenApiResponse) -> } fn required_server(context: &RuntimeContext, output: OutputFormat) -> Result { - context.server.clone().ok_or_else(|| { - CliError::invalid_input( - "provide a server with --server, APOLLO_SERVER, or profile config", - output, - ) - }) + 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( @@ -598,7 +622,13 @@ fn required_operator( ) -> Result { command_operator .map(ToOwned::to_owned) - .or_else(|| context.operator.clone()) + .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", @@ -810,10 +840,7 @@ fn prompt_yes_no(label: &str, default: bool, output: OutputFormat) -> Result(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")] @@ -914,7 +949,10 @@ impl ProfileSummaryRow { Self { active: active_profile.as_deref() == Some(name), name: name.to_owned(), - server: profile.server.clone().unwrap_or_default(), + 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(), @@ -999,6 +1037,7 @@ struct ProfileUseResponse { } #[derive(Serialize)] +#[serde(rename_all = "camelCase")] struct ProfileSetupResponse { profile: String, active_profile: Option, @@ -1085,6 +1124,22 @@ impl AuthLoginResponse { } } +#[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")] diff --git a/src/config.rs b/src/config.rs index f5f6405..0b9ce5d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -108,16 +108,17 @@ pub fn resolve_context( .global .server .clone() - .or_else(|| env::var("APOLLO_SERVER").ok()) + .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(|profile| profile.server.clone().and_then(non_blank)) }), output, operator: profile_config .as_ref() - .and_then(|profile| profile.operator.clone()), + .and_then(|profile| profile.operator.clone().and_then(non_blank)), credential: profile_config.and_then(|profile| profile.credential), }) } @@ -161,7 +162,11 @@ fn config_path_for_platform( .join("apollo") .join("config.toml")), Platform::Linux => { - if let Some(xdg_config_home) = vars.get("XDG_CONFIG_HOME").cloned() { + if let Some(xdg_config_home) = vars + .get("XDG_CONFIG_HOME") + .filter(|value| !value.is_empty()) + .cloned() + { Ok(PathBuf::from(xdg_config_home) .join("apollo") .join("config.toml")) @@ -184,7 +189,7 @@ fn collect_env_vars() -> HashMap { .collect() } -fn read_env_output() -> Option { +pub(crate) fn read_env_output() -> Option { env::var("APOLLO_OUTPUT") .ok() .and_then(|value| OutputFormat::parse(&value)) @@ -199,8 +204,9 @@ fn selected_profile_and_config( .global .profile .clone() - .or_else(|| env::var("APOLLO_PROFILE").ok()) - .or_else(|| loaded.config.active_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( @@ -217,9 +223,17 @@ fn selected_profile_and_config( 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 { + (!value.trim().is_empty()).then_some(value) +} + impl OutputFormat { pub fn parse(value: &str) -> Option { - match value.to_ascii_lowercase().as_str() { + match value.trim().to_ascii_lowercase().as_str() { "json" => Some(Self::Json), "table" => Some(Self::Table), _ => None, @@ -268,6 +282,19 @@ mod tests { 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_uses_windows_appdata_convention() { let vars = HashMap::from([( diff --git a/src/credential.rs b/src/credential.rs index 18cecaf..637e5ce 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -1,5 +1,5 @@ use std::env; -use std::fs; +use std::fs::{self, OpenOptions}; use std::io::{BufRead, IsTerminal, Write}; use std::path::{Path, PathBuf}; @@ -9,7 +9,7 @@ use std::mem; use std::os::fd::AsRawFd; #[cfg(unix)] -use std::os::unix::fs::PermissionsExt; +use std::os::unix::fs::OpenOptionsExt; use keyring::Entry; @@ -103,14 +103,15 @@ impl FileCredentialStore { } } - pub fn path_for_key(&self, key: &str) -> PathBuf { - self.base_dir.join(format!("{}.token", key)) + 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); + let path = self.path_for_key(key)?; if !path.exists() { return Ok(None); } @@ -120,18 +121,13 @@ impl CredentialStore for FileCredentialStore { fn set(&self, key: &str, token: &Sensitive) -> Result<(), String> { fs::create_dir_all(&self.base_dir).map_err(|error| error.to_string())?; - let path = self.path_for_key(key); - fs::write(&path, token.expose_secret()).map_err(|error| error.to_string())?; - #[cfg(unix)] - { - fs::set_permissions(&path, fs::Permissions::from_mode(0o600)) - .map_err(|error| error.to_string())?; - } + let path = self.path_for_key(key)?; + write_token_file(&path, token.expose_secret())?; Ok(()) } fn delete(&self, key: &str) -> Result<(), String> { - let path = self.path_for_key(key); + let path = self.path_for_key(key)?; if path.exists() { fs::remove_file(path).map_err(|error| error.to_string())?; } @@ -139,6 +135,36 @@ impl CredentialStore for FileCredentialStore { } } +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())?; + file.write_all(token.as_bytes()) + .map_err(|error| error.to_string()) +} + +#[cfg(not(unix))] +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, diff --git a/src/error.rs b/src/error.rs index 9e2c779..116504b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -39,6 +39,7 @@ pub enum CliErrorKind { }, ProfileAlreadyExists { profile: String, + command: String, }, } @@ -84,10 +85,11 @@ impl CliError { } } - pub fn profile_already_exists(profile: &str, format: OutputFormat) -> Self { + 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, } @@ -280,19 +282,20 @@ impl CliError { path: None, profile: Some(profile.clone()), }), - CliErrorKind::ProfileAlreadyExists { profile } => OutputWriter::new(self.format) - .render_error(&StructuredError { + 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("profile add".to_owned()), + command: Some(command.clone()), follow_up_issue: None, path: None, profile: Some(profile.clone()), - }), + }) + } } } } diff --git a/src/http.rs b/src/http.rs index db491ce..5a61476 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,9 +1,13 @@ use serde::Serialize; use serde_json::Value; +use std::time::Duration; use crate::cli::OutputFormat; use crate::error::CliError; -use crate::redaction::Sensitive; +use crate::redaction::{Redactor, Sensitive}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_ERROR_BODY_CHARS: usize = 4096; #[derive(Clone, Debug, Serialize)] pub struct OpenApiResponse { @@ -54,6 +58,7 @@ impl OpenApiClient { } let response = request + .timeout(REQUEST_TIMEOUT) .send() .map_err(|error| CliError::network(&path, &error.to_string(), self.format))?; let status = response.status(); @@ -62,6 +67,7 @@ impl OpenApiClient { .map_err(|error| CliError::network(&path, &error.to_string(), self.format))?; if !status.is_success() { + let body = sanitize_error_body(&body); return Err(CliError::http_status( status.as_u16(), &path, @@ -83,6 +89,25 @@ impl OpenApiClient { } } +fn sanitize_error_body(body: &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)); + truncate_chars(redacted, MAX_ERROR_BODY_CHARS) +} + +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() } diff --git a/src/output.rs b/src/output.rs index 5d2e263..5a0044a 100644 --- a/src/output.rs +++ b/src/output.rs @@ -39,10 +39,13 @@ impl OutputWriter { match self.format { OutputFormat::Json => { let value = redactor.redact_json(json!({ "error": error })); - RenderedOutput::stdout( - serde_json::to_string_pretty(&value) - .expect("structured error json serialization"), - ) + 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)]; diff --git a/src/redaction.rs b/src/redaction.rs index c7cd67c..75a3565 100644 --- a/src/redaction.rs +++ b/src/redaction.rs @@ -1,23 +1,31 @@ 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 authorization = Regex::new("(?i)(authorization\\s*:\\s*bearer\\s+)[^\\s]+") - .expect("authorization regex"); - let consumer_token = - Regex::new("(?i)(consumer\\s+token\\s+)[^\\s]+").expect("consumer token regex"); - - let value = authorization.replace_all(value, format!("${{1}}{}", REDACTED)); - consumer_token + 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() } diff --git a/tests/auth.rs b/tests/auth.rs index 8da5068..a658910 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -57,11 +57,12 @@ server = "https://apollo-dev.example.com" .assert() .failure(); - 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!(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!(!stdout.contains("secret-from-stdin")); + assert!(!stderr.contains("secret-from-stdin")); assert!(!credential_file_path(&home, "dev").exists()); } @@ -148,6 +149,41 @@ key = "dev" 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("dev.token").exists()); +} + #[test] fn auth_logout_removes_file_credential_and_keeps_profile_config() { let home = temp_home(); diff --git a/tests/cli.rs b/tests/cli.rs index 58494ba..b928f5f 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1,6 +1,7 @@ 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() { @@ -40,7 +41,8 @@ fn openapi_command_without_token_returns_structured_json_error() { .assert() .failure(); - let output = String::from_utf8(assert.get_output().stdout.clone()).expect("utf8 output"); + 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"); @@ -67,6 +69,24 @@ fn global_flags_are_accepted_before_subcommands() { .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") @@ -89,3 +109,46 @@ fn profile_help_lists_add_command() { .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 index 6fe2275..1b1af85 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -4,6 +4,7 @@ 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; @@ -151,11 +152,37 @@ fn mutating_commands_require_yes_before_network_call() { .assert() .failure(); - 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!(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#"{"authorization":"consumer-token","message":"failed with consumer token 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 config_set_with_yes_sends_update_payload() { let server = TestServer::empty(); @@ -351,12 +378,18 @@ impl TestServer { } fn request(self) -> CapturedRequest { - self.request_rx.recv().expect("captured request") + 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().expect("captured request")) + .map(|_| { + self.request_rx + .recv_timeout(Duration::from_secs(5)) + .expect("timed out waiting for captured request") + }) .collect() } } diff --git a/tests/profile.rs b/tests/profile.rs index 3779294..365dd08 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -68,6 +68,34 @@ output = "table" 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(); @@ -176,6 +204,32 @@ output = "json" ); } +#[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(); @@ -203,6 +257,29 @@ output = "json" assert!(config.contains("active_profile = \"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(); @@ -222,8 +299,9 @@ output = "table" .assert() .failure(); - 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!(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"); @@ -249,7 +327,7 @@ fn init_creates_local_profile_and_file_credential_without_printing_token() { let json: Value = serde_json::from_str(&stdout).expect("json stdout"); assert_eq!(json["profile"], "local"); - assert_eq!(json["active_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")); @@ -265,6 +343,27 @@ fn init_creates_local_profile_and_file_credential_without_printing_token() { 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"], "json"); + + let config = fs::read_to_string(config_path(&home)).expect("config file"); + assert!(!config.contains("output = \"json\"")); +} + #[test] fn profile_add_creates_profile_without_switching_active_profile() { let home = temp_home(); @@ -301,7 +400,7 @@ output = "json" let json: Value = serde_json::from_str(&stdout).expect("json stdout"); assert_eq!(json["profile"], "dev"); - assert_eq!(json["active_profile"], "local"); + 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"); @@ -348,6 +447,46 @@ output = "json" 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"); + + base_command(&home) + .args([ + "--server", + "https://apollo-new.example.com", + "profile", + "add", + "dev", + "--overwrite", + ]) + .assert() + .success(); + + 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(); @@ -374,7 +513,7 @@ output = "json" ]) .assert() .failure() - .stdout(predicate::str::contains("profile_already_exists")); + .stderr(predicate::str::contains("profile_already_exists")); } fn base_command(home: &TempDir) -> Command { diff --git a/tests/redaction.rs b/tests/redaction.rs index 29e0f46..dcdcfbe 100644 --- a/tests/redaction.rs +++ b/tests/redaction.rs @@ -9,10 +9,18 @@ fn redacts_token_like_text_and_authorization_headers() { 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] From c847b1889c3fbf1a22086622b9e6d171108e9128 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 13:51:11 +0800 Subject: [PATCH 10/18] fix: address latest review comments --- src/command.rs | 23 ++++++++++---- src/config.rs | 15 +++++++++ src/credential.rs | 2 +- tests/auth.rs | 7 +++- tests/profile.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 119 insertions(+), 9 deletions(-) diff --git a/src/command.rs b/src/command.rs index 66da308..9eb7962 100644 --- a/src/command.rs +++ b/src/command.rs @@ -43,6 +43,14 @@ fn output_from_flags_or_env(cli: &Cli) -> Option { cli.global.output.or_else(read_env_output) } +fn non_blank(value: String) -> Option { + if value.trim().is_empty() { + None + } else { + Some(value) + } +} + fn execute_init( args: InitArgs, cli: &Cli, @@ -252,13 +260,14 @@ fn execute_profile_setup( } let server = resolve_setup_server(&options, cli, interactive, writer_output)?; - let profile_output = cli.global.output.unwrap_or(OutputFormat::Json); + 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: cli.global.output, + output: profile_output, operator: operator.clone(), credential: existing_profile.and_then(|profile| profile.credential.clone()), }; @@ -291,7 +300,7 @@ fn execute_profile_setup( profile: profile_name, active_profile: config.active_profile.clone(), server, - output: profile_output.to_string(), + output: response_output.to_string(), operator, credential, config_path: loaded.path.display().to_string(), @@ -694,7 +703,8 @@ fn resolve_setup_profile_name( options .name .clone() - .or_else(|| cli.global.profile.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, @@ -721,6 +731,7 @@ fn resolve_setup_server( cli.global .server .clone() + .and_then(non_blank) .or_else(|| match options.mode { ProfileSetupMode::Init => Some(DEFAULT_INIT_SERVER.to_owned()), ProfileSetupMode::Add => None, @@ -743,8 +754,8 @@ fn resolve_setup_operator( interactive: bool, output: OutputFormat, ) -> Result, CliError> { - if let Some(operator) = &options.operator { - return Ok(Some(operator.clone())); + 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())); diff --git a/src/config.rs b/src/config.rs index 0b9ce5d..6482701 100644 --- a/src/config.rs +++ b/src/config.rs @@ -150,6 +150,7 @@ fn config_path_for_platform( ) -> Result { let home = || { vars.get("HOME") + .filter(|value| !value.is_empty()) .cloned() .map(PathBuf::from) .ok_or_else(|| "HOME is not set".to_owned()) @@ -295,6 +296,20 @@ mod tests { ); } + #[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([( diff --git a/src/credential.rs b/src/credential.rs index 637e5ce..7cce251 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -120,8 +120,8 @@ impl CredentialStore for FileCredentialStore { } fn set(&self, key: &str, token: &Sensitive) -> Result<(), String> { - fs::create_dir_all(&self.base_dir).map_err(|error| error.to_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(()) } diff --git a/tests/auth.rs b/tests/auth.rs index a658910..1b20aa2 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -181,7 +181,12 @@ server = "https://apollo-dev.example.com" assert_eq!(json["error"]["code"], "credential_store_unavailable"); assert!(!stderr.contains("secret-from-stdin")); - assert!(!config_root(&home).join("dev.token").exists()); + assert!( + !config_root(&home) + .join("apollo") + .join("credentials") + .exists() + ); } #[test] diff --git a/tests/profile.rs b/tests/profile.rs index 365dd08..2a552a2 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -358,12 +358,51 @@ fn init_with_apollo_output_json_does_not_persist_implicit_output() { let json: Value = serde_json::from_str(&stdout).expect("json stdout"); assert_eq!(json["activeProfile"], "local"); - assert_eq!(json["output"], "json"); + 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_creates_profile_without_switching_active_profile() { let home = temp_home(); @@ -516,6 +555,46 @@ output = "json" .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"); From a758b3a0c4dd7fd3e72568b4f4607825865172ba Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 14:58:13 +0800 Subject: [PATCH 11/18] fix: address review thread history --- .github/workflows/ci.yml | 6 +- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 8 +- src/cli.rs | 5 +- src/command.rs | 238 +++++++++++++++++++++++++++------------ src/config.rs | 11 +- src/credential.rs | 18 ++- src/http.rs | 14 ++- tests/auth.rs | 118 +++++++++++++++++++ tests/openapi.rs | 131 ++++++++++++++++++--- tests/profile.rs | 60 ++++++++++ 12 files changed, 513 insertions(+), 98 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e84f24..fa9034c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,11 +12,11 @@ jobs: rust: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 - name: cargo fmt run: cargo fmt --check - name: cargo clippy diff --git a/Cargo.lock b/Cargo.lock index 7d3fd8b..1ed3f73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,6 +72,7 @@ name = "apollo-cli" version = "0.1.0" dependencies = [ "assert_cmd", + "base64", "clap", "keyring", "libc", diff --git a/Cargo.toml b/Cargo.toml index d53d020..3d97871 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ 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" diff --git a/README.md b/README.md index 4407a22..07b6e75 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ apollo profile add dev apollo profile add prod --use apollo app list apollo app get sample-app -apollo env list +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 @@ -81,13 +81,13 @@ For local Apollo assembly testing: ```bash apollo --output json init --store-token-in-file apollo profile show -apollo env list +apollo env list --app sample-app ``` By default, `apollo init` creates a `local` profile with: - `server = "http://127.0.0.1:8070"` -- `output = "json"` +- no persisted `output` unless `--output` is passed - `operator = "apollo"` - `active_profile = "local"` @@ -288,7 +288,7 @@ 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 +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 ``` diff --git a/src/cli.rs b/src/cli.rs index b119d07..ced8375 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -131,7 +131,10 @@ pub enum AppCommand { #[derive(Clone, Debug, Eq, PartialEq, Subcommand)] pub enum EnvCommand { - List, + List { + #[arg(long)] + app: String, + }, } #[derive(Clone, Debug, Eq, PartialEq, Subcommand)] diff --git a/src/command.rs b/src/command.rs index 9eb7962..480520a 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,5 +1,6 @@ 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}; @@ -44,11 +45,8 @@ fn output_from_flags_or_env(cli: &Cli) -> Option { } fn non_blank(value: String) -> Option { - if value.trim().is_empty() { - None - } else { - Some(value) - } + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) } fn execute_init( @@ -79,13 +77,34 @@ fn execute_auth( match command { AuthCommand::Status => { + if std::env::var("APOLLO_TOKEN") + .ok() + .is_some_and(|token| !token.trim().is_empty()) + { + 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.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 context = resolve_context(cli, &loaded, output)?; - let profile = required_profile(&context, 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, + profile: Some(profile), backend: status.backend, key: status.key, }; @@ -96,7 +115,10 @@ fn execute_auth( store_token_in_file, } => { let context = resolve_context(cli, &loaded, output)?; - let profile = required_profile(&context, 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_env_or_stdin(token_stdin, writer_output)?; let credential_ref = store_setup_token( @@ -178,7 +200,9 @@ fn execute_profile( execute_profile_setup(options, cli, output) } ProfileCommand::List => { - let writer = OutputWriter::new(output_from_flags_or_env(cli).unwrap_or(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 response = ProfileListResponse::from_loaded_config(&loaded); Ok(writer.render_success(&response, response.render_table())) } @@ -306,7 +330,8 @@ fn execute_profile_setup( config_path: loaded.path.display().to_string(), next_steps: vec![ "apollo profile show".to_owned(), - "apollo env list".to_owned(), + "apollo app list".to_owned(), + "apollo env list --app ".to_owned(), ], }; Ok(writer.render_success(&response, response.render_table())) @@ -327,7 +352,9 @@ fn execute_app( path } } - AppCommand::Get { app_id } => format!("/openapi/v1/apps/{}", encode_path_segment(&app_id)), + AppCommand::Get { app_id } => { + append_query("/openapi/v1/apps".to_owned(), "appIds", &app_id) + } }; openapi.request("GET", &path, None) } @@ -339,7 +366,10 @@ fn execute_env( ) -> Result { let openapi = openapi_context(cli, output)?; match command { - EnvCommand::List => openapi.request("GET", "/openapi/v1/envs", None), + EnvCommand::List { app } => { + let path = format!("/openapi/v1/apps/{}/envclusters", encode_path_segment(&app)); + openapi.request("GET", &path, None) + } } } @@ -348,6 +378,9 @@ fn execute_namespace( 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 } => { @@ -363,15 +396,22 @@ fn execute_namespace( name, operator, } => { - require_yes(cli, output)?; - let operator = required_operator(operator.as_deref(), &openapi.context, output)?; - let path = append_query("/openapi/v1/namespaces".to_owned(), "operator", &operator); - let body = json!([{ + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; + let path = format!( + "/openapi/v1/apps/{}/appnamespaces", + encode_path_segment(&scope.app) + ); + let body = json!({ "appId": scope.app, - "env": scope.env, - "clusterName": scope.cluster, - "appNamespaceName": name, - }]); + "name": name, + "format": "properties", + "isPublic": true, + "dataChangeCreatedBy": operator, + }); openapi.request("POST", &path, Some(body)) } } @@ -382,6 +422,9 @@ fn execute_config( 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 } => { @@ -391,11 +434,7 @@ fn execute_config( openapi.request("GET", &path, None) } ConfigCommand::Get { scope, key } => { - let path = format!( - "{}/items/{}", - namespace_path(&scope), - encode_path_segment(&key) - ); + let path = item_path(&scope, &key); openapi.request("GET", &path, None) } ConfigCommand::Set { @@ -405,17 +444,12 @@ fn execute_config( comment, operator, } => { - require_yes(cli, output)?; - let operator = required_operator(operator.as_deref(), &openapi.context, output)?; - let update_path = append_query( - format!( - "{}/items/{}", - namespace_path(&scope), - encode_path_segment(&key) - ), - "createIfNotExists", - "true", - ); + 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", @@ -445,17 +479,12 @@ fn execute_config( key, operator, } => { - require_yes(cli, output)?; - let operator = required_operator(operator.as_deref(), &openapi.context, output)?; - let path = append_query( - format!( - "{}/items/{}", - namespace_path(&scope), - encode_path_segment(&key) - ), - "operator", - &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 { @@ -475,8 +504,11 @@ fn execute_config( target_namespace, operator, } => { - require_yes(cli, output)?; - let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; let body = sync_body(&scope, target_env, target_cluster, target_namespace); let path = append_query( format!("{}/items/synchronize", namespace_path(&scope)), @@ -493,12 +525,19 @@ fn execute_release( 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()); + let mut path = format!("{}/releases/latest", namespace_path(&scope)); + if let Some(page) = page { + path = append_query(path, "page", &page.to_string()); + } + if let Some(size) = size { + path = append_query(path, "size", &size.to_string()); + } openapi.request("GET", &path, None) } ReleaseCommand::Create { @@ -508,8 +547,11 @@ fn execute_release( emergency, operator, } => { - require_yes(cli, output)?; - let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; let path = format!("{}/releases", namespace_path(&scope)); let body = json!({ "releaseTitle": title, @@ -525,8 +567,11 @@ fn execute_release( to_release_id, operator, } => { - require_yes(cli, output)?; - let operator = required_operator(operator.as_deref(), &openapi.context, output)?; + let operator = required_operator( + operator.as_deref(), + &openapi.context, + openapi.context.output, + )?; let mut path = append_query( format!( "/openapi/v1/envs/{}/releases/{}/rollback", @@ -545,23 +590,16 @@ fn execute_release( } 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(), output))?, - ), + Some(body) => Some(serde_json::from_str::(&body).map_err(|error| { + CliError::invalid_input(&error.to_string(), openapi.context.output) + })?), None => None, }; - if matches!( - args.method, - crate::cli::HttpMethod::Post - | crate::cli::HttpMethod::Put - | crate::cli::HttpMethod::Patch - | crate::cli::HttpMethod::Delete - ) { - require_yes(cli, output)?; - } openapi.request(args.method.as_str(), &args.path, body) } @@ -611,6 +649,45 @@ fn render_openapi_response(writer: &OutputWriter, response: &OpenApiResponse) -> 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 required_server(context: &RuntimeContext, output: OutputFormat) -> Result { context .server @@ -678,6 +755,22 @@ fn namespace_path(scope: &NamespaceScopeArgs) -> String { ) } +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 sync_body( scope: &NamespaceScopeArgs, target_env: String, @@ -1097,7 +1190,8 @@ impl ProfileSetupResponse { struct AuthStatusResponse { authenticated: bool, source: String, - profile: 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")] @@ -1113,7 +1207,9 @@ impl AuthStatusResponse { }; format!( "Profile: {}\nStatus: {}\nSource: {}", - self.profile, state, self.source + self.profile.as_deref().unwrap_or(""), + state, + self.source ) } } diff --git a/src/config.rs b/src/config.rs index 6482701..dc23dff 100644 --- a/src/config.rs +++ b/src/config.rs @@ -177,6 +177,7 @@ fn config_path_for_platform( } Platform::Windows => vars .get("APPDATA") + .filter(|value| !value.is_empty()) .cloned() .map(PathBuf::from) .ok_or_else(|| "APPDATA is not set".to_owned()) @@ -229,7 +230,8 @@ fn env_var_non_blank(name: &str) -> Option { } fn non_blank(value: String) -> Option { - (!value.trim().is_empty()).then_some(value) + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) } impl OutputFormat { @@ -324,4 +326,11 @@ mod tests { .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 index 7cce251..a9cb294 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -1,15 +1,17 @@ use std::env; -use std::fs::{self, OpenOptions}; +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; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; use keyring::Entry; @@ -156,11 +158,21 @@ fn write_token_file(path: &Path, token: &str) -> Result<(), String> { .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(not(unix))] +#[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()) } diff --git a/src/http.rs b/src/http.rs index 5a61476..7b4fe2a 100644 --- a/src/http.rs +++ b/src/http.rs @@ -67,7 +67,7 @@ impl OpenApiClient { .map_err(|error| CliError::network(&path, &error.to_string(), self.format))?; if !status.is_success() { - let body = sanitize_error_body(&body); + let body = sanitize_error_body(&body, self.token.expose_secret()); return Err(CliError::http_status( status.as_u16(), &path, @@ -89,15 +89,25 @@ impl OpenApiClient { } } -fn sanitize_error_body(body: &str) -> String { +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 truncate_chars(value: String, max_chars: usize) -> String { let mut chars = value.chars(); let truncated: String = chars.by_ref().take(max_chars).collect(); diff --git a/tests/auth.rs b/tests/auth.rs index 1b20aa2..3774059 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -38,6 +38,34 @@ output = "table" 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_login_file_fallback_requires_explicit_opt_in() { let home = temp_home(); @@ -116,6 +144,59 @@ server = "https://apollo-dev.example.com" 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(); @@ -189,6 +270,43 @@ server = "https://apollo-dev.example.com" ); } +#[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(); diff --git a/tests/openapi.rs b/tests/openapi.rs index 1b1af85..fdfc51d 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -60,15 +60,31 @@ fn app_and_env_commands_call_openapi_endpoints() { .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?appIds=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"]) + .args(["--output", "json", "env", "list", "--app", "demo"]) .assert() .success() .stdout(predicate::str::contains("DEV")); - assert_eq!(env_server.request().path, "/openapi/v1/envs"); + assert_eq!( + env_server.request().path, + "/openapi/v1/apps/demo/envclusters" + ); } #[test] @@ -135,7 +151,7 @@ fn namespace_config_and_release_commands_map_to_openapi_paths() { .success(); assert_eq!( release_server.request().path, - "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/active?page=0&size=20" + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/latest" ); } @@ -159,12 +175,29 @@ fn mutating_commands_require_yes_before_network_call() { } #[test] -fn openapi_error_redacts_sensitive_response_body_to_stderr() { - let server = TestServer::new( - 500, - "application/json", - r#"{"authorization":"consumer-token","message":"failed with consumer token consumer-token"}"#, +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())); @@ -214,6 +247,63 @@ fn config_set_with_yes_sends_update_payload() { assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); } +#[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![ @@ -285,12 +375,13 @@ fn namespace_create_with_yes_sends_namespace_instance_payload() { let request = server.request(); assert_eq!(request.method, "POST"); - assert_eq!(request.path, "/openapi/v1/namespaces?operator=apollo-bot"); + assert_eq!(request.path, "/openapi/v1/apps/demo/appnamespaces"); let body: Value = serde_json::from_str(&request.body).expect("json body"); - assert_eq!(body[0]["appId"], "demo"); - assert_eq!(body[0]["env"], "DEV"); - assert_eq!(body[0]["clusterName"], "default"); - assert_eq!(body[0]["appNamespaceName"], "application"); + assert_eq!(body["appId"], "demo"); + assert_eq!(body["name"], "application"); + assert_eq!(body["format"], "properties"); + assert_eq!(body["isPublic"], true); + assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); } #[test] @@ -505,6 +596,20 @@ 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#" diff --git a/tests/profile.rs b/tests/profile.rs index 2a552a2..ea0a54a 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -123,6 +123,32 @@ output = "table" 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(); @@ -403,6 +429,40 @@ fn init_ignores_blank_setup_values_and_uses_defaults() { 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(); From e8e43a6f614888ac1f33e3af76d8db694f878d87 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 15:00:14 +0800 Subject: [PATCH 12/18] fix: avoid persisting environment auth token --- src/command.rs | 2 +- src/credential.rs | 19 +++++++++++++++++++ tests/auth.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/command.rs b/src/command.rs index 480520a..00a3ff4 100644 --- a/src/command.rs +++ b/src/command.rs @@ -119,7 +119,7 @@ fn execute_auth( if !loaded.config.profiles.contains_key(&profile) { return Err(CliError::profile_not_found(&profile, writer_output)); } - let token = credential::token_from_env_or_stdin(token_stdin, writer_output)?; + let token = credential::token_from_login_input(token_stdin, writer_output)?; let credential_ref = store_setup_token( &loaded.path, diff --git a/src/credential.rs b/src/credential.rs index a9cb294..83f54b8 100644 --- a/src/credential.rs +++ b/src/credential.rs @@ -272,6 +272,25 @@ pub fn token_from_env_or_stdin( )) } +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) diff --git a/tests/auth.rs b/tests/auth.rs index 3774059..1320c48 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -94,6 +94,35 @@ server = "https://apollo-dev.example.com" 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(); From 1cc8f74787a7cc590cc6e0f44efe2263c820ce5e Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 15:32:19 +0800 Subject: [PATCH 13/18] fix: address latest review feedback --- src/command.rs | 89 +++++++++++++++++++++++++++++++--- src/http.rs | 1 + tests/auth.rs | 25 ++++++++++ tests/openapi.rs | 122 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 230 insertions(+), 7 deletions(-) diff --git a/src/command.rs b/src/command.rs index 00a3ff4..c78b785 100644 --- a/src/command.rs +++ b/src/command.rs @@ -72,15 +72,13 @@ fn execute_auth( output: OutputFormat, ) -> Result { let loaded = load_config(output)?; - let writer_output = resolve_output(cli, &loaded, output)?; - let writer = OutputWriter::new(writer_output); match command { AuthCommand::Status => { - if std::env::var("APOLLO_TOKEN") - .ok() - .is_some_and(|token| !token.trim().is_empty()) - { + if env_token_is_set() { + 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 profile = cli .global .profile @@ -98,6 +96,8 @@ fn execute_auth( return Ok(writer.render_success(&response, response.render_table())); } + 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()); @@ -114,6 +114,8 @@ fn execute_auth( token_stdin, store_token_in_file, } => { + 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) { @@ -147,6 +149,8 @@ fn execute_auth( Ok(writer.render_success(&response, response.render_table())) } AuthCommand::Logout => { + 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") @@ -458,10 +462,13 @@ fn execute_config( let body = json!({ "key": key, "value": value, - "comment": comment.unwrap_or_default(), "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())) @@ -623,6 +630,10 @@ impl OpenApiCommandContext { fn openapi_context(cli: &Cli, output: OutputFormat) -> Result { 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)?; @@ -645,6 +656,55 @@ fn openapi_context(cli: &Cli, output: OutputFormat) -> Result 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 render_openapi_response(writer: &OutputWriter, response: &OpenApiResponse) -> RenderedOutput { writer.render_success(response, response.render_table()) } @@ -688,6 +748,20 @@ fn output_for_confirmation(cli: &Cli, output: OutputFormat) -> OutputFormat { .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 @@ -784,6 +858,7 @@ fn sync_body( "clusterName": target_cluster, "namespaceName": target_namespace.unwrap_or_else(|| scope.namespace.clone()), }], + "syncItems": [], }) } diff --git a/src/http.rs b/src/http.rs index 7b4fe2a..9a98ec7 100644 --- a/src/http.rs +++ b/src/http.rs @@ -76,6 +76,7 @@ impl OpenApiClient { )); } + let body = redact_exact_token(body, self.token.expose_secret()); let data = if body.trim().is_empty() { Value::Null } else { diff --git a/tests/auth.rs b/tests/auth.rs index 1320c48..9330cc6 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -66,6 +66,31 @@ fn auth_status_reports_environment_token_without_profile() { 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(); diff --git a/tests/openapi.rs b/tests/openapi.rs index fdfc51d..4225d82 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -46,6 +46,30 @@ fn api_get_calls_openapi_with_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 app_and_env_commands_call_openapi_endpoints() { let app_server = TestServer::json(r#"[{"appId":"demo"}]"#); @@ -216,6 +240,32 @@ fn openapi_error_redacts_sensitive_response_body_to_stderr() { assert!(stderr.contains("[REDACTED]")); } +#[test] +fn openapi_success_redacts_exact_token_from_response_body() { + let server = TestServer::json(r#"{"message":"consumer-token"}"#); + 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!(!stdout.contains("consumer-token")); +} + #[test] fn config_set_with_yes_sends_update_payload() { let server = TestServer::empty(); @@ -245,6 +295,41 @@ fn config_set_with_yes_sends_update_payload() { 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] @@ -422,6 +507,43 @@ fn config_apply_with_yes_uses_synchronize_endpoint() { 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"], Value::Array(vec![])); +} + +#[test] +fn config_diff_sends_empty_sync_items() { + 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([ + "--output", + "json", + "config", + "diff", + "--env", + "DEV", + "--app", + "demo", + "--target-env", + "FAT", + ]) + .assert() + .success(); + + let request = server.request(); + assert_eq!(request.method, "POST"); + assert_eq!( + request.path, + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/items/diff" + ); + let body: Value = serde_json::from_str(&request.body).expect("json body"); + assert_eq!(body["syncItems"], Value::Array(vec![])); } #[derive(Debug)] From 497c017ead79ad4014dc9e4d778d08d59a75587c Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 16:06:53 +0800 Subject: [PATCH 14/18] fix: address new review feedback --- README.md | 2 ++ src/cli.rs | 2 ++ src/command.rs | 76 ++++++++++++++++++++++++++++++++++++------ tests/openapi.rs | 87 ++++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 142 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 07b6e75..9747aea 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,8 @@ 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` creates a private namespace by default. Pass `--public` only when the +namespace should be public. ## Global flags diff --git a/src/cli.rs b/src/cli.rs index ced8375..5cb84bf 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -153,6 +153,8 @@ pub enum NamespaceCommand { name: String, #[arg(long)] operator: Option, + #[arg(long = "public")] + public_namespace: bool, }, } diff --git a/src/command.rs b/src/command.rs index c78b785..f2b13ac 100644 --- a/src/command.rs +++ b/src/command.rs @@ -20,6 +20,7 @@ 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"; @@ -399,6 +400,7 @@ fn execute_namespace( scope, name, operator, + public_namespace, } => { let operator = required_operator( operator.as_deref(), @@ -413,7 +415,7 @@ fn execute_namespace( "appId": scope.app, "name": name, "format": "properties", - "isPublic": true, + "isPublic": public_namespace, "dataChangeCreatedBy": operator, }); openapi.request("POST", &path, Some(body)) @@ -500,7 +502,14 @@ fn execute_config( target_cluster, target_namespace, } => { - let body = sync_body(&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)) } @@ -516,7 +525,14 @@ fn execute_config( &openapi.context, openapi.context.output, )?; - let body = sync_body(&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 = append_query( format!("{}/items/synchronize", namespace_path(&scope)), "operator", @@ -538,13 +554,9 @@ fn execute_release( let openapi = openapi_context(cli, output)?; match command { ReleaseCommand::List { scope, page, size } => { - let mut path = format!("{}/releases/latest", namespace_path(&scope)); - if let Some(page) = page { - path = append_query(path, "page", &page.to_string()); - } - if let Some(size) = size { - path = append_query(path, "size", &size.to_string()); - } + 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 { @@ -845,11 +857,53 @@ fn item_path(scope: &NamespaceScopeArgs, key: &str) -> String { } } +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": [{ @@ -858,7 +912,7 @@ fn sync_body( "clusterName": target_cluster, "namespaceName": target_namespace.unwrap_or_else(|| scope.namespace.clone()), }], - "syncItems": [], + "syncItems": sync_items, }) } diff --git a/tests/openapi.rs b/tests/openapi.rs index 4225d82..78d8b19 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -175,7 +175,7 @@ fn namespace_config_and_release_commands_map_to_openapi_paths() { .success(); assert_eq!( release_server.request().path, - "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/latest" + "/openapi/v1/envs/DEV/apps/demo/clusters/default/namespaces/application/releases/active?page=0&size=20" ); } @@ -465,13 +465,53 @@ fn namespace_create_with_yes_sends_namespace_instance_payload() { assert_eq!(body["appId"], "demo"); assert_eq!(body["name"], "application"); assert_eq!(body["format"], "properties"); + assert_eq!(body["isPublic"], false); + assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); +} + +#[test] +fn namespace_create_with_public_flag_sends_public_namespace_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", + "namespace", + "create", + "--env", + "DEV", + "--app", + "demo", + "--public", + "application", + ]) + .assert() + .success(); + + let request = server.request(); + let body: Value = serde_json::from_str(&request.body).expect("json body"); assert_eq!(body["isPublic"], true); assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); } #[test] fn config_apply_with_yes_uses_synchronize_endpoint() { - let server = TestServer::empty(); + 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, @@ -496,23 +536,36 @@ fn config_apply_with_yes_uses_synchronize_endpoint() { .assert() .success(); - let request = server.request(); - assert_eq!(request.method, "POST"); + let requests = server.requests(2); + assert_eq!(requests[0].method, "GET"); assert_eq!( - request.path, + 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(&request.body).expect("json body"); + 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"], Value::Array(vec![])); + assert_eq!(body["syncItems"][0]["key"], "timeout"); + assert_eq!(body["syncItems"][0]["value"], "3000"); } #[test] -fn config_diff_sends_empty_sync_items() { - let server = TestServer::empty(); +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, @@ -536,14 +589,20 @@ fn config_diff_sends_empty_sync_items() { .assert() .success(); - let request = server.request(); - assert_eq!(request.method, "POST"); + let requests = server.requests(2); + assert_eq!(requests[0].method, "GET"); assert_eq!( - request.path, + 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(&request.body).expect("json body"); - assert_eq!(body["syncItems"], Value::Array(vec![])); + 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"); } #[derive(Debug)] From f5bf9aaf42222441e91cde831d18b104ec5044bb Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 17:28:14 +0800 Subject: [PATCH 15/18] fix: address additional review comments --- README.md | 6 ++-- src/command.rs | 41 ++++++++++++++++------- src/http.rs | 59 +++++++++++++++++++++++++++++++--- src/redaction.rs | 1 + tests/openapi.rs | 84 +++++++++++++++++++++++++++++++++++++++++------- tests/profile.rs | 28 ++++++++++++++++ 6 files changed, 191 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 9747aea..3cbff28 100644 --- a/README.md +++ b/README.md @@ -61,8 +61,9 @@ 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` creates a private namespace by default. Pass `--public` only when the -namespace should be public. +`apollo namespace create` creates the namespace in the requested environment and cluster. It creates +a private namespace by default. Pass `--public` only when the namespace should first be registered as +a public AppNamespace and then created in the requested environment and cluster. ## Global flags @@ -252,6 +253,7 @@ Path and payload mapping follows the current Apollo Portal OpenAPI contract, inc - `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 explicit public namespace 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` diff --git a/src/command.rs b/src/command.rs index f2b13ac..e629cc3 100644 --- a/src/command.rs +++ b/src/command.rs @@ -218,7 +218,8 @@ fn execute_profile( Ok(writer.render_success(&response, response.render_table())) } ProfileCommand::Use { name } => { - let writer_output = output_from_flags_or_env(cli).unwrap_or(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); if !loaded.config.profiles.contains_key(&name) { return Err(CliError::profile_not_found(&name, writer_output)); @@ -407,17 +408,35 @@ fn execute_namespace( &openapi.context, openapi.context.output, )?; - let path = format!( - "/openapi/v1/apps/{}/appnamespaces", - encode_path_segment(&scope.app) - ); - let body = json!({ + let app_namespace_name = if public_namespace { + let path = format!( + "/openapi/v1/apps/{}/appnamespaces", + encode_path_segment(&scope.app) + ); + let body = json!({ + "appId": scope.app, + "name": name, + "format": "properties", + "isPublic": true, + "dataChangeCreatedBy": operator, + }); + let response = openapi.client.request("POST", &path, Some(body))?; + response + .data + .get("name") + .and_then(Value::as_str) + .unwrap_or(&name) + .to_owned() + } else { + name + }; + let path = append_query("/openapi/v1/namespaces".to_owned(), "operator", &operator); + let body = json!([{ "appId": scope.app, - "name": name, - "format": "properties", - "isPublic": public_namespace, - "dataChangeCreatedBy": operator, - }); + "env": scope.env, + "clusterName": scope.cluster, + "appNamespaceName": app_namespace_name, + }]); openapi.request("POST", &path, Some(body)) } } diff --git a/src/http.rs b/src/http.rs index 9a98ec7..54a4f41 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,5 +1,6 @@ -use serde::Serialize; +use serde::{Serialize, Serializer, ser::SerializeStruct}; use serde_json::Value; +use std::fmt; use std::time::Duration; use crate::cli::OutputFormat; @@ -9,15 +10,42 @@ use crate::redaction::{Redactor, Sensitive}; const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); const MAX_ERROR_BODY_CHARS: usize = 4096; -#[derive(Clone, Debug, Serialize)] +#[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.data).expect("openapi response table json") + 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() } } @@ -76,7 +104,6 @@ impl OpenApiClient { )); } - let body = redact_exact_token(body, self.token.expose_secret()); let data = if body.trim().is_empty() { Value::Null } else { @@ -86,6 +113,7 @@ impl OpenApiClient { Ok(OpenApiResponse { status: status.as_u16(), data, + redaction_token: self.token.clone(), }) } } @@ -109,6 +137,29 @@ fn redact_exact_token(value: String, token: &str) -> String { } } +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, 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(); diff --git a/src/redaction.rs b/src/redaction.rs index 75a3565..28070ed 100644 --- a/src/redaction.rs +++ b/src/redaction.rs @@ -56,6 +56,7 @@ impl Redactor { } } +#[derive(Clone)] pub struct Sensitive(String); impl Sensitive { diff --git a/tests/openapi.rs b/tests/openapi.rs index 78d8b19..87e1757 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -460,18 +460,20 @@ fn namespace_create_with_yes_sends_namespace_instance_payload() { let request = server.request(); assert_eq!(request.method, "POST"); - assert_eq!(request.path, "/openapi/v1/apps/demo/appnamespaces"); + assert_eq!(request.path, "/openapi/v1/namespaces?operator=apollo-bot"); let body: Value = serde_json::from_str(&request.body).expect("json body"); - assert_eq!(body["appId"], "demo"); - assert_eq!(body["name"], "application"); - assert_eq!(body["format"], "properties"); - assert_eq!(body["isPublic"], false); - assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); + assert_eq!(body[0]["appId"], "demo"); + assert_eq!(body[0]["env"], "DEV"); + assert_eq!(body[0]["clusterName"], "default"); + assert_eq!(body[0]["appNamespaceName"], "application"); } #[test] fn namespace_create_with_public_flag_sends_public_namespace_payload() { - let server = TestServer::empty(); + let server = TestServer::sequence(vec![ + (200, "application/json", r#"{"name":"public.application"}"#), + (200, "application/json", "{}"), + ]); let home = temp_home(); write_config( &home, @@ -496,10 +498,26 @@ fn namespace_create_with_public_flag_sends_public_namespace_payload() { .assert() .success(); - let request = server.request(); - let body: Value = serde_json::from_str(&request.body).expect("json body"); - assert_eq!(body["isPublic"], true); - assert_eq!(body["dataChangeCreatedBy"], "apollo-bot"); + let requests = server.requests(2); + assert_eq!(requests[0].method, "POST"); + assert_eq!(requests[0].path, "/openapi/v1/apps/demo/appnamespaces"); + let app_namespace_body: Value = serde_json::from_str(&requests[0].body).expect("json body"); + assert_eq!(app_namespace_body["appId"], "demo"); + assert_eq!(app_namespace_body["name"], "application"); + assert_eq!(app_namespace_body["format"], "properties"); + assert_eq!(app_namespace_body["isPublic"], true); + assert_eq!(app_namespace_body["dataChangeCreatedBy"], "apollo-bot"); + + 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]["appId"], "demo"); + assert_eq!(namespace_body[0]["env"], "DEV"); + assert_eq!(namespace_body[0]["clusterName"], "default"); + assert_eq!(namespace_body[0]["appNamespaceName"], "public.application"); } #[test] @@ -605,6 +623,50 @@ fn config_diff_populates_sync_items_from_source_namespace() { 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, diff --git a/tests/profile.rs b/tests/profile.rs index ea0a54a..7775ca9 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -283,6 +283,34 @@ output = "json" 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(); From bc5d56094a0351bab79106710d57c0419b178b2f Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 19:07:14 +0800 Subject: [PATCH 16/18] fix: address follow-up review comments --- src/command.rs | 62 +++++++++++++++++++++++++++++++++++++++++++- src/http.rs | 7 ++++- tests/openapi.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++- tests/profile.rs | 6 ++++- 4 files changed, 138 insertions(+), 4 deletions(-) diff --git a/src/command.rs b/src/command.rs index e629cc3..385847c 100644 --- a/src/command.rs +++ b/src/command.rs @@ -325,6 +325,10 @@ fn execute_profile_setup( 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, @@ -332,7 +336,7 @@ fn execute_profile_setup( server, output: response_output.to_string(), operator, - credential, + credential: response_credential, config_path: loaded.path.display().to_string(), next_steps: vec![ "apollo profile show".to_owned(), @@ -544,6 +548,14 @@ fn execute_config( &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, @@ -660,6 +672,15 @@ impl OpenApiCommandContext { } 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); @@ -736,6 +757,45 @@ fn env_openapi_context( })) } +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()) } diff --git a/src/http.rs b/src/http.rs index 54a4f41..6ed22bc 100644 --- a/src/http.rs +++ b/src/http.rs @@ -153,7 +153,12 @@ fn redact_exact_token_value(value: Value, token: &str) -> Value { ), Value::Object(map) => Value::Object( map.into_iter() - .map(|(key, value)| (key, redact_exact_token_value(value, token))) + .map(|(key, value)| { + ( + key.replace(token, "[REDACTED]"), + redact_exact_token_value(value, token), + ) + }) .collect(), ), value => value, diff --git a/tests/openapi.rs b/tests/openapi.rs index 87e1757..7525d02 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -70,6 +70,34 @@ active_profile = "missing" 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"}]"#); @@ -242,7 +270,7 @@ fn openapi_error_redacts_sensitive_response_body_to_stderr() { #[test] fn openapi_success_redacts_exact_token_from_response_body() { - let server = TestServer::json(r#"{"message":"consumer-token"}"#); + let server = TestServer::json(r#"{"message":"consumer-token","consumer-token":"value"}"#); let home = temp_home(); let assert = base_command(&home) @@ -263,6 +291,7 @@ fn openapi_success_redacts_exact_token_from_response_body() { 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")); } @@ -574,6 +603,42 @@ fn config_apply_with_yes_uses_synchronize_endpoint() { 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![ diff --git a/tests/profile.rs b/tests/profile.rs index 7775ca9..82a4879 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -595,7 +595,7 @@ key = "dev" .expect("credential dir"); fs::write(credential_file_path(&home, "dev"), "secret-from-file\n").expect("credential file"); - base_command(&home) + let assert = base_command(&home) .args([ "--server", "https://apollo-new.example.com", @@ -607,6 +607,10 @@ key = "dev" .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\"")); From 252be79bd77e58d8f9d59fe18921d973e670645b Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sat, 13 Jun 2026 20:01:46 +0800 Subject: [PATCH 17/18] fix: address latest review comments --- README.md | 9 +++-- src/command.rs | 99 ++++++++++++++++++++++++++++++++++-------------- src/config.rs | 19 ++++++++-- tests/auth.rs | 24 ++++++++++++ tests/openapi.rs | 57 ++++++++++++++++++---------- tests/profile.rs | 31 +++++++++++++++ 6 files changed, 184 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 3cbff28..a79553a 100644 --- a/README.md +++ b/README.md @@ -61,9 +61,10 @@ 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` creates the namespace in the requested environment and cluster. It creates -a private namespace by default. Pass `--public` only when the namespace should first be registered as -a public AppNamespace and then created in the requested environment and cluster. +`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 @@ -253,7 +254,7 @@ Path and payload mapping follows the current Apollo Portal OpenAPI contract, inc - `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 explicit public namespace registration +- `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` diff --git a/src/command.rs b/src/command.rs index 385847c..624f617 100644 --- a/src/command.rs +++ b/src/command.rs @@ -72,13 +72,14 @@ fn execute_auth( cli: &Cli, output: OutputFormat, ) -> Result { - let loaded = load_config(output)?; - match command { AuthCommand::Status => { if env_token_is_set() { - let writer_output = resolve_output(cli, &loaded, output) - .unwrap_or_else(|_| output_from_flags_or_env(cli).unwrap_or(output)); + 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 @@ -86,7 +87,12 @@ fn execute_auth( .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)); + .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(), @@ -97,6 +103,7 @@ fn execute_auth( 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)?; @@ -115,6 +122,7 @@ fn execute_auth( 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)?; @@ -150,6 +158,7 @@ fn execute_auth( 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)?; @@ -276,7 +285,8 @@ fn execute_profile_setup( output: OutputFormat, ) -> Result { let loaded = load_config(output)?; - let writer_output = output_from_flags_or_env(cli).unwrap_or(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(); @@ -363,7 +373,7 @@ fn execute_app( } } AppCommand::Get { app_id } => { - append_query("/openapi/v1/apps".to_owned(), "appIds", &app_id) + format!("/openapi/v1/apps/{}", encode_path_segment(&app_id)) } }; openapi.request("GET", &path, None) @@ -412,28 +422,8 @@ fn execute_namespace( &openapi.context, openapi.context.output, )?; - let app_namespace_name = if public_namespace { - let path = format!( - "/openapi/v1/apps/{}/appnamespaces", - encode_path_segment(&scope.app) - ); - let body = json!({ - "appId": scope.app, - "name": name, - "format": "properties", - "isPublic": true, - "dataChangeCreatedBy": operator, - }); - let response = openapi.client.request("POST", &path, Some(body))?; - response - .data - .get("name") - .and_then(Value::as_str) - .unwrap_or(&name) - .to_owned() - } else { - name - }; + 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, @@ -446,6 +436,57 @@ fn execute_namespace( } } +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 { + 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 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, diff --git a/src/config.rs b/src/config.rs index dc23dff..340cba7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -167,10 +167,10 @@ fn config_path_for_platform( .get("XDG_CONFIG_HOME") .filter(|value| !value.is_empty()) .cloned() + .map(PathBuf::from) + .filter(|path| path.is_absolute()) { - Ok(PathBuf::from(xdg_config_home) - .join("apollo") - .join("config.toml")) + Ok(xdg_config_home.join("apollo").join("config.toml")) } else { Ok(home()?.join(".config").join("apollo").join("config.toml")) } @@ -298,6 +298,19 @@ mod tests { ); } + #[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(""))]); diff --git a/tests/auth.rs b/tests/auth.rs index 9330cc6..9f2f6f7 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -66,6 +66,30 @@ fn auth_status_reports_environment_token_without_profile() { 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(); diff --git a/tests/openapi.rs b/tests/openapi.rs index 7525d02..9bb3466 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -112,7 +112,7 @@ fn app_and_env_commands_call_openapi_endpoints() { .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"}]"#); + 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") @@ -120,10 +120,7 @@ fn app_and_env_commands_call_openapi_endpoints() { .assert() .success() .stdout(predicate::str::contains(r#""appId": "demo""#)); - assert_eq!( - app_get_server.request().path, - "/openapi/v1/apps?appIds=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())); @@ -463,7 +460,10 @@ fn config_set_falls_back_to_create_when_update_reports_missing_item() { #[test] fn namespace_create_with_yes_sends_namespace_instance_payload() { - let server = TestServer::empty(); + let server = TestServer::sequence(vec![ + (200, "application/json", r#"{"name":"settings.json"}"#), + (200, "application/json", "{}"), + ]); let home = temp_home(); write_config( &home, @@ -482,25 +482,41 @@ fn namespace_create_with_yes_sends_namespace_instance_payload() { "DEV", "--app", "demo", - "application", + "settings.json", ]) .assert() .success(); - let request = server.request(); - assert_eq!(request.method, "POST"); - assert_eq!(request.path, "/openapi/v1/namespaces?operator=apollo-bot"); - let body: Value = serde_json::from_str(&request.body).expect("json body"); - assert_eq!(body[0]["appId"], "demo"); - assert_eq!(body[0]["env"], "DEV"); - assert_eq!(body[0]["clusterName"], "default"); - assert_eq!(body[0]["appNamespaceName"], "application"); + let requests = server.requests(2); + assert_eq!(requests[0].method, "POST"); + assert_eq!(requests[0].path, "/openapi/v1/apps/demo/appnamespaces"); + let app_namespace_body: Value = serde_json::from_str(&requests[0].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[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]["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_with_public_flag_sends_public_namespace_payload() { let server = TestServer::sequence(vec![ - (200, "application/json", r#"{"name":"public.application"}"#), + ( + 200, + "application/json", + r#"{"name":"public.application.yml"}"#, + ), (200, "application/json", "{}"), ]); let home = temp_home(); @@ -522,7 +538,7 @@ fn namespace_create_with_public_flag_sends_public_namespace_payload() { "--app", "demo", "--public", - "application", + "application.yml", ]) .assert() .success(); @@ -533,7 +549,7 @@ fn namespace_create_with_public_flag_sends_public_namespace_payload() { let app_namespace_body: Value = serde_json::from_str(&requests[0].body).expect("json body"); assert_eq!(app_namespace_body["appId"], "demo"); assert_eq!(app_namespace_body["name"], "application"); - assert_eq!(app_namespace_body["format"], "properties"); + assert_eq!(app_namespace_body["format"], "yml"); assert_eq!(app_namespace_body["isPublic"], true); assert_eq!(app_namespace_body["dataChangeCreatedBy"], "apollo-bot"); @@ -546,7 +562,10 @@ fn namespace_create_with_public_flag_sends_public_namespace_payload() { 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"); + assert_eq!( + namespace_body[0]["appNamespaceName"], + "public.application.yml" + ); } #[test] diff --git a/tests/profile.rs b/tests/profile.rs index 82a4879..5a01dc3 100644 --- a/tests/profile.rs +++ b/tests/profile.rs @@ -543,6 +543,37 @@ output = "json" 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(); From bd7cb17359021245e3412e47265f0ff78fbcf1c4 Mon Sep 17 00:00:00 2001 From: Jason Song Date: Sun, 14 Jun 2026 10:34:38 +0800 Subject: [PATCH 18/18] fix: reuse existing app namespaces --- src/command.rs | 28 ++++++++++++++++ tests/openapi.rs | 86 ++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 100 insertions(+), 14 deletions(-) diff --git a/src/command.rs b/src/command.rs index 624f617..f4c7cb0 100644 --- a/src/command.rs +++ b/src/command.rs @@ -448,6 +448,10 @@ fn register_app_namespace( 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", @@ -469,6 +473,30 @@ fn register_app_namespace( .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"] { diff --git a/tests/openapi.rs b/tests/openapi.rs index 9bb3466..4f2f43a 100644 --- a/tests/openapi.rs +++ b/tests/openapi.rs @@ -461,6 +461,7 @@ fn config_set_falls_back_to_create_when_update_reports_missing_item() { #[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", "{}"), ]); @@ -487,31 +488,82 @@ fn namespace_create_with_yes_sends_namespace_instance_payload() { .assert() .success(); - let requests = server.requests(2); - assert_eq!(requests[0].method, "POST"); - assert_eq!(requests[0].path, "/openapi/v1/apps/demo/appnamespaces"); - let app_namespace_body: Value = serde_json::from_str(&requests[0].body).expect("json body"); + 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[1].method, "POST"); + assert_eq!(requests[2].method, "POST"); assert_eq!( - requests[1].path, + requests[2].path, "/openapi/v1/namespaces?operator=apollo-bot" ); - let namespace_body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + 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", @@ -543,22 +595,28 @@ fn namespace_create_with_public_flag_sends_public_namespace_payload() { .assert() .success(); - let requests = server.requests(2); - assert_eq!(requests[0].method, "POST"); - assert_eq!(requests[0].path, "/openapi/v1/apps/demo/appnamespaces"); - let app_namespace_body: Value = serde_json::from_str(&requests[0].body).expect("json body"); + 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[1].method, "POST"); + assert_eq!(requests[2].method, "POST"); assert_eq!( - requests[1].path, + requests[2].path, "/openapi/v1/namespaces?operator=apollo-bot" ); - let namespace_body: Value = serde_json::from_str(&requests[1].body).expect("json body"); + 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");