From 6912a4600141a6c45fa9177f18a8ec72ec37571c750d76dc57ad0790a78ae683 Mon Sep 17 00:00:00 2001 From: Tyler J King Date: Fri, 27 Mar 2026 19:52:54 -0400 Subject: [PATCH] =?UTF-8?q?feat:=20bxnet-ops=20=E2=80=94=20BXNet=20governe?= =?UTF-8?q?d=20shell?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fork of guildhouse/org-ops. Binary: guildhouse-ops → bxnet-ops DID: guildhouse.dev → bxnet.io Upstream remote configured for sync. Co-Authored-By: Claude Opus 4.6 (1M context) --- Cargo.lock | 1943 +++++++++++++++++++++++++ Cargo.toml | 8 + README.md | 23 +- org-ops-cli/Cargo.toml | 13 + org-ops-cli/src/main.rs | 31 + org-ops-core/Cargo.toml | 17 + org-ops-core/src/ai_risk_analysis.rs | 207 +++ org-ops-core/src/apply_gate.rs | 246 ++++ org-ops-core/src/auth_commands.rs | 332 +++++ org-ops-core/src/config.rs | 26 + org-ops-core/src/display.rs | 29 + org-ops-core/src/git_commands.rs | 403 +++++ org-ops-core/src/lib.rs | 265 ++++ org-ops-core/src/pkce.rs | 135 ++ org-ops-core/src/playbook_commands.rs | 257 ++++ org-ops-core/src/score_fetcher.rs | 51 + org-ops-core/src/session.rs | 6 + org-ops-core/src/test_evidence.rs | 98 ++ org-ops-core/src/traits.rs | 88 ++ 19 files changed, 4177 insertions(+), 1 deletion(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 org-ops-cli/Cargo.toml create mode 100644 org-ops-cli/src/main.rs create mode 100644 org-ops-core/Cargo.toml create mode 100644 org-ops-core/src/ai_risk_analysis.rs create mode 100644 org-ops-core/src/apply_gate.rs create mode 100644 org-ops-core/src/auth_commands.rs create mode 100644 org-ops-core/src/config.rs create mode 100644 org-ops-core/src/display.rs create mode 100644 org-ops-core/src/git_commands.rs create mode 100644 org-ops-core/src/lib.rs create mode 100644 org-ops-core/src/pkce.rs create mode 100644 org-ops-core/src/playbook_commands.rs create mode 100644 org-ops-core/src/score_fetcher.rs create mode 100644 org-ops-core/src/session.rs create mode 100644 org-ops-core/src/test_evidence.rs create mode 100644 org-ops-core/src/traits.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..40155fd --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1943 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[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.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" +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 = "clap" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" +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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a" +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 = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[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 = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[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 = "guildhouse-ops" +version = "0.1.0" +dependencies = [ + "anyhow", + "org-ops-core", +] + +[[package]] +name = "h2" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[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.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +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.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[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", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8e7418f59cc01c88316161279a7f665217ae316b388e58a0d10e29f54f1e5eb" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[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.183" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[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 = "openssl" +version = "0.10.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.112" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "org-ops-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64", + "clap", + "rand", + "reqwest", + "serde", + "serde_json", + "sha2", + "urlencoding", + "uuid", +] + +[[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 = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +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 = "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 = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[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 = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef" +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 = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[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.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[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 = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[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 = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[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 = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[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.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[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", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[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_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[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-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..515e285 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +members = ["org-ops-core", "org-ops-cli"] +resolver = "2" + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" diff --git a/README.md b/README.md index 5180b39..2f28aae 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,24 @@ # bxnet-ops -BXNet governed shell binary — fork of org-ops with BXNet identity \ No newline at end of file +BXNet governed shell binary. Fork of [guildhouse/org-ops](https://git.guildhouse.dev/guildhouse/org-ops). + +## Identity + +- Consultancy DID: `did:web:bxnet.io` +- Operator DID: `did:web:bxnet.io/user/tking` +- Platform: Guildhouse PaaS + +## Usage + +```bash +bxnet-ops auth login +bxnet-ops playbook list +bxnet-ops playbook run cpanel-provision-account --target cpanel-server-01 +``` + +## Upstream sync + +```bash +git fetch upstream +git merge upstream/main +``` diff --git a/org-ops-cli/Cargo.toml b/org-ops-cli/Cargo.toml new file mode 100644 index 0000000..cbb7c84 --- /dev/null +++ b/org-ops-cli/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "bxnet-ops" +description = "Guildhouse governed operations CLI — reference org-ops implementation" +version.workspace = true +edition.workspace = true + +[[bin]] +name = "bxnet-ops" +path = "src/main.rs" + +[dependencies] +org-ops-core = { path = "../org-ops-core" } +anyhow = "1" diff --git a/org-ops-cli/src/main.rs b/org-ops-cli/src/main.rs new file mode 100644 index 0000000..148833b --- /dev/null +++ b/org-ops-cli/src/main.rs @@ -0,0 +1,31 @@ +use org_ops_core::{ + AuthCommands, AuthConfig, GitConfig, GovernedGitCommands, OrgOps, OrgOpsConfig, + PlaybookCommands, +}; + +fn main() -> anyhow::Result<()> { + let forgejo_token = std::env::var("FORGEJO_TOKEN").ok(); + + OrgOps::builder() + .with_config(OrgOpsConfig { + org_name: "BXNet".into(), + trust_domain: "bxnet.io".into(), + bascule_endpoint: "bascule.bxnet.io:443".into(), + chronicle_endpoint: "chronicle.bxnet.io:8080".into(), + binary_name: "bxnet-ops".into(), + description: "BXNet governed operations CLI".into(), + version: env!("CARGO_PKG_VERSION").into(), + }) + .with_commands(AuthCommands::new(AuthConfig::default())) + .with_commands(GovernedGitCommands::new(GitConfig { + forgejo_url: "https://git.bxnet.io".into(), + forgejo_token, + chronicle_webhook: "http://localhost:8090/webhook/forgejo".into(), + })) + .with_commands(PlaybookCommands::new( + "./playbooks", + "http://localhost:8090/webhook/forgejo", + )) + .build() + .run() +} diff --git a/org-ops-core/Cargo.toml b/org-ops-core/Cargo.toml new file mode 100644 index 0000000..3e33627 --- /dev/null +++ b/org-ops-core/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "org-ops-core" +description = "Framework for building governed consortium CLI tools" +version.workspace = true +edition.workspace = true + +[dependencies] +clap = { version = "4", features = ["derive", "string"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +anyhow = "1" +reqwest = { version = "0.12", features = ["json", "blocking"] } +rand = "0.8" +sha2 = "0.10" +base64 = "0.22" +urlencoding = "2" +uuid = { version = "1", features = ["v4"] } diff --git a/org-ops-core/src/ai_risk_analysis.rs b/org-ops-core/src/ai_risk_analysis.rs new file mode 100644 index 0000000..8ce612e --- /dev/null +++ b/org-ops-core/src/ai_risk_analysis.rs @@ -0,0 +1,207 @@ +//! AI agent risk analysis for playbook runs. +//! +//! Analyzes test result CIDs before production apply. +//! Produces confidence score + recommendation. + +use crate::test_evidence::TestRunResult; +use sha2::{Digest, Sha256}; + +/// Confidence thresholds for AI recommendations. +/// Loaded from AccordTemplate min_confidence_* fields when available. +/// Falls back to GCAP defaults when absent. +#[derive(Debug, Clone)] +pub struct ConfidenceThresholds { + pub auto_approve: u8, + pub totp_sufficient: u8, + pub peer_review_required: u8, +} + +impl Default for ConfidenceThresholds { + fn default() -> Self { + Self { + auto_approve: 90, + totp_sufficient: 75, + peer_review_required: 50, + } + } +} + +impl ConfidenceThresholds { + /// Load from AccordTemplate on cluster. + /// Falls back to defaults if fields are absent. + /// Unlike AccordMfaPolicy::from_accord, this is NOT fail-closed — + /// threshold absence falls back to safe defaults, not permissive ones. + pub fn from_accord(accord_name: &str) -> Self { + let output = std::process::Command::new("kubectl") + .args(["get", "accordtemplate", accord_name, "-o", "json"]) + .output(); + + match output { + Ok(out) if out.status.success() => { + let val: serde_json::Value = + serde_json::from_slice(&out.stdout).unwrap_or_default(); + let spec = &val["spec"]; + Self { + auto_approve: spec["min_confidence_for_auto_approve"] + .as_u64() + .unwrap_or(90) as u8, + totp_sufficient: spec["min_confidence_for_totp"] + .as_u64() + .unwrap_or(75) as u8, + peer_review_required: spec["min_confidence_for_peer_review"] + .as_u64() + .unwrap_or(50) as u8, + } + } + _ => Self::default(), + } + } +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RiskAnalysis { + pub confidence_score: u8, + pub recommendation: String, + pub reasoning: Vec, + pub test_results_analyzed: Vec, + pub diff_match: bool, + pub test_run_confidence: u8, +} + +impl RiskAnalysis { + /// Analyze test results and produce risk assessment. + pub fn analyze(test_results: &[TestRunResult], prod_diff_hash: Option<&str>) -> Self { + if test_results.is_empty() { + return Self { + confidence_score: 30, + recommendation: "APPROVE_WITH_REVIEW".into(), + reasoning: vec!["No test evidence. Manual review required.".into()], + test_results_analyzed: vec![], + diff_match: false, + test_run_confidence: 0, + }; + } + + let mut reasoning = Vec::new(); + let mut confidence: u32 = 50; + let mut all_passed = true; + let mut any_idempotent = false; + let mut diff_match = false; + let mut op_scores = Vec::new(); + + let cids: Vec = test_results.iter().map(|r| r.compute_cid()).collect(); + + for result in test_results { + op_scores.push(result.test_run_confidence_score()); + + if result.tasks_failed > 0 { + all_passed = false; + reasoning.push(format!("{} failure(s) in {} env", result.tasks_failed, result.test_environment.env_type)); + } + if result.idempotency_verified { + any_idempotent = true; + reasoning.push("Idempotency verified".into()); + } + if let Some(prod_hash) = prod_diff_hash { + let m = result.diff_matches_prod(prod_hash); + if m >= 0.9 { + diff_match = true; + reasoning.push("Test diff matches prod diff exactly".into()); + confidence += 20; + } else if m >= 0.5 { + reasoning.push("Test diff partially matches".into()); + confidence += 5; + } + } + } + + if all_passed { + confidence += 20; + reasoning.push("All test runs passed".into()); + } + if any_idempotent { + confidence += 10; + } + + let avg_op = if op_scores.is_empty() { + 0 + } else { + op_scores.iter().map(|&s| s as u32).sum::() / op_scores.len() as u32 + } as u8; + + confidence += (avg_op as u32 * 20) / 100; + let confidence = confidence.min(100) as u8; + + // Accord-controlled thresholds. Defaults: auto=90, totp=75, peer=50. + let thresholds = ConfidenceThresholds::default(); + let recommendation = if confidence >= thresholds.auto_approve { + reasoning.push(format!( + "High confidence ({}%). Auto-approve threshold ({}) met.", + confidence, thresholds.auto_approve + )); + "APPROVE" + } else if confidence >= thresholds.totp_sufficient { + reasoning.push(format!( + "Good confidence ({}%). Standard MFA sufficient (threshold: {}).", + confidence, thresholds.totp_sufficient + )); + "APPROVE_WITH_REVIEW" + } else if confidence >= thresholds.peer_review_required { + reasoning.push(format!( + "Moderate confidence ({}%). Peer review recommended (threshold: {}).", + confidence, thresholds.peer_review_required + )); + "PEER_REVIEW" + } else { + reasoning.push(format!("Low confidence ({}%). Do not apply.", confidence)); + "REJECT" + }; + + Self { + confidence_score: confidence, + recommendation: recommendation.into(), + reasoning, + test_results_analyzed: cids, + diff_match, + test_run_confidence: avg_op, + } + } + + pub fn print_summary(&self) { + println!("\n-- AI Risk Analysis --"); + println!(" {}% confidence", self.confidence_score); + println!(" Recommendation: {}", self.recommendation); + for r in &self.reasoning { + println!(" - {}", r); + } + if self.diff_match { + println!(" Diff match: exact"); + } + println!("--"); + } + + /// Emit AI_RISK_ASSESSMENT to Chronicle. + pub fn emit_chronicle(&self, agent_did: &str, playbook_name: &str, webhook: &str) { + let reasoning_json = serde_json::to_string(&self.reasoning).unwrap_or_default(); + let mut h = Sha256::new(); + h.update(reasoning_json.as_bytes()); + let reasoning_cid = format!("sha256:{:x}", h.finalize()); + + let body = serde_json::json!({ + "pusher": {"login": agent_did}, + "ref": "refs/ai/AI_RISK_ASSESSMENT", + "repository": {"full_name": "platform/ai-governance"}, + "commits": [{"message": format!("AI_RISK_ASSESSMENT: {} {}%", playbook_name, self.confidence_score)}], + }); + + reqwest::blocking::Client::new() + .post(webhook) + .header("X-Forgejo-Event", "push") + .json(&body) + .timeout(std::time::Duration::from_secs(5)) + .send() + .ok(); + + let _ = reasoning_cid; // used in full implementation + } +} diff --git a/org-ops-core/src/apply_gate.rs b/org-ops-core/src/apply_gate.rs new file mode 100644 index 0000000..8ac3e33 --- /dev/null +++ b/org-ops-core/src/apply_gate.rs @@ -0,0 +1,246 @@ +//! The apply authorization gate. +//! +//! Sits between --check (diff) and apply phases. +//! Accord-controlled MFA before any CAP_MUTATE+ operation. +//! +//! SECURITY INVARIANT: All accord loading failures are fail-closed. +//! If the accord cannot be loaded, the operation MUST be blocked. +//! Never fall back to a permissive default on error. + +use sha2::{Digest, Sha256}; +use std::io::{BufRead, Write}; +use std::time::{Duration, Instant}; + +/// Error type for accord loading failures. +/// All variants are fail-closed: the caller MUST block the operation. +#[derive(Debug)] +pub enum AccordLoadError { + /// kubectl unavailable or returned non-zero exit code. + KubectlUnavailable(String), + /// kubectl returned non-JSON output. + JsonParseFailed(String), + /// AccordTemplate not found on cluster. + NotFound(String), +} + +impl std::fmt::Display for AccordLoadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::KubectlUnavailable(e) => write!( + f, + "kubectl unavailable: {e}. Governed operations blocked \ + until cluster connectivity is restored." + ), + Self::JsonParseFailed(e) => write!( + f, + "AccordTemplate returned non-JSON: {e}. \ + Governed operations blocked." + ), + Self::NotFound(name) => write!( + f, + "AccordTemplate '{name}' not found on cluster. \ + Governed operations require a named accord. Blocked." + ), + } + } +} + +impl std::error::Error for AccordLoadError {} + +#[derive(Debug, Clone)] +pub struct AccordMfaPolicy { + pub mfa_required: bool, + pub mfa_method: String, + pub change_review_window_secs: u64, + pub require_diff_acknowledgment: bool, + pub diff_hash_in_token: bool, + pub mfa_timeout_secs: u64, +} + +impl AccordMfaPolicy { + /// Load from AccordTemplate via kubectl. + /// + /// Returns `Err` on any failure — kubectl unavailable, non-JSON output, + /// or accord not found. The caller MUST block the governed operation. + /// This is a fail-closed governance control. + pub fn from_accord(accord_name: &str) -> Result { + let output = std::process::Command::new("kubectl") + .args(["get", "accordtemplate", accord_name, "-o", "json"]) + .output(); + + match output { + Ok(out) if out.status.success() => { + let val: serde_json::Value = serde_json::from_slice(&out.stdout) + .map_err(|e| { + AccordLoadError::JsonParseFailed(format!( + "{e}. stdout: {}", + String::from_utf8_lossy(&out.stdout) + .chars() + .take(200) + .collect::() + )) + })?; + let spec = &val["spec"]; + Ok(Self { + mfa_required: spec["mfa_required_for_apply"].as_bool().unwrap_or(false), + mfa_method: spec["mfa_method"] + .as_str() + .unwrap_or("none") + .to_string(), + change_review_window_secs: spec["change_review_window_secs"] + .as_u64() + .unwrap_or(30), + require_diff_acknowledgment: spec["require_diff_acknowledgment"] + .as_bool() + .unwrap_or(true), + diff_hash_in_token: spec["diff_hash_in_mfa_token"] + .as_bool() + .unwrap_or(true), + mfa_timeout_secs: spec["mfa_timeout_secs"].as_u64().unwrap_or(300), + }) + } + Ok(out) => { + let stderr = String::from_utf8_lossy(&out.stderr).to_string(); + if stderr.contains("not found") || stderr.contains("NotFound") { + Err(AccordLoadError::NotFound(accord_name.to_string())) + } else { + Err(AccordLoadError::KubectlUnavailable(format!( + "exit {:?}: {}", + out.status.code(), + stderr.chars().take(200).collect::() + ))) + } + } + Err(e) => Err(AccordLoadError::KubectlUnavailable(e.to_string())), + } + } +} + +/// Hash the diff output. +pub fn hash_diff(diff: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(diff.as_bytes()); + format!("sha256:{:x}", hasher.finalize()) +} + +/// Display diff with review countdown. +fn display_diff_with_countdown(diff: &str, diff_hash: &str, window_secs: u64) { + println!("\n-- Proposed changes (diff) --"); + println!("{}", diff); + println!("--"); + println!(" Diff hash: {}", diff_hash); + + if window_secs > 0 { + let start = Instant::now(); + let window = Duration::from_secs(window_secs); + while start.elapsed() < window { + let remaining = window.saturating_sub(start.elapsed()).as_secs(); + print!("\r Review: {} seconds remaining... ", remaining); + std::io::stdout().flush().ok(); + std::thread::sleep(Duration::from_secs(1)); + } + println!("\r Review: complete. "); + } +} + +/// Prompt for diff acknowledgment. +fn prompt_acknowledgment(diff_hash: &str) -> anyhow::Result<()> { + println!("\nI have reviewed the diff and confirm it is the intended change."); + println!("Diff: {}", diff_hash); + print!("Confirm [yes/no]: "); + std::io::stdout().flush()?; + let mut line = String::new(); + std::io::stdin().lock().read_line(&mut line)?; + if line.trim().eq_ignore_ascii_case("yes") { + println!(" Acknowledged."); + Ok(()) + } else { + anyhow::bail!("Change not acknowledged. Apply cancelled.") + } +} + +/// TOTP verification (format check — server validation next sprint). +fn verify_totp(diff_hash: &str, timeout_secs: u64) -> anyhow::Result { + println!("\n-- MFA Sign-off Required --"); + println!(" Method: TOTP"); + if diff_hash.len() > 16 { + println!(" Signing: {}...", &diff_hash[..24]); + } + println!(" Expires in: {} seconds", timeout_secs); + print!(" Enter 6-digit code: "); + std::io::stdout().flush()?; + + let mut code = String::new(); + std::io::stdin().lock().read_line(&mut code)?; + let code = code.trim().to_string(); + + if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) { + anyhow::bail!("Invalid TOTP code. Expected 6 digits."); + } + + println!(" MFA accepted. (Server validation: next sprint)"); + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + Ok(format!("totp-auth:{}:{}", diff_hash, now)) +} + +/// Run the full apply gate. Returns the authorized diff_hash. +pub fn run_apply_gate( + diff: &str, + policy: &AccordMfaPolicy, + actor_did: &str, + chronicle_webhook: &str, +) -> anyhow::Result { + let diff_hash = hash_diff(diff); + + // Step 1: Display diff with countdown + display_diff_with_countdown(diff, &diff_hash, policy.change_review_window_secs); + + // Step 2: Acknowledgment + if policy.require_diff_acknowledgment { + prompt_acknowledgment(&diff_hash)?; + } + + // Step 3: MFA + let _auth_token = match policy.mfa_method.as_str() { + "totp" => verify_totp(&diff_hash, policy.mfa_timeout_secs)?, + "webauthn" | "push" | "peer_review" => { + println!(" {} method: falling back to TOTP (next sprint)", policy.mfa_method); + verify_totp(&diff_hash, policy.mfa_timeout_secs)? + } + _ => "no-mfa".to_string(), + }; + + // Step 4: Chronicle APPLY_AUTHORIZED + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let body = serde_json::json!({ + "pusher": {"login": actor_did}, + "ref": "refs/governance/APPLY_AUTHORIZED", + "repository": {"full_name": "platform/apply-governance"}, + "commits": [{"message": format!("APPLY_AUTHORIZED: {} signed {}", actor_did, &diff_hash[..24])}], + }); + + let ok = reqwest::blocking::Client::new() + .post(chronicle_webhook) + .header("X-Forgejo-Event", "push") + .json(&body) + .timeout(Duration::from_secs(5)) + .send() + .map(|r| r.status().is_success()) + .unwrap_or(false); + + if ok { + println!("\n Chronicle: APPLY_AUTHORIZED recorded"); + } + + println!(" Authorization valid for {} seconds.", policy.mfa_timeout_secs); + println!("--"); + + Ok(diff_hash) +} diff --git a/org-ops-core/src/auth_commands.rs b/org-ops-core/src/auth_commands.rs new file mode 100644 index 0000000..fce37df --- /dev/null +++ b/org-ops-core/src/auth_commands.rs @@ -0,0 +1,332 @@ +//! OIDC authentication via did-bridge. +//! +//! auth login: start did-bridge → token → certificate → store +//! auth status: show identity + expiry +//! auth logout: remove credentials + +use crate::session::SessionContext; +use crate::traits::OrgCommands; +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +pub struct AuthConfig { + pub oidc_issuer: String, + pub client_id: String, + pub did_bridge_port: u16, +} + +impl Default for AuthConfig { + fn default() -> Self { + Self { + oidc_issuer: "https://auth.bxnet.io/realms/guildhouse".into(), + client_id: "bxnet-ops".into(), + did_bridge_port: 7777, + } + } +} + +fn config_dir() -> PathBuf { + let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); + PathBuf::from(home).join(".config").join("bxnet-ops") +} + +fn cert_path() -> PathBuf { + config_dir().join("identity.pem") +} + +fn key_path() -> PathBuf { + config_dir().join("identity.key") +} + +fn did_path() -> PathBuf { + config_dir().join("identity.did") +} + +fn expiry_path() -> PathBuf { + config_dir().join("identity.expiry") +} + +pub struct AuthCommands { + config: AuthConfig, +} + +impl AuthCommands { + pub fn new(config: AuthConfig) -> Self { + Self { config } + } + + fn ensure_config_dir() { + let dir = config_dir(); + if !dir.exists() { + fs::create_dir_all(&dir).ok(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).ok(); + } + } + } + + fn start_did_bridge(&self) -> anyhow::Result> { + // Find did_bridge.py + let home = std::env::var("HOME").unwrap_or_default(); + let bridge_paths = [ + format!("{}/projects/substrate-project/guildhouse/services/did-bridge/did_bridge.py", home), + "did_bridge.py".to_string(), + ]; + + for path in &bridge_paths { + if std::path::Path::new(path).exists() { + let child = Command::new("python3") + .arg(path) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn()?; + std::thread::sleep(std::time::Duration::from_secs(2)); + eprintln!(" did-bridge started (pid {})", child.id()); + return Ok(Some(child)); + } + } + + // Try docker + let output = Command::new("docker") + .args(["run", "--rm", "-d", "-p", "127.0.0.1:7777:7777", "guildhouse/did-bridge:latest"]) + .output(); + + if let Ok(o) = output { + if o.status.success() { + std::thread::sleep(std::time::Duration::from_secs(2)); + eprintln!(" did-bridge started (docker)"); + return Ok(None); + } + } + + anyhow::bail!("did-bridge not available. Install Python cryptography package or Docker.") + } + + fn derive_certificate(&self, token: &str) -> anyhow::Result<(String, String, String, i64)> { + let url = format!("http://127.0.0.1:{}/derive", self.config.did_bridge_port); + let body = serde_json::json!({"oidc_token": token}).to_string(); + + let client = reqwest::blocking::Client::new(); + let resp = client + .post(&url) + .header("Content-Type", "application/json") + .body(body) + .timeout(std::time::Duration::from_secs(10)) + .send()?; + + if !resp.status().is_success() { + anyhow::bail!("did-bridge error: {}", resp.status()); + } + + let data: serde_json::Value = resp.json()?; + let cert = data["certificate_pem"].as_str().ok_or_else(|| anyhow::anyhow!("No cert"))?.to_string(); + let key = data["private_key_pem"].as_str().unwrap_or("").to_string(); + let did = data["did"].as_str().unwrap_or("unknown").to_string(); + let expires = data["expires_at"].as_i64().unwrap_or(0); + + Ok((cert, key, did, expires)) + } + + fn cmd_login(&self, _ctx: &SessionContext) -> anyhow::Result<()> { + println!("Authenticating via OIDC..."); + println!(" Issuer: {}", self.config.oidc_issuer); + + Self::ensure_config_dir(); + + // Start did-bridge + eprintln!("Starting did-bridge..."); + let mut bridge = self.start_did_bridge()?; + + // PKCE browser flow (RFC 7636): + use crate::pkce; + + let port = pkce::find_free_port(); + let redirect_uri = format!("http://127.0.0.1:{}/callback", port); + let code_verifier = pkce::generate_code_verifier(); + let code_challenge = pkce::derive_code_challenge(&code_verifier); + let state = format!("{:x}", rand::random::()); + + let auth_url = pkce::authorization_url( + &self.config.oidc_issuer, + &self.config.client_id, + &redirect_uri, + &code_challenge, + &state, + ); + + println!(); + // Open browser: + let opener = if std::env::var("WSL_DISTRO_NAME").is_ok() { + "wslview" + } else if cfg!(target_os = "macos") { + "open" + } else { + "xdg-open" + }; + println!(" Opening browser..."); + Command::new(opener).arg(&auth_url).spawn().ok(); + println!(" If browser didn't open, visit:"); + println!(" {}", auth_url); + println!(" Waiting for callback on port {}...", port); + + let (code, _returned_state) = match pkce::wait_for_callback(port) { + Ok(result) => result, + Err(e) => { + if let Some(ref mut child) = bridge { + child.kill().ok(); + } + anyhow::bail!("Auth failed: {}", e); + } + }; + + if code.is_empty() { + if let Some(ref mut child) = bridge { + child.kill().ok(); + } + anyhow::bail!("No authorization code received"); + } + + println!(" Authorization code received."); + + // Exchange code for token: + let token = match pkce::exchange_code( + &self.config.oidc_issuer, + &self.config.client_id, + &code, + &code_verifier, + &redirect_uri, + ) { + Ok(t) => t, + Err(e) => { + if let Some(ref mut child) = bridge { + child.kill().ok(); + } + anyhow::bail!("Token exchange failed: {}", e); + } + }; + + if token.is_empty() { + if let Some(ref mut child) = bridge { + child.kill().ok(); + } + anyhow::bail!("Empty token received"); + } + + println!("Deriving DID via did-bridge..."); + let result = self.derive_certificate(&token); + + // Kill bridge + if let Some(ref mut child) = bridge { + child.kill().ok(); + } + + // Token NOT stored. Drop it. + drop(token); + + let (cert, key, did, expires) = result?; + + // Store certificate and key (not token) + fs::write(cert_path(), &cert)?; + fs::write(key_path(), &key)?; + fs::write(did_path(), &did)?; + fs::write(expiry_path(), expires.to_string())?; + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(key_path(), fs::Permissions::from_mode(0o600)).ok(); + } + + println!(); + println!("Authenticated."); + println!(" DID: {}", did); + println!(" Certificate: {}", cert_path().display()); + println!(" Expires: 1 hour"); + println!(" Token: zeroized"); + + Ok(()) + } + + fn cmd_status(&self, _ctx: &SessionContext) -> anyhow::Result<()> { + if !cert_path().exists() { + println!("Not authenticated."); + println!("Run: guildhouse-ops auth login"); + return Ok(()); + } + + let did = fs::read_to_string(did_path()).unwrap_or("unknown".into()); + let expires: i64 = fs::read_to_string(expiry_path()) + .unwrap_or("0".into()) + .trim() + .parse() + .unwrap_or(0); + + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + + if expires > 0 && now > expires { + println!("Session expired."); + println!("Run: guildhouse-ops auth login"); + return Ok(()); + } + + let remaining = if expires > 0 { + format!("{} minutes", (expires - now) / 60) + } else { + "unknown".into() + }; + + println!("Authenticated"); + println!(" DID: {}", did); + println!(" Remaining: {}", remaining); + println!(" Certificate: {}", cert_path().display()); + + Ok(()) + } + + fn cmd_logout(&self, _ctx: &SessionContext) -> anyhow::Result<()> { + for path in &[cert_path(), key_path(), did_path(), expiry_path()] { + if path.exists() { + fs::remove_file(path)?; + } + } + println!("Logged out."); + Ok(()) + } +} + +impl OrgCommands for AuthCommands { + fn commands(&self) -> Vec { + vec![clap::Command::new("auth") + .about("OIDC authentication via did-bridge") + .subcommand(clap::Command::new("login").about("Authenticate and store certificate")) + .subcommand(clap::Command::new("status").about("Show identity and expiry")) + .subcommand(clap::Command::new("logout").about("Remove credentials"))] + } + + fn handles(&self, name: &str) -> bool { + name == "auth" + } + + fn handle( + &self, + _name: &str, + matches: &clap::ArgMatches, + ctx: &SessionContext, + ) -> anyhow::Result<()> { + match matches.subcommand() { + Some(("login", _)) => self.cmd_login(ctx), + Some(("status", _)) => self.cmd_status(ctx), + Some(("logout", _)) => self.cmd_logout(ctx), + _ => { + println!("Usage: auth "); + Ok(()) + } + } + } +} diff --git a/org-ops-core/src/config.rs b/org-ops-core/src/config.rs new file mode 100644 index 0000000..a704cc9 --- /dev/null +++ b/org-ops-core/src/config.rs @@ -0,0 +1,26 @@ +/// Configuration for an org-ops instance. +/// Fork org-ops and set these values for your consortium. +#[derive(Debug, Clone)] +pub struct OrgOpsConfig { + pub org_name: String, + pub trust_domain: String, + pub bascule_endpoint: String, + pub chronicle_endpoint: String, + pub binary_name: String, + pub description: String, + pub version: String, +} + +impl Default for OrgOpsConfig { + fn default() -> Self { + Self { + org_name: "BXNet".into(), + trust_domain: "bxnet.io".into(), + bascule_endpoint: "bascule.bxnet.io:443".into(), + chronicle_endpoint: "chronicle.bxnet.io:8080".into(), + binary_name: "bxnet-ops".into(), + description: "BXNet governed operations CLI".into(), + version: env!("CARGO_PKG_VERSION").into(), + } + } +} diff --git a/org-ops-core/src/display.rs b/org-ops-core/src/display.rs new file mode 100644 index 0000000..c4c7c8a --- /dev/null +++ b/org-ops-core/src/display.rs @@ -0,0 +1,29 @@ +pub struct SessionBanner<'a> { + pub org_name: &'a str, + pub cluster: &'a str, + pub risk_score: u8, + pub capability_ceiling: &'a str, + pub bom_triad_complete: bool, +} + +impl SessionBanner<'_> { + pub fn print(&self) { + let triad = if self.bom_triad_complete { + "Complete" + } else { + "Incomplete" + }; + + println!(); + println!(" ╔══════════════════════════════════════════╗"); + println!(" ║ {} Governed Shell", self.org_name); + println!(" ║ Cluster: {}", self.cluster); + println!( + " ║ Score: {}/100 {}", + self.risk_score, self.capability_ceiling + ); + println!(" ║ BOM Triad: {}", triad); + println!(" ╚══════════════════════════════════════════╝"); + println!(); + } +} diff --git a/org-ops-core/src/git_commands.rs b/org-ops-core/src/git_commands.rs new file mode 100644 index 0000000..9c3faf1 --- /dev/null +++ b/org-ops-core/src/git_commands.rs @@ -0,0 +1,403 @@ +//! Governed git subcommands. +//! +//! Wraps git operations with accord validation, corpus score checks, +//! and Chronicle attribution. + +use crate::session::SessionContext; +use crate::traits::OrgCommands; +use std::process::Command; + +pub struct GitConfig { + pub forgejo_url: String, + pub forgejo_token: Option, + pub chronicle_webhook: String, +} + +impl Default for GitConfig { + fn default() -> Self { + Self { + forgejo_url: "https://git.bxnet.io".into(), + forgejo_token: None, + chronicle_webhook: "http://localhost:8090/webhook/forgejo".into(), + } + } +} + +pub struct GovernedGitCommands { + config: GitConfig, +} + +impl GovernedGitCommands { + pub fn new(config: GitConfig) -> Self { + Self { config } + } + + fn git(args: &[&str]) -> (String, String, i32) { + let output = Command::new("git") + .args(args) + .output() + .expect("git not found in PATH"); + ( + String::from_utf8_lossy(&output.stdout).to_string(), + String::from_utf8_lossy(&output.stderr).to_string(), + output.status.code().unwrap_or(-1), + ) + } + + fn corpus_score(entry_name: &str) -> Option<(u8, String, bool)> { + let output = Command::new("kubectl") + .args([ + "get", "corpusentry", entry_name, "-o", + "jsonpath={.status.riskScore.composite}|{.status.riskScore.capabilityCeiling}|{.status.riskScore.bomTriadComplete}", + ]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let s = String::from_utf8_lossy(&output.stdout); + let parts: Vec<&str> = s.trim().split('|').collect(); + Some(( + parts.first().and_then(|v| v.parse().ok()).unwrap_or(0), + parts.get(1).unwrap_or(&"CAP_READ").to_string(), + parts.get(2).map(|v| *v == "true").unwrap_or(false), + )) + } + + fn changed_files() -> Vec { + let (out, _, _) = Self::git(&["diff", "--name-only", "HEAD"]); + let mut files: Vec = out.lines().map(|s| s.to_string()).collect(); + // Also include staged but not yet committed + let (staged, _, _) = Self::git(&["diff", "--cached", "--name-only"]); + for f in staged.lines() { + if !files.contains(&f.to_string()) { + files.push(f.to_string()); + } + } + files + } + + fn infer_corpus_entry(path: &str) -> Option { + std::path::Path::new(path) + .file_stem() + .and_then(|s| s.to_str()) + .map(|s| s.to_string()) + } + + fn emit_chronicle(&self, kind: &str, actor_did: &str, message: &str) -> bool { + let body = serde_json::json!({ + "pusher": {"login": actor_did}, + "ref": format!("refs/governed/{}", kind), + "repository": {"full_name": "platform/git-governance"}, + "commits": [{"message": format!("{}: {}", kind, message)}], + }); + reqwest::blocking::Client::new() + .post(&self.config.chronicle_webhook) + .header("X-Forgejo-Event", "push") + .json(&body) + .timeout(std::time::Duration::from_secs(5)) + .send() + .map(|r| r.status().is_success()) + .unwrap_or(false) + } + + fn cmd_status(&self, _ctx: &SessionContext) -> anyhow::Result<()> { + let (out, _, _) = Self::git(&["status", "--short"]); + if out.is_empty() { + println!("Nothing to commit, working tree clean."); + return Ok(()); + } + println!("{}", out.trim()); + + // Governance overlay + let changed = Self::changed_files(); + if changed.is_empty() { + return Ok(()); + } + + println!("\n-- Governance Impact --"); + for file in &changed { + if let Some(entry) = Self::infer_corpus_entry(file) { + if let Some((score, ceiling, triad)) = Self::corpus_score(&entry) { + let triad_mark = if triad { "Y" } else { "N" }; + println!( + " {} -> corpus:{} score={}/100 {} triad={}", + file, entry, score, ceiling, triad_mark + ); + } else { + println!(" {} (no corpus entry)", file); + } + } else { + println!(" {}", file); + } + } + println!("--"); + Ok(()) + } + + fn cmd_clone(&self, repo: &str, ctx: &SessionContext) -> anyhow::Result<()> { + let url = if repo.contains("://") { + repo.to_string() + } else { + format!("{}/{}.git", self.config.forgejo_url, repo) + }; + println!("Cloning {}...", url); + let (out, err, rc) = Self::git(&["clone", &url]); + if rc != 0 { + anyhow::bail!("git clone failed: {}", err); + } + if !out.is_empty() { + println!("{}", out.trim()); + } + self.emit_chronicle( + "REPO_CLONED", + &format!("did:web:{}/user/operator", ctx.trust_domain), + &format!("repo={}", repo), + ); + println!("Cloned. Chronicle: REPO_CLONED"); + Ok(()) + } + + fn cmd_commit(&self, message: &str, _ctx: &SessionContext) -> anyhow::Result<()> { + // Pre-commit checks + let changed = Self::changed_files(); + let yaml_files: Vec<&String> = changed + .iter() + .filter(|f| f.ends_with(".yml") || f.ends_with(".yaml")) + .collect(); + + // Basic secret scan + for f in &yaml_files { + if let Ok(content) = std::fs::read_to_string(f) { + let lc = content.to_lowercase(); + for pat in &["password:", "secret:", "api_key:", "private_key:"] { + if lc.contains(pat) { + eprintln!(" [secrets] {}: possible secret ({}) — review", f, pat); + } + } + } + } + + let (out, err, rc) = Self::git(&["commit", "-m", message]); + if rc != 0 { + anyhow::bail!("git commit failed: {}", err); + } + println!("{}", out.trim()); + Ok(()) + } + + fn cmd_push( + &self, + remote: &str, + branch: &str, + ctx: &SessionContext, + ) -> anyhow::Result<()> { + println!("-- Pre-push governance checks --"); + + // Corpus score check for changed files + let changed = Self::changed_files(); + let mut blocked = false; + + for file in &changed { + if let Some(entry) = Self::infer_corpus_entry(file) { + if let Some((score, ceiling, _)) = Self::corpus_score(&entry) { + print!(" corpus [{}]: {}/100 {}", entry, score, ceiling); + if branch == "main" && score < 70 { + println!(" BLOCKED (main requires >= 70)"); + blocked = true; + } else { + println!(" OK"); + } + } + } + } + + if blocked { + anyhow::bail!("Push blocked by governance checks."); + } + + // Governance summary + let (log, _, _) = Self::git(&["log", "--oneline", "-3"]); + println!("\n Commits:"); + for line in log.lines() { + println!(" {}", line); + } + println!(" Target: {}/{}", remote, branch); + println!(" Actor: did:web:{}/user/operator", ctx.trust_domain); + println!("--"); + + // Emit COMMIT_CREATED for each commit in the push range (0x1704) + let actor_did = format!("did:web:{}/user/operator", ctx.trust_domain); + let (commit_log, _, _) = + Self::git(&["log", &format!("{}/{}..HEAD", remote, branch), "--format=%H|%s", "--no-merges"]); + for line in commit_log.lines().filter(|l| !l.is_empty()) { + let parts: Vec<&str> = line.splitn(2, '|').collect(); + if parts.len() >= 2 { + self.emit_chronicle( + "COMMIT_CREATED", + &actor_did, + &format!("sha={} msg={}", parts[0], parts[1]), + ); + } + } + + // Chronicle event + let (sha, _, _) = Self::git(&["rev-parse", "HEAD"]); + self.emit_chronicle( + "GOVERNED_PUSH", + &actor_did, + &format!("{}@{} -> {}/{}", sha.trim(), branch, remote, branch), + ); + + // Actual push + let (out, err, rc) = Self::git(&["push", remote, branch]); + if rc != 0 { + anyhow::bail!("git push failed: {}", err); + } + if !out.is_empty() { + println!("{}", out.trim()); + } + println!("Chronicle: GOVERNED_PUSH recorded"); + Ok(()) + } + + fn cmd_pr_create(&self, title: &str, ctx: &SessionContext) -> anyhow::Result<()> { + let (branch, _, _) = Self::git(&["branch", "--show-current"]); + let branch = branch.trim(); + + let (remote_url, _, _) = Self::git(&["remote", "get-url", "origin"]); + let repo = remote_url + .trim() + .trim_end_matches(".git") + .rsplit('/') + .take(2) + .collect::>() + .into_iter() + .rev() + .collect::>() + .join("/"); + + let url = format!("{}/api/v1/repos/{}/pulls", self.config.forgejo_url, repo); + let mut req = reqwest::blocking::Client::new().post(&url).json(&serde_json::json!({ + "title": title, + "head": branch, + "base": "main", + "body": format!( + "## Governance\n\nActor: did:web:{}/user/operator\n\n*Created via guildhouse-ops git pr create*", + ctx.trust_domain + ) + })); + if let Some(ref tok) = self.config.forgejo_token { + req = req.bearer_auth(tok); + } + + match req.send() { + Ok(resp) if resp.status().is_success() => { + let data: serde_json::Value = resp.json().unwrap_or_default(); + let pr_url = data["html_url"].as_str().unwrap_or("?"); + println!("PR created: {}", pr_url); + self.emit_chronicle( + "PR_CREATED", + &format!("did:web:{}/user/operator", ctx.trust_domain), + &format!("PR: {} ({})", title, pr_url), + ); + } + Ok(resp) => eprintln!("PR creation failed: {}", resp.status()), + Err(e) => eprintln!("PR creation error: {}", e), + } + Ok(()) + } +} + +impl OrgCommands for GovernedGitCommands { + fn commands(&self) -> Vec { + use clap::{Arg, Command}; + vec![Command::new("git") + .about("Governed git operations with Chronicle attribution") + .subcommand( + Command::new("clone") + .about("Clone a governed repository") + .arg(Arg::new("repo").required(true)), + ) + .subcommand(Command::new("status").about("git status with governance overlay")) + .subcommand( + Command::new("add") + .about("Stage files") + .arg(Arg::new("files").num_args(1..)), + ) + .subcommand( + Command::new("commit") + .about("Commit with pre-commit checks") + .arg(Arg::new("message").short('m').required(true)), + ) + .subcommand( + Command::new("push") + .about("Governed push: corpus check -> Chronicle -> push") + .arg(Arg::new("remote").default_value("origin")) + .arg(Arg::new("branch").default_value("main")), + ) + .subcommand( + Command::new("pr").about("PR governance").subcommand( + Command::new("create") + .about("Create governed PR") + .arg(Arg::new("title").short('t').required(true)), + ), + )] + } + + fn handles(&self, name: &str) -> bool { + name == "git" + } + + fn handle( + &self, + _name: &str, + matches: &clap::ArgMatches, + ctx: &SessionContext, + ) -> anyhow::Result<()> { + match matches.subcommand() { + Some(("status", _)) => self.cmd_status(ctx), + Some(("clone", sub)) => { + let repo = sub.get_one::("repo").unwrap(); + self.cmd_clone(repo, ctx) + } + Some(("add", sub)) => { + let files: Vec<&str> = sub + .get_many::("files") + .unwrap_or_default() + .map(|s| s.as_str()) + .collect(); + let mut args = vec!["add"]; + args.extend(files); + let (_, err, rc) = Self::git(&args); + if rc != 0 { + anyhow::bail!(err); + } + Ok(()) + } + Some(("commit", sub)) => { + let msg = sub.get_one::("message").unwrap(); + self.cmd_commit(msg, ctx) + } + Some(("push", sub)) => { + let remote = sub.get_one::("remote").map(|s| s.as_str()).unwrap_or("origin"); + let branch = sub.get_one::("branch").map(|s| s.as_str()).unwrap_or("main"); + self.cmd_push(remote, branch, ctx) + } + Some(("pr", sub)) => match sub.subcommand() { + Some(("create", s)) => { + let title = s.get_one::("title").unwrap(); + self.cmd_pr_create(title, ctx) + } + _ => { + println!("Usage: git pr create -t 'title'"); + Ok(()) + } + }, + _ => { + println!("Usage: guildhouse-ops git "); + Ok(()) + } + } + } +} diff --git a/org-ops-core/src/lib.rs b/org-ops-core/src/lib.rs new file mode 100644 index 0000000..d9bae8c --- /dev/null +++ b/org-ops-core/src/lib.rs @@ -0,0 +1,265 @@ +//! org-ops-core: Framework for building governed consortium CLI tools. +//! +//! Fork org-ops to create your own governed CLI (slayer-ops, gator-ops): +//! 1. Clone this repo +//! 2. Edit org-ops-cli/src/main.rs (org_name, trust_domain, bascule_endpoint) +//! 3. Implement OrgCommands for your domain +//! 4. cargo build --release + +pub mod ai_risk_analysis; +pub mod apply_gate; +pub mod auth_commands; +pub mod config; +pub mod test_evidence; +pub mod display; +pub mod git_commands; +pub mod pkce; +pub mod playbook_commands; +pub mod score_fetcher; +pub mod session; +pub mod traits; + +pub use auth_commands::{AuthCommands, AuthConfig}; +pub use config::OrgOpsConfig; +pub use playbook_commands::PlaybookCommands; +pub use display::SessionBanner; +pub use git_commands::{GitConfig, GovernedGitCommands}; +pub use traits::{OrgCommands, RiskScorer}; + +/// The main entry point. Build with your config and commands, then call run(). +pub struct OrgOps { + pub config: OrgOpsConfig, + pub scorer: Box, + pub commands: Vec>, +} + +impl OrgOps { + pub fn builder() -> OrgOpsBuilder { + OrgOpsBuilder::default() + } + + pub fn run(self) -> anyhow::Result<()> { + use clap::{Arg, Command}; + + let binary_name = self.config.binary_name.clone(); + let description = self.config.description.clone(); + let version = self.config.version.clone(); + let mut app = Command::new(binary_name) + .about(description) + .version(version) + .subcommand( + Command::new("connect") + .about("Open a governed shell via Bascule") + .arg(Arg::new("cluster").help("Cluster name or endpoint")), + ) + .subcommand(Command::new("status").about("Show cluster risk posture")) + .subcommand( + Command::new("corpus") + .about("Manage corpus entries") + .subcommand(Command::new("list").about("List corpus entries with scores")), + ); + + for cmd in &self.commands { + for subcmd in cmd.commands() { + app = app.subcommand(subcmd); + } + } + + let matches = app.get_matches(); + + match matches.subcommand() { + Some(("connect", sub)) => { + let cluster = sub + .get_one::("cluster") + .map(|s| s.as_str()) + .unwrap_or(&self.config.bascule_endpoint); + self.cmd_connect(cluster) + } + Some(("status", _)) => self.cmd_status(), + Some(("corpus", sub)) => match sub.subcommand() { + Some(("list", _)) => self.cmd_corpus_list(), + _ => Ok(()), + }, + Some((name, sub)) => { + let ctx = session::SessionContext { + org_name: self.config.org_name.clone(), + trust_domain: self.config.trust_domain.clone(), + bascule_endpoint: self.config.bascule_endpoint.clone(), + }; + for cmd in &self.commands { + if cmd.handles(name) { + return cmd.handle(name, sub, &ctx); + } + } + eprintln!("Unknown command: {name}"); + Ok(()) + } + None => { + println!("{}", self.config.org_name); + println!("Run --help for usage."); + Ok(()) + } + } + } + + fn cmd_connect(&self, cluster: &str) -> anyhow::Result<()> { + // 1. Fetch live score from cluster + let score = score_fetcher::fetch_cluster_score(); + + let banner = SessionBanner { + org_name: &self.config.org_name, + cluster, + risk_score: score.composite, + capability_ceiling: &score.capability_ceiling, + bom_triad_complete: score.bom_triad_complete, + }; + banner.print(); + + // 2. Determine SSH endpoint + // If cluster contains ':' or '.', treat as explicit endpoint. + // Otherwise use configured bascule_endpoint. + let endpoint = if cluster.contains(':') || cluster.contains('.') { + cluster.to_string() + } else { + self.config.bascule_endpoint.clone() + }; + + // 3. Parse host:port (default port 2222) + let (host, port) = if let Some(idx) = endpoint.rfind(':') { + (&endpoint[..idx], &endpoint[idx + 1..]) + } else { + (endpoint.as_str(), "2222") + }; + + // 4. Start kubectl port-forward if connecting to ClusterIP + let mut port_forward: Option = None; + let (ssh_host, ssh_port) = if host == "127.0.0.1" || host == "localhost" { + // Direct: already port-forwarded or local + (host.to_string(), port.to_string()) + } else { + // Port-forward to a substrate-bridge pod (Bascule DaemonSet) + eprintln!("Starting kubectl port-forward..."); + let pf = std::process::Command::new("kubectl") + .args([ + "port-forward", + "-n", "guildhouse-infra", + "daemonset/substrate-bridge", + "12222:2222", + ]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn(); + + match pf { + Ok(child) => { + port_forward = Some(child); + // Wait for port-forward to establish + std::thread::sleep(std::time::Duration::from_secs(3)); + ("127.0.0.1".to_string(), "12222".to_string()) + } + Err(e) => { + eprintln!("kubectl port-forward failed: {e}"); + eprintln!("Trying direct SSH to {host}:{port}..."); + (host.to_string(), port.to_string()) + } + } + }; + + println!("Connecting to {ssh_host}:{ssh_port}..."); + + // 5. Exec SSH — use certificate if available + let home = std::env::var("HOME").unwrap_or_default(); + let cert_file = format!("{}/.config/guildhouse-ops/identity.pem", home); + let key_file = format!("{}/.config/guildhouse-ops/identity.key", home); + let has_cert = std::path::Path::new(&cert_file).exists() + && std::path::Path::new(&key_file).exists(); + + let mut ssh_args = vec![ + "-p".to_string(), ssh_port.clone(), + "-o".to_string(), "StrictHostKeyChecking=no".to_string(), + "-o".to_string(), "UserKnownHostsFile=/dev/null".to_string(), + "-o".to_string(), "LogLevel=ERROR".to_string(), + ]; + + if has_cert { + ssh_args.push("-i".to_string()); + ssh_args.push(key_file); + eprintln!(" Using: certificate auth"); + } else { + eprintln!(" Using: SSH key auth"); + eprintln!(" Tip: run 'auth login' for certificate auth"); + } + + ssh_args.push(format!("tking@{ssh_host}")); + + let status = std::process::Command::new("ssh") + .args(&ssh_args) + .status(); + + // 6. Cleanup port-forward + if let Some(mut pf) = port_forward { + let _ = pf.kill(); + let _ = pf.wait(); + } + + match status { + Ok(s) if s.success() => Ok(()), + Ok(s) => { + eprintln!("Session ended (exit {})", s.code().unwrap_or(-1)); + Ok(()) + } + Err(e) => { + eprintln!("SSH failed: {e}"); + Ok(()) + } + } + } + + fn cmd_status(&self) -> anyhow::Result<()> { + println!("Cluster risk posture:"); + println!(" Trust domain: {}", self.config.trust_domain); + println!(" Bascule: {}", self.config.bascule_endpoint); + println!(" (Chronicle query — next sprint)"); + Ok(()) + } + + fn cmd_corpus_list(&self) -> anyhow::Result<()> { + println!("Corpus entries:"); + println!(" (K8s API query — next sprint)"); + Ok(()) + } +} + +#[derive(Default)] +pub struct OrgOpsBuilder { + config: Option, + scorer: Option>, + commands: Vec>, +} + +impl OrgOpsBuilder { + pub fn with_config(mut self, config: OrgOpsConfig) -> Self { + self.config = Some(config); + self + } + + pub fn with_scorer(mut self, scorer: impl RiskScorer + 'static) -> Self { + self.scorer = Some(Box::new(scorer)); + self + } + + pub fn with_commands(mut self, cmd: impl OrgCommands + 'static) -> Self { + self.commands.push(Box::new(cmd)); + self + } + + pub fn build(self) -> OrgOps { + OrgOps { + config: self.config.unwrap_or_default(), + scorer: self + .scorer + .unwrap_or_else(|| Box::new(traits::DefaultRiskScorer)), + commands: self.commands, + } + } +} diff --git a/org-ops-core/src/pkce.rs b/org-ops-core/src/pkce.rs new file mode 100644 index 0000000..75f4d7a --- /dev/null +++ b/org-ops-core/src/pkce.rs @@ -0,0 +1,135 @@ +//! PKCE (RFC 7636) browser auth flow. +//! +//! Starts a localhost callback server, opens the browser, +//! waits for the authorization code, exchanges it for a token. + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::sync::mpsc; + +/// Generate PKCE code verifier (random 64 bytes, base64url). +pub fn generate_code_verifier() -> String { + let mut bytes = [0u8; 64]; + use rand::RngCore; + rand::thread_rng().fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} + +/// Derive code_challenge = BASE64URL(SHA256(verifier)). +pub fn derive_code_challenge(verifier: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(verifier.as_bytes()); + URL_SAFE_NO_PAD.encode(hasher.finalize()) +} + +/// Find a free localhost port. +pub fn find_free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .expect("No free port") + .local_addr() + .unwrap() + .port() +} + +/// Build the PKCE authorization URL. +pub fn authorization_url( + issuer: &str, + client_id: &str, + redirect_uri: &str, + code_challenge: &str, + state: &str, +) -> String { + format!( + "{}/protocol/openid-connect/auth?client_id={}&response_type=code&redirect_uri={}&code_challenge={}&code_challenge_method=S256&scope=openid+email+profile&state={}", + issuer.trim_end_matches('/'), + client_id, + urlencoding::encode(redirect_uri), + code_challenge, + state, + ) +} + +/// Start localhost callback server. Returns (code, state). +pub fn wait_for_callback(port: u16) -> anyhow::Result<(String, String)> { + let listener = TcpListener::bind(format!("127.0.0.1:{}", port))?; + let (tx, rx) = mpsc::channel(); + + std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut buf = [0u8; 4096]; + let request = match stream.read(&mut buf) { + Ok(n) => String::from_utf8_lossy(&buf[..n]).to_string(), + Err(_) => String::new(), + }; + + let query = request + .split_whitespace() + .nth(1) + .and_then(|path| path.split('?').nth(1)) + .unwrap_or(""); + + let code = query + .split('&') + .find(|p| p.starts_with("code=")) + .map(|p| p.trim_start_matches("code=").to_string()) + .unwrap_or_default(); + + let state = query + .split('&') + .find(|p| p.starts_with("state=")) + .map(|p| p.trim_start_matches("state=").to_string()) + .unwrap_or_default(); + + let html = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\ +

Authenticated

\ +

Return to your terminal.

\ + "; + stream.write_all(html.as_bytes()).ok(); + tx.send((code, state)).ok(); + } + }); + + rx.recv_timeout(std::time::Duration::from_secs(120)) + .map_err(|_| anyhow::anyhow!("Timeout waiting for browser callback")) +} + +/// Exchange authorization code for access token. +pub fn exchange_code( + issuer: &str, + client_id: &str, + code: &str, + code_verifier: &str, + redirect_uri: &str, +) -> anyhow::Result { + let token_url = format!( + "{}/protocol/openid-connect/token", + issuer.trim_end_matches('/') + ); + + let client = reqwest::blocking::Client::new(); + let resp = client + .post(&token_url) + .form(&[ + ("grant_type", "authorization_code"), + ("client_id", client_id), + ("code", code), + ("code_verifier", code_verifier), + ("redirect_uri", redirect_uri), + ]) + .timeout(std::time::Duration::from_secs(30)) + .send()?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().unwrap_or_default(); + anyhow::bail!("Token exchange failed ({status}): {body}"); + } + + let data: serde_json::Value = resp.json()?; + data["access_token"] + .as_str() + .map(|s| s.to_string()) + .ok_or_else(|| anyhow::anyhow!("No access_token in response")) +} diff --git a/org-ops-core/src/playbook_commands.rs b/org-ops-core/src/playbook_commands.rs new file mode 100644 index 0000000..3840307 --- /dev/null +++ b/org-ops-core/src/playbook_commands.rs @@ -0,0 +1,257 @@ +//! Governed Ansible playbook execution. +//! +//! guildhouse-ops playbook run — validates corpus, runs ansible-playbook, Chronicle +//! guildhouse-ops playbook list — lists governed playbooks + +use crate::session::SessionContext; +use crate::traits::OrgCommands; +use std::collections::HashMap; +use std::process::Command; + +pub struct PlaybookCommands { + pub playbook_base: String, + pub chronicle_webhook: String, +} + +impl PlaybookCommands { + pub fn new(playbook_base: &str, chronicle_webhook: &str) -> Self { + Self { + playbook_base: playbook_base.into(), + chronicle_webhook: chronicle_webhook.into(), + } + } + + fn get_corpus_entry(name: &str) -> Option { + let out = Command::new("kubectl") + .args(["get", "corpusentry", name, "-o", "json"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + serde_json::from_slice(&out.stdout).ok() + } + + fn find_playbook(&self, name: &str) -> Option { + let out = Command::new("find") + .args([&self.playbook_base, "-name", &format!("{}.yml", name)]) + .output() + .ok()?; + let path = String::from_utf8_lossy(&out.stdout).trim().lines().next()?.to_string(); + if path.is_empty() { None } else { Some(path) } + } + + fn emit_chronicle(&self, kind: &str, actor_did: &str, message: &str) -> bool { + let body = serde_json::json!({ + "pusher": {"login": actor_did}, + "ref": format!("refs/playbook/{}", kind), + "repository": {"full_name": "platform/ansible-governance"}, + "commits": [{"message": format!("{}: {}", kind, message)}], + }); + reqwest::blocking::Client::new() + .post(&self.chronicle_webhook) + .header("X-Forgejo-Event", "push") + .json(&body) + .timeout(std::time::Duration::from_secs(5)) + .send() + .map(|r| r.status().is_success()) + .unwrap_or(false) + } + + fn cmd_run( + &self, + name: &str, + target: Option<&str>, + extra_vars: &HashMap, + dry_run: bool, + ctx: &SessionContext, + ) -> anyhow::Result<()> { + println!("-- Playbook governance check --"); + println!(" Playbook: {}", name); + + // Find playbook file + let path = self.find_playbook(name).ok_or_else(|| { + anyhow::anyhow!("Playbook '{}' not found under {}", name, self.playbook_base) + })?; + println!(" Path: {}", path); + + // Validate corpus entry + let entry = Self::get_corpus_entry(name) + .ok_or_else(|| anyhow::anyhow!("No CorpusEntry for '{}'. Create one first.", name))?; + + let rs = entry.get("status").and_then(|s| s.get("riskScore")).cloned().unwrap_or_default(); + let composite = rs.get("composite").and_then(|v| v.as_u64()).unwrap_or(0) as u8; + let ceiling = rs.get("capabilityCeiling").and_then(|v| v.as_str()).unwrap_or("CAP_READ"); + let triad = rs.get("bomTriadComplete").and_then(|v| v.as_bool()).unwrap_or(false); + + println!(" Score: {}/100 {} triad={}", composite, ceiling, if triad { "Y" } else { "N" }); + + if composite < 70 { + println!("\n BLOCKED: score {} < 70 (CAP_MUTATE required)", composite); + anyhow::bail!("Playbook blocked by governance check."); + } + + println!(" Governance check passed."); + if dry_run { + println!(" [--check] Dry run mode."); + } + println!("--\n"); + + // Chronicle: PLAYBOOK_STARTED + let actor_did = format!("did:web:{}/user/operator", ctx.trust_domain); + let pb_cid = entry.get("spec").and_then(|s| s.get("cid")).and_then(|v| v.as_str()).unwrap_or("?"); + + self.emit_chronicle( + "PLAYBOOK_STARTED", + &actor_did, + &format!("{} cid={} target={}", name, pb_cid, target.unwrap_or("all")), + ); + + // Helper to build ansible-playbook command + let build_cmd = |check_mode: bool| { + let mut c = Command::new("ansible-playbook"); + c.arg(&path); + if let Some(hosts) = target { + c.arg("--limit").arg(hosts); + } + for (k, v) in extra_vars { + c.arg("--extra-vars").arg(format!("{}={}", k, v)); + } + if check_mode || dry_run { + c.arg("--check").arg("--diff"); + } + c.env("GUILDHOUSE_DID", &actor_did); + c + }; + + // Load accord MFA policy — fail-closed on any error. + let accord_name = std::env::var("GUILDHOUSE_ACCORD").unwrap_or("dev-operations".into()); + let mfa_policy = match crate::apply_gate::AccordMfaPolicy::from_accord(&accord_name) { + Ok(policy) => policy, + Err(e) => { + eprintln!("\n BLOCKED: Accord load failed: {}", e); + self.emit_chronicle( + "ACCORD_LOAD_FAILED", + &actor_did, + &format!("{} accord={} error={}", name, accord_name, e), + ); + anyhow::bail!( + "Accord '{}' could not be loaded. Governed operation blocked. {}", + accord_name, + e + ); + } + }; + + // Phase 1: --check to generate diff + println!("Phase 1: Generating diff (--check)..."); + let check_output = build_cmd(true).output()?; + let diff = String::from_utf8_lossy(&check_output.stdout).to_string(); + + if dry_run { + print!("{}", diff); + println!("\n [--check] Dry run complete."); + self.emit_chronicle("PLAYBOOK_COMPLETED", &actor_did, &format!("{} dry_run=true", name)); + return Ok(()); + } + + // Phase 2: Apply gate (if MFA required) + if mfa_policy.mfa_required { + println!("\n Accord: {} (MFA: {})", accord_name, mfa_policy.mfa_method); + let diff_hash = crate::apply_gate::run_apply_gate( + &diff, &mfa_policy, &actor_did, &self.chronicle_webhook, + )?; + + // Re-verify diff hasn't changed (TOCTOU prevention) + let recheck = build_cmd(true).output()?; + let recheck_diff = String::from_utf8_lossy(&recheck.stdout).to_string(); + let recheck_hash = crate::apply_gate::hash_diff(&recheck_diff); + if recheck_hash != diff_hash { + eprintln!("\n BLOCKED: Diff changed since MFA sign-off!"); + self.emit_chronicle("DIFF_MISMATCH_DETECTED", &actor_did, + &format!("{} signed={} actual={}", name, &diff_hash[..24], &recheck_hash[..24])); + anyhow::bail!("Apply blocked: diff changed after MFA."); + } + } else if !diff.trim().is_empty() { + println!("{}", diff); + } + + // Phase 3: Apply + println!("\nApplying changes..."); + let start = std::time::Instant::now(); + let status = build_cmd(false).status()?; + let duration = start.elapsed(); + let rc = status.code().unwrap_or(-1); + + // Chronicle: PLAYBOOK_COMPLETED + self.emit_chronicle( + "PLAYBOOK_COMPLETED", + &actor_did, + &format!("{} rc={} duration={}s", name, rc, duration.as_secs()), + ); + + if status.success() { + println!("\nPlaybook complete. ({:.1}s)", duration.as_secs_f64()); + println!("Chronicle: PLAYBOOK_COMPLETED recorded"); + } else { + anyhow::bail!("ansible-playbook exited with code {}", rc); + } + Ok(()) + } + + fn cmd_list(&self, _ctx: &SessionContext) -> anyhow::Result<()> { + let out = Command::new("kubectl") + .args([ + "get", "corpusentry", "-l", "substrate.io/playbook-type=ansible", + "-o", "custom-columns=NAME:.metadata.name,SCORE:.status.riskScore.composite,CEILING:.status.riskScore.capabilityCeiling,TRIAD:.status.riskScore.bomTriadComplete,OS:.metadata.labels.substrate\\.io/target-os", + ]) + .output()?; + println!("{}", String::from_utf8_lossy(&out.stdout)); + Ok(()) + } +} + +impl OrgCommands for PlaybookCommands { + fn commands(&self) -> Vec { + use clap::{Arg, ArgAction, Command}; + vec![Command::new("playbook") + .about("Governed Ansible playbook execution") + .subcommand( + Command::new("run") + .about("Run governed playbook (corpus-validated + Chronicle)") + .arg(Arg::new("name").required(true)) + .arg(Arg::new("target").long("target").short('t')) + .arg(Arg::new("var").long("var").short('e').action(ArgAction::Append)) + .arg(Arg::new("check").long("check").action(ArgAction::SetTrue)), + ) + .subcommand(Command::new("list").about("List governed playbooks"))] + } + + fn handles(&self, name: &str) -> bool { + name == "playbook" + } + + fn handle(&self, _name: &str, matches: &clap::ArgMatches, ctx: &SessionContext) -> anyhow::Result<()> { + match matches.subcommand() { + Some(("run", sub)) => { + let name = sub.get_one::("name").unwrap(); + let target = sub.get_one::("target").map(|s| s.as_str()); + let check = sub.get_flag("check"); + let vars: HashMap = sub + .get_many::("var") + .unwrap_or_default() + .filter_map(|v| { + let mut p = v.splitn(2, '='); + Some((p.next()?.to_string(), p.next()?.to_string())) + }) + .collect(); + self.cmd_run(name, target, &vars, check, ctx) + } + Some(("list", _)) => self.cmd_list(ctx), + _ => { + println!("Usage: playbook "); + Ok(()) + } + } + } +} diff --git a/org-ops-core/src/score_fetcher.rs b/org-ops-core/src/score_fetcher.rs new file mode 100644 index 0000000..3085782 --- /dev/null +++ b/org-ops-core/src/score_fetcher.rs @@ -0,0 +1,51 @@ +//! Fetches live WorkloadRiskScore from the cluster corpus-operator. + +use crate::traits::WorkloadRiskScore; +use std::process::Command; + +/// Fetch the risk score for a corpus entry from the live cluster. +pub fn fetch_score(entry_name: &str) -> WorkloadRiskScore { + let output = Command::new("kubectl") + .args([ + "get", + "corpusentry", + entry_name, + "-o", + "jsonpath={.status.riskScore.composite}|{.status.riskScore.capabilityCeiling}|{.status.riskScore.bomTriadComplete}", + ]) + .output(); + + match output { + Ok(out) if out.status.success() => { + let s = String::from_utf8_lossy(&out.stdout); + let parts: Vec<&str> = s.trim().split('|').collect(); + let composite = parts.first().and_then(|v| v.parse().ok()).unwrap_or(0u8); + let ceiling = parts.get(1).unwrap_or(&"CAP_READ").to_string(); + let bom_complete = parts.get(2).map(|v| *v == "true").unwrap_or(false); + + WorkloadRiskScore { + hardware_score: 0, + software_score: 0, + ai_score: 0, + attestation_score: 0, + composite, + capability_ceiling: ceiling, + bom_triad_complete: bom_complete, + } + } + _ => WorkloadRiskScore { + hardware_score: 0, + software_score: 0, + ai_score: 0, + attestation_score: 0, + composite: 0, + capability_ceiling: "UNKNOWN".into(), + bom_triad_complete: false, + }, + } +} + +/// Fetch the cluster's best Tier A corpus entry score. +pub fn fetch_cluster_score() -> WorkloadRiskScore { + fetch_score("bxnet-ops") +} diff --git a/org-ops-core/src/session.rs b/org-ops-core/src/session.rs new file mode 100644 index 0000000..e9e5b1e --- /dev/null +++ b/org-ops-core/src/session.rs @@ -0,0 +1,6 @@ +#[derive(Debug, Clone)] +pub struct SessionContext { + pub org_name: String, + pub trust_domain: String, + pub bascule_endpoint: String, +} diff --git a/org-ops-core/src/test_evidence.rs b/org-ops-core/src/test_evidence.rs new file mode 100644 index 0000000..31ab663 --- /dev/null +++ b/org-ops-core/src/test_evidence.rs @@ -0,0 +1,98 @@ +//! Test run evidence for governed playbooks. +//! +//! TestRunResult captures the outcome of running a playbook against +//! a test/staging environment. Content-addressed by CID. + +use sha2::{Digest, Sha256}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct TestRunResult { + pub run_id: String, + pub playbook_cid: String, + pub playbook_name: String, + pub test_environment: TestEnvironment, + pub test_timestamp: String, + pub duration_secs: u64, + pub tasks_total: u32, + pub tasks_changed: u32, + pub tasks_failed: u32, + pub tasks_ok: u32, + pub idempotency_verified: bool, + pub diff_hash: Option, + pub exit_code: i32, + pub test_runner_did: String, + pub notes: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct TestEnvironment { + pub env_type: String, + pub target_os: String, + pub target_os_version: String, + pub description: String, +} + +impl TestRunResult { + /// Compute content-addressed CID. + pub fn compute_cid(&self) -> String { + let canonical = serde_json::to_string(self).unwrap_or_default(); + let mut hasher = Sha256::new(); + hasher.update(canonical.as_bytes()); + format!("sha256:{:x}", hasher.finalize()) + } + + /// Compute operational confidence score (0-100). + pub fn test_run_confidence_score(&self) -> u8 { + let mut score: u32 = 30; // base: test exists + if self.tasks_failed == 0 { + score += 25; + } + if self.idempotency_verified { + score += 20; + } + if self.diff_hash.is_some() { + score += 15; + } + score += 10; // test completed + score.min(100) as u8 + } + + /// Compare test diff against prod diff hash. + pub fn diff_matches_prod(&self, prod_hash: &str) -> f32 { + match &self.diff_hash { + Some(h) if h == prod_hash => 1.0, + Some(_) => 0.5, + None => 0.3, + } + } + + pub fn print_summary(&self) { + let score = self.test_run_confidence_score(); + println!( + " Test: {}/100 | env={} | tasks={}/{} ok | idem={}", + score, + self.test_environment.env_type, + self.tasks_ok, + self.tasks_total, + if self.idempotency_verified { "Y" } else { "N" } + ); + } +} + +/// Load test result from local file by CID. +pub fn load_test_result(cid: &str) -> anyhow::Result { + let path = format!("./test-results/{}.json", cid); + let content = + std::fs::read_to_string(&path).map_err(|_| anyhow::anyhow!("Test result not found: {}", cid))?; + Ok(serde_json::from_str(&content)?) +} + +/// Save test result and return CID. +pub fn save_test_result(result: &TestRunResult) -> anyhow::Result { + let cid = result.compute_cid(); + let content = serde_json::to_string_pretty(result)?; + std::fs::create_dir_all("./test-results")?; + std::fs::write(format!("./test-results/{}.json", cid), &content)?; + println!(" Test result saved: {}", cid); + Ok(cid) +} diff --git a/org-ops-core/src/traits.rs b/org-ops-core/src/traits.rs new file mode 100644 index 0000000..f95ce5b --- /dev/null +++ b/org-ops-core/src/traits.rs @@ -0,0 +1,88 @@ +use crate::session::SessionContext; + +/// Implement this to add org-specific subcommands. +pub trait OrgCommands: Send + Sync { + fn commands(&self) -> Vec; + fn handles(&self, name: &str) -> bool; + fn handle( + &self, + name: &str, + matches: &clap::ArgMatches, + ctx: &SessionContext, + ) -> anyhow::Result<()>; +} + +/// Implement this for custom risk scoring. +pub trait RiskScorer: Send + Sync { + fn score( + &self, + attestation_method: &str, + has_sbom: bool, + has_aibom: bool, + has_cdxa: bool, + human_authored: bool, + ) -> WorkloadRiskScore; +} + +#[derive(Debug, Clone)] +pub struct WorkloadRiskScore { + pub hardware_score: u8, + pub software_score: u8, + pub ai_score: u8, + pub attestation_score: u8, + pub composite: u8, + pub capability_ceiling: String, + pub bom_triad_complete: bool, +} + +/// Default GCAP reference scorer. +pub struct DefaultRiskScorer; + +impl RiskScorer for DefaultRiskScorer { + fn score( + &self, + attestation_method: &str, + has_sbom: bool, + has_aibom: bool, + has_cdxa: bool, + human_authored: bool, + ) -> WorkloadRiskScore { + let hardware_score: u8 = match attestation_method { + "tpm_psat" => 100, + "k8s_psat" => 60, + "join_token" => 30, + _ => 0, + }; + let software_score: u8 = if has_sbom { 50 } else { 0 }; + let ai_score: u8 = if has_aibom { + 90 + } else if human_authored { + 50 + } else { + 0 + }; + let attestation_score: u8 = if has_cdxa { 100 } else { 0 }; + let composite = ((hardware_score as u32 * 25) + + (software_score as u32 * 35) + + (ai_score as u32 * 20) + + (attestation_score as u32 * 20)) + / 100; + let composite = composite as u8; + let capability_ceiling = match composite { + 90..=u8::MAX => "CAP_GOVERN", + 70..=89 => "CAP_MUTATE", + 50..=69 => "CAP_PROPOSE", + _ => "CAP_READ", + } + .to_string(); + WorkloadRiskScore { + hardware_score, + software_score, + ai_score, + attestation_score, + composite, + capability_ceiling, + bom_triad_complete: hardware_score > 0 && software_score >= 50 && ai_score > 0, + } + } +}