From fbb3f9099b2dc239b8dc27c15e6a276bb00ed2da Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Mon, 16 Nov 2026 17:09:30 +0200 Subject: [PATCH 1/7] Add macOS script tests and docs for enterprise setup script - Add `make test-scripts` (shellcheck + bats) and a macOS CI job, since the script targets the stock bash 3.2 on macOS. - Add stubs for armis-cli, curl, sudo, id, pgrep, python3.12 and the JSON merge helper so tests run without network or root, using a temporary HOME. - Unignore test/scripts/stubs/armis-cli, which the `armis-cli` ignore rule would otherwise exclude. - Document fleet/MDM deployment in README and SSO-SETUP. --- .github/workflows/ci.yml | 15 ++++ .gitignore | 1 + Makefile | 8 ++- README.md | 12 ++++ docs/SSO-SETUP.md | 16 +++++ test/scripts/pystub/python3.12 | 2 + test/scripts/stubs/armis-cli | 125 +++++++++++++++++++++++++++++++++ test/scripts/stubs/curl | 28 ++++++++ test/scripts/stubs/id | 3 + test/scripts/stubs/merge.js | 17 +++++ test/scripts/stubs/pgrep | 5 ++ test/scripts/stubs/sudo | 12 ++++ 12 files changed, 243 insertions(+), 1 deletion(-) create mode 100755 test/scripts/pystub/python3.12 create mode 100755 test/scripts/stubs/armis-cli create mode 100755 test/scripts/stubs/curl create mode 100755 test/scripts/stubs/id create mode 100644 test/scripts/stubs/merge.js create mode 100755 test/scripts/stubs/pgrep create mode 100755 test/scripts/stubs/sudo diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6cc3278..4dfcf02 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,6 +102,21 @@ jobs: try { .\scripts\install.ps1 -Version "not-a-version" } catch { $message = $_.Exception.Message } if ($message -notmatch "Invalid version format") { throw "expected 'Invalid version format' error, got: $message" } + # scripts/enterprise-setup.sh runs on macOS with the stock bash 3.2, so it is + # tested only there. The tests fake armis-cli, curl and sudo and use a temporary HOME. + script-tests-macos: + name: Script tests (macOS) + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Install bats and shellcheck + run: brew install bats-core shellcheck + + - name: Shellcheck and bats + run: make test-scripts + lint: uses: ./.github/workflows/reusable-lint.yml diff --git a/.gitignore b/.gitignore index 58d04f0..86cf15c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ completions/ *.log nohup.out armis-cli +!test/scripts/stubs/armis-cli moose armis .idea/ diff --git a/Makefile b/Makefile index 725b714..877e98c 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: build install clean test lint lint-clean scan help tools coverage release try-fleet +.PHONY: build install clean test test-scripts lint lint-clean scan help tools coverage release try-fleet BINARY_NAME=armis-cli BUILD_DIR=bin @@ -14,6 +14,7 @@ help: @echo " install - Install the binary to $(INSTALL_DIR)" @echo " clean - Remove build artifacts" @echo " test - Run tests with coverage" + @echo " test-scripts - Run the shell script tests (needs bats and shellcheck; macOS)" @echo " coverage - Show coverage report" @echo " lint - Run linters" @echo " lint-clean - Clear the golangci-lint cache, then run linters" @@ -65,6 +66,11 @@ tools: @echo "Installing dev tools..." go install gotest.tools/gotestsum@v1.13.0 +# scripts/enterprise-setup.sh targets macOS and its stock bash 3.2; run the tests there. +test-scripts: + shellcheck -s bash scripts/enterprise-setup.sh + bats test/scripts + lint: @echo "Running linters..." @which golangci-lint > /dev/null || (echo "golangci-lint not installed" && exit 1) diff --git a/README.md b/README.md index e13108b..032baaf 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,18 @@ Download the latest release for your platform from the [releases page](https://g go install github.com/ArmisSecurity/armis-cli/cmd/armis-cli@latest ``` +### Fleet / MDM deployment (macOS) + +To roll out armis-cli and the Armis AppSec MCP server to many Macs, run `scripts/enterprise-setup.sh` by hand or from Jamf, Kandji or another MDM. It installs a pinned armis-cli, registers the MCP server in Cursor, VS Code with Copilot, Copilot CLI, Codex, Claude Code, Antigravity and Junie (and JetBrains projects you list), checks the result, and writes a JSON report per machine, user and component. + +```bash +ARMIS_CLI_VERSION=1.27.0 ./scripts/enterprise-setup.sh --dry-run # preview +ARMIS_CLI_VERSION=1.27.0 ARMIS_CREDENTIALS_FILE=/var/db/armis/credentials \ + sudo -E ./scripts/enterprise-setup.sh --non-interactive # roll out +``` + +It supports `--dry-run`, `--uninstall`, `--only`/`--skip`, backups of every config it changes, and exit codes 0 (ok), 1 (partial), 2 (verification failed) and 3 (bad arguments or preflight failure). See [docs/ENTERPRISE-DEPLOYMENT.md](docs/ENTERPRISE-DEPLOYMENT.md). + ### Verify Installation After installation, verify that the CLI is working: diff --git a/docs/SSO-SETUP.md b/docs/SSO-SETUP.md index 5fdb479..3e01a86 100644 --- a/docs/SSO-SETUP.md +++ b/docs/SSO-SETUP.md @@ -105,6 +105,22 @@ export ARMIS_DEFAULT_AUTH_METHOD="SSO" export ARMIS_REGION="eu1" ``` +To do the whole rollout (CLI, MCP server in every detected editor, and the +variables above) in one step, run `scripts/enterprise-setup.sh` as root from +your MDM (macOS) with `ARMIS_AUTH_MODE=sso`: + +```bash +ARMIS_AUTH_MODE="sso" ARMIS_TENANT_ID="acme" ARMIS_CLI_VERSION="1.27.0" \ + ./scripts/enterprise-setup.sh --non-interactive +``` + +Pin `ARMIS_CLI_VERSION` so every machine gets the same reviewed release, and set +`ARMIS_INSTALLER_URL` to an internal mirror if endpoints cannot reach GitHub. +The MCP server needs Python 3.11+ on each developer's `PATH`. Use +`ARMIS_SSO_LOGIN=now` to open the sign-in page in the logged-in user's session. +See [ENTERPRISE-DEPLOYMENT.md](ENTERPRISE-DEPLOYMENT.md) for every option, the +report format and uninstall. + The first Armis command a developer runs then opens the browser for sign-in (they can also run `armis-cli auth login`). The session is shared across `armis-cli` and the Armis MCP plugins, and tokens refresh silently. diff --git a/test/scripts/pystub/python3.12 b/test/scripts/pystub/python3.12 new file mode 100755 index 0000000..e4c0a79 --- /dev/null +++ b/test/scripts/pystub/python3.12 @@ -0,0 +1,2 @@ +#!/bin/sh +echo True diff --git a/test/scripts/stubs/armis-cli b/test/scripts/stubs/armis-cli new file mode 100755 index 0000000..eec3c1c --- /dev/null +++ b/test/scripts/stubs/armis-cli @@ -0,0 +1,125 @@ +#!/bin/bash +# Fake armis-cli for enterprise-setup.bats. Behaviour is switched by STUB_* variables. +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +LOG="${STUB_LOG:?STUB_LOG is required}" +printf '%s\n' "$*" >> "$LOG/armis-cli.argv" +[ -z "${ARMIS_CLIENT_SECRET:-}" ] || echo "secret-in-env: $1" >> "$LOG/env.flags" + +label() { + case $1 in + cursor) echo "Cursor" ;; vscode) echo "VS Code" ;; copilot) echo "Copilot CLI" ;; + codex) echo "Codex CLI (MCP)" ;; claude) echo "Claude Code" ;; antigravity) echo "Antigravity" ;; + junie) echo "Junie" ;; + esac +} + +# target -> "file|topkey" +target_cfg() { + case $1 in + cursor) echo "$HOME/.cursor/mcp.json|mcpServers" ;; + vscode) echo "$HOME/Library/Application Support/Code/User/mcp.json|servers" ;; + copilot) echo "$HOME/.copilot/mcp-config.json|mcpServers" ;; + antigravity) echo "$HOME/.gemini/config/mcp_config.json|mcpServers" ;; + junie) echo "$HOME/.junie/mcp/mcp.json|mcpServers" ;; + esac +} + +write_env() { # write_env FILE: like the real CLI, only when absent + [ ! -f "$1" ] || return 0 + [ -n "${ARMIS_CLIENT_ID:-}" ] || return 0 + mkdir -p "$(dirname "$1")" + ( umask 077; printf 'ARMIS_CLIENT_ID=%s\nARMIS_CLIENT_SECRET=%s\n' "$ARMIS_CLIENT_ID" "$ARMIS_CLIENT_SECRET" > "$1" ) +} + +do_install() { + local t cfg file top + if [ "${1:-}" = "--help" ]; then + echo "Usage: armis-cli install [editor...]" + if [ "${STUB_OLD_CLI:-0}" != 1 ]; then + echo " --plugin-version string Install this MCP server release" + echo " --project string Project directory for the jetbrains target" + fi + return 0 + fi + local targets="" + while [ $# -gt 0 ]; do + case $1 in + --project) project=$2; shift ;; + --plugin-version) shift ;; + --*) ;; + *) targets="$targets $1" ;; + esac + shift + done + if [ "${STUB_PYTHON_FAIL:-0}" = 1 ]; then echo "Error: no suitable Python 3.11+ interpreter found" >&2; return 1; fi + write_env "$HOME/.armis/plugins/armis-appsec-mcp/.env" + echo "MCP server v1.4.2 downloaded." + local failed=0 + for t in $targets; do + case " ${STUB_FAIL_TARGETS:-} " in + *" $t "*) + IFS='|' read -r file top <<< "$(target_cfg "$t")" + [ -z "$file" ] || echo "garbage{" > "$file" + echo " ✗ $(label "$t"): boom" + failed=1 + continue ;; + esac + case $t in + claude) + write_env "$HOME/.claude/plugins/cache/armis-appsec-mcp/armis-appsec/latest/.env" + mkdir -p "$HOME/.claude/plugins" + printf '{"version":2,"plugins":{"armis-appsec@armis-appsec-mcp":[{"version":"1.4.2"}]}}\n' > "$HOME/.claude/plugins/installed_plugins.json" + echo " ✓ Claude Code v1.4.2" ;; + codex) + grep -q armis_scanner "$HOME/.codex/config.toml" 2>/dev/null || printf '[mcp_servers.armis_scanner]\ncommand = "python"\n' >> "$HOME/.codex/config.toml" + echo " ✓ Codex CLI (MCP)" ;; + jetbrains) + osascript -l JavaScript "$DIR/merge.js" "$project/.jb-mcp.json" mcpServers + echo " ✓ JetBrains ($project/.jb-mcp.json)" ;; + *) + IFS='|' read -r file top <<< "$(target_cfg "$t")" + mkdir -p "$(dirname "$file")" + osascript -l JavaScript "$DIR/merge.js" "$file" "$top" + echo " ✓ $(label "$t")" + [ "${STUB_HOOK_WARN:-}" != "$t" ] || echo " ⚠ $(label "$t") (hooks): adapter missing" ;; + esac + done + [ "$failed" -eq 0 ] || return "${STUB_FAIL_EXIT:-1}" + return 0 +} + +case "${1:-}" in + --version) echo "armis-cli version ${STUB_CLI_VERSION:-1.2.3} (commit: none, built: unknown)" ;; + install) shift; do_install "$@"; exit $? ;; + uninstall) + shift + targets="" + for a in "$@"; do case $a in --*) ;; *) targets="$targets $a" ;; esac; done + [ -n "$targets" ] || targets="cursor vscode copilot antigravity junie" + for t in $targets; do + IFS='|' read -r file top <<< "$(target_cfg "$t")" + [ -z "$file" ] || [ ! -f "$file" ] || osascript -l JavaScript "$DIR/merge.js" "$file" "$top" remove + done + exit 0 ;; + auth) + if [ "${2:-}" = whoami ]; then [ "${STUB_WHOAMI_FAIL:-0}" != 1 ] || { echo "Error: unauthorized" >&2; exit 1; }; echo "Tenant: acme" >&2; exit 0; fi + exit 0 ;; + mcp) + if [ "${3:-}" = "--network" ] || [ "${4:-}" = "--network" ]; then + [ "${STUB_NETWORK_FAIL:-0}" != 1 ] || { echo "TLS handshake failed" >&2; exit 1; } + exit 0 + fi + if [ -n "${STUB_DOCTOR_JSON:-}" ]; then cat "$STUB_DOCTOR_JSON"; else + echo '{"checks":[{"component":"scanner","name":"python venv","status":"ok","detail":"ok"}]}' + fi + exit "${STUB_DOCTOR_EXIT:-0}" ;; + scan) + [ "${STUB_SCAN_FAIL:-0}" != 1 ] || { echo "scan failed" >&2; exit 1; } + echo '{"findings":[]}'; exit 0 ;; + hook) + if [ "${2:-}" = init ]; then + mkdir -p .git/hooks && printf '#!/bin/sh\nexit 0\n' > .git/hooks/pre-commit && chmod 755 .git/hooks/pre-commit + fi + exit 0 ;; +esac +exit 0 diff --git a/test/scripts/stubs/curl b/test/scripts/stubs/curl new file mode 100755 index 0000000..bb952ea --- /dev/null +++ b/test/scripts/stubs/curl @@ -0,0 +1,28 @@ +#!/bin/bash +# Fake curl: answers reachability probes and serves a fake installer. +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +LOG="${STUB_LOG:?}" +url="" out="" probe=0 +while [ $# -gt 0 ]; do + case $1 in + -o) out=$2; shift ;; + -w) probe=1; shift ;; + http*) url=$1 ;; + esac + shift +done +printf '%s\n' "$url" >> "$LOG/curl.urls" +if [ "$probe" = 1 ]; then + if [ "${STUB_CURL_FAIL:-0}" = 1 ]; then printf '000'; exit 7; fi + printf '200'; exit 0 +fi +cat > "$out" <> "${STUB_LOG:?}/sudo.argv" +while [ $# -gt 0 ]; do + case $1 in + -n | -H) shift ;; + -u) shift 2 ;; + --preserve-env=*) shift ;; + *) break ;; + esac +done +exec "$@" From 49699c6e9bcf7a3f9942e0427b9a0a14f45fa364 Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Mon, 16 Nov 2026 19:28:33 +0200 Subject: [PATCH 2/7] Add macOS enterprise setup script for armis-cli and MCP rollout - Add scripts/enterprise-setup.sh to install a pinned, checksum-verified armis-cli, authenticate, register the MCP server in detected editors and agents, and verify the result. It runs by hand or from an MDM. - Back up each client config before changing it, skip invalid JSON, and restore the backup if registration fails, so one client's failure does not affect the others or remove a user's existing servers. - Report per endpoint, user and component, with a JSON file and exit codes 0-3 that an MDM can act on. - Support --dry-run and --uninstall, and keep credentials out of arguments, logs and reports. - Add bats tests with stubbed armis-cli, curl and sudo, and docs/ENTERPRISE-DEPLOYMENT.md covering configuration, MDM use and troubleshooting. --- docs/ENTERPRISE-DEPLOYMENT.md | 245 ++++ scripts/enterprise-setup.sh | 1845 ++++++++++++++++++++++++++++ test/scripts/enterprise-setup.bats | 541 ++++++++ 3 files changed, 2631 insertions(+) create mode 100644 docs/ENTERPRISE-DEPLOYMENT.md create mode 100755 scripts/enterprise-setup.sh create mode 100644 test/scripts/enterprise-setup.bats diff --git a/docs/ENTERPRISE-DEPLOYMENT.md b/docs/ENTERPRISE-DEPLOYMENT.md new file mode 100644 index 0000000..d77535c --- /dev/null +++ b/docs/ENTERPRISE-DEPLOYMENT.md @@ -0,0 +1,245 @@ +# Enterprise deployment on macOS + +`scripts/enterprise-setup.sh` installs armis-cli and the Armis AppSec MCP server on macOS developer machines, registers the server in the editors and code agents it finds, checks the result, and reports per machine, user and component. You can run it by hand or push it from an MDM (Jamf, Kandji, Intune for macOS). + +It does these things in order, and each stage checks its own result: + +1. **preflight**: macOS version, tools, disk space, network, proxy and certificate settings. +2. **cli**: installs a pinned armis-cli, verified with the release checksum (and cosign when it is installed). +3. **auth**: client credentials or browser sign-in (SSO). +4. **mcp**: registers the MCP server in each detected client. +5. **jetbrains**: JetBrains AI Assistant projects you list. +6. **hook**: the commit gate in repositories you list (off by default). +7. **verify**: `armis-cli mcp doctor --deep` and a sample scan. +8. **report**: a table on stdout, plus a JSON file. + +A component that fails does not stop the others. Only a preflight failure or a failed armis-cli install stops the run. + +## Supported clients + +| Client name | What gets configured | Detected by | +|---|---|---| +| `cursor` | `~/.cursor/mcp.json`, `~/.cursor/hooks.json` | `~/.cursor` exists | +| `vscode` | `~/Library/Application Support/Code/User/mcp.json` (VS Code with GitHub Copilot Chat) | the `Code/User` directory exists | +| `copilot` | `~/.copilot/mcp-config.json`, `~/.copilot/settings.json` (GitHub Copilot CLI) | `~/.copilot` exists | +| `codex` | `~/.codex/config.toml`, `~/.codex/hooks.json` | `~/.codex` exists | +| `claude` | the Claude Code plugin (`~/.claude/plugins/...`, `~/.claude/settings.json`) | `~/.claude` exists | +| `antigravity` | `~/.gemini/config/mcp_config.json` | `~/.gemini/config` exists | +| `junie` | `~/.junie/mcp/mcp.json` (JetBrains Junie) | `~/.junie/mcp` exists | +| `jetbrains` | `/.jb-mcp.json` for each project you list (JetBrains AI Assistant) | see [JetBrains](#jetbrains) | + +A client that is not installed is reported as `skip (not installed)` and is not an error. + +## Prerequisites + +- macOS 12 or later, on Apple silicon or Intel. The script runs on the stock `/bin/bash` (3.2). You can start it from zsh. +- `curl`, `git` and `osascript`, which ship with macOS. +- Python 3.11 or later on each developer's `PATH` (the MCP server runs on it). If it is missing, the script reports it per user and exits 1; armis-cli still installs. Install it with `brew install python@3.12` or the python.org installer, then re-run. +- Network access to the endpoints below, directly or through your proxy: + - `moose.armis.com` (`eu.moose.armis.com` for region `eu1`) + - `api.github.com`, `github.com` and `raw.githubusercontent.com`. Set `ARMIS_INSTALLER_URL` to an internal mirror of `scripts/install.sh` if you cannot reach `raw.githubusercontent.com`. +- A proxy or TLS inspection is supported through `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (upper or lower case) and `SSL_CERT_FILE` (a PEM file with your root CA). The script passes them, and `ARMIS_API_URL` when set, to `curl` and to every armis-cli command. +- To pin the MCP server version (`ARMIS_MCP_VERSION`), armis-cli must be a release that has `install --plugin-version`. To register JetBrains projects it must have `install jetbrains --project`. The script checks both and tells you when a release is too old. + +## Quick start + +```bash +# Interactive, as the developer +ARMIS_CLI_VERSION=1.27.0 ARMIS_CLIENT_ID=... ARMIS_CLIENT_SECRET=... ./scripts/enterprise-setup.sh + +# See what would change first +ARMIS_CLI_VERSION=1.27.0 ./scripts/enterprise-setup.sh --dry-run + +# From an MDM, as root, for the logged-in user +sudo ARMIS_CLI_VERSION=1.27.0 ARMIS_CREDENTIALS_FILE=/var/db/armis/credentials \ + ./scripts/enterprise-setup.sh --non-interactive --report /Library/Logs/Armis/last +``` + +The script reads its settings from the environment. Run `./scripts/enterprise-setup.sh --help` to see the commented configuration block. + +## Flags + +| Flag | Effect | +|---|---| +| `--dry-run` | Prints what would change and writes nothing: no files, no backups, no logs, no reports. Read-only probes still run. | +| `--uninstall` | Removes what the script installed. See [Uninstall](#uninstall-and-rollback). | +| `--non-interactive` | Never prompts. Implied when stdin is not a terminal. Requires `ARMIS_CLI_VERSION` unless `ARMIS_ALLOW_LATEST=1`. | +| `--only a,b` | Only these components: `cursor`, `vscode`, `copilot`, `codex`, `claude`, `antigravity`, `junie`, `jetbrains`, `hook`. | +| `--skip a,b` | Everything except these. | +| `--report PATH` | Writes the JSON report to `PATH.json` (a `.json` extension is ignored). Default: next to the log. | +| `--bundle` | Also writes an `armis-cli mcp doctor` support bundle per user, next to the log. It contains no credentials. | +| `--verbose` | Logs every command the script runs. | +| `--help` | Usage and the configuration block. | + +An unknown flag or component exits 3. + +## Configuration + +Every value can come from the environment, so an MDM can set them as script parameters or variables. + +| Variable | Default | Meaning | +|---|---|---| +| `ARMIS_CLI_VERSION` | none | armis-cli release to install, for example `1.27.0`. The installer is fetched from the same tag. | +| `ARMIS_ALLOW_LATEST` | `0` | `1` allows an unpinned install with `--non-interactive`. | +| `ARMIS_MCP_VERSION` | latest | MCP server release to pin. A pin is saved and kept by `armis-cli mcp update` and `armis-cli mcp doctor --fix`. | +| `ARMIS_TENANT_ID` | none | Tenant. Required for `sso`. | +| `ARMIS_REGION` | default region | For example `eu1`. | +| `ARMIS_AUTH_MODE` | `client-credentials` | `client-credentials` or `sso`. | +| `ARMIS_CLIENT_ID`, `ARMIS_CLIENT_SECRET` | none | Client credentials. | +| `ARMIS_CREDENTIALS_FILE` | none | A file with `ARMIS_CLIENT_ID=` and `ARMIS_CLIENT_SECRET=` lines. Used when the variables are not set. | +| `ARMIS_SSO_LOGIN` | `auto` | `now` opens the sign-in page, `skip` leaves it, `auto` signs in when a developer runs the script in a terminal. | +| `ARMIS_CLIENTS` | all seven clients | Which clients to configure. | +| `ARMIS_JETBRAINS_PROJECTS` | none | Comma-separated project directories for JetBrains AI Assistant. | +| `ARMIS_HOOK_ENABLE`, `ARMIS_HOOK_REPOS` | `0`, none | Install the commit gate in these repositories (comma-separated). | +| `ARMIS_HOOK_FAIL_OPEN` | `0` | `1` makes the gate warn instead of block. | +| `ARMIS_WITH_KNOWLEDGE` | `0` | Also install Armis Knowledge. It cannot be pinned. | +| `ARMIS_SAMPLE_SCAN` | `1` | Scan a two-line sample to prove the whole path. This uses tenant scan quota. `0` skips it. | +| `ARMIS_TARGET_USERS` | console user | Comma-separated accounts to configure. | +| `ARMIS_INSTALL_DIR` | `/usr/local/bin` as root, `~/.local/bin` otherwise | Where armis-cli goes. | +| `ARMIS_INSTALLER_URL` | GitHub raw | Internal mirror of `scripts/install.sh`. | +| `ARMIS_EXTRA_PATH` | none | Extra directories to search for Python. | +| `ARMIS_LOG_DIR` | `/Library/Logs/Armis` as root, `~/Library/Logs/Armis` otherwise | Log and report location. | +| `ARMIS_KEEP_CREDENTIALS`, `ARMIS_REMOVE_CLI` | `0`, `0` | Uninstall options. | + +## Credentials + +Do not pass credentials as MDM policy parameters, because Jamf and Kandji show parameters in their logs and consoles. Use one of: + +- Secret variables that your MDM injects into the script's environment at run time. +- A credentials file owned by the user running the script, with mode `0600` or `0400`, for example `/var/db/armis/credentials` owned by root. The script refuses a file with wider permissions. + +The script never puts credentials in command-line arguments, so they do not appear in `ps`. They reach armis-cli only through the process environment. They are not written to the log or the report; a masking filter also hides the secret value if a command echoes it. + +Each editor starts the MCP server without your shell environment, so credentials must also be in the `.env` files that armis-cli writes. armis-cli does not overwrite an existing `.env`. After installing, the script compares every `.env` it knows about (the shared plugin, the Claude Code plugin cache and Knowledge) with the credentials you supplied, rewrites the ones that differ at mode `0600` while keeping other keys such as `HTTPS_PROXY`, and deletes the `.env.bak` copies that hold the old secret. Rotating a credential is therefore a re-run with the new value. + +With `ARMIS_AUTH_MODE=sso`, developers sign in through the identity provider you registered (see [SSO-SETUP.md](SSO-SETUP.md)). Under `--non-interactive` the script does not open a browser unless `ARMIS_SSO_LOGIN=now`. A user who has not signed in is reported as `sign-in pending: run 'armis-cli auth login'`. When run as root, a browser sign-in only works for the user logged in at the console. + +## What changes on disk + +For each user (the home directory is that user's): + +| Path | Change | +|---|---| +| `ARMIS_INSTALL_DIR/armis-cli` | The binary. | +| `~/.armis/plugins/armis-appsec-mcp/` | The MCP server, its Python environment and `.env` (mode 0600). | +| The client files in the [table above](#supported-clients) | One `armis-appsec` entry added. Other servers are kept. | +| `~/.zshenv`, `~/.profile` or `~/.bash_profile`, `~/.bashrc` | A block between `# >>> armis-cli (managed) >>>` and `# <<< armis-cli (managed) <<<` with `ARMIS_TENANT_ID`, `ARMIS_REGION`, `ARMIS_DEFAULT_AUTH_METHOD` (sso) and `PATH`. Written only when it has content. Everything outside the markers is untouched. | +| `/.jb-mcp.json`, `/.git/hooks/pre-commit` | Only for the projects and repositories you list. | +| `ARMIS_LOG_DIR` | `enterprise-setup-.log` and `.json`. | + +The script also reads, but never edits, VS Code's `settings.json` to check that Copilot Agent mode and MCP are not switched off. + +### Backups and safety + +Before changing a file the script copies it to `.armis-bak.` (mode 0600, owned by the user). Then: + +- A config that does not parse as JSON is **skipped** and left byte-for-byte as it was. armis-cli would otherwise replace it and delete the user's other servers. Comments and trailing commas (as VS Code allows) are accepted. +- After the install the script checks that the file parses, that `armis-appsec` is present and that every earlier server is still there. If not, it restores the backup for that client and reports it as failed. Other clients are not affected. +- A backup whose original did not change is deleted, so re-running the script does not pile up backups. +- VS Code's `mcp.json` loses its comments the first time armis-cli rewrites it. The backup keeps them. + +## Idempotent re-runs + +A second run with the same settings makes no new backups, does not download armis-cli again (the installed version matches the pin) and, when `ARMIS_MCP_VERSION` is set, does not call GitHub or rebuild the Python environment. + +## Results and exit codes + +The matrix has one row per endpoint, user and component, with these columns: Endpoint, User, Component, Detected, Installed, Auth, Verified, Action needed. Statuses are `ok`, `warn` (needs attention), `fail` and `skip`; `-` means not applicable. The last line is `ARMIS_STATUS= components= failing=`. + +| Exit code | Meaning | +|---|---| +| 0 | Everything succeeded. | +| 1 | Partial: something needs attention (a client failed, Python is missing, sign-in is pending, a JetBrains project is not set up). | +| 2 | A verification failed (`mcp doctor`, the sample scan), or armis-cli could not be installed. | +| 3 | Bad arguments, an unreadable credentials file, a checksum or signature mismatch, or a preflight failure. | + +The JSON report has `endpoint`, `serial`, `timestamp`, `script_version`, `cli_version`, `mcp_version`, `exit_code`, `status` and a `components` list with `user`, `component`, `detected`, `installed`, `auth`, `verified` and `action`. + +### Jamf Extension Attribute + +```bash +#!/bin/bash +last=$(ls -t /Library/Logs/Armis/enterprise-setup-*.json 2>/dev/null | head -n 1) +[ -n "$last" ] || { echo "not run"; exit 0; } +status=$(sed -n 's/.*"status": "\(.*\)",/\1/p' "$last" | head -n 1) +echo "$status" +``` + +## JetBrains + +Junie is automatic (`junie` above). JetBrains AI Assistant reads a `.jb-mcp.json` in each project, so list the projects: + +```bash +ARMIS_JETBRAINS_PROJECTS="$HOME/code/api,$HOME/code/web" ./scripts/enterprise-setup.sh --only jetbrains +``` + +The script runs `armis-cli install jetbrains --project ` for each project that belongs to the user. The developer then enables the server in the IDE's AI Assistant MCP settings. Without a project list, the script reports `run 'armis-cli install jetbrains --project ' in each repo, or use Junie`. + +## Commit gate + +`armis-cli hook init` installs a pre-commit hook in one repository, so the gate is per repository. Set `ARMIS_HOOK_ENABLE=1` and `ARMIS_HOOK_REPOS` to the repositories to cover. The script backs up an existing `pre-commit`, installs the hook where Git resolves the hooks directory (`core.hooksPath` is honoured) and checks that it is executable. + +## Uninstall and rollback + +```bash +./scripts/enterprise-setup.sh --uninstall --non-interactive +``` + +- **Without `--only` or `--skip`**: runs `armis-cli uninstall --force`, which removes the MCP server from every client and deletes the plugin directory and its `.env`. Add `ARMIS_KEEP_CREDENTIALS=1` to keep credentials. +- **With `--only` or `--skip`**: runs `armis-cli uninstall `. This removes only those registrations and leaves the shared plugin directory and `.env` in place. When the selection names no client (for example `--only hook`), armis-cli is not called. +- The managed profile blocks are removed by a full uninstall, or when the selection covers every client. A partial uninstall keeps them, because the remaining clients need `ARMIS_TENANT_ID`, `ARMIS_REGION` and the sign-in method. +- Uninstall skips the network and disk-space checks, so it also works offline. +- Also removed: hooks the script installed in `ARMIS_HOOK_REPOS` (`hook init --remove`) and the `armis-appsec` entry in `.jb-mcp.json` of the listed JetBrains projects. With `ARMIS_REMOVE_CLI=1` as root, `/usr/local/bin/armis-cli` too. +- The result is checked: a client that still has the entry is reported as failed. + +The script never restores `*.armis-bak.*` files by itself, because that could undo changes the developer made later. To roll a file back by hand, copy the backup over the original, for example `cp -p ~/.cursor/mcp.json.armis-bak.20260101-120000 ~/.cursor/mcp.json`, then restart the editor. + +## Troubleshooting + +| Symptom | What to do | +|---|---| +| `cannot reach https://...` in preflight | Check the network, `HTTPS_PROXY` and `SSL_CERT_FILE`. Run `armis-cli mcp doctor --network` as the user for a step-by-step report (proxy, DNS, TLS, certificate issuer). | +| `Python 3.11+ is missing` | `brew install python@3.12` or the python.org installer, then re-run. If Python is in an unusual place, add it to `ARMIS_EXTRA_PATH`. | +| `client credentials were rejected` | Check `ARMIS_CLIENT_ID`, `ARMIS_CLIENT_SECRET` and `ARMIS_REGION`. Run `armis-cli auth whoami` as the user. | +| `sign-in pending` | The user runs `armis-cli auth login`, or you re-run with `ARMIS_SSO_LOGIN=now` while they are logged in. | +| `config at ... is not valid JSON` | The file was left untouched. Fix or remove it and re-run. | +| The editor does not show the Armis tools | Restart the editor (the matrix says `restart ` when it is running). For VS Code, open "MCP: List Servers". | +| VS Code: `enable Copilot Agent mode and MCP` | A VS Code setting (`chat.agent.enabled`, `chat.mcp.enabled` or `chat.mcp.access`) or a GitHub organization policy turns it off. The script only reports this and never edits settings. | +| `mcp doctor` failures | Run `armis-cli mcp doctor` as the user. Use `--bundle` here, or `armis-cli mcp doctor --bundle`, to produce a support bundle. In an editor, call the `debug_config` tool. | +| The sample scan fails | Check `armis-cli auth whoami` and the network. Set `ARMIS_SAMPLE_SCAN=0` to skip it. | +| `only the checksum was verified` | Install [cosign](https://docs.sigstore.dev/cosign/installation/) to also verify the release signature. This is advice and does not change the exit code. | + +Exit code 1 for a missing Python is deliberate: armis-cli itself installed correctly, so the run is partial rather than failed. + +The log is at `ARMIS_LOG_DIR/enterprise-setup-.log`. Add `--verbose` to see every command. + +## Example output + +A re-run on a machine where the CLI is already installed, with one malformed Junie config. The endpoint and paths are shortened. + +``` +[armis-setup] armis enterprise-setup 1.0.0 +[armis-setup] Preflight +[armis-setup] macOS 26.7.1 on arm64 +[armis-setup] armis-cli +[armis-setup] armis-cli 9.9.9 already installed at ~/bin/armis-cli +[armis-setup] [alice] auth (client-credentials) +[armis-setup] [alice] MCP server +[armis-setup] [alice] JetBrains +[armis-setup] [alice] verify +Endpoint User Component Detected Installed Auth Verified Action needed +MBP-0042 (machine) armis-cli yes ok - ok - +MBP-0042 alice cursor yes ok ok ok - +MBP-0042 alice vscode yes ok ok ok - +MBP-0042 alice copilot no skip (not installed) - - - +MBP-0042 alice codex yes ok ok ok - +MBP-0042 alice claude yes ok ok ok restart Claude Code +MBP-0042 alice antigravity no skip (not installed) - - - +MBP-0042 alice junie yes fail ok - config at ~/.junie/mcp/mcp.json is not valid JSON; fix or remove it, then re-run +MBP-0042 alice mcp-server - ok ok ok - +MBP-0042 alice jetbrains no skip (not installed) - - - +MBP-0042 alice sample-scan yes ok ok ok - +ARMIS_STATUS=partial components=11 failing=1 +``` + +The exit code of that run is 1. Fixing the Junie file and re-running turns the row green and the exit code to 0. diff --git a/scripts/enterprise-setup.sh b/scripts/enterprise-setup.sh new file mode 100755 index 0000000..a193c25 --- /dev/null +++ b/scripts/enterprise-setup.sh @@ -0,0 +1,1845 @@ +#!/usr/bin/env bash +# Enterprise rollout of armis-cli and the Armis AppSec MCP server on macOS. +# +# Run it by hand, or as root from an MDM (Jamf, Kandji, Intune for macOS). It +# installs armis-cli, signs developers in, registers the MCP server in every +# supported editor and code agent it finds, checks that the result works, and +# reports per endpoint, user and component. +# +# Stages: preflight, cli, auth, mcp, jetbrains, hook, verify, report. +# A component that fails does not stop components that do not depend on it. +# Only a preflight failure or a failed armis-cli install stops the run. +# +# Usage: +# enterprise-setup.sh [--dry-run] [--uninstall] [--non-interactive] +# [--only a,b] [--skip a,b] [--report PATH] [--bundle] +# [--verbose] [--help] +# +# --dry-run Print what would change; write nothing. +# --uninstall Remove what this script installed (see docs). +# --non-interactive Never prompt (implied when stdin is not a terminal). +# --only / --skip Comma-separated components: cursor, vscode, copilot, +# codex, claude, antigravity, junie, jetbrains, hook. +# --report PATH Write the JSON report to PATH.json. +# --bundle Also write an `armis-cli mcp doctor` support bundle per user. +# --verbose Log every command the script runs. +# +# Exit codes: 0 ok, 1 partial (something needs attention), 2 verification +# failed or armis-cli could not be installed, 3 bad arguments or preflight failure. +# +# Secrets: client credentials come from the environment or a root-owned 0600 +# file, never from arguments. They are not written to logs or reports. +# +# Requirements: macOS 12+, curl, git, Python 3.11+ on each developer's PATH. +set -u +set -o pipefail + +# Started with zsh or sh instead of bash: re-run under bash. +if [ -z "${BASH_VERSION:-}" ]; then + exec /bin/bash "$0" "$@" +fi + +# ---- CONFIG BEGIN ---------------------------------------------------------- +# Every value can be set from the environment (MDM script parameters or a +# wrapper). Values given here are the defaults. + +# armis-cli release to install, e.g. 1.27.0. Required with --non-interactive +# unless ARMIS_ALLOW_LATEST=1. The installer script is fetched from the same tag. +ARMIS_CLI_VERSION="${ARMIS_CLI_VERSION:-}" +ARMIS_ALLOW_LATEST="${ARMIS_ALLOW_LATEST:-0}" +# MCP server release to pin, e.g. 1.4.2. Empty follows the latest release. +# Needs an armis-cli with `install --plugin-version`. +ARMIS_MCP_VERSION="${ARMIS_MCP_VERSION:-}" + +# Tenant and region. The tenant is required for sso. The region is only needed +# outside the default one (for example eu1). +ARMIS_TENANT_ID="${ARMIS_TENANT_ID:-}" +ARMIS_REGION="${ARMIS_REGION:-}" + +# client-credentials: ARMIS_CLIENT_ID and ARMIS_CLIENT_SECRET from the +# environment, or from ARMIS_CREDENTIALS_FILE (KEY=VALUE lines, owned by the +# user running this script, mode 0600 or 0400). +# sso: developers sign in through the browser (see docs/SSO-SETUP.md). +ARMIS_AUTH_MODE="${ARMIS_AUTH_MODE:-client-credentials}" +ARMIS_CREDENTIALS_FILE="${ARMIS_CREDENTIALS_FILE:-}" +# Browser sign-in: auto (when run by a developer in a terminal), now, or skip. +ARMIS_SSO_LOGIN="${ARMIS_SSO_LOGIN:-auto}" + +# Clients to configure (space or comma separated). +ARMIS_CLIENTS="${ARMIS_CLIENTS:-cursor vscode copilot codex claude antigravity junie}" +# JetBrains AI Assistant is per project: comma-separated project directories. +ARMIS_JETBRAINS_PROJECTS="${ARMIS_JETBRAINS_PROJECTS:-}" +# Commit gate (pre-commit hook) in specific repositories: 1 to enable, plus a +# comma-separated list of repositories. ARMIS_HOOK_FAIL_OPEN=1 warns instead of blocking. +ARMIS_HOOK_ENABLE="${ARMIS_HOOK_ENABLE:-0}" +ARMIS_HOOK_REPOS="${ARMIS_HOOK_REPOS:-}" +ARMIS_HOOK_FAIL_OPEN="${ARMIS_HOOK_FAIL_OPEN:-0}" + +# Also install Armis Knowledge (cannot be pinned). +ARMIS_WITH_KNOWLEDGE="${ARMIS_WITH_KNOWLEDGE:-0}" +# Scan a two-line sample through the API to prove the whole path. This uses +# tenant scan quota. 0 to skip. +ARMIS_SAMPLE_SCAN="${ARMIS_SAMPLE_SCAN:-1}" + +# Accounts to configure (comma separated). Default: the console user when run +# as root, otherwise the current user. +ARMIS_TARGET_USERS="${ARMIS_TARGET_USERS:-}" + +# Where armis-cli goes. Default: /usr/local/bin as root, ~/.local/bin otherwise. +ARMIS_INSTALL_DIR="${ARMIS_INSTALL_DIR:-}" +# Internal mirror of scripts/install.sh, for endpoints that cannot reach GitHub raw. +ARMIS_INSTALLER_URL="${ARMIS_INSTALLER_URL:-}" +# Extra directories appended to every user's PATH when looking for Python. +ARMIS_EXTRA_PATH="${ARMIS_EXTRA_PATH:-}" + +# Logs and reports. Default: /Library/Logs/Armis as root, ~/Library/Logs/Armis otherwise. +ARMIS_LOG_DIR="${ARMIS_LOG_DIR:-}" +ARMIS_REPORT_PATH="${ARMIS_REPORT_PATH:-}" + +# Uninstall: keep credentials / also remove /usr/local/bin/armis-cli (root only). +ARMIS_KEEP_CREDENTIALS="${ARMIS_KEEP_CREDENTIALS:-0}" +ARMIS_REMOVE_CLI="${ARMIS_REMOVE_CLI:-0}" + +# Proxy and TLS inspection: HTTPS_PROXY, HTTP_PROXY, NO_PROXY (either case), +# SSL_CERT_FILE and ARMIS_API_URL are passed on to curl and to every armis-cli command. +# ---- CONFIG END ------------------------------------------------------------ + +SCRIPT_VERSION="1.0.0" +MARK_BEGIN="# >>> armis-cli (managed) >>>" +MARK_END="# <<< armis-cli (managed) <<<" +REPO="ArmisSecurity/armis-cli" +# Fixed so MDM runs do not depend on the caller's PATH. ARMIS_SAFE_PATH exists for tests. +SAFE_PATH="${ARMIS_SAFE_PATH:-/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin}" +SERVER_KEY="armis-appsec" +ALL_CLIENTS="cursor vscode copilot codex claude antigravity junie" +VALID_NAMES="$ALL_CLIENTS jetbrains hook" +# Variables passed through sudo to the user's armis-cli commands. Credentials +# travel only this way, never as arguments. +PRESERVE_ENV="ARMIS_CLIENT_ID,ARMIS_CLIENT_SECRET,ARMIS_TENANT_ID,ARMIS_REGION,ARMIS_API_URL,ARMIS_DEFAULT_AUTH_METHOD,ARMIS_MCP_VERSION,HTTPS_PROXY,https_proxy,HTTP_PROXY,http_proxy,NO_PROXY,no_proxy,SSL_CERT_FILE" + +DRY_RUN=0 +DO_UNINSTALL=0 +NONINTERACTIVE=0 +VERBOSE=0 +WANT_BUNDLE=0 +ONLY="" +SKIP="" +IS_ROOT=0 +[ "$(id -u)" -eq 0 ] && IS_ROOT=1 + +CRED_ID="" +CRED_SECRET="" +WORK="" +RESULTS="" +LOG_FILE="" +LOG_DIR="" +RUN_TS=$(date +%Y%m%d-%H%M%S) +CLI_BIN="" +CLI_HAS_PIN=0 +CLI_HAS_PROJECT=0 +CLI_COSIGN="unknown" +FORCED_EXIT=0 +LAST_OUT="" +LAST_RC=0 +SEQ=0 +USERS="" +NO_PYTHON_USERS="" + +# ---- logging and results --------------------------------------------------- + +redact() { + sed -E \ + -e 's/(ARMIS_CLIENT_SECRET[[:space:]]*[=:][[:space:]]*)[^[:space:]]+/\1***/g' \ + -e 's/([Bb]earer[[:space:]]+)[A-Za-z0-9._~+\/=-]+/\1***/g' \ + -e 's/("?client_secret"?[[:space:]]*[=:][[:space:]]*"?)[^[:space:]",}]+/\1***/g' | + if [ "${#CRED_SECRET}" -ge 8 ]; then + CS="$CRED_SECRET" awk '{ + s = ENVIRON["CS"] + while ((i = index($0, s)) > 0) $0 = substr($0, 1, i - 1) "***" substr($0, i + length(s)) + print + }' + else + cat + fi +} + +emit() { + local line + line=$(printf '%s' "$1" | redact) + printf '%s\n' "$line" >&2 + if [ -n "$LOG_FILE" ]; then printf '%s\n' "$line" >> "$LOG_FILE"; fi +} + +log() { emit "[armis-setup] $*"; } +warn() { emit "[armis-setup] WARNING: $*"; } +vlog() { if [ "$VERBOSE" -eq 1 ]; then emit "[armis-setup] + $*"; fi; } + +# show_out FILE: log a command's captured output, indented. +show_out() { + local text + [ -s "$1" ] || return 0 + text=$(redact < "$1" | sed 's/^/ /') + printf '%s\n' "$text" >&2 + if [ -n "$LOG_FILE" ]; then printf '%s\n' "$text" >> "$LOG_FILE"; fi +} + +# rec USER COMPONENT FIELD VALUE: append one fact to the results table. +rec() { + local v=${4//$'\t'/ } + v=${v//$'\n'/ } + printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$v" >> "$RESULTS" +} + +die_usage() { + printf '[armis-setup] ERROR: %s\n' "$*" >&2 + printf 'Run with --help for usage.\n' >&2 + exit 3 +} + +# ---- small helpers --------------------------------------------------------- + +has() { command -v "$1" >/dev/null 2>&1; } + +in_list() { # in_list WORD "a b c" + case " $2 " in *" $1 "*) return 0 ;; esac + return 1 +} + +split_list() { printf '%s' "$1" | tr ',' ' ' | tr -s ' '; } + +# lines_of_list "a,b c": one entry per line, splitting on commas only (paths may contain spaces). +lines_of_list() { printf '%s' "$1" | tr ',' '\n' | sed '/^[[:space:]]*$/d'; } + +require_ident() { + local name=$1 value=$2 + printf '%s' "$value" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' \ + || die_usage "$name has invalid characters or length: '$value'" +} + +user_home() { + if [ "$1" = "$(id -un)" ] && [ -n "${HOME:-}" ]; then + printf '%s\n' "$HOME" + return + fi + dscl . -read "/Users/$1" NFSHomeDirectory 2>/dev/null | awk '{ $1 = ""; sub(/^ /, ""); print }' +} + +resolve_users() { + if [ -n "$ARMIS_TARGET_USERS" ]; then + split_list "$ARMIS_TARGET_USERS" | tr ' ' '\n' + return + fi + if [ "$IS_ROOT" -eq 0 ]; then + id -un + return + fi + local u + u=$(stat -f%Su /dev/console 2>/dev/null || true) + case "$u" in "" | root | loginwindow) ;; *) printf '%s\n' "$u" ;; esac +} + +# kill_tree SIGNAL PID: signal PID and every descendant, children first. +kill_tree() { + local c + for c in $(pgrep -P "$2" 2>/dev/null); do kill_tree "$1" "$c"; done + kill "-$1" "$2" 2>/dev/null +} + +# with_timeout SECONDS CMD...: run CMD, kill it and everything it started after +# SECONDS. CMD is usually as_user, whose real command is a grandchild (sudo). +with_timeout() { + local secs=$1 pid watcher rc + shift + "$@" & + pid=$! + ( + sleep "$secs" & + sleeper=$! + trap 'kill "$sleeper" 2>/dev/null; exit 0' TERM + wait "$sleeper" + kill_tree TERM "$pid" + sleep 5 & + sleeper=$! + wait "$sleeper" + kill_tree KILL "$pid" + ) >/dev/null 2>&1 & + watcher=$! + wait "$pid" 2>/dev/null + rc=$? + kill -TERM "$watcher" 2>/dev/null + wait "$watcher" 2>/dev/null + return "$rc" +} + +# exec_cmd CMD...: run CMD, capture all output in LAST_OUT, status in LAST_RC. +exec_cmd() { + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + vlog "$*" + "$@" > "$LAST_OUT" 2>&1 < /dev/null + LAST_RC=$? +} + +# as_user USER HOME CREDS GUI CMD...: run CMD as USER. Credentials are put in +# the child's environment only, and only when CREDS is 1. GUI=1 attaches the +# command to the user's login session so a browser can open. +as_user() { + local user=$1 home=$2 creds=$3 gui=$4 uid upath + shift 4 + uid=$(id -u "$user" 2>/dev/null) || return 127 + upath="$SAFE_PATH:$home/.local/bin" + if [ -n "$ARMIS_EXTRA_PATH" ]; then upath="$ARMIS_EXTRA_PATH:$upath"; fi + if [ -n "$CLI_BIN" ]; then upath="$upath:$(dirname "$CLI_BIN")"; fi + ( + if [ "$creds" = 1 ] && [ -n "$CRED_ID" ]; then + # shellcheck disable=SC2030 # subshell-local on purpose: secrets never leak into this shell + export ARMIS_CLIENT_ID="$CRED_ID" ARMIS_CLIENT_SECRET="$CRED_SECRET" + fi + if [ "$uid" = "$(id -u)" ]; then + exec env PATH="$upath" HOME="$home" USER="$user" LOGNAME="$user" "$@" < /dev/null + elif [ "$gui" = 1 ]; then + exec launchctl asuser "$uid" sudo -n -H -u "$user" --preserve-env="$PRESERVE_ENV" \ + env PATH="$upath" HOME="$home" USER="$user" LOGNAME="$user" "$@" < /dev/null + else + exec sudo -n -H -u "$user" --preserve-env="$PRESERVE_ENV" \ + env PATH="$upath" HOME="$home" USER="$user" LOGNAME="$user" "$@" < /dev/null + fi + ) +} + +# user_cmd USER HOME CREDS GUI CMD...: as_user with captured output. +user_cmd() { + local user=$1 home=$2 creds=$3 gui=$4 + shift 4 + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + vlog "as $user: $*" + as_user "$user" "$home" "$creds" "$gui" "$@" > "$LAST_OUT" 2>&1 + LAST_RC=$? +} + +# ---- JSON helper (JavaScript for Automation, ships with macOS) -------------- + +write_json_tool() { + cat > "$WORK/json_tool.js" <<'JSEOF' +ObjC.import('Foundation'); + +function readFile(p) { + var s = $.NSString.stringWithContentsOfFileEncodingError($(p), $.NSUTF8StringEncoding, $()); + return s.isNil() ? null : ObjC.unwrap(s); +} + +function writeFile(p, text) { + var ok = $(text).writeToFileAtomicallyEncodingError($(p), true, $.NSUTF8StringEncoding, $()); + if (!ok) throw new Error('cannot write ' + p); +} + +// Comments and trailing commas outside strings, as VS Code's mcp.json allows. +function stripJsonc(s) { + var out = '', i = 0, n = s.length, inStr = false, c; + while (i < n) { + c = s[i]; + if (inStr) { + out += c; + if (c === '\\') { out += s[i + 1] || ''; i += 2; continue; } + if (c === '"') inStr = false; + i++; + continue; + } + if (c === '"') { inStr = true; out += c; i++; continue; } + if (c === '/' && s[i + 1] === '/') { while (i < n && s[i] !== '\n') i++; continue; } + if (c === '/' && s[i + 1] === '*') { + i += 2; + while (i < n && !(s[i] === '*' && s[i + 1] === '/')) i++; + i += 2; + continue; + } + out += c; + i++; + } + var res = '', j, k; + inStr = false; + for (i = 0; i < out.length; i++) { + c = out[i]; + if (inStr) { + res += c; + if (c === '\\') { res += out[i + 1] || ''; i++; continue; } + if (c === '"') inStr = false; + continue; + } + if (c === '"') { inStr = true; res += c; continue; } + if (c === ',') { + k = i + 1; + while (k < out.length && /\s/.test(out[k])) k++; + if (out[k] === '}' || out[k] === ']') continue; + } + res += c; + } + return res; +} + +function load(p) { + var t = readFile(p); + if (t === null) throw new Error('cannot read ' + p); + t = t.replace(/^/, ''); + if (t.trim() === '') return {}; + var o = JSON.parse(stripJsonc(t)); + if (o === null || typeof o !== 'object' || Array.isArray(o)) throw new Error('top level is not an object'); + return o; +} + +function run(argv) { + var cmd = argv[0], o, v; + if (cmd === 'check') { + load(argv[1]); + return ''; + } + if (cmd === 'keys') { + o = load(argv[1]); + v = o[argv[2]]; + if (v && typeof v === 'object' && !Array.isArray(v)) return Object.keys(v).sort().join('\n'); + return ''; + } + if (cmd === 'get') { + o = load(argv[1]); + return o.hasOwnProperty(argv[2]) ? JSON.stringify(o[argv[2]]) : ''; + } + if (cmd === 'delserver') { + o = load(argv[1]); + v = o[argv[2]]; + if (!v || typeof v !== 'object' || !v.hasOwnProperty(argv[3])) return 'absent'; + delete v[argv[3]]; + writeFile(argv[1], JSON.stringify(o, null, 2) + '\n'); + return 'removed'; + } + if (cmd === 'doctor') { + o = JSON.parse(readFile(argv[1])); + return (o.checks || []).map(function (c) { + return [c.component || '', c.editor || '', c.name || '', c.status || '', c.detail || '', c.remediation || ''] + .map(function (x) { return String(x).replace(/[\u001f\n\r]+/g, ' '); }).join('\u001f'); + }).join('\n'); + } + throw new Error('unknown command ' + cmd); +} +JSEOF + chmod 644 "$WORK/json_tool.js" +} + +# jt CMD ARGS...: run the JSON helper; output in stdout, nonzero on invalid input. +jt() { osascript -l JavaScript "$WORK/json_tool.js" "$@" 2>/dev/null; } + +# json_ok FILE: 0 if FILE is absent, empty, or parses as JSON (comments allowed). +json_ok() { + [ -e "$1" ] || return 0 + jt check "$1" >/dev/null +} + +# ---- per-client definitions ------------------------------------------------- + +# client_name CLIENT KIND: KIND is install (label in `armis-cli install` status +# lines), doctor (editor name in `mcp doctor` checks) or display (shown to people). +client_name() { + local install doctor display + case $1 in + cursor) install="Cursor" doctor="Cursor" display="Cursor" ;; + vscode) install="VS Code" doctor="VS Code" display="VS Code" ;; + copilot) install="Copilot CLI" doctor="Copilot CLI" display="Copilot CLI" ;; + codex) install="Codex CLI (MCP)" doctor="Codex CLI" display="Codex" ;; + claude) install="Claude Code" doctor="Claude Code" display="Claude Code" ;; + antigravity) install="Antigravity" doctor="Antigravity" display="Antigravity" ;; + junie) install="Junie" doctor="Junie" display="Junie" ;; + *) return 1 ;; + esac + case $2 in + install) echo "$install" ;; + doctor) echo "$doctor" ;; + display) echo "$display" ;; + esac +} + +# client_from_doctor NAME: the client whose doctor editor name is NAME. +client_from_doctor() { + local c + for c in $ALL_CLIENTS; do + if [ "$(client_name "$c" doctor)" = "$1" ]; then echo "$c"; return; fi + done +} + +client_detect_dir() { # client HOME: directory whose presence means "installed" + case $1 in + cursor) echo "$2/.cursor" ;; + vscode) echo "$2/Library/Application Support/Code/User" ;; + copilot) echo "$2/.copilot" ;; + codex) echo "$2/.codex" ;; + claude) echo "$2/.claude" ;; + antigravity) echo "$2/.gemini/config" ;; + junie) echo "$2/.junie/mcp" ;; + esac +} + +# client_files CLIENT HOME: lines of "kind|path|topkey". Kinds: json (parsed +# before and after), toml (backed up only). topkey names the object holding servers. +client_files() { + case $1 in + cursor) printf 'json|%s|mcpServers\njson|%s|\n' "$2/.cursor/mcp.json" "$2/.cursor/hooks.json" ;; + vscode) printf 'json|%s|servers\n' "$2/Library/Application Support/Code/User/mcp.json" ;; + copilot) printf 'json|%s|mcpServers\njson|%s|\n' "$2/.copilot/mcp-config.json" "$2/.copilot/settings.json" ;; + codex) printf 'toml|%s|\njson|%s|\n' "$2/.codex/config.toml" "$2/.codex/hooks.json" ;; + claude) printf 'json|%s|\njson|%s|\njson|%s|\n' "$2/.claude/settings.json" \ + "$2/.claude/plugins/installed_plugins.json" "$2/.claude/plugins/known_marketplaces.json" ;; + antigravity) printf 'json|%s|mcpServers\n' "$2/.gemini/config/mcp_config.json" ;; + junie) printf 'json|%s|mcpServers\n' "$2/.junie/mcp/mcp.json" ;; + esac +} + +is_running() { # is_running CLIENT USER + local uid + uid=$(id -u "$2" 2>/dev/null) || return 1 + case $1 in + cursor) pgrep -f -u "$uid" "Cursor.app/Contents/MacOS" >/dev/null 2>&1 ;; + vscode) pgrep -f -u "$uid" "Visual Studio Code.app/Contents/MacOS" >/dev/null 2>&1 ;; + antigravity) pgrep -f -u "$uid" "Antigravity.app/Contents/MacOS" >/dev/null 2>&1 ;; + claude) pgrep -x -u "$uid" claude >/dev/null 2>&1 ;; + codex) pgrep -x -u "$uid" codex >/dev/null 2>&1 ;; + *) return 1 ;; + esac +} + +# ---- backups --------------------------------------------------------------- + +# Every write under a developer's home runs as that developer (as_user), never +# as root: the paths are theirs to symlink anywhere. + +# backup_file USER HOME FILE LISTFILE: copy FILE to FILE.armis-bak. once per +# run and note it in LISTFILE as "origbak". +backup_file() { + local user=$1 home=$2 f=$3 list=$4 bak + [ -f "$f" ] || return 0 + bak="$f.armis-bak.$RUN_TS" + if [ ! -e "$bak" ] && [ ! -L "$bak" ]; then + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would back up $f to $bak" + return 0 + fi + # shellcheck disable=SC2016 # expanded by the inner shell + as_user "$user" "$home" 0 0 /bin/sh -c 'umask 077; cp -p "$1" "$2"' sh "$f" "$bak" || return 1 + fi + printf '%s\t%s\n' "$f" "$bak" >> "$list" +} + +# norm_sum FILE: checksum ignoring timestamps the installers refresh. +norm_sum() { + [ -f "$1" ] || { echo none; return; } + grep -v -e '"installedAt"' -e '"lastUpdated"' "$1" | shasum -a 256 | awk '{print $1}' +} + +# drop_unchanged USER HOME LISTFILE: delete backups whose original did not change. +drop_unchanged() { + local orig bak + while IFS=$'\t' read -r orig bak; do + [ -f "$bak" ] || continue + if [ -f "$orig" ] && [ "$(norm_sum "$orig")" = "$(norm_sum "$bak")" ]; then + as_user "$1" "$2" 0 0 /bin/rm -f "$bak" + fi + done < "$3" +} + +# ---- credentials ----------------------------------------------------------- + +load_credentials() { + local f owner mode id="" secret="" + # shellcheck disable=SC2031 # the export in as_user is deliberately subshell-local + CRED_ID="${ARMIS_CLIENT_ID:-}" + # shellcheck disable=SC2031 + CRED_SECRET="${ARMIS_CLIENT_SECRET:-}" + unset ARMIS_CLIENT_ID ARMIS_CLIENT_SECRET + f=$ARMIS_CREDENTIALS_FILE + if [ -n "$f" ] && { [ -z "$CRED_ID" ] || [ -z "$CRED_SECRET" ]; }; then + [ -f "$f" ] || die_usage "ARMIS_CREDENTIALS_FILE not found: $f" + owner=$(stat -f %u "$f") + mode=$(stat -f %Lp "$f") + if [ "$owner" != "$(id -u)" ]; then + die_usage "credentials file $f must be owned by the user running this script" + fi + case $mode in + 600 | 400) ;; + *) die_usage "credentials file $f has mode $mode; it must be 600 or 400" ;; + esac + id=$(sed -n 's/^ARMIS_CLIENT_ID=//p' "$f" | head -n 1) + secret=$(sed -n 's/^ARMIS_CLIENT_SECRET=//p' "$f" | head -n 1) + [ -n "$CRED_ID" ] || CRED_ID=$id + [ -n "$CRED_SECRET" ] || CRED_SECRET=$secret + fi + if [ -n "$CRED_ID$CRED_SECRET" ] && { [ -z "$CRED_ID" ] || [ -z "$CRED_SECRET" ]; }; then + die_usage "set both ARMIS_CLIENT_ID and ARMIS_CLIENT_SECRET (or neither)" + fi + case "$CRED_ID$CRED_SECRET" in + *$'\n'* | *$'\r'*) die_usage "client credentials must not contain newlines" ;; + esac +} + +# rotate_env FILE MODE AWKPROG, run as the user with the configured credentials +# in ARMIS_CLIENT_ID/ARMIS_CLIENT_SECRET. MODE is check or write. Exits 0 when +# FILE already holds them, 10 when it did not (and, with write, now does), 1 on error. +# shellcheck disable=SC2016 # expanded by the inner shell +ROTATE_SH='f=$1 +[ -f "$f" ] || exit 0 +cur_id=$(sed -n "s/^ARMIS_CLIENT_ID=//p" "$f" | head -n 1) +cur_secret=$(sed -n "s/^ARMIS_CLIENT_SECRET=//p" "$f" | head -n 1) +rc=0 +if [ "$cur_id" != "$ARMIS_CLIENT_ID" ] || [ "$cur_secret" != "$ARMIS_CLIENT_SECRET" ]; then + rc=10 + if [ "$2" = write ]; then + tmp=$(mktemp "$(dirname "$f")/.env.tmp.XXXXXX") || exit 1 + chmod 600 "$tmp" + if ! awk "$3" "$f" > "$tmp" || ! mv -f "$tmp" "$f"; then rm -f "$tmp"; exit 1; fi + fi +fi +if [ "$2" = write ]; then + chmod 600 "$f" || exit 1 + # The installers leave a copy of the old file next to the new one. + rm -f "$f.bak" +fi +exit $rc' + +# Sets the client credentials in a .env, keeping other keys. +# shellcheck disable=SC2016 # awk program +ROTATE_AWK=' + BEGIN { id = ENVIRON["ARMIS_CLIENT_ID"]; sec = ENVIRON["ARMIS_CLIENT_SECRET"] } + /^ARMIS_CLIENT_ID=/ { if (!d1) { print "ARMIS_CLIENT_ID=" id; d1 = 1 } ; next } + /^ARMIS_CLIENT_SECRET=/ { if (!d2) { print "ARMIS_CLIENT_SECRET=" sec; d2 = 1 } ; next } + { print } + END { if (!d1) print "ARMIS_CLIENT_ID=" id; if (!d2) print "ARMIS_CLIENT_SECRET=" sec }' + +# rotate_credentials USER HOME: bring every .env the installers wrote to the +# configured credentials. armis-cli keeps an existing .env as is. +rotate_credentials() { + local user=$1 home=$2 f mode=write rc changed=0 bad=0 + [ -n "$CRED_ID" ] || return 0 + [ "$DRY_RUN" -eq 0 ] || mode=check + for f in \ + "$home/.armis/plugins/armis-appsec-mcp/.env" \ + "$home/.claude/plugins/cache/armis-appsec-mcp/armis-appsec/latest/.env" \ + "$home/.armis/plugins/armis-knowledge-mcp/.env"; do + [ -f "$f" ] || continue + as_user "$user" "$home" 1 0 /bin/sh -c "$ROTATE_SH" sh "$f" "$mode" "$ROTATE_AWK" + rc=$? + case $rc:$mode in + 0:*) ;; + 10:check) log "[dry-run] would update credentials in $f" ;; + 10:write) log "[$user] updated credentials in $f"; changed=1 ;; + *) warn "[$user] could not update credentials in $f"; bad=1 ;; + esac + done + if [ "$bad" -eq 1 ]; then + rec "$user" _user auth fail + rec "$user" mcp-server action "could not rotate credentials; fix permissions on ~/.armis/plugins and re-run" + elif [ "$changed" -eq 1 ]; then + rec "$user" mcp-server action "credentials rotated; restart editors" + fi +} + +# ---- preflight -------------------------------------------------------------- + +fatal() { # fatal CODE MESSAGE + warn "$2" + rec "-" preflight installed fail + rec "-" preflight action "$2" + FORCED_EXIT=$1 + finish +} + +probe() { # probe URL: prints the HTTP status, 000 if unreachable + local code + if [ -n "${SSL_CERT_FILE:-}" ]; then + code=$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 10 --max-time 20 \ + --cacert "$SSL_CERT_FILE" "$1" 2>/dev/null) || code=000 + else + code=$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 10 --max-time 20 "$1" 2>/dev/null) || code=000 + fi + printf '%s' "${code:-000}" +} + +api_base() { + if [ -n "${ARMIS_API_URL:-}" ]; then + printf '%s' "$ARMIS_API_URL" + elif [ "$ARMIS_REGION" = eu1 ]; then + printf '%s' "https://eu.moose.armis.com" + else + printf '%s' "https://moose.armis.com" + fi +} + +stage_preflight() { + local os ver major arch translated free dir target code url name + log "Preflight" + os=$(uname -s) + [ "$os" = Darwin ] || fatal 3 "unsupported OS: $os (this script is for macOS)" + ver=$(sw_vers -productVersion 2>/dev/null || echo 0) + major=${ver%%.*} + if [ "${major:-0}" -lt 12 ] 2>/dev/null; then + fatal 3 "macOS $ver is not supported (12 or later is required)" + fi + arch=$(uname -m) + translated=$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0) + log "macOS $ver on $arch$([ "$translated" = 1 ] && echo ' (under Rosetta)')" + + for name in curl git osascript; do + has "$name" || fatal 3 "$name is required but was not found" + done + if [ "$IS_ROOT" -eq 1 ]; then + for name in dscl launchctl sudo; do + has "$name" || fatal 3 "$name is required when running as root but was not found" + done + fi + + # Uninstall downloads nothing and writes nothing new. + [ "$DO_UNINSTALL" -eq 0 ] || return 0 + + dir=$CLI_DIR + target=$dir + while [ ! -d "$target" ] && [ "$target" != / ]; do target=$(dirname "$target"); done + free=$(df -k "$target" | awk 'NR == 2 { print int($4 / 1024) }') + if [ "${free:-0}" -lt 500 ]; then + fatal 3 "less than 500 MB free on the volume holding $dir (${free:-0} MB)" + fi + if [ "$DRY_RUN" -eq 0 ] && [ ! -w "$target" ]; then + fatal 3 "$dir is not writable by $(id -un)" + fi + + for url in "$(api_base)" "https://api.github.com" "https://github.com/$REPO/releases"; do + code=$(probe "$url") + if [ "$code" = 000 ]; then + fatal 3 "cannot reach $url (check the network, HTTPS_PROXY and SSL_CERT_FILE)" + fi + vlog "reachable: $url ($code)" + done + if [ -z "$ARMIS_INSTALLER_URL" ]; then + code=$(probe "https://raw.githubusercontent.com") + [ "$code" != 000 ] || fatal 3 "cannot reach https://raw.githubusercontent.com (set ARMIS_INSTALLER_URL to an internal mirror)" + fi +} + +# ---- armis-cli -------------------------------------------------------------- + +cli_version_ok() { # does the installed binary report exactly the wanted version? + local got + [ -x "$CLI_BIN" ] || return 1 + got=$("$CLI_BIN" --version 2>/dev/null | awk '{ + for (i = 1; i <= NF; i++) if ($i ~ /^v?[0-9]+\.[0-9]+\.[0-9]+/) { sub(/^v/, "", $i); print $i; exit } + }') + [ -n "$got" ] && [ "$got" = "$ARMIS_CLI_VERSION" ] +} + +detect_cli_features() { + local help + CLI_HAS_PIN=0 + CLI_HAS_PROJECT=0 + [ -x "$CLI_BIN" ] || return 0 + help=$("$CLI_BIN" install --help 2>&1 || true) + case $help in *--plugin-version*) CLI_HAS_PIN=1 ;; esac + case $help in *--project*) CLI_HAS_PROJECT=1 ;; esac +} + +stage_cli() { + local ref installer_url version_arg + log "armis-cli" + CLI_BIN="$CLI_DIR/armis-cli" + + if [ "$ARMIS_CLI_VERSION" != latest ] && cli_version_ok; then + log "armis-cli $ARMIS_CLI_VERSION already installed at $CLI_BIN" + rec "-" armis-cli detected yes + rec "-" armis-cli installed ok + rec "-" armis-cli verified ok + detect_cli_features + return 0 + fi + + if [ "$ARMIS_CLI_VERSION" = latest ]; then ref=main; version_arg=latest; else ref="v$ARMIS_CLI_VERSION"; version_arg="v$ARMIS_CLI_VERSION"; fi + installer_url="${ARMIS_INSTALLER_URL:-https://raw.githubusercontent.com/$REPO/$ref/scripts/install.sh}" + + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would download $installer_url and install armis-cli $ARMIS_CLI_VERSION to $CLI_DIR" + rec "-" armis-cli detected no + rec "-" armis-cli installed skip + rec "-" armis-cli action "dry-run: would install armis-cli $ARMIS_CLI_VERSION" + return 0 + fi + + mkdir -p "$CLI_DIR" || { rec "-" armis-cli installed fail; FORCED_EXIT=2; finish; } + exec_cmd curl -fsSL "$installer_url" -o "$WORK/install.sh" + if [ "$LAST_RC" -ne 0 ]; then + show_out "$LAST_OUT" + rec "-" armis-cli installed fail + rec "-" armis-cli action "could not download the installer from $installer_url" + FORCED_EXIT=2 + finish + fi + + log "Installing armis-cli $ARMIS_CLI_VERSION to $CLI_DIR" + # CI=1 keeps the installer from editing the invoking account's shell rc; + # profiles are managed per developer below. + exec_cmd env CI=1 SHELL="${SHELL:-/bin/bash}" INSTALL_DIR="$CLI_DIR" VERIFY=true \ + PATH="$SAFE_PATH:$CLI_DIR:$PATH" bash "$WORK/install.sh" "$version_arg" + show_out "$LAST_OUT" + if grep -Eq "(Checksum|Signature) verification failed" "$LAST_OUT"; then + rec "-" armis-cli installed fail + rec "-" armis-cli action "checksum or signature verification failed; the download may have been tampered with" + FORCED_EXIT=3 + finish + fi + if [ "$LAST_RC" -ne 0 ] || [ ! -x "$CLI_BIN" ]; then + rec "-" armis-cli installed fail + rec "-" armis-cli action "installer failed; see the log" + FORCED_EXIT=2 + finish + fi + if [ "$IS_ROOT" -eq 1 ]; then chmod 755 "$CLI_BIN"; fi + + rec "-" armis-cli detected yes + rec "-" armis-cli installed ok + if [ "$ARMIS_CLI_VERSION" != latest ] && ! cli_version_ok; then + rec "-" armis-cli verified fail + rec "-" armis-cli action "installed binary does not report version $ARMIS_CLI_VERSION" + FORCED_EXIT=2 + finish + fi + rec "-" armis-cli verified ok + + if grep -q "Verifying signature with cosign" "$LAST_OUT" && ! grep -q "verifying checksums only" "$LAST_OUT"; then + CLI_COSIGN=yes + else + CLI_COSIGN=no + rec "-" armis-cli action "only the checksum was verified; install cosign for signature verification" + fi + detect_cli_features +} + +# ---- profiles --------------------------------------------------------------- + +# shellcheck disable=SC2016 # expanded by the inner shell +MANAGED_BLOCK_SH='f=$1 b=$2 e=$3 c=$4 +tmp=$(mktemp "${TMPDIR:-/tmp}/armis-profile.XXXXXX") || exit 1 +if [ -f "$f" ]; then + awk -v b="$b" -v e="$e" "\$0 == b { skip = 1; next } \$0 == e { skip = 0; next } !skip" "$f" > "$tmp" \ + || { rm -f "$tmp"; exit 1; } +fi +if [ -n "$c" ]; then printf "%s\n%s\n%s\n" "$b" "$c" "$e" >> "$tmp"; fi +cat "$tmp" > "$f" +rc=$? +rm -f "$tmp" +exit $rc' + +set_managed_block() { # set_managed_block FILE USER HOME CONTENT + local file=$1 user=$2 home=$3 content=$4 list + list="$WORK/profile-backups" + : > "$list" + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would update the managed block in $file" + return 0 + fi + backup_file "$user" "$home" "$file" "$list" + as_user "$user" "$home" 0 0 /bin/sh -c "$MANAGED_BLOCK_SH" sh "$file" "$MARK_BEGIN" "$MARK_END" "$content" \ + || warn "[$user] could not update $file" + drop_unchanged "$user" "$home" "$list" +} + +profile_block_content() { + local c="" + if [ -n "$ARMIS_TENANT_ID" ]; then c="export ARMIS_TENANT_ID='$ARMIS_TENANT_ID'"; fi + if [ "$ARMIS_AUTH_MODE" = sso ]; then c="${c:+$c$'\n'}export ARMIS_DEFAULT_AUTH_METHOD='SSO'"; fi + if [ -n "$ARMIS_REGION" ]; then c="${c:+$c$'\n'}export ARMIS_REGION='$ARMIS_REGION'"; fi + if [ "$IS_ROOT" -eq 0 ] && [ "$CLI_DIR" = "$HOME/.local/bin" ]; then + # shellcheck disable=SC2016 # $HOME must expand when the profile is sourced + c="${c:+$c$'\n'}"'export PATH="$HOME/.local/bin:$PATH"' + fi + printf '%s' "$c" +} + +configure_profiles() { # configure_profiles USER HOME + local user=$1 home=$2 content f + content=$(profile_block_content) + [ -n "$content" ] || return 0 + set_managed_block "$home/.zshenv" "$user" "$home" "$content" + if [ -f "$home/.bash_profile" ]; then f="$home/.bash_profile"; else f="$home/.profile"; fi + set_managed_block "$f" "$user" "$home" "$content" + if [ -f "$home/.bashrc" ]; then set_managed_block "$home/.bashrc" "$user" "$home" "$content"; fi +} + +remove_profiles() { # remove_profiles USER HOME + local user=$1 home=$2 f + for f in "$home/.zshenv" "$home/.bash_profile" "$home/.profile" "$home/.bashrc"; do + if [ -f "$f" ] && grep -qF "$MARK_BEGIN" "$f"; then set_managed_block "$f" "$user" "$home" ""; fi + done +} + +# ---- auth ------------------------------------------------------------------- + +session_present() { + [ -f "$1/.armis/.sessions" ] && grep -q refresh_token "$1/.armis/.sessions" 2>/dev/null +} + +stage_auth() { # stage_auth USER HOME + local user=$1 home=$2 want login_rc + log "[$user] auth ($ARMIS_AUTH_MODE)" + configure_profiles "$user" "$home" + + if [ "$DRY_RUN" -eq 1 ]; then + rec "$user" _user auth skip + return 0 + fi + + local authmethod_env="" + if [ "$ARMIS_AUTH_MODE" = sso ]; then authmethod_env=SSO; fi + + if [ "$ARMIS_AUTH_MODE" = client-credentials ] && [ -n "$CRED_ID" ]; then + user_cmd "$user" "$home" 1 0 "$CLI_BIN" auth whoami + show_out "$LAST_OUT" + if [ "$LAST_RC" -eq 0 ]; then + rec "$user" _user auth ok + else + rec "$user" _user auth fail + rec "$user" _user action "client credentials were rejected; check ARMIS_CLIENT_ID/ARMIS_CLIENT_SECRET and ARMIS_REGION" + fi + return 0 + fi + + # sso, or client-credentials with no credentials supplied + if session_present "$home"; then + user_cmd "$user" "$home" 0 0 env ARMIS_DEFAULT_AUTH_METHOD="$authmethod_env" "$CLI_BIN" auth whoami + show_out "$LAST_OUT" + if [ "$LAST_RC" -eq 0 ]; then + rec "$user" _user auth ok + return 0 + fi + fi + + want=$ARMIS_SSO_LOGIN + if [ "$want" = auto ]; then + if [ "$IS_ROOT" -eq 0 ] && [ "$NONINTERACTIVE" -eq 0 ]; then want=now; else want=skip; fi + fi + if [ "$ARMIS_AUTH_MODE" = client-credentials ] && [ "$NONINTERACTIVE" -eq 1 ] && [ "$ARMIS_SSO_LOGIN" != now ]; then + want=skip + fi + if [ "$want" = now ]; then + log "[$user] starting browser sign-in" + local tenant_args="" + [ -z "$ARMIS_TENANT_ID" ] || tenant_args="--tenant-id $ARMIS_TENANT_ID" + # shellcheck disable=SC2086 # tenant_args is two words on purpose + with_timeout 300 as_user "$user" "$home" 0 1 env ARMIS_DEFAULT_AUTH_METHOD=SSO "$CLI_BIN" auth login $tenant_args >&2 + login_rc=$? + if [ "$login_rc" -eq 0 ]; then + rec "$user" _user auth ok + return 0 + fi + fi + rec "$user" _user auth warn + rec "$user" _user action "sign-in pending: run 'armis-cli auth login'" +} + +# ---- python ----------------------------------------------------------------- + +# shellcheck disable=SC2016 # expanded by the inner shell +PY_PROBE='for p in python3.14 python3.13 python3.12 python3.11 python3 python; do + b=$(command -v "$p" 2>/dev/null) || continue + if [ "$("$b" -c "import sys; print(sys.version_info >= (3, 11))" 2>/dev/null)" = True ]; then echo "$b"; exit 0; fi +done +exit 1' + +user_has_python() { # user_has_python USER HOME + user_cmd "$1" "$2" 0 0 /bin/sh -c "$PY_PROBE" + [ "$LAST_RC" -eq 0 ] +} + +# ---- mcp -------------------------------------------------------------------- + +# out_find SYMBOL LABEL FILE: first status line "SYMBOL LABEL..." in an armis-cli +# transcript, with the symbol and label removed. +out_find() { + awk -v sym="$1" -v label="$2" ' + { sub(/^[ \t]+/, "") } + index($0, sym " " label) == 1 { print substr($0, length(sym " " label) + 1); found = 1; exit } + END { exit found ? 0 : 1 } + ' "$3" +} + +# check_client_state USER HOME CLIENT KEYFILE: did registration leave the +# server in place and the earlier servers intact? +check_client_state() { + local user=$1 home=$2 client=$3 before=$4 kind path top after + local primary_ok=1 + while IFS='|' read -r kind path top; do + [ -n "$kind" ] || continue + if [ "$kind" = json ]; then + if ! json_ok "$path"; then + CHECK_MSG="$path is not valid JSON after install" + return 1 + fi + if [ -n "$top" ]; then + after=$(jt keys "$path" "$top") + if ! printf '%s\n' "$after" | grep -qx "$SERVER_KEY"; then + CHECK_MSG="$SERVER_KEY is missing from $path" + primary_ok=0 + fi + if [ -f "$before" ]; then + local lost + lost=$(awk 'NR == FNR { a[$0] = 1; next } !($0 in a)' <(printf '%s\n' "$after") "$before" | head -n 1) + if [ -n "$lost" ]; then + CHECK_MSG="existing server '$lost' disappeared from $path" + return 1 + fi + fi + fi + fi + done <<< "$(client_files "$client" "$home")" + case $client in + claude) + grep -q 'armis-appsec@armis-appsec-mcp' "$home/.claude/plugins/installed_plugins.json" 2>/dev/null \ + || { CHECK_MSG="plugin missing from ~/.claude/plugins/installed_plugins.json"; return 1; } ;; + codex) + grep -q '^\[mcp_servers.armis_scanner\]' "$home/.codex/config.toml" 2>/dev/null \ + || { CHECK_MSG="armis_scanner section missing from ~/.codex/config.toml"; return 1; } ;; + esac + [ "$primary_ok" -eq 1 ] +} + +stage_mcp() { # stage_mcp USER HOME + local user=$1 home=$2 client dir targets="" kind path top msg hook_msg list c + local bad_dir="$WORK/mcp.$user" + log "[$user] MCP server" + mkdir -p "$bad_dir" + list="$bad_dir/backups" + : > "$list" + + for client in $CLIENT_LIST; do + in_list "$client" "$ALL_CLIENTS" || continue + dir=$(client_detect_dir "$client" "$home") + if [ -d "$dir" ]; then + rec "$user" "$client" detected yes + else + rec "$user" "$client" detected no + rec "$user" "$client" installed skip + continue + fi + # Validate every config we are about to touch. A file that does not + # parse would be replaced by armis-cli, deleting the user's other servers. + local invalid="" + while IFS='|' read -r kind path top; do + [ -n "$kind" ] || continue + if [ "$kind" = json ] && ! json_ok "$path"; then invalid=$path; break; fi + done <<< "$(client_files "$client" "$home")" + if [ -n "$invalid" ]; then + rec "$user" "$client" installed fail + rec "$user" "$client" action "config at $invalid is not valid JSON; fix or remove it, then re-run" + continue + fi + # Record the servers already registered, and back the files up. + while IFS='|' read -r kind path top; do + [ -n "$kind" ] || continue + if [ -n "$top" ] && [ -f "$path" ]; then jt keys "$path" "$top" > "$bad_dir/$client.before" || true; fi + backup_file "$user" "$home" "$path" "$list" + done <<< "$(client_files "$client" "$home")" + targets="$targets $client" + done + targets=${targets# } + + if [ -z "$targets" ]; then + log "[$user] no clients to configure" + return 0 + fi + + if ! user_has_python "$user" "$home"; then + NO_PYTHON_USERS="$NO_PYTHON_USERS $user" + rec "$user" mcp-server installed warn + rec "$user" mcp-server action "install Python 3.11+ (brew install python@3.12, or the python.org installer), then re-run" + for client in $targets; do + rec "$user" "$client" installed fail + rec "$user" "$client" action "blocked: Python 3.11+ is missing for $user" + done + return 0 + fi + + local flags="--non-interactive" + [ "$ARMIS_WITH_KNOWLEDGE" = 1 ] && flags="$flags --with-knowledge" + if [ -n "$ARMIS_MCP_VERSION" ]; then + if [ "$CLI_HAS_PIN" -eq 1 ] || { [ "$DRY_RUN" -eq 1 ] && [ ! -x "$CLI_BIN" ]; }; then + flags="$flags --plugin-version $ARMIS_MCP_VERSION" + else + rec "$user" mcp-server action "MCP version not pinned: this armis-cli has no --plugin-version; use a newer armis-cli" + rec "$user" mcp-server installed warn + fi + fi + + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would run: armis-cli install $targets $flags" + for client in $targets; do + rec "$user" "$client" installed skip + rec "$user" "$client" action "dry-run: would register" + done + return 0 + fi + + # shellcheck disable=SC2086 # targets and flags are word lists + user_cmd "$user" "$home" 1 0 "$CLI_BIN" install $targets $flags + show_out "$LAST_OUT" + local install_rc=$LAST_RC install_out=$LAST_OUT + local tail_msg + tail_msg=$(grep -v '^[[:space:]]*$' "$install_out" | tail -n 1) + + for client in $targets; do + c=$(client_name "$client" install) + CHECK_MSG="" + if msg=$(out_find "✗" "$c" "$install_out"); then + rec "$user" "$client" installed fail + rec "$user" "$client" action "${msg#: }" + restore_files "$user" "$home" "$client" "$list" + continue + fi + if ! out_find "✓" "$c" "$install_out" >/dev/null && [ "$install_rc" -ne 0 ]; then + rec "$user" "$client" installed fail + rec "$user" "$client" action "${tail_msg:-armis-cli install failed}" + restore_files "$user" "$home" "$client" "$list" + continue + fi + if ! check_client_state "$user" "$home" "$client" "$bad_dir/$client.before"; then + rec "$user" "$client" installed fail + rec "$user" "$client" action "${CHECK_MSG:-registration was not found}; restored the previous config" + restore_files "$user" "$home" "$client" "$list" + continue + fi + rec "$user" "$client" installed ok + if hook_msg=$(out_find "⚠" "$(client_hook_label "$client")" "$install_out"); then + rec "$user" "$client" installed warn + rec "$user" "$client" action "native hook not installed${hook_msg}" + fi + done + + # Restart hints, only for clients whose config changed. + for client in $targets; do + if config_changed "$home" "$client" "$list" && is_running "$client" "$user"; then + rec "$user" "$client" action "restart $(client_name "$client" display)" + fi + done + + drop_unchanged "$user" "$home" "$list" + stage_mcp_extras "$user" "$home" + rotate_credentials "$user" "$home" + + if [ "$install_rc" -ne 0 ]; then + rec "$user" mcp-server installed warn + rec "$user" mcp-server action "armis-cli install exited $install_rc; failed clients are listed above" + else + rec "$user" mcp-server installed ok + fi +} + +client_hook_label() { + case $1 in + cursor) echo "Cursor (hooks)" ;; + copilot) echo "Copilot CLI (hooks)" ;; + codex) echo "Codex CLI (hooks)" ;; + *) echo "-" ;; + esac +} + +restore_files() { # restore_files USER HOME CLIENT LIST + local kind path top + while IFS='|' read -r kind path top; do + [ -n "$kind" ] || continue + restore_one "$1" "$2" "$path" "$4" + done <<< "$(client_files "$3" "$2")" +} + +restore_one() { # restore_one USER HOME FILE LIST + local bak + bak=$(awk -F'\t' -v o="$3" '$1 == o { b = $2 } END { print b }' "$4") + if [ -n "$bak" ] && [ -f "$bak" ]; then + as_user "$1" "$2" 0 0 /bin/cp -p "$bak" "$3" && log "restored $3 from $bak" + fi +} + +config_changed() { # config_changed HOME CLIENT LIST + local kind path top bak + while IFS='|' read -r kind path top; do + [ -n "$kind" ] || continue + bak=$(awk -F'\t' -v o="$path" '$1 == o { b = $2 } END { print b }' "$3") + if [ -z "$bak" ]; then + [ -f "$path" ] && return 0 + continue + fi + [ "$(norm_sum "$path")" = "$(norm_sum "$bak")" ] || return 0 + done <<< "$(client_files "$2" "$1")" + return 1 +} + +# Copilot Agent mode and MCP can be switched off in VS Code settings or by +# organization policy. Only reported, never edited. +stage_mcp_extras() { # stage_mcp_extras USER HOME + local user=$1 home=$2 settings v + settings="$home/Library/Application Support/Code/User/settings.json" + [ -f "$settings" ] || return 0 + if ! in_list vscode "$CLIENT_LIST"; then return 0; fi + for key in chat.agent.enabled chat.mcp.enabled; do + v=$(jt get "$settings" "$key") || continue + if [ "$v" = false ]; then + rec "$user" vscode installed warn + rec "$user" vscode action "enable Copilot Agent mode and MCP ($key is false in VS Code settings, or ask the GitHub org admin about the MCP policy)" + fi + done + v=$(jt get "$settings" chat.mcp.access) || v="" + if [ "$v" = '"none"' ]; then + rec "$user" vscode installed warn + rec "$user" vscode action "chat.mcp.access is none in VS Code settings; set it to all" + fi +} + +# ---- jetbrains -------------------------------------------------------------- + +stage_jetbrains() { # stage_jetbrains USER HOME + local user=$1 home=$2 p owner cfg list found=0 ok=1 shown=0 + in_list jetbrains "$ENABLED_EXTRAS" || return 0 + log "[$user] JetBrains" + list="$WORK/jb.$user" + : > "$list" + + if [ -z "$ARMIS_JETBRAINS_PROJECTS" ]; then + if ls -d "$home/Library/Application Support/JetBrains"/* >/dev/null 2>&1; then + rec "$user" jetbrains detected yes + rec "$user" jetbrains installed warn + rec "$user" jetbrains action "JetBrains AI Assistant is per project: run 'armis-cli install jetbrains --project ' in each repo, set ARMIS_JETBRAINS_PROJECTS, or use Junie" + else + rec "$user" jetbrains detected no + rec "$user" jetbrains installed skip + fi + return 0 + fi + + rec "$user" jetbrains detected yes + if [ "$CLI_HAS_PROJECT" -eq 0 ] && [ "$DRY_RUN" -eq 0 ]; then + rec "$user" jetbrains installed fail + rec "$user" jetbrains action "this armis-cli has no 'install jetbrains --project'; use a newer armis-cli" + return 0 + fi + while IFS= read -r p; do + [ -n "$p" ] || continue + owner=$(stat -f %Su "$p" 2>/dev/null || true) + [ "$owner" = "$user" ] || continue + found=1 + cfg="$p/.jb-mcp.json" + if ! json_ok "$cfg"; then + rec "$user" jetbrains action "$cfg is not valid JSON; fix or remove it" + ok=0 + continue + fi + backup_file "$user" "$home" "$cfg" "$list" + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would run: armis-cli install jetbrains --project $p" + continue + fi + user_cmd "$user" "$home" 1 0 "$CLI_BIN" install jetbrains --project "$p" --non-interactive + show_out "$LAST_OUT" + if [ "$LAST_RC" -ne 0 ] || ! jt keys "$cfg" mcpServers | grep -qx "$SERVER_KEY"; then + restore_one "$user" "$home" "$cfg" "$list" + rec "$user" jetbrains action "registration failed for $p" + ok=0 + else + shown=$((shown + 1)) + fi + done <<< "$(lines_of_list "$ARMIS_JETBRAINS_PROJECTS")" + drop_unchanged "$user" "$home" "$list" + if [ "$found" -eq 0 ]; then + rec "$user" jetbrains installed skip + rec "$user" jetbrains action "no configured project belongs to $user" + elif [ "$DRY_RUN" -eq 1 ]; then + rec "$user" jetbrains installed skip + elif [ "$ok" -eq 1 ]; then + rec "$user" jetbrains installed ok + rec "$user" jetbrains action "enable the server in the IDE's AI Assistant MCP settings" + else + rec "$user" jetbrains installed fail + fi +} + +# ---- hook ------------------------------------------------------------------- + +stage_hook() { # stage_hook USER HOME + local user=$1 home=$2 repo owner hooks hook list found=0 ok=1 flags="" + in_list hook "$ENABLED_EXTRAS" || return 0 + log "[$user] commit gate" + if [ -z "$ARMIS_HOOK_REPOS" ]; then + rec "$user" hook installed warn + rec "$user" hook action "the commit gate is per repository: run 'armis-cli hook init' in each repo, or set ARMIS_HOOK_REPOS" + return 0 + fi + list="$WORK/hook.$user" + : > "$list" + [ "$ARMIS_HOOK_FAIL_OPEN" = 1 ] && flags="--fail-open" + rec "$user" hook detected yes + while IFS= read -r repo; do + [ -n "$repo" ] || continue + owner=$(stat -f %Su "$repo" 2>/dev/null || true) + [ "$owner" = "$user" ] || continue + found=1 + user_cmd "$user" "$home" 0 0 git -C "$repo" rev-parse --git-path hooks + if [ "$LAST_RC" -ne 0 ]; then + rec "$user" hook action "$repo is not a git repository" + ok=0 + continue + fi + hooks=$(tail -n 1 "$LAST_OUT") + case $hooks in /*) ;; *) hooks="$repo/$hooks" ;; esac + hook="$hooks/pre-commit" + backup_file "$user" "$home" "$hook" "$list" + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would run: armis-cli hook init $flags in $repo" + continue + fi + # shellcheck disable=SC2016 # expanded by the inner shell + user_cmd "$user" "$home" 0 0 /bin/sh -c 'cd "$1" && shift && exec "$@"' sh "$repo" "$CLI_BIN" hook init $flags + show_out "$LAST_OUT" + if [ "$LAST_RC" -ne 0 ] || [ ! -x "$hook" ]; then + restore_one "$user" "$home" "$hook" "$list" + rec "$user" hook action "could not install the hook in $repo" + ok=0 + fi + done <<< "$(lines_of_list "$ARMIS_HOOK_REPOS")" + drop_unchanged "$user" "$home" "$list" + if [ "$found" -eq 0 ]; then + rec "$user" hook installed skip + rec "$user" hook action "no configured repository belongs to $user" + elif [ "$DRY_RUN" -eq 1 ]; then + rec "$user" hook installed skip + elif [ "$ok" -eq 1 ]; then + rec "$user" hook installed ok + else + rec "$user" hook installed fail + fi +} + +# ---- verify ----------------------------------------------------------------- + +stage_verify() { # stage_verify USER HOME + local user=$1 home=$2 bundle="" report comp editor name status detail fix client c + log "[$user] verify" + if [ "$DRY_RUN" -eq 1 ]; then return 0; fi + if in_list "$user" "$NO_PYTHON_USERS"; then + log "[$user] MCP server not installed (no Python 3.11+); skipping mcp doctor" + if [ "$ARMIS_SAMPLE_SCAN" = 1 ]; then sample_scan "$user" "$home"; fi + return 0 + fi + + if [ "$WANT_BUNDLE" -eq 1 ]; then + bundle="--bundle-path $LOG_DIR/doctor-$user-$RUN_TS.zip" + fi + report="$WORK/doctor.$user.json" + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + # shellcheck disable=SC2086 # bundle is two words on purpose + with_timeout 300 as_user "$user" "$home" 1 0 "$CLI_BIN" mcp doctor -f json --deep $bundle > "$report" 2> "$LAST_OUT" + LAST_RC=$? + show_out "$LAST_OUT" + + if ! jt doctor "$report" > "$WORK/doctor.$user.tsv" 2>/dev/null; then + rec "$user" mcp-server verified fail + rec "$user" mcp-server action "mcp doctor produced no report; run 'armis-cli mcp doctor' as $user" + else + while IFS=$'\037' read -r comp editor name status detail fix; do + [ -n "$comp" ] || continue + client="" + [ -z "$editor" ] || client=$(client_from_doctor "$editor") + case $status in ok | info) continue ;; esac + c=warn + [ "$status" = fail ] && c=fail + if [ -n "$client" ]; then + if in_list "$client" "$CLIENT_LIST" && ! install_failed "$user" "$client"; then + rec "$user" "$client" verified "$c" + rec "$user" "$client" action "$(doctor_action "$name" "$detail" "$fix")" + fi + else + rec "$user" mcp-server verified "$c" + rec "$user" mcp-server action "$(doctor_action "$name" "$detail" "$fix")" + fi + done < "$WORK/doctor.$user.tsv" + fi + for client in $CLIENT_LIST; do + in_list "$client" "$ALL_CLIENTS" || continue + if client_is_ok "$user" "$client"; then rec "$user" "$client" verified ok; fi + done + if ! awk -F'\t' -v u="$user" '$1 == u && $2 == "mcp-server" && $3 == "verified" { f = 1 } END { exit f ? 0 : 1 }' "$RESULTS"; then + rec "$user" mcp-server verified ok + fi + + if [ "$ARMIS_SAMPLE_SCAN" = 1 ]; then sample_scan "$user" "$home"; fi +} + +# doctor_action NAME DETAIL REMEDIATION: one-line action text, capped in length. +doctor_action() { + local t="$1: $2" + [ -z "$3" ] || t="$t. $3" + if [ "${#t}" -gt 300 ]; then t="${t:0:297}..."; fi + printf '%s' "$t" +} + +install_failed() { # install_failed USER CLIENT + awk -F'\t' -v u="$1" -v c="$2" '$1 == u && $2 == c && $3 == "installed" && $4 == "fail" { f = 1 } END { exit f ? 0 : 1 }' "$RESULTS" +} + +# client_is_ok USER CLIENT: installed ok and no verification result yet. +client_is_ok() { + awk -F'\t' -v u="$1" -v c="$2" ' + $1 == u && $2 == c && $3 == "installed" { i = $4 } + $1 == u && $2 == c && $3 == "verified" { v = 1 } + END { exit (i == "ok" && !v) ? 0 : 1 } + ' "$RESULTS" +} + +sample_scan() { # sample_scan USER HOME + local user=$1 home=$2 dir + dir=$(mktemp -d "$WORK/sample.XXXXXX") + chmod 755 "$dir" + printf 'import hashlib\nprint(hashlib.md5(b"armis-sample").hexdigest())\n' > "$dir/sample.py" + chmod 644 "$dir/sample.py" + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + with_timeout 600 as_user "$user" "$home" 1 0 "$CLI_BIN" scan repo "$dir" --format json > "$LAST_OUT" 2>&1 + LAST_RC=$? + # Findings make the scan exit non-zero by design; only a missing result counts as failure. + if [ "$LAST_RC" -ne 0 ] && ! grep -q '"findings"' "$LAST_OUT"; then + show_out "$LAST_OUT" + rec "$user" sample-scan verified fail + rec "$user" sample-scan action "the sample scan did not complete; check 'armis-cli auth whoami' and the network" + else + rec "$user" sample-scan verified ok + fi + rec "$user" sample-scan detected yes + rec "$user" sample-scan installed ok +} + +# network check once, as the first user +network_check() { # network_check USER HOME + [ "$DRY_RUN" -eq 0 ] || return 0 + user_cmd "$1" "$2" 0 0 "$CLI_BIN" mcp doctor --network + if [ "$LAST_RC" -ne 0 ]; then + show_out "$LAST_OUT" + rec "-" armis-cli verified warn + rec "-" armis-cli action "network check reported problems; run 'armis-cli mcp doctor --network' (proxy, TLS inspection, certificates)" + fi +} + +# ---- uninstall -------------------------------------------------------------- + +stage_uninstall() { # stage_uninstall USER HOME + local user=$1 home=$2 client targets="" flags="--force" p repo cfg top + log "[$user] uninstall" + for client in $CLIENT_LIST; do + in_list "$client" "$ALL_CLIENTS" || continue + rec "$user" "$client" detected "$([ -d "$(client_detect_dir "$client" "$home")" ] && echo yes || echo no)" + targets="$targets $client" + done + targets=${targets# } + [ "$ARMIS_KEEP_CREDENTIALS" = 1 ] && flags="$flags --keep-credentials" + + if [ "$FULL_UNINSTALL" -eq 0 ] && [ -z "$targets" ]; then + # A bare `armis-cli uninstall` means everything; nothing here was selected. + vlog "[$user] no client selected; not running armis-cli uninstall" + elif [ "$DRY_RUN" -eq 1 ]; then + if [ "$FULL_UNINSTALL" -eq 1 ]; then + log "[dry-run] would run: armis-cli uninstall $flags" + else + log "[dry-run] would run: armis-cli uninstall $targets" + fi + elif [ -x "$CLI_BIN" ]; then + if [ "$FULL_UNINSTALL" -eq 1 ]; then + # shellcheck disable=SC2086 + user_cmd "$user" "$home" 0 0 "$CLI_BIN" uninstall $flags + else + # shellcheck disable=SC2086 + user_cmd "$user" "$home" 0 0 "$CLI_BIN" uninstall $targets + fi + show_out "$LAST_OUT" + if [ "$LAST_RC" -ne 0 ]; then + rec "$user" mcp-server installed fail + rec "$user" mcp-server action "armis-cli uninstall exited $LAST_RC; see the log" + else + rec "$user" mcp-server installed ok + rec "$user" mcp-server action "uninstalled" + fi + else + rec "$user" mcp-server installed skip + rec "$user" mcp-server action "armis-cli is not installed; nothing to uninstall through it" + fi + + for client in $targets; do + [ "$DRY_RUN" -eq 0 ] || continue + if [ ! -d "$(client_detect_dir "$client" "$home")" ]; then + rec "$user" "$client" installed skip + continue + fi + cfg=$(client_files "$client" "$home" | head -n 1 | cut -d'|' -f2) + top=$(client_files "$client" "$home" | head -n 1 | cut -d'|' -f3) + if [ -n "$top" ] && [ -f "$cfg" ] && jt keys "$cfg" "$top" | grep -qx "$SERVER_KEY"; then + rec "$user" "$client" installed fail + rec "$user" "$client" action "$SERVER_KEY is still registered in $cfg" + else + rec "$user" "$client" installed ok + rec "$user" "$client" verified ok + rec "$user" "$client" action "removed" + fi + done + + # The profile block serves every client: keep it while any client stays registered. + local keep_profile=0 + for client in $ALL_CLIENTS; do in_list "$client" "$targets" || keep_profile=1; done + if [ "$FULL_UNINSTALL" -eq 1 ] || [ "$keep_profile" -eq 0 ]; then remove_profiles "$user" "$home"; fi + + if in_list hook "$ENABLED_EXTRAS" && [ -x "$CLI_BIN" ] && [ "$DRY_RUN" -eq 0 ]; then + while IFS= read -r repo; do + [ -n "$repo" ] || continue + [ "$(stat -f %Su "$repo" 2>/dev/null)" = "$user" ] || continue + # shellcheck disable=SC2016 + user_cmd "$user" "$home" 0 0 /bin/sh -c 'cd "$1" && shift && exec "$@"' sh "$repo" "$CLI_BIN" hook init --remove + show_out "$LAST_OUT" + done <<< "$(lines_of_list "$ARMIS_HOOK_REPOS")" + fi + if in_list jetbrains "$ENABLED_EXTRAS" && [ "$DRY_RUN" -eq 0 ]; then + while IFS= read -r p; do + [ -n "$p" ] || continue + [ "$(stat -f %Su "$p" 2>/dev/null)" = "$user" ] || continue + cfg="$p/.jb-mcp.json" + [ -f "$cfg" ] || continue + user_cmd "$user" "$home" 0 0 osascript -l JavaScript "$WORK/json_tool.js" delserver "$cfg" mcpServers "$SERVER_KEY" + show_out "$LAST_OUT" + rec "$user" jetbrains installed ok + rec "$user" jetbrains action "removed from $cfg" + done <<< "$(lines_of_list "$ARMIS_JETBRAINS_PROJECTS")" + fi + + if [ "$DRY_RUN" -eq 0 ]; then + as_user "$user" "$home" 0 0 /bin/rm -f \ + "$home/.armis/plugins/armis-appsec-mcp/.env.bak" "$home/.armis/plugins/armis-knowledge-mcp/.env.bak" + fi +} + +# ---- report ----------------------------------------------------------------- + +# compute_exit: 3 > 2 > 1 > 0 +compute_exit() { + local code=0 + if [ "$FORCED_EXIT" -ne 0 ]; then + echo "$FORCED_EXIT" + return + fi + if awk -F'\t' '$3 == "verified" && $4 == "fail" { f = 1 } END { exit f ? 0 : 1 }' "$RESULTS"; then + code=2 + elif awk -F'\t' '($3 == "installed" || $3 == "auth" || $3 == "verified") && ($4 == "fail" || $4 == "warn") { f = 1 } END { exit f ? 0 : 1 }' "$RESULTS"; then + code=1 + fi + echo "$code" +} + +# build_table: one row per (user, component), fields separated by \037 so that +# empty fields survive `read`: +# user component detected installed auth verified action +build_table() { + awk -F'\t' ' + BEGIN { rank["skip"] = 1; rank["ok"] = 2; rank["warn"] = 3; rank["fail"] = 4 } + $2 == "_user" { + if ($3 == "auth") auth[$1] = $4 + if ($3 == "action") uact[$1] = (uact[$1] == "" ? $4 : uact[$1] "; " $4) + next + } + { + k = $1 SUBSEP $2 + if (!(k in seen)) { seen[k] = 1; order[++n] = k; u[k] = $1; c[k] = $2 } + if ($3 == "action") { act[k] = (act[k] == "" ? $4 : act[k] "; " $4) } + else if ($3 == "detected") det[k] = $4 + else if ($3 == "installed") { if (rank[$4] >= rank[ins[k]]) ins[k] = $4 } + else if ($3 == "verified") { if (rank[$4] >= rank[ver[k]]) ver[k] = $4 } + } + END { + for (i = 1; i <= n; i++) { + k = order[i] + a = (u[k] in auth) ? auth[u[k]] : "" + if (c[k] == "armis-cli" || c[k] == "preflight" || det[k] == "no") a = "" + action = act[k] + if (c[k] == "mcp-server" && uact[u[k]] != "") action = (action == "" ? uact[u[k]] : action "; " uact[u[k]]) + printf "%s\037%s\037%s\037%s\037%s\037%s\037%s\n", u[k], c[k], det[k], ins[k], a, ver[k], action + } + } + ' "$RESULTS" +} + +print_matrix() { # print_matrix TABLEFILE ENDPOINT + local u c d i a v act + { + printf 'Endpoint\tUser\tComponent\tDetected\tInstalled\tAuth\tVerified\tAction needed\n' + while IFS=$'\037' read -r u c d i a v act; do + if [ "$d" = no ] && [ "$i" = skip ]; then i="skip (not installed)"; fi + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$2" "${u/#-/(machine)}" "$c" "${d:--}" "${i:--}" \ + "${a:--}" "${v:--}" "${act:--}" + done < "$1" + } | column -t -s $'\t' +} + +json_str() { # JSON-escape stdin lines into one quoted string + awk 'BEGIN { ORS = "" } { gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR > 1) print "\\n"; print }' | { printf '"'; cat; printf '"'; } +} + +write_reports() { # write_reports TABLEFILE ENDPOINT SERIAL CODE STATUS + local json=${ARMIS_REPORT_PATH%.json}.json u c d i a v act first=1 mcp_ver + mkdir -p "$(dirname "$json")" 2>/dev/null || return 1 + mcp_ver=${ARMIS_MCP_VERSION:-latest} + { + printf '{\n' + printf ' "endpoint": %s,\n' "$(printf '%s' "$2" | json_str)" + printf ' "serial": %s,\n' "$(printf '%s' "$3" | json_str)" + printf ' "timestamp": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" + printf ' "script_version": "%s",\n' "$SCRIPT_VERSION" + printf ' "cli_version": %s,\n' "$(printf '%s' "$ARMIS_CLI_VERSION" | json_str)" + printf ' "mcp_version": %s,\n' "$(printf '%s' "$mcp_ver" | json_str)" + printf ' "cosign_verified": "%s",\n' "$CLI_COSIGN" + printf ' "mode": "%s",\n' "$([ "$DO_UNINSTALL" -eq 1 ] && echo uninstall || echo install)" + printf ' "exit_code": %s,\n' "$4" + printf ' "status": "%s",\n' "$5" + printf ' "components": [' + while IFS=$'\037' read -r u c d i a v act; do + [ "$first" -eq 1 ] || printf ',' + first=0 + printf '\n {"user": %s, "component": %s, "detected": %s, "installed": %s, "auth": %s, "verified": %s, "action": %s}' \ + "$(printf '%s' "$u" | json_str)" "$(printf '%s' "$c" | json_str)" "$(printf '%s' "${d:-}" | json_str)" \ + "$(printf '%s' "${i:-}" | json_str)" "$(printf '%s' "${a:-}" | json_str)" "$(printf '%s' "${v:-}" | json_str)" \ + "$(printf '%s' "${act:-}" | json_str)" + done < "$1" + printf '\n ]\n}\n' + } > "$json" + chmod 644 "$json" + log "report: $json" +} + +stage_report() { + local code status table endpoint serial n_components n_failing + table="$WORK/table.tsv" + build_table > "$table" + code=$(compute_exit) + case $code in + 0) status=ok ;; + 1) status=partial ;; + *) status=failed ;; + esac + endpoint=$(scutil --get ComputerName 2>/dev/null || hostname) + serial=$(ioreg -rd1 -c IOPlatformExpertDevice 2>/dev/null | awk -F'"' '/IOPlatformSerialNumber/ { print $4 }') + print_matrix "$table" "$endpoint" + n_components=$(awk -F'\037' 'END { print NR }' "$table") + n_failing=$(awk -F'\037' '$4 == "fail" || $4 == "warn" || $5 == "fail" || $5 == "warn" || $6 == "fail" || $6 == "warn" { n++ } END { print n + 0 }' "$table") + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] no report written" + elif [ -n "$ARMIS_REPORT_PATH" ]; then + write_reports "$table" "$endpoint" "$serial" "$code" "$status" || warn "could not write the report to $ARMIS_REPORT_PATH" + fi + printf 'ARMIS_STATUS=%s components=%s failing=%s\n' "$status" "$n_components" "$n_failing" + FINAL_CODE=$code +} + +# shellcheck disable=SC2329 # runs from the EXIT trap +cleanup() { + [ -z "$WORK" ] || rm -rf "$WORK" +} + +finish() { + stage_report + exit "$FINAL_CODE" +} + +FINAL_CODE=0 + +# ---- arguments --------------------------------------------------------------- + +usage() { + awk 'NR > 1 && /^set -u$/ { exit } NR > 1 { sub(/^# ?/, ""); print }' "$0" + echo "" + echo "Configuration (environment variables):" + awk '/^# ---- CONFIG BEGIN/ { on = 1; next } /^# ---- CONFIG END/ { on = 0 } on { print }' "$0" +} + +while [ $# -gt 0 ]; do + case $1 in + -h | --help) usage; exit 0 ;; + --dry-run) DRY_RUN=1 ;; + --uninstall) DO_UNINSTALL=1 ;; + --non-interactive) NONINTERACTIVE=1 ;; + --verbose) VERBOSE=1 ;; + --bundle) WANT_BUNDLE=1 ;; + --only) [ $# -ge 2 ] || die_usage "--only needs a value"; ONLY=$(split_list "$2"); shift ;; + --skip) [ $# -ge 2 ] || die_usage "--skip needs a value"; SKIP=$(split_list "$2"); shift ;; + --report) [ $# -ge 2 ] || die_usage "--report needs a path"; ARMIS_REPORT_PATH=$2; shift ;; + *) die_usage "unknown option: $1" ;; + esac + shift +done + +[ -t 0 ] || NONINTERACTIVE=1 + +[ -z "$ARMIS_TENANT_ID" ] || export ARMIS_TENANT_ID +[ -z "$ARMIS_REGION" ] || export ARMIS_REGION + +for n in $ONLY $SKIP; do + in_list "$n" "$VALID_NAMES" || die_usage "unknown component '$n' (valid: $VALID_NAMES)" +done + +ARMIS_CLIENTS=$(split_list "$ARMIS_CLIENTS") +for n in $ARMIS_CLIENTS; do + in_list "$n" "$ALL_CLIENTS" || die_usage "unknown client '$n' in ARMIS_CLIENTS (valid: $ALL_CLIENTS)" +done + +case $ARMIS_AUTH_MODE in client-credentials | sso) ;; *) die_usage "ARMIS_AUTH_MODE must be client-credentials or sso" ;; esac +case $ARMIS_SSO_LOGIN in auto | now | skip) ;; *) die_usage "ARMIS_SSO_LOGIN must be auto, now or skip" ;; esac +for v in ARMIS_ALLOW_LATEST ARMIS_HOOK_ENABLE ARMIS_HOOK_FAIL_OPEN ARMIS_WITH_KNOWLEDGE ARMIS_SAMPLE_SCAN ARMIS_KEEP_CREDENTIALS ARMIS_REMOVE_CLI; do + case ${!v} in 0 | 1) ;; *) die_usage "$v must be 0 or 1" ;; esac +done +[ -z "$ARMIS_TENANT_ID" ] || require_ident ARMIS_TENANT_ID "$ARMIS_TENANT_ID" +[ -z "$ARMIS_REGION" ] || require_ident ARMIS_REGION "$ARMIS_REGION" +if [ -n "$ARMIS_MCP_VERSION" ]; then + ARMIS_MCP_VERSION=${ARMIS_MCP_VERSION#v} + printf '%s' "$ARMIS_MCP_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$' \ + || die_usage "ARMIS_MCP_VERSION must look like 1.4.2" +fi + +if [ "$DO_UNINSTALL" -eq 0 ]; then + if [ -z "$ARMIS_CLI_VERSION" ]; then + if [ "$NONINTERACTIVE" -eq 1 ] && [ "$ARMIS_ALLOW_LATEST" != 1 ]; then + die_usage "ARMIS_CLI_VERSION is required with --non-interactive (or set ARMIS_ALLOW_LATEST=1)" + fi + ARMIS_CLI_VERSION=latest + fi + if [ "$ARMIS_CLI_VERSION" != latest ]; then + ARMIS_CLI_VERSION=${ARMIS_CLI_VERSION#v} + printf '%s' "$ARMIS_CLI_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?$' \ + || die_usage "ARMIS_CLI_VERSION must look like 1.27.0" + fi + if [ "$ARMIS_AUTH_MODE" = sso ] && [ -z "$ARMIS_TENANT_ID" ]; then + die_usage "ARMIS_TENANT_ID is required with ARMIS_AUTH_MODE=sso" + fi + if [ "$ARMIS_AUTH_MODE" = client-credentials ]; then load_credentials; fi +fi + +# The clients and extras this run touches. +CLIENT_LIST="" +if [ -n "$ONLY" ]; then + for n in $ONLY; do in_list "$n" "$ALL_CLIENTS" && CLIENT_LIST="$CLIENT_LIST $n"; done +else + CLIENT_LIST=$ARMIS_CLIENTS +fi +CLIENT_LIST=$(for n in $CLIENT_LIST; do in_list "$n" "$SKIP" || printf '%s ' "$n"; done) +CLIENT_LIST=${CLIENT_LIST% } + +ENABLED_EXTRAS="" +for n in jetbrains hook; do + in_list "$n" "$SKIP" && continue + if [ -n "$ONLY" ]; then + in_list "$n" "$ONLY" && ENABLED_EXTRAS="$ENABLED_EXTRAS $n" + elif [ "$n" = jetbrains ] && [ -n "$ARMIS_JETBRAINS_PROJECTS" ]; then + ENABLED_EXTRAS="$ENABLED_EXTRAS $n" + elif [ "$n" = hook ] && [ "$ARMIS_HOOK_ENABLE" = 1 ]; then + ENABLED_EXTRAS="$ENABLED_EXTRAS $n" + fi +done +# A bare run (no --only) still reports on JetBrains, as a hint. +if [ -z "$ONLY" ] && ! in_list jetbrains "$SKIP" && ! in_list jetbrains "$ENABLED_EXTRAS"; then + ENABLED_EXTRAS="$ENABLED_EXTRAS jetbrains" +fi +ENABLED_EXTRAS=${ENABLED_EXTRAS# } + +# A full uninstall (nothing selected) removes everything; --only/--skip narrows it. +FULL_UNINSTALL=1 +if [ -n "$ONLY" ] || [ -n "$SKIP" ]; then FULL_UNINSTALL=0; fi + +if [ "$IS_ROOT" -eq 1 ]; then + CLI_DIR=${ARMIS_INSTALL_DIR:-/usr/local/bin} + LOG_DIR=${ARMIS_LOG_DIR:-/Library/Logs/Armis} +else + CLI_DIR=${ARMIS_INSTALL_DIR:-$HOME/.local/bin} + LOG_DIR=${ARMIS_LOG_DIR:-$HOME/Library/Logs/Armis} +fi +CLI_BIN="$CLI_DIR/armis-cli" + +[ -n "${TMPDIR:-}" ] || TMPDIR=/tmp +WORK=$(mktemp -d "${TMPDIR%/}/armis-setup.XXXXXX") || die_usage "cannot create a temporary directory" +chmod 755 "$WORK" +trap cleanup EXIT +RESULTS="$WORK/results.tsv" +: > "$RESULTS" +chmod 600 "$RESULTS" +write_json_tool + +if [ "$DRY_RUN" -eq 0 ]; then + mkdir -p "$LOG_DIR" 2>/dev/null && chmod 755 "$LOG_DIR" 2>/dev/null + if [ -d "$LOG_DIR" ] && [ -w "$LOG_DIR" ]; then + LOG_FILE="$LOG_DIR/enterprise-setup-$RUN_TS.log" + : > "$LOG_FILE" + chmod 644 "$LOG_FILE" + fi + if [ -z "$ARMIS_REPORT_PATH" ] && [ -d "$LOG_DIR" ]; then + ARMIS_REPORT_PATH="$LOG_DIR/enterprise-setup-$RUN_TS" + fi +fi + +log "armis enterprise-setup $SCRIPT_VERSION$([ "$DRY_RUN" -eq 1 ] && echo ' (dry run)')" + +# ---- main ------------------------------------------------------------------- + +stage_preflight + +USERS=$(resolve_users) +if [ -z "$USERS" ]; then + rec "-" users installed warn + rec "-" users action "no user account to configure (nobody logged in?); set ARMIS_TARGET_USERS or re-run when a user is logged in" +fi + +for u in $USERS; do + require_ident user "$u" +done + +if [ "$DO_UNINSTALL" -eq 1 ]; then + for u in $USERS; do + id "$u" > /dev/null 2>&1 || { rec "$u" mcp-server installed fail; rec "$u" mcp-server action "unknown user $u"; continue; } + h=$(user_home "$u") + if [ -z "$h" ] || [ ! -d "$h" ]; then + rec "$u" mcp-server installed fail + rec "$u" mcp-server action "no home directory for $u" + continue + fi + stage_uninstall "$u" "$h" + done + if [ "$ARMIS_REMOVE_CLI" = 1 ] && [ "$IS_ROOT" -eq 1 ] && [ "$FULL_UNINSTALL" -eq 1 ]; then + if [ "$DRY_RUN" -eq 1 ]; then + log "[dry-run] would remove $CLI_BIN" + else + rm -f "$CLI_BIN" && rec "-" armis-cli installed ok && rec "-" armis-cli action "removed $CLI_BIN" + fi + fi + finish +fi + +stage_cli + +FIRST_USER="" +for u in $USERS; do + id "$u" > /dev/null 2>&1 || { rec "$u" mcp-server installed fail; rec "$u" mcp-server action "unknown user $u"; continue; } + h=$(user_home "$u") + if [ -z "$h" ] || [ ! -d "$h" ]; then + rec "$u" mcp-server installed fail + rec "$u" mcp-server action "no home directory for $u" + continue + fi + if [ -z "$FIRST_USER" ]; then + FIRST_USER=$u + network_check "$u" "$h" + fi + stage_auth "$u" "$h" + stage_mcp "$u" "$h" + stage_jetbrains "$u" "$h" + stage_hook "$u" "$h" + stage_verify "$u" "$h" +done + +finish diff --git a/test/scripts/enterprise-setup.bats b/test/scripts/enterprise-setup.bats new file mode 100644 index 0000000..0b41af8 --- /dev/null +++ b/test/scripts/enterprise-setup.bats @@ -0,0 +1,541 @@ +#!/usr/bin/env bats +# Hermetic tests for scripts/enterprise-setup.sh. +# +# Every test runs the script under /bin/bash (3.2 on macOS) with a temporary +# HOME, log directory and install directory, and with fake armis-cli, curl, +# sudo, id and pgrep first on PATH. Nothing touches the real machine. + +REPO_ROOT="$(cd "$BATS_TEST_DIRNAME/../.." && pwd)" +SCRIPT="$REPO_ROOT/scripts/enterprise-setup.sh" +STUBS="$BATS_TEST_DIRNAME/stubs" +PYSTUB="$BATS_TEST_DIRNAME/pystub" +SECRET="SUPERSECRET_abc123" + +setup() { + T="$BATS_TEST_TMPDIR" + export HOME="$T/home" + export TMPDIR="$T/tmp" + export STUB_LOG="$T/stublog" + INSTALL_DIR="$T/bin" + LOG_DIR="$T/logs" + mkdir -p "$HOME" "$TMPDIR" "$STUB_LOG" "$INSTALL_DIR" "$LOG_DIR" + + export PATH="$STUBS:/usr/bin:/bin:/usr/sbin:/sbin" + export ARMIS_SAFE_PATH="/usr/bin:/bin:/usr/sbin:/sbin" + export ARMIS_EXTRA_PATH="$STUBS:$PYSTUB" + export ARMIS_INSTALL_DIR="$INSTALL_DIR" + export ARMIS_LOG_DIR="$LOG_DIR" + export ARMIS_CLI_VERSION="1.2.3" + export ARMIS_SAMPLE_SCAN=0 + export ARMIS_CLIENT_ID="test-id" + export ARMIS_CLIENT_SECRET="$SECRET" + unset ARMIS_TENANT_ID ARMIS_REGION ARMIS_MCP_VERSION ARMIS_CREDENTIALS_FILE ARMIS_API_URL + unset ARMIS_JETBRAINS_PROJECTS ARMIS_HOOK_ENABLE ARMIS_HOOK_REPOS HTTPS_PROXY SSL_CERT_FILE + + install_fake_cli +} + +# The CLI is already installed at the pinned version unless a test removes it. +install_fake_cli() { + cp "$STUBS/armis-cli" "$STUBS/merge.js" "$INSTALL_DIR/" + chmod 755 "$INSTALL_DIR/armis-cli" +} + +make_clients() { + mkdir -p "$HOME/.cursor" "$HOME/.codex" "$HOME/.claude" "$HOME/.copilot" "$HOME/.junie/mcp" \ + "$HOME/.gemini/config" "$HOME/Library/Application Support/Code/User" +} + +setup_run() { + run /bin/bash "$SCRIPT" --non-interactive "$@" +} + +tree_hash() { + (cd "$1" && find . -type f -exec shasum {} + | LC_ALL=C sort | shasum) +} + +backups() { + find "$HOME" -name '*.armis-bak.*' 2>/dev/null | LC_ALL=C sort +} + +@test "unknown flag exits 3" { + run /bin/bash "$SCRIPT" --bogus + [ "$status" -eq 3 ] + [[ "$output" == *"unknown option"* ]] +} + +@test "unknown component in --only exits 3" { + setup_run --only emacs + [ "$status" -eq 3 ] +} + +@test "--non-interactive without a CLI version exits 3" { + unset ARMIS_CLI_VERSION + setup_run + [ "$status" -eq 3 ] + [[ "$output" == *"ARMIS_CLI_VERSION is required"* ]] +} + +@test "ARMIS_ALLOW_LATEST permits an unpinned CLI" { + unset ARMIS_CLI_VERSION + export ARMIS_ALLOW_LATEST=1 + rm -f "$INSTALL_DIR/armis-cli" + make_clients + setup_run --dry-run + [ "$status" -eq 0 ] + [[ "$output" == *"would download"* ]] +} + +@test "--help prints the usage and the config block" { + run /bin/bash "$SCRIPT" --help + [ "$status" -eq 0 ] + [[ "$output" == *"Exit codes:"* ]] + [[ "$output" == *"ARMIS_AUTH_MODE"* ]] + [[ "$output" == *"ARMIS_JETBRAINS_PROJECTS"* ]] +} + +@test "preflight failure (no network) exits 3" { + export STUB_CURL_FAIL=1 + setup_run + [ "$status" -eq 3 ] + [[ "$output" == *"cannot reach"* ]] + [[ "$output" == *"ARMIS_STATUS=failed"* ]] +} + +@test "dry run changes nothing under HOME or the install dir" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + rm -f "$INSTALL_DIR/armis-cli" "$INSTALL_DIR/merge.js" + before_home=$(tree_hash "$HOME") + before_bin=$(tree_hash "$INSTALL_DIR") + setup_run --dry-run --report "$T/dry" + [ "$status" -eq 0 ] + [ "$before_home" = "$(tree_hash "$HOME")" ] + [ "$before_bin" = "$(tree_hash "$INSTALL_DIR")" ] + [ ! -e "$T/dry.json" ] + [ -z "$(ls -A "$LOG_DIR")" ] +} + +@test "installs the CLI from the matching tag when missing" { + rm -f "$INSTALL_DIR/armis-cli" "$INSTALL_DIR/merge.js" + STUB_CLI_VERSION=1.2.3 setup_run --only cursor + [ "$status" -eq 0 ] + [ -x "$INSTALL_DIR/armis-cli" ] + grep -q 'armis-cli/v1.2.3/scripts/install.sh' "$STUB_LOG/curl.urls" +} + +@test "a checksum failure in the installer exits 3" { + rm -f "$INSTALL_DIR/armis-cli" + export STUB_CHECKSUM_FAIL=1 + setup_run + [ "$status" -eq 3 ] + [[ "$output" == *"checksum"* ]] +} + +@test "a signature failure in the installer exits 3" { + rm -f "$INSTALL_DIR/armis-cli" + export STUB_SIGNATURE_FAIL=1 + setup_run + [ "$status" -eq 3 ] + [[ "$output" == *"signature verification failed"* ]] +} + +@test "an installed CLI whose version only contains the pin is reinstalled" { + export ARMIS_CLI_VERSION=1.2.3 STUB_CLI_VERSION=11.2.3 + make_clients + setup_run --only cursor + grep -q 'armis-cli/v1.2.3/scripts/install.sh' "$STUB_LOG/curl.urls" + [ "$status" -eq 2 ] + [[ "$output" == *"does not report version 1.2.3"* ]] +} + +@test "registers every detected client and exits 0" { + make_clients + setup_run --report "$T/rep" + [ "$status" -eq 0 ] + [[ "$output" == *"ARMIS_STATUS=ok"* ]] + grep -q armis-appsec "$HOME/.cursor/mcp.json" + grep -q armis-appsec "$HOME/Library/Application Support/Code/User/mcp.json" + grep -q armis-appsec "$HOME/.copilot/mcp-config.json" + grep -q armis-appsec "$HOME/.gemini/config/mcp_config.json" + grep -q armis-appsec "$HOME/.junie/mcp/mcp.json" + grep -q armis_scanner "$HOME/.codex/config.toml" + grep -q 'armis-appsec@armis-appsec-mcp' "$HOME/.claude/plugins/installed_plugins.json" +} + +@test "clients that are not installed are reported as skipped" { + mkdir -p "$HOME/.cursor" + setup_run + [ "$status" -eq 0 ] + [[ "$output" == *"skip (not installed)"* ]] + ! grep -q 'install .*vscode' "$STUB_LOG/armis-cli.argv" +} + +@test "a second run makes no new backups and does not reinstall the CLI" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + setup_run + [ "$status" -eq 0 ] + first=$(backups) + : > "$STUB_LOG/curl.urls" + sleep 1 + setup_run + [ "$status" -eq 0 ] + [ "$first" = "$(backups)" ] + ! grep -q 'install.sh' "$STUB_LOG/curl.urls" +} + +@test "servers already in a config are kept" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + setup_run + [ "$status" -eq 0 ] + grep -q '"other"' "$HOME/.cursor/mcp.json" + grep -q armis-appsec "$HOME/.cursor/mcp.json" + [ -n "$(backups)" ] +} + +@test "a malformed config is skipped and left untouched" { + make_clients + printf '{broken' > "$HOME/.cursor/mcp.json" + cp "$HOME/.cursor/mcp.json" "$T/original" + setup_run + [ "$status" -eq 1 ] + cmp "$HOME/.cursor/mcp.json" "$T/original" + [[ "$output" == *"is not valid JSON"* ]] + grep -q armis-appsec "$HOME/.copilot/mcp-config.json" +} + +@test "a config with comments and trailing commas is accepted" { + make_clients + printf '// mine\n{"mcpServers": {"other": {"command": "x", },},}\n' > "$HOME/.cursor/mcp.json" + run /bin/bash "$SCRIPT" --non-interactive --only copilot + [ "$status" -eq 0 ] +} + +@test "a client failure with exit 0 (older CLI) is recorded and restored; others unaffected" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + cp "$HOME/.cursor/mcp.json" "$T/original" + export STUB_FAIL_TARGETS="cursor" STUB_FAIL_EXIT=0 + setup_run --only cursor,vscode --report "$T/rep" + [ "$status" -eq 1 ] + cmp "$HOME/.cursor/mcp.json" "$T/original" + grep -q armis-appsec "$HOME/Library/Application Support/Code/User/mcp.json" + grep -q '"user":"-","component":"armis-cli"' <(tr -d ' ' < "$T/rep.json") + grep -q '"component": "cursor", "detected": "yes", "installed": "fail"' "$T/rep.json" + grep -q '"component": "vscode", "detected": "yes", "installed": "ok"' "$T/rep.json" +} + +@test "a failing doctor check exits 2" { + make_clients + cat > "$T/doctor.json" <<'EOF' +{"checks":[{"component":"scanner","editor":"Cursor","name":"Cursor","status":"fail","detail":"server did not start","remediation":"Run: armis-cli mcp doctor --fix"}]} +EOF + export STUB_DOCTOR_JSON="$T/doctor.json" STUB_DOCTOR_EXIT=1 + setup_run --only cursor + [ "$status" -eq 2 ] + [[ "$output" == *"server did not start"* ]] +} + +@test "missing Python is a warning with exit 1 and no registration" { + make_clients + export ARMIS_EXTRA_PATH="$STUBS" + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"Python 3.11+"* ]] + ! grep -q armis-appsec "$HOME/.cursor/mcp.json" 2>/dev/null +} + +@test "missing Python skips mcp doctor, so a failing doctor does not turn it into exit 2" { + make_clients + export ARMIS_EXTRA_PATH="$STUBS" + cat > "$T/doctor.json" <<'EOF' +{"checks":[{"component":"scanner","name":"python venv","status":"fail","detail":"no venv"}]} +EOF + export STUB_DOCTOR_JSON="$T/doctor.json" STUB_DOCTOR_EXIT=1 + setup_run --only cursor + [ "$status" -eq 1 ] + ! grep -q '^mcp doctor -f json' "$STUB_LOG/armis-cli.argv" +} + +@test "the client secret never reaches logs, reports or arguments" { + make_clients + export STUB_ROOT=1 + setup_run --report "$T/rep" + [ "$status" -eq 0 ] + [[ "$output" != *"$SECRET"* ]] + ! grep -rq "$SECRET" "$LOG_DIR" "$T/rep.json" "$STUB_LOG/armis-cli.argv" "$STUB_LOG/sudo.argv" + grep -q 'preserve-env=.*ARMIS_CLIENT_SECRET' "$STUB_LOG/sudo.argv" + grep -q '^secret-in-env: install' "$STUB_LOG/env.flags" +} + +@test "as root, files in the developer's home are written by the developer, not root" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + mkdir -p "$HOME/.armis/plugins/armis-appsec-mcp" + printf 'ARMIS_CLIENT_ID=old-id\nARMIS_CLIENT_SECRET=OLDSECRET\n' > "$HOME/.armis/plugins/armis-appsec-mcp/.env" + export STUB_ROOT=1 ARMIS_TENANT_ID=acme + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q "^-n -H -u $(id -un) .* /bin/sh -c umask 077; cp -p .*/.cursor/mcp.json " "$STUB_LOG/sudo.argv" + # sudo.argv holds one line per argv line; the multi-line scripts end in "exit $rc". + grep -q 'exit $rc sh .*/\.zshenv # >>> armis-cli' "$STUB_LOG/sudo.argv" + grep -q 'exit $rc sh .*/armis-appsec-mcp/\.env write' "$STUB_LOG/sudo.argv" + grep -q '^ARMIS_CLIENT_ID=test-id$' "$HOME/.armis/plugins/armis-appsec-mcp/.env" + grep -q "ARMIS_TENANT_ID='acme'" "$HOME/.zshenv" +} + +@test "as root, ARMIS_API_URL and lowercase proxy variables reach armis-cli" { + make_clients + export STUB_ROOT=1 + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q 'preserve-env=.*ARMIS_API_URL' "$STUB_LOG/sudo.argv" + grep -q 'preserve-env=.*https_proxy' "$STUB_LOG/sudo.argv" + grep -q 'preserve-env=.*no_proxy' "$STUB_LOG/sudo.argv" +} + +@test "credentials are written at 0600 and rotated in every .env without leaving .bak copies" { + make_clients + plugin="$HOME/.armis/plugins/armis-appsec-mcp" + claude="$HOME/.claude/plugins/cache/armis-appsec-mcp/armis-appsec/latest" + mkdir -p "$plugin" "$claude" + for d in "$plugin" "$claude"; do + printf 'ARMIS_CLIENT_ID=old-id\nARMIS_CLIENT_SECRET=OLDSECRET\nHTTPS_PROXY=http://proxy:3128\n' > "$d/.env" + cp "$d/.env" "$d/.env.bak" + chmod 644 "$d/.env" + done + setup_run --only cursor,claude + [ "$status" -eq 0 ] + for d in "$plugin" "$claude"; do + grep -q '^ARMIS_CLIENT_ID=test-id$' "$d/.env" + grep -q "^ARMIS_CLIENT_SECRET=$SECRET\$" "$d/.env" + grep -q '^HTTPS_PROXY=http://proxy:3128$' "$d/.env" + [ "$(stat -f %Lp "$d/.env")" = 600 ] + [ ! -e "$d/.env.bak" ] + done + ! grep -rq OLDSECRET "$HOME" +} + +@test "a dry run leaves .env files and their .bak copies alone" { + make_clients + plugin="$HOME/.armis/plugins/armis-appsec-mcp" + mkdir -p "$plugin" + printf 'ARMIS_CLIENT_ID=old-id\nARMIS_CLIENT_SECRET=OLDSECRET\n' > "$plugin/.env" + cp "$plugin/.env" "$plugin/.env.bak" + chmod 644 "$plugin/.env" + before=$(tree_hash "$HOME") + setup_run --dry-run --only cursor + [ "$status" -eq 0 ] + [ "$before" = "$(tree_hash "$HOME")" ] + [ "$(stat -f %Lp "$plugin/.env")" = 644 ] +} + +@test "credentials from a file need mode 0600" { + unset ARMIS_CLIENT_ID ARMIS_CLIENT_SECRET + printf 'ARMIS_CLIENT_ID=file-id\nARMIS_CLIENT_SECRET=file-secret\n' > "$T/creds" + chmod 644 "$T/creds" + export ARMIS_CREDENTIALS_FILE="$T/creds" + setup_run + [ "$status" -eq 3 ] + [[ "$output" == *"must be 600 or 400"* ]] + chmod 600 "$T/creds" + make_clients + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q '^ARMIS_CLIENT_ID=file-id$' "$HOME/.armis/plugins/armis-appsec-mcp/.env" +} + +@test "rejected credentials mark auth as failed" { + make_clients + export STUB_WHOAMI_FAIL=1 + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"credentials were rejected"* ]] +} + +@test "sso mode without a session reports a pending sign-in" { + make_clients + unset ARMIS_CLIENT_ID ARMIS_CLIENT_SECRET + export ARMIS_AUTH_MODE=sso ARMIS_TENANT_ID=acme ARMIS_SSO_LOGIN=skip + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"armis-cli auth login"* ]] + grep -q "ARMIS_DEFAULT_AUTH_METHOD='SSO'" "$HOME/.zshenv" +} + +@test "--only and --skip choose the clients" { + make_clients + setup_run --only cursor,junie + [ "$status" -eq 0 ] + grep -q 'install cursor junie ' "$STUB_LOG/armis-cli.argv" + : > "$STUB_LOG/armis-cli.argv" + setup_run --skip cursor,codex,claude + [ "$status" -eq 0 ] + line=$(grep '^install .*--non-interactive' "$STUB_LOG/armis-cli.argv" | head -n 1) + [[ "$line" != *cursor* ]] + [[ "$line" == *vscode* ]] +} + +@test "--report writes the JSON report" { + make_clients + setup_run --only cursor --report "$T/out.json" + [ "$status" -eq 0 ] + [ -f "$T/out.json" ] && [ ! -e "$T/out.csv" ] + grep -q '"exit_code": 0' "$T/out.json" + grep -q '"component": "cursor"' "$T/out.json" +} + +@test "the MCP version is passed through when the CLI supports pinning" { + make_clients + export ARMIS_MCP_VERSION=v1.4.2 + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q 'install cursor --non-interactive --plugin-version 1.4.2' "$STUB_LOG/armis-cli.argv" +} + +@test "an older CLI without --plugin-version is flagged instead of silently unpinned" { + make_clients + export ARMIS_MCP_VERSION=1.4.2 STUB_OLD_CLI=1 + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"MCP version not pinned"* ]] + ! grep -q -- '--plugin-version' "$STUB_LOG/armis-cli.argv" +} + +@test "a native hook warning is reported for the client" { + make_clients + export STUB_HOOK_WARN=cursor + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"native hook not installed"* ]] +} + +@test "restart hints appear only for running editors whose config changed" { + make_clients + export STUB_RUNNING="Cursor.app" + setup_run --only cursor,vscode + [ "$status" -eq 0 ] + [[ "$output" == *"restart Cursor"* ]] + [[ "$output" != *"restart VS Code"* ]] +} + +@test "JetBrains projects are registered through install jetbrains --project" { + make_clients + mkdir -p "$HOME/repo" + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/repo/.jb-mcp.json" + export ARMIS_JETBRAINS_PROJECTS="$HOME/repo" + setup_run --only jetbrains + [ "$status" -eq 0 ] + grep -q "install jetbrains --project $HOME/repo" "$STUB_LOG/armis-cli.argv" + grep -q '"other"' "$HOME/repo/.jb-mcp.json" + grep -q armis-appsec "$HOME/repo/.jb-mcp.json" +} + +@test "JetBrains without projects tells the admin what to do" { + make_clients + mkdir -p "$HOME/Library/Application Support/JetBrains/IntelliJIdea2025.1" + setup_run --only jetbrains + [ "$status" -eq 1 ] + [[ "$output" == *"install jetbrains --project"* ]] +} + +@test "the commit gate is installed in the listed repositories" { + make_clients + mkdir -p "$HOME/repo" + git -C "$HOME/repo" init -q + export ARMIS_HOOK_ENABLE=1 ARMIS_HOOK_REPOS="$HOME/repo" + setup_run --only hook + [ "$status" -eq 0 ] + [ -x "$HOME/repo/.git/hooks/pre-commit" ] +} + +@test "the commit gate without repositories warns that it is per repository" { + make_clients + export ARMIS_HOOK_ENABLE=1 + setup_run --only hook + [ "$status" -eq 1 ] + [[ "$output" == *"per repository"* ]] +} + +@test "full uninstall runs armis-cli uninstall --force" { + make_clients + setup_run --uninstall + [ "$status" -eq 0 ] + grep -q '^uninstall --force$' "$STUB_LOG/armis-cli.argv" +} + +@test "targeted uninstall passes only the chosen targets" { + make_clients + setup_run --uninstall --only cursor,vscode + [ "$status" -eq 0 ] + grep -q '^uninstall cursor vscode$' "$STUB_LOG/armis-cli.argv" +} + +@test "uninstall of only the commit gate does not run a bare armis-cli uninstall" { + make_clients + setup_run --uninstall --only hook + [ "$status" -eq 0 ] + ! grep -q '^uninstall' "$STUB_LOG/armis-cli.argv" +} + +@test "a partial uninstall keeps the managed profile block" { + make_clients + export ARMIS_TENANT_ID=acme + setup_run --only cursor,vscode + grep -q 'armis-cli (managed)' "$HOME/.zshenv" + setup_run --uninstall --only cursor + [ "$status" -eq 0 ] + grep -q 'armis-cli (managed)' "$HOME/.zshenv" + setup_run --uninstall --skip hook + [ "$status" -eq 0 ] + ! grep -q 'armis-cli (managed)' "$HOME/.zshenv" +} + +@test "uninstall works without network access" { + make_clients + export STUB_CURL_FAIL=1 + setup_run --uninstall + [ "$status" -eq 0 ] + grep -q '^uninstall --force$' "$STUB_LOG/armis-cli.argv" +} + +@test "uninstall removes the managed profile block and keeps other content" { + make_clients + printf 'export FOO=bar\n' > "$HOME/.zshenv" + export ARMIS_TENANT_ID=acme + setup_run --only cursor + grep -q 'armis-cli (managed)' "$HOME/.zshenv" + setup_run --uninstall + [ "$status" -eq 0 ] + ! grep -q 'armis-cli (managed)' "$HOME/.zshenv" + grep -q 'export FOO=bar' "$HOME/.zshenv" +} + +@test "as root, uninstall removes the .env.bak copies as the developer" { + make_clients + mkdir -p "$HOME/.armis/plugins/armis-appsec-mcp" + : > "$HOME/.armis/plugins/armis-appsec-mcp/.env.bak" + export STUB_ROOT=1 + setup_run --uninstall + [ "$status" -eq 0 ] + [ ! -e "$HOME/.armis/plugins/armis-appsec-mcp/.env.bak" ] + grep -q "^-n -H -u $(id -un) .* /bin/rm -f .*/armis-appsec-mcp/\.env\.bak" "$STUB_LOG/sudo.argv" +} + +@test "uninstall dry run changes nothing" { + make_clients + setup_run --only cursor + before=$(tree_hash "$HOME") + setup_run --uninstall --dry-run + [ "$status" -eq 0 ] + [ "$before" = "$(tree_hash "$HOME")" ] +} + +@test "the script runs under bash 3.2 without bash 4 features" { + [ "$(/bin/bash -c 'echo ${BASH_VERSINFO[0]}')" -le 3 ] || skip "/bin/bash is not 3.x on this machine" + make_clients + setup_run + [ "$status" -eq 0 ] +} From c48fbdfbf01633458bbdcac042af40d597afd33a Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Tue, 17 Nov 2026 09:24:21 +0200 Subject: [PATCH 3/7] Use armis-cli JSON reports in enterprise setup script - Install and uninstall now run with `--format json`. The script reads per-client status, hook warnings and credential rotation results from that report instead of scraping the human-readable output. - Credential rotation uses `armis-cli install --rotate-credentials`. This replaces the script's own .env rewriting code. - Require armis-cli 1.27.0 or later, since earlier releases lack these flags. A lower `ARMIS_CLI_VERSION` now exits with a usage error before anything is downloaded. - Remove the feature detection for `--plugin-version` and `--project`, the VS Code settings check, and the shell JSON writer for the run report. The report is now built through the osascript helper. - Update the CLI stub, bats tests and deployment docs to match. --- docs/ENTERPRISE-DEPLOYMENT.md | 8 +- scripts/enterprise-setup.sh | 425 ++++++++++------------------- test/scripts/enterprise-setup.bats | 46 ++-- test/scripts/stubs/armis-cli | 74 ++--- 4 files changed, 208 insertions(+), 345 deletions(-) diff --git a/docs/ENTERPRISE-DEPLOYMENT.md b/docs/ENTERPRISE-DEPLOYMENT.md index d77535c..9df9f65 100644 --- a/docs/ENTERPRISE-DEPLOYMENT.md +++ b/docs/ENTERPRISE-DEPLOYMENT.md @@ -39,7 +39,7 @@ A client that is not installed is reported as `skip (not installed)` and is not - `moose.armis.com` (`eu.moose.armis.com` for region `eu1`) - `api.github.com`, `github.com` and `raw.githubusercontent.com`. Set `ARMIS_INSTALLER_URL` to an internal mirror of `scripts/install.sh` if you cannot reach `raw.githubusercontent.com`. - A proxy or TLS inspection is supported through `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (upper or lower case) and `SSL_CERT_FILE` (a PEM file with your root CA). The script passes them, and `ARMIS_API_URL` when set, to `curl` and to every armis-cli command. -- To pin the MCP server version (`ARMIS_MCP_VERSION`), armis-cli must be a release that has `install --plugin-version`. To register JetBrains projects it must have `install jetbrains --project`. The script checks both and tells you when a release is too old. +- armis-cli 1.27.0 or later. The script reads the `install --format json` report and uses `--rotate-credentials`, and it exits 3 when `ARMIS_CLI_VERSION` is older. ## Quick start @@ -79,7 +79,7 @@ Every value can come from the environment, so an MDM can set them as script para | Variable | Default | Meaning | |---|---|---| -| `ARMIS_CLI_VERSION` | none | armis-cli release to install, for example `1.27.0`. The installer is fetched from the same tag. | +| `ARMIS_CLI_VERSION` | none | armis-cli release to install, `1.27.0` or later. The installer is fetched from the same tag. | | `ARMIS_ALLOW_LATEST` | `0` | `1` allows an unpinned install with `--non-interactive`. | | `ARMIS_MCP_VERSION` | latest | MCP server release to pin. A pin is saved and kept by `armis-cli mcp update` and `armis-cli mcp doctor --fix`. | | `ARMIS_TENANT_ID` | none | Tenant. Required for `sso`. | @@ -110,7 +110,7 @@ Do not pass credentials as MDM policy parameters, because Jamf and Kandji show p The script never puts credentials in command-line arguments, so they do not appear in `ps`. They reach armis-cli only through the process environment. They are not written to the log or the report; a masking filter also hides the secret value if a command echoes it. -Each editor starts the MCP server without your shell environment, so credentials must also be in the `.env` files that armis-cli writes. armis-cli does not overwrite an existing `.env`. After installing, the script compares every `.env` it knows about (the shared plugin, the Claude Code plugin cache and Knowledge) with the credentials you supplied, rewrites the ones that differ at mode `0600` while keeping other keys such as `HTTPS_PROXY`, and deletes the `.env.bak` copies that hold the old secret. Rotating a credential is therefore a re-run with the new value. +Each editor starts the MCP server without your shell environment, so credentials must also be in the `.env` files that armis-cli writes. armis-cli does not overwrite an existing `.env` on its own, so the script runs `armis-cli install --rotate-credentials`. That rewrites every `.env` armis-cli manages (the shared plugin, the Claude Code plugin cache and Knowledge) at mode `0600`, keeps other keys such as `HTTPS_PROXY`, and deletes the `.env.bak` copies that hold the old secret. Rotating a credential is therefore a re-run with the new value. With `ARMIS_AUTH_MODE=sso`, developers sign in through the identity provider you registered (see [SSO-SETUP.md](SSO-SETUP.md)). Under `--non-interactive` the script does not open a browser unless `ARMIS_SSO_LOGIN=now`. A user who has not signed in is reported as `sign-in pending: run 'armis-cli auth login'`. When run as root, a browser sign-in only works for the user logged in at the console. @@ -204,7 +204,7 @@ The script never restores `*.armis-bak.*` files by itself, because that could un | `sign-in pending` | The user runs `armis-cli auth login`, or you re-run with `ARMIS_SSO_LOGIN=now` while they are logged in. | | `config at ... is not valid JSON` | The file was left untouched. Fix or remove it and re-run. | | The editor does not show the Armis tools | Restart the editor (the matrix says `restart ` when it is running). For VS Code, open "MCP: List Servers". | -| VS Code: `enable Copilot Agent mode and MCP` | A VS Code setting (`chat.agent.enabled`, `chat.mcp.enabled` or `chat.mcp.access`) or a GitHub organization policy turns it off. The script only reports this and never edits settings. | +| VS Code: `chat.mcp.enabled`, `chat.mcp.access` or `chat.agent.enabled` in an `mcp doctor` failure | A VS Code setting or a GitHub organization policy turns MCP or Agent mode off. The script only reports this and never edits settings. | | `mcp doctor` failures | Run `armis-cli mcp doctor` as the user. Use `--bundle` here, or `armis-cli mcp doctor --bundle`, to produce a support bundle. In an editor, call the `debug_config` tool. | | The sample scan fails | Check `armis-cli auth whoami` and the network. Set `ARMIS_SAMPLE_SCAN=0` to skip it. | | `only the checksum was verified` | Install [cosign](https://docs.sigstore.dev/cosign/installation/) to also verify the release signature. This is advice and does not change the exit code. | diff --git a/scripts/enterprise-setup.sh b/scripts/enterprise-setup.sh index a193c25..b7fa9b7 100755 --- a/scripts/enterprise-setup.sh +++ b/scripts/enterprise-setup.sh @@ -43,12 +43,11 @@ fi # Every value can be set from the environment (MDM script parameters or a # wrapper). Values given here are the defaults. -# armis-cli release to install, e.g. 1.27.0. Required with --non-interactive +# armis-cli release to install, 1.27.0 or later. Required with --non-interactive # unless ARMIS_ALLOW_LATEST=1. The installer script is fetched from the same tag. ARMIS_CLI_VERSION="${ARMIS_CLI_VERSION:-}" ARMIS_ALLOW_LATEST="${ARMIS_ALLOW_LATEST:-0}" # MCP server release to pin, e.g. 1.4.2. Empty follows the latest release. -# Needs an armis-cli with `install --plugin-version`. ARMIS_MCP_VERSION="${ARMIS_MCP_VERSION:-}" # Tenant and region. The tenant is required for sso. The region is only needed @@ -105,6 +104,7 @@ ARMIS_REMOVE_CLI="${ARMIS_REMOVE_CLI:-0}" # ---- CONFIG END ------------------------------------------------------------ SCRIPT_VERSION="1.0.0" +MIN_CLI_VERSION="1.27.0" MARK_BEGIN="# >>> armis-cli (managed) >>>" MARK_END="# <<< armis-cli (managed) <<<" REPO="ArmisSecurity/armis-cli" @@ -135,8 +135,6 @@ LOG_FILE="" LOG_DIR="" RUN_TS=$(date +%Y%m%d-%H%M%S) CLI_BIN="" -CLI_HAS_PIN=0 -CLI_HAS_PROJECT=0 CLI_COSIGN="unknown" FORCED_EXIT=0 LAST_OUT="" @@ -388,8 +386,12 @@ function load(p) { return o; } +function line(fields) { + return fields.map(function (x) { return String(x || '').replace(/[\u001f\n\r]+/g, ' '); }).join('\u001f'); +} + function run(argv) { - var cmd = argv[0], o, v; + var cmd = argv[0], o, v, i; if (cmd === 'check') { load(argv[1]); return ''; @@ -400,10 +402,6 @@ function run(argv) { if (v && typeof v === 'object' && !Array.isArray(v)) return Object.keys(v).sort().join('\n'); return ''; } - if (cmd === 'get') { - o = load(argv[1]); - return o.hasOwnProperty(argv[2]) ? JSON.stringify(o[argv[2]]) : ''; - } if (cmd === 'delserver') { o = load(argv[1]); v = o[argv[2]]; @@ -415,10 +413,35 @@ function run(argv) { if (cmd === 'doctor') { o = JSON.parse(readFile(argv[1])); return (o.checks || []).map(function (c) { - return [c.component || '', c.editor || '', c.name || '', c.status || '', c.detail || '', c.remediation || ''] - .map(function (x) { return String(x).replace(/[\u001f\n\r]+/g, ' '); }).join('\u001f'); + return line([c.component, c.editor, c.name, c.status, c.detail, c.remediation]); }).join('\n'); } + // The --format json document of `armis-cli install` or `uninstall`. + if (cmd === 'result') { + o = JSON.parse(readFile(argv[1])); + v = (o.clients || []).map(function (c) { + var h = c.hook || {}; + return line([c.client, c.status, c.detail, h.status, h.detail]); + }); + if (o.credentials) { + v.push(line(['_credentials', o.credentials.status, (o.credentials.files || []) + .filter(function (f) { return f.status === 'failed'; }) + .map(function (f) { return f.path + ': ' + f.detail; }).join('; ')])); + } + if (o.error) v.push(line(['_error', 'fail', o.error])); + return v.join('\n'); + } + // report TABLE OUT KEY VALUE...: the run report, from build_table rows. + if (cmd === 'report') { + o = {}; + for (i = 3; i + 1 < argv.length; i += 2) o[argv[i]] = argv[i] === 'exit_code' ? Number(argv[i + 1]) : argv[i + 1]; + o.components = (readFile(argv[1]) || '').split('\n').filter(Boolean).map(function (r) { + var f = r.split('\u001f'); + return { user: f[0], component: f[1], detected: f[2], installed: f[3], auth: f[4], verified: f[5], action: f[6] }; + }); + writeFile(argv[2], JSON.stringify(o, null, 2) + '\n'); + return ''; + } throw new Error('unknown command ' + cmd); } JSEOF @@ -436,32 +459,23 @@ json_ok() { # ---- per-client definitions ------------------------------------------------- -# client_name CLIENT KIND: KIND is install (label in `armis-cli install` status -# lines), doctor (editor name in `mcp doctor` checks) or display (shown to people). -client_name() { - local install doctor display +# client_label CLIENT: the editor name `mcp doctor` uses. +client_label() { case $1 in - cursor) install="Cursor" doctor="Cursor" display="Cursor" ;; - vscode) install="VS Code" doctor="VS Code" display="VS Code" ;; - copilot) install="Copilot CLI" doctor="Copilot CLI" display="Copilot CLI" ;; - codex) install="Codex CLI (MCP)" doctor="Codex CLI" display="Codex" ;; - claude) install="Claude Code" doctor="Claude Code" display="Claude Code" ;; - antigravity) install="Antigravity" doctor="Antigravity" display="Antigravity" ;; - junie) install="Junie" doctor="Junie" display="Junie" ;; - *) return 1 ;; - esac - case $2 in - install) echo "$install" ;; - doctor) echo "$doctor" ;; - display) echo "$display" ;; + cursor) echo "Cursor" ;; + vscode) echo "VS Code" ;; + copilot) echo "Copilot CLI" ;; + codex) echo "Codex CLI" ;; + claude) echo "Claude Code" ;; + antigravity) echo "Antigravity" ;; + junie) echo "Junie" ;; esac } -# client_from_doctor NAME: the client whose doctor editor name is NAME. -client_from_doctor() { +client_from_doctor() { # client_from_doctor LABEL local c for c in $ALL_CLIENTS; do - if [ "$(client_name "$c" doctor)" = "$1" ]; then echo "$c"; return; fi + if [ "$(client_label "$c")" = "$1" ]; then echo "$c"; return; fi done } @@ -578,67 +592,6 @@ load_credentials() { esac } -# rotate_env FILE MODE AWKPROG, run as the user with the configured credentials -# in ARMIS_CLIENT_ID/ARMIS_CLIENT_SECRET. MODE is check or write. Exits 0 when -# FILE already holds them, 10 when it did not (and, with write, now does), 1 on error. -# shellcheck disable=SC2016 # expanded by the inner shell -ROTATE_SH='f=$1 -[ -f "$f" ] || exit 0 -cur_id=$(sed -n "s/^ARMIS_CLIENT_ID=//p" "$f" | head -n 1) -cur_secret=$(sed -n "s/^ARMIS_CLIENT_SECRET=//p" "$f" | head -n 1) -rc=0 -if [ "$cur_id" != "$ARMIS_CLIENT_ID" ] || [ "$cur_secret" != "$ARMIS_CLIENT_SECRET" ]; then - rc=10 - if [ "$2" = write ]; then - tmp=$(mktemp "$(dirname "$f")/.env.tmp.XXXXXX") || exit 1 - chmod 600 "$tmp" - if ! awk "$3" "$f" > "$tmp" || ! mv -f "$tmp" "$f"; then rm -f "$tmp"; exit 1; fi - fi -fi -if [ "$2" = write ]; then - chmod 600 "$f" || exit 1 - # The installers leave a copy of the old file next to the new one. - rm -f "$f.bak" -fi -exit $rc' - -# Sets the client credentials in a .env, keeping other keys. -# shellcheck disable=SC2016 # awk program -ROTATE_AWK=' - BEGIN { id = ENVIRON["ARMIS_CLIENT_ID"]; sec = ENVIRON["ARMIS_CLIENT_SECRET"] } - /^ARMIS_CLIENT_ID=/ { if (!d1) { print "ARMIS_CLIENT_ID=" id; d1 = 1 } ; next } - /^ARMIS_CLIENT_SECRET=/ { if (!d2) { print "ARMIS_CLIENT_SECRET=" sec; d2 = 1 } ; next } - { print } - END { if (!d1) print "ARMIS_CLIENT_ID=" id; if (!d2) print "ARMIS_CLIENT_SECRET=" sec }' - -# rotate_credentials USER HOME: bring every .env the installers wrote to the -# configured credentials. armis-cli keeps an existing .env as is. -rotate_credentials() { - local user=$1 home=$2 f mode=write rc changed=0 bad=0 - [ -n "$CRED_ID" ] || return 0 - [ "$DRY_RUN" -eq 0 ] || mode=check - for f in \ - "$home/.armis/plugins/armis-appsec-mcp/.env" \ - "$home/.claude/plugins/cache/armis-appsec-mcp/armis-appsec/latest/.env" \ - "$home/.armis/plugins/armis-knowledge-mcp/.env"; do - [ -f "$f" ] || continue - as_user "$user" "$home" 1 0 /bin/sh -c "$ROTATE_SH" sh "$f" "$mode" "$ROTATE_AWK" - rc=$? - case $rc:$mode in - 0:*) ;; - 10:check) log "[dry-run] would update credentials in $f" ;; - 10:write) log "[$user] updated credentials in $f"; changed=1 ;; - *) warn "[$user] could not update credentials in $f"; bad=1 ;; - esac - done - if [ "$bad" -eq 1 ]; then - rec "$user" _user auth fail - rec "$user" mcp-server action "could not rotate credentials; fix permissions on ~/.armis/plugins and re-run" - elif [ "$changed" -eq 1 ]; then - rec "$user" mcp-server action "credentials rotated; restart editors" - fi -} - # ---- preflight -------------------------------------------------------------- fatal() { # fatal CODE MESSAGE @@ -731,16 +684,6 @@ cli_version_ok() { # does the installed binary report exactly the wanted version [ -n "$got" ] && [ "$got" = "$ARMIS_CLI_VERSION" ] } -detect_cli_features() { - local help - CLI_HAS_PIN=0 - CLI_HAS_PROJECT=0 - [ -x "$CLI_BIN" ] || return 0 - help=$("$CLI_BIN" install --help 2>&1 || true) - case $help in *--plugin-version*) CLI_HAS_PIN=1 ;; esac - case $help in *--project*) CLI_HAS_PROJECT=1 ;; esac -} - stage_cli() { local ref installer_url version_arg log "armis-cli" @@ -751,7 +694,6 @@ stage_cli() { rec "-" armis-cli detected yes rec "-" armis-cli installed ok rec "-" armis-cli verified ok - detect_cli_features return 0 fi @@ -812,7 +754,6 @@ stage_cli() { CLI_COSIGN=no rec "-" armis-cli action "only the checksum was verified; install cosign for signature verification" fi - detect_cli_features } # ---- profiles --------------------------------------------------------------- @@ -953,62 +894,36 @@ user_has_python() { # user_has_python USER HOME # ---- mcp -------------------------------------------------------------------- -# out_find SYMBOL LABEL FILE: first status line "SYMBOL LABEL..." in an armis-cli -# transcript, with the symbol and label removed. -out_find() { - awk -v sym="$1" -v label="$2" ' - { sub(/^[ \t]+/, "") } - index($0, sym " " label) == 1 { print substr($0, length(sym " " label) + 1); found = 1; exit } - END { exit found ? 0 : 1 } - ' "$3" -} - -# check_client_state USER HOME CLIENT KEYFILE: did registration leave the -# server in place and the earlier servers intact? -check_client_state() { - local user=$1 home=$2 client=$3 before=$4 kind path top after - local primary_ok=1 +# servers_kept HOME CLIENT DIR: are the client's configs still valid JSON, with +# every server that was registered before install still there? +servers_kept() { + local kind path top lost while IFS='|' read -r kind path top; do - [ -n "$kind" ] || continue - if [ "$kind" = json ]; then - if ! json_ok "$path"; then - CHECK_MSG="$path is not valid JSON after install" - return 1 - fi - if [ -n "$top" ]; then - after=$(jt keys "$path" "$top") - if ! printf '%s\n' "$after" | grep -qx "$SERVER_KEY"; then - CHECK_MSG="$SERVER_KEY is missing from $path" - primary_ok=0 - fi - if [ -f "$before" ]; then - local lost - lost=$(awk 'NR == FNR { a[$0] = 1; next } !($0 in a)' <(printf '%s\n' "$after") "$before" | head -n 1) - if [ -n "$lost" ]; then - CHECK_MSG="existing server '$lost' disappeared from $path" - return 1 - fi - fi - fi + [ "$kind" = json ] || continue + if ! json_ok "$path"; then + CHECK_MSG="$path is not valid JSON after install" + return 1 fi - done <<< "$(client_files "$client" "$home")" - case $client in - claude) - grep -q 'armis-appsec@armis-appsec-mcp' "$home/.claude/plugins/installed_plugins.json" 2>/dev/null \ - || { CHECK_MSG="plugin missing from ~/.claude/plugins/installed_plugins.json"; return 1; } ;; - codex) - grep -q '^\[mcp_servers.armis_scanner\]' "$home/.codex/config.toml" 2>/dev/null \ - || { CHECK_MSG="armis_scanner section missing from ~/.codex/config.toml"; return 1; } ;; - esac - [ "$primary_ok" -eq 1 ] + [ -n "$top" ] && [ -f "$3/$2.before" ] || continue + lost=$(jt keys "$path" "$top" | awk 'NR == FNR { a[$0] = 1; next } !($0 in a)' - "$3/$2.before" | head -n 1) + if [ -n "$lost" ]; then + CHECK_MSG="existing server '$lost' disappeared from $path" + return 1 + fi + done <<< "$(client_files "$2" "$1")" +} + +# result_field FILE CLIENT N: field N of CLIENT's line from `jt result`. +result_field() { + awk -F'\037' -v c="$2" -v n="$3" '$1 == c { print $n; exit }' "$1" } stage_mcp() { # stage_mcp USER HOME - local user=$1 home=$2 client dir targets="" kind path top msg hook_msg list c - local bad_dir="$WORK/mcp.$user" + local user=$1 home=$2 client dir targets="" kind path top list status detail + local mdir="$WORK/mcp.$user" log "[$user] MCP server" - mkdir -p "$bad_dir" - list="$bad_dir/backups" + mkdir -p "$mdir" + list="$mdir/backups" : > "$list" for client in $CLIENT_LIST; do @@ -1021,8 +936,8 @@ stage_mcp() { # stage_mcp USER HOME rec "$user" "$client" installed skip continue fi - # Validate every config we are about to touch. A file that does not - # parse would be replaced by armis-cli, deleting the user's other servers. + # armis-cli replaces a config it cannot parse, which would delete the + # user's other servers, so such a client is skipped. local invalid="" while IFS='|' read -r kind path top; do [ -n "$kind" ] || continue @@ -1033,10 +948,9 @@ stage_mcp() { # stage_mcp USER HOME rec "$user" "$client" action "config at $invalid is not valid JSON; fix or remove it, then re-run" continue fi - # Record the servers already registered, and back the files up. while IFS='|' read -r kind path top; do [ -n "$kind" ] || continue - if [ -n "$top" ] && [ -f "$path" ]; then jt keys "$path" "$top" > "$bad_dir/$client.before" || true; fi + if [ -n "$top" ] && [ -f "$path" ]; then jt keys "$path" "$top" > "$mdir/$client.before" || true; fi backup_file "$user" "$home" "$path" "$list" done <<< "$(client_files "$client" "$home")" targets="$targets $client" @@ -1059,16 +973,12 @@ stage_mcp() { # stage_mcp USER HOME return 0 fi - local flags="--non-interactive" + local flags="--format json" [ "$ARMIS_WITH_KNOWLEDGE" = 1 ] && flags="$flags --with-knowledge" - if [ -n "$ARMIS_MCP_VERSION" ]; then - if [ "$CLI_HAS_PIN" -eq 1 ] || { [ "$DRY_RUN" -eq 1 ] && [ ! -x "$CLI_BIN" ]; }; then - flags="$flags --plugin-version $ARMIS_MCP_VERSION" - else - rec "$user" mcp-server action "MCP version not pinned: this armis-cli has no --plugin-version; use a newer armis-cli" - rec "$user" mcp-server installed warn - fi - fi + [ -z "$ARMIS_MCP_VERSION" ] || flags="$flags --plugin-version $ARMIS_MCP_VERSION" + # armis-cli keeps an existing .env as is; this brings every one it manages + # to the configured credentials. + [ -z "$CRED_ID" ] || flags="$flags --rotate-credentials" if [ "$DRY_RUN" -eq 1 ]; then log "[dry-run] would run: armis-cli install $targets $flags" @@ -1079,69 +989,60 @@ stage_mcp() { # stage_mcp USER HOME return 0 fi + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + vlog "as $user: $CLI_BIN install $targets $flags" # shellcheck disable=SC2086 # targets and flags are word lists - user_cmd "$user" "$home" 1 0 "$CLI_BIN" install $targets $flags + as_user "$user" "$home" 1 0 "$CLI_BIN" install $targets $flags > "$mdir/install.json" 2> "$LAST_OUT" + local install_rc=$? show_out "$LAST_OUT" - local install_rc=$LAST_RC install_out=$LAST_OUT - local tail_msg - tail_msg=$(grep -v '^[[:space:]]*$' "$install_out" | tail -n 1) + jt result "$mdir/install.json" > "$mdir/install.tsv" || : > "$mdir/install.tsv" + local install_err + install_err=$(result_field "$mdir/install.tsv" _error 3) + [ -s "$mdir/install.tsv" ] || install_err=$(grep -v '^[[:space:]]*$' "$LAST_OUT" | tail -n 1) for client in $targets; do - c=$(client_name "$client" install) + status=$(result_field "$mdir/install.tsv" "$client" 2) + detail=$(result_field "$mdir/install.tsv" "$client" 3) CHECK_MSG="" - if msg=$(out_find "✗" "$c" "$install_out"); then + if [ "$status" != ok ]; then rec "$user" "$client" installed fail - rec "$user" "$client" action "${msg#: }" + rec "$user" "$client" action "${detail:-${install_err:-armis-cli install failed}}" restore_files "$user" "$home" "$client" "$list" continue fi - if ! out_find "✓" "$c" "$install_out" >/dev/null && [ "$install_rc" -ne 0 ]; then + if ! servers_kept "$home" "$client" "$mdir"; then rec "$user" "$client" installed fail - rec "$user" "$client" action "${tail_msg:-armis-cli install failed}" - restore_files "$user" "$home" "$client" "$list" - continue - fi - if ! check_client_state "$user" "$home" "$client" "$bad_dir/$client.before"; then - rec "$user" "$client" installed fail - rec "$user" "$client" action "${CHECK_MSG:-registration was not found}; restored the previous config" + rec "$user" "$client" action "$CHECK_MSG; restored the previous config" restore_files "$user" "$home" "$client" "$list" continue fi rec "$user" "$client" installed ok - if hook_msg=$(out_find "⚠" "$(client_hook_label "$client")" "$install_out"); then + if [ "$(result_field "$mdir/install.tsv" "$client" 4)" = warn ]; then rec "$user" "$client" installed warn - rec "$user" "$client" action "native hook not installed${hook_msg}" + rec "$user" "$client" action "native hook not installed: $(result_field "$mdir/install.tsv" "$client" 5)" fi - done - - # Restart hints, only for clients whose config changed. - for client in $targets; do if config_changed "$home" "$client" "$list" && is_running "$client" "$user"; then - rec "$user" "$client" action "restart $(client_name "$client" display)" + rec "$user" "$client" action "restart $(client_label "$client")" fi done - drop_unchanged "$user" "$home" "$list" - stage_mcp_extras "$user" "$home" - rotate_credentials "$user" "$home" + + case $(result_field "$mdir/install.tsv" _credentials 2) in + failed) + rec "$user" _user auth fail + rec "$user" mcp-server action "could not rotate credentials ($(result_field "$mdir/install.tsv" _credentials 3)); fix permissions on ~/.armis/plugins and re-run" ;; + rotated) rec "$user" mcp-server action "credentials rotated; restart editors" ;; + esac if [ "$install_rc" -ne 0 ]; then rec "$user" mcp-server installed warn - rec "$user" mcp-server action "armis-cli install exited $install_rc; failed clients are listed above" + rec "$user" mcp-server action "armis-cli install exited $install_rc${install_err:+: $install_err}" else rec "$user" mcp-server installed ok fi } -client_hook_label() { - case $1 in - cursor) echo "Cursor (hooks)" ;; - copilot) echo "Copilot CLI (hooks)" ;; - codex) echo "Codex CLI (hooks)" ;; - *) echo "-" ;; - esac -} - restore_files() { # restore_files USER HOME CLIENT LIST local kind path top while IFS='|' read -r kind path top; do @@ -1172,31 +1073,10 @@ config_changed() { # config_changed HOME CLIENT LIST return 1 } -# Copilot Agent mode and MCP can be switched off in VS Code settings or by -# organization policy. Only reported, never edited. -stage_mcp_extras() { # stage_mcp_extras USER HOME - local user=$1 home=$2 settings v - settings="$home/Library/Application Support/Code/User/settings.json" - [ -f "$settings" ] || return 0 - if ! in_list vscode "$CLIENT_LIST"; then return 0; fi - for key in chat.agent.enabled chat.mcp.enabled; do - v=$(jt get "$settings" "$key") || continue - if [ "$v" = false ]; then - rec "$user" vscode installed warn - rec "$user" vscode action "enable Copilot Agent mode and MCP ($key is false in VS Code settings, or ask the GitHub org admin about the MCP policy)" - fi - done - v=$(jt get "$settings" chat.mcp.access) || v="" - if [ "$v" = '"none"' ]; then - rec "$user" vscode installed warn - rec "$user" vscode action "chat.mcp.access is none in VS Code settings; set it to all" - fi -} - # ---- jetbrains -------------------------------------------------------------- stage_jetbrains() { # stage_jetbrains USER HOME - local user=$1 home=$2 p owner cfg list found=0 ok=1 shown=0 + local user=$1 home=$2 p owner cfg list found=0 ok=1 in_list jetbrains "$ENABLED_EXTRAS" || return 0 log "[$user] JetBrains" list="$WORK/jb.$user" @@ -1215,11 +1095,6 @@ stage_jetbrains() { # stage_jetbrains USER HOME fi rec "$user" jetbrains detected yes - if [ "$CLI_HAS_PROJECT" -eq 0 ] && [ "$DRY_RUN" -eq 0 ]; then - rec "$user" jetbrains installed fail - rec "$user" jetbrains action "this armis-cli has no 'install jetbrains --project'; use a newer armis-cli" - return 0 - fi while IFS= read -r p; do [ -n "$p" ] || continue owner=$(stat -f %Su "$p" 2>/dev/null || true) @@ -1242,8 +1117,6 @@ stage_jetbrains() { # stage_jetbrains USER HOME restore_one "$user" "$home" "$cfg" "$list" rec "$user" jetbrains action "registration failed for $p" ok=0 - else - shown=$((shown + 1)) fi done <<< "$(lines_of_list "$ARMIS_JETBRAINS_PROJECTS")" drop_unchanged "$user" "$home" "$list" @@ -1429,7 +1302,7 @@ network_check() { # network_check USER HOME # ---- uninstall -------------------------------------------------------------- stage_uninstall() { # stage_uninstall USER HOME - local user=$1 home=$2 client targets="" flags="--force" p repo cfg top + local user=$1 home=$2 client targets="" flags="--force" p repo cfg log "[$user] uninstall" for client in $CLIENT_LIST; do in_list "$client" "$ALL_CLIENTS" || continue @@ -1439,24 +1312,22 @@ stage_uninstall() { # stage_uninstall USER HOME targets=${targets# } [ "$ARMIS_KEEP_CREDENTIALS" = 1 ] && flags="$flags --keep-credentials" + local args=$targets res="$WORK/uninstall.$user" status detail + [ "$FULL_UNINSTALL" -eq 0 ] || args=$flags + : > "$res.tsv" if [ "$FULL_UNINSTALL" -eq 0 ] && [ -z "$targets" ]; then # A bare `armis-cli uninstall` means everything; nothing here was selected. vlog "[$user] no client selected; not running armis-cli uninstall" elif [ "$DRY_RUN" -eq 1 ]; then - if [ "$FULL_UNINSTALL" -eq 1 ]; then - log "[dry-run] would run: armis-cli uninstall $flags" - else - log "[dry-run] would run: armis-cli uninstall $targets" - fi + log "[dry-run] would run: armis-cli uninstall $args" elif [ -x "$CLI_BIN" ]; then - if [ "$FULL_UNINSTALL" -eq 1 ]; then - # shellcheck disable=SC2086 - user_cmd "$user" "$home" 0 0 "$CLI_BIN" uninstall $flags - else - # shellcheck disable=SC2086 - user_cmd "$user" "$home" 0 0 "$CLI_BIN" uninstall $targets - fi + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + # shellcheck disable=SC2086 # args is a word list + as_user "$user" "$home" 0 0 "$CLI_BIN" uninstall $args --format json > "$res.json" 2> "$LAST_OUT" + LAST_RC=$? show_out "$LAST_OUT" + jt result "$res.json" > "$res.tsv" || true if [ "$LAST_RC" -ne 0 ]; then rec "$user" mcp-server installed fail rec "$user" mcp-server action "armis-cli uninstall exited $LAST_RC; see the log" @@ -1475,16 +1346,17 @@ stage_uninstall() { # stage_uninstall USER HOME rec "$user" "$client" installed skip continue fi - cfg=$(client_files "$client" "$home" | head -n 1 | cut -d'|' -f2) - top=$(client_files "$client" "$home" | head -n 1 | cut -d'|' -f3) - if [ -n "$top" ] && [ -f "$cfg" ] && jt keys "$cfg" "$top" | grep -qx "$SERVER_KEY"; then - rec "$user" "$client" installed fail - rec "$user" "$client" action "$SERVER_KEY is still registered in $cfg" - else - rec "$user" "$client" installed ok - rec "$user" "$client" verified ok - rec "$user" "$client" action "removed" - fi + status=$(result_field "$res.tsv" "$client" 2) + detail=$(result_field "$res.tsv" "$client" 3) + case $status in + fail | warn) + rec "$user" "$client" installed "$status" + rec "$user" "$client" action "${detail:-could not be removed}" ;; + *) + rec "$user" "$client" installed ok + rec "$user" "$client" verified ok + rec "$user" "$client" action "removed" ;; + esac done # The profile block serves every client: keep it while any client stays registered. @@ -1581,37 +1453,13 @@ print_matrix() { # print_matrix TABLEFILE ENDPOINT } | column -t -s $'\t' } -json_str() { # JSON-escape stdin lines into one quoted string - awk 'BEGIN { ORS = "" } { gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR > 1) print "\\n"; print }' | { printf '"'; cat; printf '"'; } -} - -write_reports() { # write_reports TABLEFILE ENDPOINT SERIAL CODE STATUS - local json=${ARMIS_REPORT_PATH%.json}.json u c d i a v act first=1 mcp_ver +write_report() { # write_report TABLEFILE ENDPOINT SERIAL CODE STATUS + local json=${ARMIS_REPORT_PATH%.json}.json mkdir -p "$(dirname "$json")" 2>/dev/null || return 1 - mcp_ver=${ARMIS_MCP_VERSION:-latest} - { - printf '{\n' - printf ' "endpoint": %s,\n' "$(printf '%s' "$2" | json_str)" - printf ' "serial": %s,\n' "$(printf '%s' "$3" | json_str)" - printf ' "timestamp": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" - printf ' "script_version": "%s",\n' "$SCRIPT_VERSION" - printf ' "cli_version": %s,\n' "$(printf '%s' "$ARMIS_CLI_VERSION" | json_str)" - printf ' "mcp_version": %s,\n' "$(printf '%s' "$mcp_ver" | json_str)" - printf ' "cosign_verified": "%s",\n' "$CLI_COSIGN" - printf ' "mode": "%s",\n' "$([ "$DO_UNINSTALL" -eq 1 ] && echo uninstall || echo install)" - printf ' "exit_code": %s,\n' "$4" - printf ' "status": "%s",\n' "$5" - printf ' "components": [' - while IFS=$'\037' read -r u c d i a v act; do - [ "$first" -eq 1 ] || printf ',' - first=0 - printf '\n {"user": %s, "component": %s, "detected": %s, "installed": %s, "auth": %s, "verified": %s, "action": %s}' \ - "$(printf '%s' "$u" | json_str)" "$(printf '%s' "$c" | json_str)" "$(printf '%s' "${d:-}" | json_str)" \ - "$(printf '%s' "${i:-}" | json_str)" "$(printf '%s' "${a:-}" | json_str)" "$(printf '%s' "${v:-}" | json_str)" \ - "$(printf '%s' "${act:-}" | json_str)" - done < "$1" - printf '\n ]\n}\n' - } > "$json" + jt report "$1" "$json" endpoint "$2" serial "$3" timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + script_version "$SCRIPT_VERSION" cli_version "$ARMIS_CLI_VERSION" mcp_version "${ARMIS_MCP_VERSION:-latest}" \ + cosign_verified "$CLI_COSIGN" mode "$([ "$DO_UNINSTALL" -eq 1 ] && echo uninstall || echo install)" \ + exit_code "$4" status "$5" || return 1 chmod 644 "$json" log "report: $json" } @@ -1634,7 +1482,7 @@ stage_report() { if [ "$DRY_RUN" -eq 1 ]; then log "[dry-run] no report written" elif [ -n "$ARMIS_REPORT_PATH" ]; then - write_reports "$table" "$endpoint" "$serial" "$code" "$status" || warn "could not write the report to $ARMIS_REPORT_PATH" + write_report "$table" "$endpoint" "$serial" "$code" "$status" || warn "could not write the report to $ARMIS_REPORT_PATH" fi printf 'ARMIS_STATUS=%s components=%s failing=%s\n' "$status" "$n_components" "$n_failing" FINAL_CODE=$code @@ -1715,6 +1563,13 @@ if [ "$DO_UNINSTALL" -eq 0 ]; then ARMIS_CLI_VERSION=${ARMIS_CLI_VERSION#v} printf '%s' "$ARMIS_CLI_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?$' \ || die_usage "ARMIS_CLI_VERSION must look like 1.27.0" + # This script reads `install --format json`, added in this release. + if awk -v a="${ARMIS_CLI_VERSION%%-*}" -v b="$MIN_CLI_VERSION" 'BEGIN { + split(a, x, "."); split(b, y, ".") + for (i = 1; i <= 3; i++) if (x[i] + 0 != y[i] + 0) exit !(x[i] + 0 < y[i] + 0) + exit 1 }'; then + die_usage "ARMIS_CLI_VERSION $ARMIS_CLI_VERSION is too old; this script needs $MIN_CLI_VERSION or later" + fi fi if [ "$ARMIS_AUTH_MODE" = sso ] && [ -z "$ARMIS_TENANT_ID" ]; then die_usage "ARMIS_TENANT_ID is required with ARMIS_AUTH_MODE=sso" diff --git a/test/scripts/enterprise-setup.bats b/test/scripts/enterprise-setup.bats index 0b41af8..04703d4 100644 --- a/test/scripts/enterprise-setup.bats +++ b/test/scripts/enterprise-setup.bats @@ -25,7 +25,7 @@ setup() { export ARMIS_EXTRA_PATH="$STUBS:$PYSTUB" export ARMIS_INSTALL_DIR="$INSTALL_DIR" export ARMIS_LOG_DIR="$LOG_DIR" - export ARMIS_CLI_VERSION="1.2.3" + export ARMIS_CLI_VERSION="1.27.0" export ARMIS_SAMPLE_SCAN=0 export ARMIS_CLIENT_ID="test-id" export ARMIS_CLIENT_SECRET="$SECRET" @@ -118,10 +118,10 @@ backups() { @test "installs the CLI from the matching tag when missing" { rm -f "$INSTALL_DIR/armis-cli" "$INSTALL_DIR/merge.js" - STUB_CLI_VERSION=1.2.3 setup_run --only cursor + setup_run --only cursor [ "$status" -eq 0 ] [ -x "$INSTALL_DIR/armis-cli" ] - grep -q 'armis-cli/v1.2.3/scripts/install.sh' "$STUB_LOG/curl.urls" + grep -q 'armis-cli/v1.27.0/scripts/install.sh' "$STUB_LOG/curl.urls" } @test "a checksum failure in the installer exits 3" { @@ -141,12 +141,12 @@ backups() { } @test "an installed CLI whose version only contains the pin is reinstalled" { - export ARMIS_CLI_VERSION=1.2.3 STUB_CLI_VERSION=11.2.3 + export STUB_CLI_VERSION=11.27.0 make_clients setup_run --only cursor - grep -q 'armis-cli/v1.2.3/scripts/install.sh' "$STUB_LOG/curl.urls" + grep -q 'armis-cli/v1.27.0/scripts/install.sh' "$STUB_LOG/curl.urls" [ "$status" -eq 2 ] - [[ "$output" == *"does not report version 1.2.3"* ]] + [[ "$output" == *"does not report version 1.27.0"* ]] } @test "registers every detected client and exits 0" { @@ -213,7 +213,7 @@ backups() { [ "$status" -eq 0 ] } -@test "a client failure with exit 0 (older CLI) is recorded and restored; others unaffected" { +@test "a client failure in the install report is recorded and restored, even with exit 0" { make_clients echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" cp "$HOME/.cursor/mcp.json" "$T/original" @@ -222,9 +222,10 @@ backups() { [ "$status" -eq 1 ] cmp "$HOME/.cursor/mcp.json" "$T/original" grep -q armis-appsec "$HOME/Library/Application Support/Code/User/mcp.json" - grep -q '"user":"-","component":"armis-cli"' <(tr -d ' ' < "$T/rep.json") - grep -q '"component": "cursor", "detected": "yes", "installed": "fail"' "$T/rep.json" - grep -q '"component": "vscode", "detected": "yes", "installed": "ok"' "$T/rep.json" + rep=$(tr -d ' \n' < "$T/rep.json") + [[ "$rep" == *'"user":"-","component":"armis-cli"'* ]] + [[ "$rep" == *'"component":"cursor","detected":"yes","installed":"fail","auth":"ok","verified":"","action":"boom'* ]] + [[ "$rep" == *'"component":"vscode","detected":"yes","installed":"ok"'* ]] } @test "a failing doctor check exits 2" { @@ -281,7 +282,7 @@ EOF grep -q "^-n -H -u $(id -un) .* /bin/sh -c umask 077; cp -p .*/.cursor/mcp.json " "$STUB_LOG/sudo.argv" # sudo.argv holds one line per argv line; the multi-line scripts end in "exit $rc". grep -q 'exit $rc sh .*/\.zshenv # >>> armis-cli' "$STUB_LOG/sudo.argv" - grep -q 'exit $rc sh .*/armis-appsec-mcp/\.env write' "$STUB_LOG/sudo.argv" + grep -q 'install cursor --format json --rotate-credentials' "$STUB_LOG/sudo.argv" grep -q '^ARMIS_CLIENT_ID=test-id$' "$HOME/.armis/plugins/armis-appsec-mcp/.env" grep -q "ARMIS_TENANT_ID='acme'" "$HOME/.zshenv" } @@ -373,7 +374,7 @@ EOF : > "$STUB_LOG/armis-cli.argv" setup_run --skip cursor,codex,claude [ "$status" -eq 0 ] - line=$(grep '^install .*--non-interactive' "$STUB_LOG/armis-cli.argv" | head -n 1) + line=$(grep '^install .*--format json' "$STUB_LOG/armis-cli.argv" | head -n 1) [[ "$line" != *cursor* ]] [[ "$line" == *vscode* ]] } @@ -392,16 +393,15 @@ EOF export ARMIS_MCP_VERSION=v1.4.2 setup_run --only cursor [ "$status" -eq 0 ] - grep -q 'install cursor --non-interactive --plugin-version 1.4.2' "$STUB_LOG/armis-cli.argv" + grep -q 'install cursor --format json --plugin-version 1.4.2' "$STUB_LOG/armis-cli.argv" } -@test "an older CLI without --plugin-version is flagged instead of silently unpinned" { - make_clients - export ARMIS_MCP_VERSION=1.4.2 STUB_OLD_CLI=1 +@test "a CLI version older than the minimum is rejected before any download" { + export ARMIS_CLI_VERSION=1.26.0 setup_run --only cursor - [ "$status" -eq 1 ] - [[ "$output" == *"MCP version not pinned"* ]] - ! grep -q -- '--plugin-version' "$STUB_LOG/armis-cli.argv" + [ "$status" -eq 3 ] + [[ "$output" == *"needs 1.27.0 or later"* ]] + [ ! -e "$STUB_LOG/curl.urls" ] } @test "a native hook warning is reported for the client" { @@ -409,7 +409,7 @@ EOF export STUB_HOOK_WARN=cursor setup_run --only cursor [ "$status" -eq 1 ] - [[ "$output" == *"native hook not installed"* ]] + [[ "$output" == *"native hook not installed: adapter missing"* ]] } @test "restart hints appear only for running editors whose config changed" { @@ -463,14 +463,14 @@ EOF make_clients setup_run --uninstall [ "$status" -eq 0 ] - grep -q '^uninstall --force$' "$STUB_LOG/armis-cli.argv" + grep -q '^uninstall --force --format json$' "$STUB_LOG/armis-cli.argv" } @test "targeted uninstall passes only the chosen targets" { make_clients setup_run --uninstall --only cursor,vscode [ "$status" -eq 0 ] - grep -q '^uninstall cursor vscode$' "$STUB_LOG/armis-cli.argv" + grep -q '^uninstall cursor vscode --format json$' "$STUB_LOG/armis-cli.argv" } @test "uninstall of only the commit gate does not run a bare armis-cli uninstall" { @@ -498,7 +498,7 @@ EOF export STUB_CURL_FAIL=1 setup_run --uninstall [ "$status" -eq 0 ] - grep -q '^uninstall --force$' "$STUB_LOG/armis-cli.argv" + grep -q '^uninstall --force --format json$' "$STUB_LOG/armis-cli.argv" } @test "uninstall removes the managed profile block and keeps other content" { diff --git a/test/scripts/stubs/armis-cli b/test/scripts/stubs/armis-cli index eec3c1c..0b1c6a6 100755 --- a/test/scripts/stubs/armis-cli +++ b/test/scripts/stubs/armis-cli @@ -5,14 +5,6 @@ LOG="${STUB_LOG:?STUB_LOG is required}" printf '%s\n' "$*" >> "$LOG/armis-cli.argv" [ -z "${ARMIS_CLIENT_SECRET:-}" ] || echo "secret-in-env: $1" >> "$LOG/env.flags" -label() { - case $1 in - cursor) echo "Cursor" ;; vscode) echo "VS Code" ;; copilot) echo "Copilot CLI" ;; - codex) echo "Codex CLI (MCP)" ;; claude) echo "Claude Code" ;; antigravity) echo "Antigravity" ;; - junie) echo "Junie" ;; - esac -} - # target -> "file|topkey" target_cfg() { case $1 in @@ -31,36 +23,47 @@ write_env() { # write_env FILE: like the real CLI, only when absent ( umask 077; printf 'ARMIS_CLIENT_ID=%s\nARMIS_CLIENT_SECRET=%s\n' "$ARMIS_CLIENT_ID" "$ARMIS_CLIENT_SECRET" > "$1" ) } +rotate_env() { # rotate_env FILE: like --rotate-credentials + [ -f "$1" ] || return 0 + awk -v id="$ARMIS_CLIENT_ID" -v sec="$ARMIS_CLIENT_SECRET" ' + /^ARMIS_CLIENT_ID=/ { print "ARMIS_CLIENT_ID=" id; next } + /^ARMIS_CLIENT_SECRET=/ { print "ARMIS_CLIENT_SECRET=" sec; next } + { print }' "$1" > "$1.tmp" && mv "$1.tmp" "$1" && chmod 600 "$1" && rm -f "$1.bak" + creds=rotated +} + +# report CLIENT STATUS [DETAIL] [HOOKSTATUS HOOKDETAIL]: one clients[] entry +report() { + local e="{\"client\":\"$1\",\"status\":\"$2\",\"detail\":\"${3:-}\"" + [ -z "${4:-}" ] || e="$e,\"hook\":{\"status\":\"$4\",\"detail\":\"${5:-}\"}" + clients="${clients:+$clients,}$e}" +} + do_install() { - local t cfg file top - if [ "${1:-}" = "--help" ]; then - echo "Usage: armis-cli install [editor...]" - if [ "${STUB_OLD_CLI:-0}" != 1 ]; then - echo " --plugin-version string Install this MCP server release" - echo " --project string Project directory for the jetbrains target" - fi - return 0 - fi - local targets="" + local t file top targets="" rotate=0 project="" clients="" creds=none failed=0 f while [ $# -gt 0 ]; do case $1 in --project) project=$2; shift ;; - --plugin-version) shift ;; + --plugin-version | --format) shift ;; + --rotate-credentials) rotate=1 ;; --*) ;; *) targets="$targets $1" ;; esac shift done - if [ "${STUB_PYTHON_FAIL:-0}" = 1 ]; then echo "Error: no suitable Python 3.11+ interpreter found" >&2; return 1; fi + if [ "${STUB_PYTHON_FAIL:-0}" = 1 ]; then + echo "Error: no suitable Python 3.11+ interpreter found" >&2 + echo '{"clients":[],"error":"no suitable Python 3.11+ interpreter found"}' + return 1 + fi write_env "$HOME/.armis/plugins/armis-appsec-mcp/.env" - echo "MCP server v1.4.2 downloaded." - local failed=0 + echo "MCP server v1.4.2 downloaded." >&2 for t in $targets; do case " ${STUB_FAIL_TARGETS:-} " in *" $t "*) IFS='|' read -r file top <<< "$(target_cfg "$t")" [ -z "$file" ] || echo "garbage{" > "$file" - echo " ✗ $(label "$t"): boom" + report "$t" fail boom failed=1 continue ;; esac @@ -68,38 +71,43 @@ do_install() { claude) write_env "$HOME/.claude/plugins/cache/armis-appsec-mcp/armis-appsec/latest/.env" mkdir -p "$HOME/.claude/plugins" - printf '{"version":2,"plugins":{"armis-appsec@armis-appsec-mcp":[{"version":"1.4.2"}]}}\n' > "$HOME/.claude/plugins/installed_plugins.json" - echo " ✓ Claude Code v1.4.2" ;; + printf '{"version":2,"plugins":{"armis-appsec@armis-appsec-mcp":[{"version":"1.4.2"}]}}\n' > "$HOME/.claude/plugins/installed_plugins.json" ;; codex) - grep -q armis_scanner "$HOME/.codex/config.toml" 2>/dev/null || printf '[mcp_servers.armis_scanner]\ncommand = "python"\n' >> "$HOME/.codex/config.toml" - echo " ✓ Codex CLI (MCP)" ;; + grep -q armis_scanner "$HOME/.codex/config.toml" 2>/dev/null || printf '[mcp_servers.armis_scanner]\ncommand = "python"\n' >> "$HOME/.codex/config.toml" ;; jetbrains) - osascript -l JavaScript "$DIR/merge.js" "$project/.jb-mcp.json" mcpServers - echo " ✓ JetBrains ($project/.jb-mcp.json)" ;; + osascript -l JavaScript "$DIR/merge.js" "$project/.jb-mcp.json" mcpServers ;; *) IFS='|' read -r file top <<< "$(target_cfg "$t")" mkdir -p "$(dirname "$file")" - osascript -l JavaScript "$DIR/merge.js" "$file" "$top" - echo " ✓ $(label "$t")" - [ "${STUB_HOOK_WARN:-}" != "$t" ] || echo " ⚠ $(label "$t") (hooks): adapter missing" ;; + osascript -l JavaScript "$DIR/merge.js" "$file" "$top" ;; esac + if [ "${STUB_HOOK_WARN:-}" = "$t" ]; then report "$t" ok "" warn "adapter missing"; failed=1; else report "$t" ok; fi done + if [ "$rotate" = 1 ]; then + for f in "$HOME/.armis/plugins/armis-appsec-mcp/.env" "$HOME/.claude/plugins/cache/armis-appsec-mcp/armis-appsec/latest/.env"; do + rotate_env "$f" + done + fi + printf '{"clients":[%s],"credentials":{"status":"%s","files":[]}}\n' "$clients" "$creds" [ "$failed" -eq 0 ] || return "${STUB_FAIL_EXIT:-1}" return 0 } case "${1:-}" in - --version) echo "armis-cli version ${STUB_CLI_VERSION:-1.2.3} (commit: none, built: unknown)" ;; + --version) echo "armis-cli version ${STUB_CLI_VERSION:-1.27.0} (commit: none, built: unknown)" ;; install) shift; do_install "$@"; exit $? ;; uninstall) shift targets="" for a in "$@"; do case $a in --*) ;; *) targets="$targets $a" ;; esac; done [ -n "$targets" ] || targets="cursor vscode copilot antigravity junie" + clients="" for t in $targets; do IFS='|' read -r file top <<< "$(target_cfg "$t")" [ -z "$file" ] || [ ! -f "$file" ] || osascript -l JavaScript "$DIR/merge.js" "$file" "$top" remove + report "$t" ok removed done + printf '{"clients":[%s],"warnings":[]}\n' "$clients" exit 0 ;; auth) if [ "${2:-}" = whoami ]; then [ "${STUB_WHOAMI_FAIL:-0}" != 1 ] || { echo "Error: unauthorized" >&2; exit 1; }; echo "Tenant: acme" >&2; exit 0; fi From 47b2459c454fa9b1b0c079e2ddea75157a05abf2 Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Tue, 17 Nov 2026 09:39:38 +0200 Subject: [PATCH 4/7] Fix enterprise setup rollback, sample scan and hook uninstall order - Record configs that did not exist before install as "orig-" so a failed install deletes its leftover file instead of leaving it behind. - Leave a client unchanged and report failure when its config cannot be backed up, instead of installing without a rollback path. - Run the sample scan once per user through `mcp doctor --deep` rather than a separate scan, and skip it while an SSO sign-in is pending. - Check a stored SSO session with ARMIS_DEFAULT_AUTH_METHOD unset so a broken session fails fast instead of starting a device-flow prompt. - Write the doctor support bundle to a user-writable temp dir, then copy it to the root-owned log dir. - Remove commit-gate hooks before `uninstall --force` deletes the plugin directory they exec, and do so without ARMIS_HOOK_ENABLE. - Force TMPDIR=/tmp when running as root so per-user steps can read WORK under `sudo -E`. - Update the deployment doc and add bats tests and stub support. --- docs/ENTERPRISE-DEPLOYMENT.md | 6 +- scripts/enterprise-setup.sh | 106 ++++++++++++++++++++++------- test/scripts/enterprise-setup.bats | 83 ++++++++++++++++++++++ test/scripts/stubs/armis-cli | 8 ++- 4 files changed, 173 insertions(+), 30 deletions(-) diff --git a/docs/ENTERPRISE-DEPLOYMENT.md b/docs/ENTERPRISE-DEPLOYMENT.md index 9df9f65..5ecaeb6 100644 --- a/docs/ENTERPRISE-DEPLOYMENT.md +++ b/docs/ENTERPRISE-DEPLOYMENT.md @@ -10,7 +10,7 @@ It does these things in order, and each stage checks its own result: 4. **mcp**: registers the MCP server in each detected client. 5. **jetbrains**: JetBrains AI Assistant projects you list. 6. **hook**: the commit gate in repositories you list (off by default). -7. **verify**: `armis-cli mcp doctor --deep` and a sample scan. +7. **verify**: `armis-cli mcp doctor`. With `ARMIS_SAMPLE_SCAN=1` it runs with `--deep`, which scans a sample through the MCP server. Users without Python 3.11+ get a CLI sample scan instead. The scan is skipped while a user's sign-in is pending. 8. **report**: a table on stdout, plus a JSON file. A component that fails does not stop the others. Only a preflight failure or a failed armis-cli install stops the run. @@ -93,7 +93,7 @@ Every value can come from the environment, so an MDM can set them as script para | `ARMIS_HOOK_ENABLE`, `ARMIS_HOOK_REPOS` | `0`, none | Install the commit gate in these repositories (comma-separated). | | `ARMIS_HOOK_FAIL_OPEN` | `0` | `1` makes the gate warn instead of block. | | `ARMIS_WITH_KNOWLEDGE` | `0` | Also install Armis Knowledge. It cannot be pinned. | -| `ARMIS_SAMPLE_SCAN` | `1` | Scan a two-line sample to prove the whole path. This uses tenant scan quota. `0` skips it. | +| `ARMIS_SAMPLE_SCAN` | `1` | Scan a two-line sample once per user to prove the whole path. This uses tenant scan quota. `0` skips it, including `mcp doctor --deep`. | | `ARMIS_TARGET_USERS` | console user | Comma-separated accounts to configure. | | `ARMIS_INSTALL_DIR` | `/usr/local/bin` as root, `~/.local/bin` otherwise | Where armis-cli goes. | | `ARMIS_INSTALLER_URL` | GitHub raw | Internal mirror of `scripts/install.sh`. | @@ -189,7 +189,7 @@ The script runs `armis-cli install jetbrains --project ` for each project - **With `--only` or `--skip`**: runs `armis-cli uninstall `. This removes only those registrations and leaves the shared plugin directory and `.env` in place. When the selection names no client (for example `--only hook`), armis-cli is not called. - The managed profile blocks are removed by a full uninstall, or when the selection covers every client. A partial uninstall keeps them, because the remaining clients need `ARMIS_TENANT_ID`, `ARMIS_REGION` and the sign-in method. - Uninstall skips the network and disk-space checks, so it also works offline. -- Also removed: hooks the script installed in `ARMIS_HOOK_REPOS` (`hook init --remove`) and the `armis-appsec` entry in `.jb-mcp.json` of the listed JetBrains projects. With `ARMIS_REMOVE_CLI=1` as root, `/usr/local/bin/armis-cli` too. +- Also removed: hooks in `ARMIS_HOOK_REPOS` (`hook init --remove`, run before the plugin directory is deleted; `ARMIS_HOOK_ENABLE` is not needed) and the `armis-appsec` entry in `.jb-mcp.json` of the listed JetBrains projects. With `ARMIS_REMOVE_CLI=1` as root, `/usr/local/bin/armis-cli` too. - The result is checked: a client that still has the entry is reported as failed. The script never restores `*.armis-bak.*` files by itself, because that could undo changes the developer made later. To roll a file back by hand, copy the backup over the original, for example `cp -p ~/.cursor/mcp.json.armis-bak.20260101-120000 ~/.cursor/mcp.json`, then restart the editor. diff --git a/scripts/enterprise-setup.sh b/scripts/enterprise-setup.sh index b7fa9b7..153bd63 100755 --- a/scripts/enterprise-setup.sh +++ b/scripts/enterprise-setup.sh @@ -525,9 +525,14 @@ is_running() { # is_running CLIENT USER # as root: the paths are theirs to symlink anywhere. # backup_file USER HOME FILE LISTFILE: copy FILE to FILE.armis-bak. once per -# run and note it in LISTFILE as "origbak". +# run and note it in LISTFILE as "origbak". A FILE that does not exist yet +# is noted as "orig-" so a failed install's leftover can be deleted. backup_file() { local user=$1 home=$2 f=$3 list=$4 bak + if [ ! -e "$f" ] && [ ! -L "$f" ]; then + printf '%s\t-\n' "$f" >> "$list" + return 0 + fi [ -f "$f" ] || return 0 bak="$f.armis-bak.$RUN_TS" if [ ! -e "$bak" ] && [ ! -L "$bak" ]; then @@ -830,9 +835,6 @@ stage_auth() { # stage_auth USER HOME return 0 fi - local authmethod_env="" - if [ "$ARMIS_AUTH_MODE" = sso ]; then authmethod_env=SSO; fi - if [ "$ARMIS_AUTH_MODE" = client-credentials ] && [ -n "$CRED_ID" ]; then user_cmd "$user" "$home" 1 0 "$CLI_BIN" auth whoami show_out "$LAST_OUT" @@ -847,7 +849,10 @@ stage_auth() { # stage_auth USER HOME # sso, or client-credentials with no credentials supplied if session_present "$home"; then - user_cmd "$user" "$home" 0 0 env ARMIS_DEFAULT_AUTH_METHOD="$authmethod_env" "$CLI_BIN" auth whoami + # Unset so a session that doesn't load fails here instead of starting a + # device-flow sign-in that nobody can approve; armis-cli reads the stored + # session either way. + user_cmd "$user" "$home" 0 0 env -u ARMIS_DEFAULT_AUTH_METHOD "$CLI_BIN" auth whoami show_out "$LAST_OUT" if [ "$LAST_RC" -eq 0 ]; then rec "$user" _user auth ok @@ -948,11 +953,17 @@ stage_mcp() { # stage_mcp USER HOME rec "$user" "$client" action "config at $invalid is not valid JSON; fix or remove it, then re-run" continue fi + local nobak="" while IFS='|' read -r kind path top; do [ -n "$kind" ] || continue if [ -n "$top" ] && [ -f "$path" ]; then jt keys "$path" "$top" > "$mdir/$client.before" || true; fi - backup_file "$user" "$home" "$path" "$list" + backup_file "$user" "$home" "$path" "$list" || { nobak=$path; break; } done <<< "$(client_files "$client" "$home")" + if [ -n "$nobak" ]; then + rec "$user" "$client" installed fail + rec "$user" "$client" action "could not back up $nobak; left it unchanged" + continue + fi targets="$targets $client" done targets=${targets# } @@ -1054,7 +1065,11 @@ restore_files() { # restore_files USER HOME CLIENT LIST restore_one() { # restore_one USER HOME FILE LIST local bak bak=$(awk -F'\t' -v o="$3" '$1 == o { b = $2 } END { print b }' "$4") - if [ -n "$bak" ] && [ -f "$bak" ]; then + if [ "$bak" = - ]; then + if [ -f "$3" ] || [ -L "$3" ]; then + as_user "$1" "$2" 0 0 /bin/rm -f "$3" && log "removed $3 (it did not exist before)" + fi + elif [ -n "$bak" ] && [ -f "$bak" ]; then as_user "$1" "$2" 0 0 /bin/cp -p "$bak" "$3" && log "restored $3 from $bak" fi } @@ -1064,7 +1079,7 @@ config_changed() { # config_changed HOME CLIENT LIST while IFS='|' read -r kind path top; do [ -n "$kind" ] || continue bak=$(awk -F'\t' -v o="$path" '$1 == o { b = $2 } END { print b }' "$3") - if [ -z "$bak" ]; then + if [ -z "$bak" ] || [ "$bak" = - ]; then [ -f "$path" ] && return 0 continue fi @@ -1106,7 +1121,11 @@ stage_jetbrains() { # stage_jetbrains USER HOME ok=0 continue fi - backup_file "$user" "$home" "$cfg" "$list" + if ! backup_file "$user" "$home" "$cfg" "$list"; then + rec "$user" jetbrains action "could not back up $cfg; left it unchanged" + ok=0 + continue + fi if [ "$DRY_RUN" -eq 1 ]; then log "[dry-run] would run: armis-cli install jetbrains --project $p" continue @@ -1162,7 +1181,11 @@ stage_hook() { # stage_hook USER HOME hooks=$(tail -n 1 "$LAST_OUT") case $hooks in /*) ;; *) hooks="$repo/$hooks" ;; esac hook="$hooks/pre-commit" - backup_file "$user" "$home" "$hook" "$list" + if ! backup_file "$user" "$home" "$hook" "$list"; then + rec "$user" hook action "could not back up $hook; left it unchanged" + ok=0 + continue + fi if [ "$DRY_RUN" -eq 1 ]; then log "[dry-run] would run: armis-cli hook init $flags in $repo" continue @@ -1192,25 +1215,49 @@ stage_hook() { # stage_hook USER HOME # ---- verify ----------------------------------------------------------------- stage_verify() { # stage_verify USER HOME - local user=$1 home=$2 bundle="" report comp editor name status detail fix client c + local user=$1 home=$2 bundle="" bdir="" deep="" report comp editor name status detail fix client c log "[$user] verify" if [ "$DRY_RUN" -eq 1 ]; then return 0; fi + + local scan=0 + if [ "$ARMIS_SAMPLE_SCAN" = 1 ]; then + if sign_in_pending "$user"; then + rec "$user" sample-scan detected yes + rec "$user" sample-scan verified skip + rec "$user" sample-scan action "skipped until $user signs in" + else + scan=1 + fi + fi + if in_list "$user" "$NO_PYTHON_USERS"; then log "[$user] MCP server not installed (no Python 3.11+); skipping mcp doctor" - if [ "$ARMIS_SAMPLE_SCAN" = 1 ]; then sample_scan "$user" "$home"; fi + if [ "$scan" -eq 1 ]; then sample_scan "$user" "$home"; fi return 0 fi + # --deep is the sample scan, through the MCP server. + [ "$scan" -eq 0 ] || deep="--deep" if [ "$WANT_BUNDLE" -eq 1 ]; then - bundle="--bundle-path $LOG_DIR/doctor-$user-$RUN_TS.zip" + # doctor runs as the user, who can't write to a root-owned LOG_DIR. + bdir=$(mktemp -d "$WORK/bundle.XXXXXX") + [ "$IS_ROOT" -eq 0 ] || chown "$user" "$bdir" + bundle="--bundle-path $bdir/doctor-$user-$RUN_TS.zip" fi report="$WORK/doctor.$user.json" SEQ=$((SEQ + 1)) LAST_OUT="$WORK/out.$SEQ" - # shellcheck disable=SC2086 # bundle is two words on purpose - with_timeout 300 as_user "$user" "$home" 1 0 "$CLI_BIN" mcp doctor -f json --deep $bundle > "$report" 2> "$LAST_OUT" + # shellcheck disable=SC2086 # deep and bundle are word lists + with_timeout 300 as_user "$user" "$home" 1 0 "$CLI_BIN" mcp doctor -f json $deep $bundle > "$report" 2> "$LAST_OUT" LAST_RC=$? show_out "$LAST_OUT" + if [ -n "$bdir" ]; then + if [ -f "$bdir/doctor-$user-$RUN_TS.zip" ] && cp "$bdir/doctor-$user-$RUN_TS.zip" "$LOG_DIR/"; then + log "[$user] support bundle: $LOG_DIR/doctor-$user-$RUN_TS.zip" + else + rec "$user" mcp-server action "no support bundle was written; run 'armis-cli mcp doctor --bundle' as $user" + fi + fi if ! jt doctor "$report" > "$WORK/doctor.$user.tsv" 2>/dev/null; then rec "$user" mcp-server verified fail @@ -1241,8 +1288,10 @@ stage_verify() { # stage_verify USER HOME if ! awk -F'\t' -v u="$user" '$1 == u && $2 == "mcp-server" && $3 == "verified" { f = 1 } END { exit f ? 0 : 1 }' "$RESULTS"; then rec "$user" mcp-server verified ok fi +} - if [ "$ARMIS_SAMPLE_SCAN" = 1 ]; then sample_scan "$user" "$home"; fi +sign_in_pending() { # sign_in_pending USER + awk -F'\t' -v u="$1" '$1 == u && $2 == "_user" && $3 == "auth" { a = $4 } END { exit a == "warn" ? 0 : 1 }' "$RESULTS" } # doctor_action NAME DETAIL REMEDIATION: one-line action text, capped in length. @@ -1312,6 +1361,17 @@ stage_uninstall() { # stage_uninstall USER HOME targets=${targets# } [ "$ARMIS_KEEP_CREDENTIALS" = 1 ] && flags="$flags --keep-credentials" + # Before `uninstall --force`, which deletes the plugin directory these hooks exec. + if in_list hook "$ENABLED_EXTRAS" && [ -x "$CLI_BIN" ] && [ "$DRY_RUN" -eq 0 ]; then + while IFS= read -r repo; do + [ -n "$repo" ] || continue + [ "$(stat -f %Su "$repo" 2>/dev/null)" = "$user" ] || continue + # shellcheck disable=SC2016 + user_cmd "$user" "$home" 0 0 /bin/sh -c 'cd "$1" && shift && exec "$@"' sh "$repo" "$CLI_BIN" hook init --remove + show_out "$LAST_OUT" + done <<< "$(lines_of_list "$ARMIS_HOOK_REPOS")" + fi + local args=$targets res="$WORK/uninstall.$user" status detail [ "$FULL_UNINSTALL" -eq 0 ] || args=$flags : > "$res.tsv" @@ -1364,15 +1424,6 @@ stage_uninstall() { # stage_uninstall USER HOME for client in $ALL_CLIENTS; do in_list "$client" "$targets" || keep_profile=1; done if [ "$FULL_UNINSTALL" -eq 1 ] || [ "$keep_profile" -eq 0 ]; then remove_profiles "$user" "$home"; fi - if in_list hook "$ENABLED_EXTRAS" && [ -x "$CLI_BIN" ] && [ "$DRY_RUN" -eq 0 ]; then - while IFS= read -r repo; do - [ -n "$repo" ] || continue - [ "$(stat -f %Su "$repo" 2>/dev/null)" = "$user" ] || continue - # shellcheck disable=SC2016 - user_cmd "$user" "$home" 0 0 /bin/sh -c 'cd "$1" && shift && exec "$@"' sh "$repo" "$CLI_BIN" hook init --remove - show_out "$LAST_OUT" - done <<< "$(lines_of_list "$ARMIS_HOOK_REPOS")" - fi if in_list jetbrains "$ENABLED_EXTRAS" && [ "$DRY_RUN" -eq 0 ]; then while IFS= read -r p; do [ -n "$p" ] || continue @@ -1594,7 +1645,7 @@ for n in jetbrains hook; do in_list "$n" "$ONLY" && ENABLED_EXTRAS="$ENABLED_EXTRAS $n" elif [ "$n" = jetbrains ] && [ -n "$ARMIS_JETBRAINS_PROJECTS" ]; then ENABLED_EXTRAS="$ENABLED_EXTRAS $n" - elif [ "$n" = hook ] && [ "$ARMIS_HOOK_ENABLE" = 1 ]; then + elif [ "$n" = hook ] && { [ "$ARMIS_HOOK_ENABLE" = 1 ] || { [ "$DO_UNINSTALL" -eq 1 ] && [ -n "$ARMIS_HOOK_REPOS" ]; }; }; then ENABLED_EXTRAS="$ENABLED_EXTRAS $n" fi done @@ -1618,6 +1669,9 @@ fi CLI_BIN="$CLI_DIR/armis-cli" [ -n "${TMPDIR:-}" ] || TMPDIR=/tmp +# Steps run as other users read WORK; under `sudo -E` TMPDIR is the admin's +# private 0700 directory. +[ "$IS_ROOT" -eq 0 ] || TMPDIR=/tmp WORK=$(mktemp -d "${TMPDIR%/}/armis-setup.XXXXXX") || die_usage "cannot create a temporary directory" chmod 755 "$WORK" trap cleanup EXIT diff --git a/test/scripts/enterprise-setup.bats b/test/scripts/enterprise-setup.bats index 04703d4..2991980 100644 --- a/test/scripts/enterprise-setup.bats +++ b/test/scripts/enterprise-setup.bats @@ -228,6 +228,26 @@ backups() { [[ "$rep" == *'"component":"vscode","detected":"yes","installed":"ok"'* ]] } +@test "a config the failed install created is removed" { + make_clients + export STUB_FAIL_TARGETS="cursor" STUB_FAIL_EXIT=0 + setup_run --only cursor + [ "$status" -eq 1 ] + [ ! -e "$HOME/.cursor/mcp.json" ] +} + +@test "a client whose config cannot be backed up is left unchanged" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + chmod 555 "$HOME/.cursor" + setup_run --only cursor,vscode + chmod 755 "$HOME/.cursor" + [ "$status" -eq 1 ] + [[ "$output" == *"could not back up"* ]] + ! grep -q '^install .*cursor' "$STUB_LOG/armis-cli.argv" + grep -q '^install vscode ' "$STUB_LOG/armis-cli.argv" +} + @test "a failing doctor check exits 2" { make_clients cat > "$T/doctor.json" <<'EOF' @@ -366,6 +386,52 @@ EOF grep -q "ARMIS_DEFAULT_AUTH_METHOD='SSO'" "$HOME/.zshenv" } +@test "sso mode with a pending sign-in skips the sample scan and exits 1" { + make_clients + unset ARMIS_CLIENT_ID ARMIS_CLIENT_SECRET + export ARMIS_AUTH_MODE=sso ARMIS_TENANT_ID=acme ARMIS_SSO_LOGIN=skip ARMIS_SAMPLE_SCAN=1 + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"skipped until"* ]] + ! grep -q -- '--deep' "$STUB_LOG/armis-cli.argv" + ! grep -q '^scan repo' "$STUB_LOG/armis-cli.argv" +} + +@test "a stored session is checked without the SSO auto sign-in" { + make_clients + unset ARMIS_CLIENT_ID ARMIS_CLIENT_SECRET + export ARMIS_AUTH_MODE=sso ARMIS_TENANT_ID=acme ARMIS_SSO_LOGIN=skip ARMIS_DEFAULT_AUTH_METHOD=SSO + mkdir -p "$HOME/.armis" + echo '{"refresh_token":"x"}' > "$HOME/.armis/.sessions" + setup_run --only cursor + [ "$status" -eq 0 ] + ! grep -q '^whoami ARMIS_DEFAULT_AUTH_METHOD=' "$STUB_LOG/env.probe" +} + +@test "ARMIS_SAMPLE_SCAN=1 scans once, through mcp doctor --deep" { + make_clients + export ARMIS_SAMPLE_SCAN=1 + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q '^mcp doctor -f json --deep' "$STUB_LOG/armis-cli.argv" + ! grep -q '^scan repo' "$STUB_LOG/armis-cli.argv" +} + +@test "ARMIS_SAMPLE_SCAN=0 also leaves out mcp doctor --deep" { + make_clients + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q '^mcp doctor -f json' "$STUB_LOG/armis-cli.argv" + ! grep -q -- '--deep' "$STUB_LOG/armis-cli.argv" +} + +@test "--bundle copies the support bundle next to the log" { + make_clients + setup_run --only cursor --bundle + [ "$status" -eq 0 ] + ls "$LOG_DIR"/doctor-*.zip +} + @test "--only and --skip choose the clients" { make_clients setup_run --only cursor,junie @@ -466,6 +532,23 @@ EOF grep -q '^uninstall --force --format json$' "$STUB_LOG/armis-cli.argv" } +@test "full uninstall removes the commit gate first, without ARMIS_HOOK_ENABLE" { + make_clients + mkdir -p "$HOME/repo" + git -C "$HOME/repo" init -q + export ARMIS_HOOK_ENABLE=1 ARMIS_HOOK_REPOS="$HOME/repo" + setup_run --only hook + [ -x "$HOME/repo/.git/hooks/pre-commit" ] + unset ARMIS_HOOK_ENABLE + : > "$STUB_LOG/armis-cli.argv" + setup_run --uninstall + [ "$status" -eq 0 ] + [ ! -e "$HOME/repo/.git/hooks/pre-commit" ] + first=$(grep -n '^hook init --remove' "$STUB_LOG/armis-cli.argv" | cut -d: -f1) + later=$(grep -n '^uninstall --force' "$STUB_LOG/armis-cli.argv" | cut -d: -f1) + [ "$first" -lt "$later" ] +} + @test "targeted uninstall passes only the chosen targets" { make_clients setup_run --uninstall --only cursor,vscode diff --git a/test/scripts/stubs/armis-cli b/test/scripts/stubs/armis-cli index 0b1c6a6..03f0ea1 100755 --- a/test/scripts/stubs/armis-cli +++ b/test/scripts/stubs/armis-cli @@ -4,6 +4,8 @@ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" LOG="${STUB_LOG:?STUB_LOG is required}" printf '%s\n' "$*" >> "$LOG/armis-cli.argv" [ -z "${ARMIS_CLIENT_SECRET:-}" ] || echo "secret-in-env: $1" >> "$LOG/env.flags" +touch "$LOG/env.probe" +[ -z "${ARMIS_DEFAULT_AUTH_METHOD:-}" ] || echo "${2:-$1} ARMIS_DEFAULT_AUTH_METHOD=$ARMIS_DEFAULT_AUTH_METHOD" >> "$LOG/env.probe" # target -> "file|topkey" target_cfg() { @@ -117,6 +119,8 @@ case "${1:-}" in [ "${STUB_NETWORK_FAIL:-0}" != 1 ] || { echo "TLS handshake failed" >&2; exit 1; } exit 0 fi + prev="" + for a in "$@"; do [ "$prev" != --bundle-path ] || echo zip > "$a"; prev=$a; done if [ -n "${STUB_DOCTOR_JSON:-}" ]; then cat "$STUB_DOCTOR_JSON"; else echo '{"checks":[{"component":"scanner","name":"python venv","status":"ok","detail":"ok"}]}' fi @@ -125,7 +129,9 @@ case "${1:-}" in [ "${STUB_SCAN_FAIL:-0}" != 1 ] || { echo "scan failed" >&2; exit 1; } echo '{"findings":[]}'; exit 0 ;; hook) - if [ "${2:-}" = init ]; then + if [ "${2:-}" = init ] && [ "${3:-}" = --remove ]; then + rm -f .git/hooks/pre-commit + elif [ "${2:-}" = init ]; then mkdir -p .git/hooks && printf '#!/bin/sh\nexit 0\n' > .git/hooks/pre-commit && chmod 755 .git/hooks/pre-commit fi exit 0 ;; From 1c13fb53c03918fa42ff3ee1600cc0f378e0d3f0 Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Tue, 17 Nov 2026 10:15:19 +0200 Subject: [PATCH 5/7] Harden enterprise setup uninstall and credential handling - Drop ARMIS_CLIENT_ID/SECRET from the environment in sso mode and during uninstall so they cannot override the SSO session or leak through sudo --preserve-env. Keep masking the dropped secret in logs. - Treat an ARMIS_CLIENTS subset as a partial uninstall instead of running `armis-cli uninstall --force`. - Verify uninstall results: fail clients with no report entry or whose JSON config still has the armis-appsec entry, and report JetBrains config edit failures instead of claiming removal. - Skip mcp doctor for users where no client was configured. - Fix servers_kept so an empty post-install config reports every previous server as lost. - Extend the armis-cli stub and bats tests to cover these cases. --- docs/ENTERPRISE-DEPLOYMENT.md | 8 +-- scripts/enterprise-setup.sh | 89 +++++++++++++++++++++++++----- test/scripts/enterprise-setup.bats | 77 ++++++++++++++++++++++++++ test/scripts/stubs/armis-cli | 13 ++++- 4 files changed, 165 insertions(+), 22 deletions(-) diff --git a/docs/ENTERPRISE-DEPLOYMENT.md b/docs/ENTERPRISE-DEPLOYMENT.md index 5ecaeb6..7ae06b0 100644 --- a/docs/ENTERPRISE-DEPLOYMENT.md +++ b/docs/ENTERPRISE-DEPLOYMENT.md @@ -112,7 +112,7 @@ The script never puts credentials in command-line arguments, so they do not appe Each editor starts the MCP server without your shell environment, so credentials must also be in the `.env` files that armis-cli writes. armis-cli does not overwrite an existing `.env` on its own, so the script runs `armis-cli install --rotate-credentials`. That rewrites every `.env` armis-cli manages (the shared plugin, the Claude Code plugin cache and Knowledge) at mode `0600`, keeps other keys such as `HTTPS_PROXY`, and deletes the `.env.bak` copies that hold the old secret. Rotating a credential is therefore a re-run with the new value. -With `ARMIS_AUTH_MODE=sso`, developers sign in through the identity provider you registered (see [SSO-SETUP.md](SSO-SETUP.md)). Under `--non-interactive` the script does not open a browser unless `ARMIS_SSO_LOGIN=now`. A user who has not signed in is reported as `sign-in pending: run 'armis-cli auth login'`. When run as root, a browser sign-in only works for the user logged in at the console. +With `ARMIS_AUTH_MODE=sso`, developers sign in through the identity provider you registered (see [SSO-SETUP.md](SSO-SETUP.md)). Under `--non-interactive` the script does not open a browser unless `ARMIS_SSO_LOGIN=now`. A user who has not signed in is reported as `sign-in pending: run 'armis-cli auth login'`. When run as root, a browser sign-in only works for the user logged in at the console. In `sso` mode and during `--uninstall`, `ARMIS_CLIENT_ID` and `ARMIS_CLIENT_SECRET` in the environment are removed before any armis-cli command runs, so they cannot take precedence over the SSO session. ## What changes on disk @@ -185,12 +185,12 @@ The script runs `armis-cli install jetbrains --project ` for each project ./scripts/enterprise-setup.sh --uninstall --non-interactive ``` -- **Without `--only` or `--skip`**: runs `armis-cli uninstall --force`, which removes the MCP server from every client and deletes the plugin directory and its `.env`. Add `ARMIS_KEEP_CREDENTIALS=1` to keep credentials. -- **With `--only` or `--skip`**: runs `armis-cli uninstall `. This removes only those registrations and leaves the shared plugin directory and `.env` in place. When the selection names no client (for example `--only hook`), armis-cli is not called. +- **Without `--only`, `--skip` or an `ARMIS_CLIENTS` subset**: runs `armis-cli uninstall --force`, which removes the MCP server from every client and deletes the plugin directory and its `.env`. Add `ARMIS_KEEP_CREDENTIALS=1` to keep credentials. +- **With `--only`, `--skip`, or `ARMIS_CLIENTS` naming fewer than all clients**: runs `armis-cli uninstall `. This removes only those registrations and leaves the shared plugin directory and `.env` in place. When the selection names no client (for example `--only hook`), armis-cli is not called. - The managed profile blocks are removed by a full uninstall, or when the selection covers every client. A partial uninstall keeps them, because the remaining clients need `ARMIS_TENANT_ID`, `ARMIS_REGION` and the sign-in method. - Uninstall skips the network and disk-space checks, so it also works offline. - Also removed: hooks in `ARMIS_HOOK_REPOS` (`hook init --remove`, run before the plugin directory is deleted; `ARMIS_HOOK_ENABLE` is not needed) and the `armis-appsec` entry in `.jb-mcp.json` of the listed JetBrains projects. With `ARMIS_REMOVE_CLI=1` as root, `/usr/local/bin/armis-cli` too. -- The result is checked: a client that still has the entry is reported as failed. +- The result is checked: a client that armis-cli reports as failed, that is missing from its report, or whose JSON config still has the `armis-appsec` entry is reported as failed. The script never restores `*.armis-bak.*` files by itself, because that could undo changes the developer made later. To roll a file back by hand, copy the backup over the original, for example `cp -p ~/.cursor/mcp.json.armis-bak.20260101-120000 ~/.cursor/mcp.json`, then restart the editor. diff --git a/scripts/enterprise-setup.sh b/scripts/enterprise-setup.sh index 153bd63..6bb4a4d 100755 --- a/scripts/enterprise-setup.sh +++ b/scripts/enterprise-setup.sh @@ -129,6 +129,8 @@ IS_ROOT=0 CRED_ID="" CRED_SECRET="" +# Masked in every log line, even when the run does not use client credentials. +REDACT_SECRET="" WORK="" RESULTS="" LOG_FILE="" @@ -142,6 +144,8 @@ LAST_RC=0 SEQ=0 USERS="" NO_PYTHON_USERS="" +# Users for whom `armis-cli install` did not run, so there is nothing for mcp doctor to check. +NO_MCP_USERS="" # ---- logging and results --------------------------------------------------- @@ -150,8 +154,8 @@ redact() { -e 's/(ARMIS_CLIENT_SECRET[[:space:]]*[=:][[:space:]]*)[^[:space:]]+/\1***/g' \ -e 's/([Bb]earer[[:space:]]+)[A-Za-z0-9._~+\/=-]+/\1***/g' \ -e 's/("?client_secret"?[[:space:]]*[=:][[:space:]]*"?)[^[:space:]",}]+/\1***/g' | - if [ "${#CRED_SECRET}" -ge 8 ]; then - CS="$CRED_SECRET" awk '{ + if [ "${#REDACT_SECRET}" -ge 8 ]; then + CS="$REDACT_SECRET" awk '{ s = ENVIRON["CS"] while ((i = index($0, s)) > 0) $0 = substr($0, 1, i - 1) "***" substr($0, i + length(s)) print @@ -595,6 +599,16 @@ load_credentials() { case "$CRED_ID$CRED_SECRET" in *$'\n'* | *$'\r'*) die_usage "client credentials must not contain newlines" ;; esac + REDACT_SECRET=$CRED_SECRET +} + +# drop_ambient_credentials: for runs that must not authenticate with client +# credentials (sso, uninstall). JWT credentials in the environment would win over +# SSO in every armis-cli child and would reach them through sudo --preserve-env. +drop_ambient_credentials() { + # shellcheck disable=SC2031 + REDACT_SECRET="${ARMIS_CLIENT_SECRET:-}" + unset ARMIS_CLIENT_ID ARMIS_CLIENT_SECRET } # ---- preflight -------------------------------------------------------------- @@ -910,7 +924,9 @@ servers_kept() { return 1 fi [ -n "$top" ] && [ -f "$3/$2.before" ] || continue - lost=$(jt keys "$path" "$top" | awk 'NR == FNR { a[$0] = 1; next } !($0 in a)' - "$3/$2.before" | head -n 1) + jt keys "$path" "$top" > "$3/$2.after" || : > "$3/$2.after" + # FILENAME, not NR == FNR: an empty "after" must still report every key as lost. + lost=$(awk 'FILENAME == ARGV[1] { a[$0] = 1; next } $0 != "" && !($0 in a)' "$3/$2.after" "$3/$2.before" | head -n 1) if [ -n "$lost" ]; then CHECK_MSG="existing server '$lost' disappeared from $path" return 1 @@ -970,11 +986,13 @@ stage_mcp() { # stage_mcp USER HOME if [ -z "$targets" ]; then log "[$user] no clients to configure" + NO_MCP_USERS="$NO_MCP_USERS $user" return 0 fi if ! user_has_python "$user" "$home"; then NO_PYTHON_USERS="$NO_PYTHON_USERS $user" + NO_MCP_USERS="$NO_MCP_USERS $user" rec "$user" mcp-server installed warn rec "$user" mcp-server action "install Python 3.11+ (brew install python@3.12, or the python.org installer), then re-run" for client in $targets; do @@ -1230,8 +1248,12 @@ stage_verify() { # stage_verify USER HOME fi fi - if in_list "$user" "$NO_PYTHON_USERS"; then - log "[$user] MCP server not installed (no Python 3.11+); skipping mcp doctor" + if in_list "$user" "$NO_MCP_USERS"; then + if in_list "$user" "$NO_PYTHON_USERS"; then + log "[$user] MCP server not installed (no Python 3.11+); skipping mcp doctor" + else + log "[$user] no client was configured; skipping mcp doctor" + fi if [ "$scan" -eq 1 ]; then sample_scan "$user" "$home"; fi return 0 fi @@ -1372,7 +1394,7 @@ stage_uninstall() { # stage_uninstall USER HOME done <<< "$(lines_of_list "$ARMIS_HOOK_REPOS")" fi - local args=$targets res="$WORK/uninstall.$user" status detail + local args=$targets res="$WORK/uninstall.$user" status detail ran=0 parsed=0 kind path top left [ "$FULL_UNINSTALL" -eq 0 ] || args=$flags : > "$res.tsv" if [ "$FULL_UNINSTALL" -eq 0 ] && [ -z "$targets" ]; then @@ -1386,8 +1408,9 @@ stage_uninstall() { # stage_uninstall USER HOME # shellcheck disable=SC2086 # args is a word list as_user "$user" "$home" 0 0 "$CLI_BIN" uninstall $args --format json > "$res.json" 2> "$LAST_OUT" LAST_RC=$? + ran=1 show_out "$LAST_OUT" - jt result "$res.json" > "$res.tsv" || true + if jt result "$res.json" > "$res.tsv"; then parsed=1; else : > "$res.tsv"; fi if [ "$LAST_RC" -ne 0 ]; then rec "$user" mcp-server installed fail rec "$user" mcp-server action "armis-cli uninstall exited $LAST_RC; see the log" @@ -1406,17 +1429,42 @@ stage_uninstall() { # stage_uninstall USER HOME rec "$user" "$client" installed skip continue fi + if [ "$ran" -eq 0 ]; then + rec "$user" "$client" installed skip + continue + fi status=$(result_field "$res.tsv" "$client" 2) detail=$(result_field "$res.tsv" "$client" 3) + # A full uninstall lists only the clients it deregistered; a missing one had no entry. + if [ -z "$status" ] && [ "$parsed" -eq 1 ] && [ "$FULL_UNINSTALL" -eq 1 ]; then + status=ok + detail="not registered" + fi case $status in + ok) ;; fail | warn) rec "$user" "$client" installed "$status" - rec "$user" "$client" action "${detail:-could not be removed}" ;; + rec "$user" "$client" action "${detail:-could not be removed}" + continue ;; *) - rec "$user" "$client" installed ok - rec "$user" "$client" verified ok - rec "$user" "$client" action "removed" ;; + rec "$user" "$client" installed fail + rec "$user" "$client" action "armis-cli uninstall reported no result for $client; see the log" + continue ;; esac + left="" + while IFS='|' read -r kind path top; do + [ "$kind" = json ] && [ -n "$top" ] && [ -f "$path" ] || continue + if ! jt keys "$path" "$top" > "$res.keys"; then left="$path is not valid JSON"; break; fi + if grep -qxF "$SERVER_KEY" "$res.keys"; then left="$SERVER_KEY is still registered in $path"; break; fi + done <<< "$(client_files "$client" "$home")" + rec "$user" "$client" installed ok + if [ -n "$left" ]; then + rec "$user" "$client" verified fail + rec "$user" "$client" action "$left" + else + rec "$user" "$client" verified ok + rec "$user" "$client" action "${detail:-removed}" + fi done # The profile block serves every client: keep it while any client stays registered. @@ -1431,9 +1479,17 @@ stage_uninstall() { # stage_uninstall USER HOME cfg="$p/.jb-mcp.json" [ -f "$cfg" ] || continue user_cmd "$user" "$home" 0 0 osascript -l JavaScript "$WORK/json_tool.js" delserver "$cfg" mcpServers "$SERVER_KEY" - show_out "$LAST_OUT" - rec "$user" jetbrains installed ok - rec "$user" jetbrains action "removed from $cfg" + if [ "$LAST_RC" -ne 0 ]; then + show_out "$LAST_OUT" + rec "$user" jetbrains installed fail + rec "$user" jetbrains action "could not remove $SERVER_KEY from $cfg (invalid JSON or not writable)" + elif grep -qx absent "$LAST_OUT"; then + rec "$user" jetbrains installed ok + rec "$user" jetbrains action "not registered in $cfg" + else + rec "$user" jetbrains installed ok + rec "$user" jetbrains action "removed from $cfg" + fi done <<< "$(lines_of_list "$ARMIS_JETBRAINS_PROJECTS")" fi @@ -1627,6 +1683,7 @@ if [ "$DO_UNINSTALL" -eq 0 ]; then fi if [ "$ARMIS_AUTH_MODE" = client-credentials ]; then load_credentials; fi fi +if [ "$DO_UNINSTALL" -eq 1 ] || [ "$ARMIS_AUTH_MODE" != client-credentials ]; then drop_ambient_credentials; fi # The clients and extras this run touches. CLIENT_LIST="" @@ -1655,9 +1712,11 @@ if [ -z "$ONLY" ] && ! in_list jetbrains "$SKIP" && ! in_list jetbrains "$ENABLE fi ENABLED_EXTRAS=${ENABLED_EXTRAS# } -# A full uninstall (nothing selected) removes everything; --only/--skip narrows it. +# A full uninstall (nothing selected) removes everything; --only, --skip or an +# ARMIS_CLIENTS subset narrows it to those clients. FULL_UNINSTALL=1 if [ -n "$ONLY" ] || [ -n "$SKIP" ]; then FULL_UNINSTALL=0; fi +for n in $ALL_CLIENTS; do in_list "$n" "$ARMIS_CLIENTS" || FULL_UNINSTALL=0; done if [ "$IS_ROOT" -eq 1 ]; then CLI_DIR=${ARMIS_INSTALL_DIR:-/usr/local/bin} diff --git a/test/scripts/enterprise-setup.bats b/test/scripts/enterprise-setup.bats index 2991980..a2203eb 100644 --- a/test/scripts/enterprise-setup.bats +++ b/test/scripts/enterprise-setup.bats @@ -616,6 +616,83 @@ EOF [ "$before" = "$(tree_hash "$HOME")" ] } +@test "a user with no detected client is not checked by mcp doctor" { + cat > "$T/doctor.json" <<'EOF' +{"checks":[{"component":"install","name":"manifest","status":"fail","detail":"no install manifest found"}]} +EOF + export STUB_DOCTOR_JSON="$T/doctor.json" STUB_DOCTOR_EXIT=1 + setup_run + [ "$status" -eq 0 ] + ! grep -q '^mcp doctor -f json' "$STUB_LOG/armis-cli.argv" +} + +@test "an install that drops existing servers is restored and reported" { + make_clients + echo '{"mcpServers":{"other":{"command":"x"}}}' > "$HOME/.cursor/mcp.json" + export STUB_WIPE_SERVERS=cursor + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"existing server 'other' disappeared"* ]] + grep -q '"other"' "$HOME/.cursor/mcp.json" +} + +@test "uninstall without a JSON report marks the clients as failed" { + make_clients + export STUB_UNINSTALL_NOJSON=1 + setup_run --uninstall --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"reported no result for cursor"* ]] + [[ "$output" != *"removed"* ]] +} + +@test "uninstall without armis-cli does not report clients as removed" { + make_clients + rm -f "$INSTALL_DIR/armis-cli" + setup_run --uninstall + [ "$status" -eq 0 ] + [[ "$output" == *"armis-cli is not installed"* ]] + [[ "$output" != *"removed"* ]] +} + +@test "a client whose config still has the server after uninstall fails verification" { + make_clients + setup_run --only cursor + grep -q armis-appsec "$HOME/.cursor/mcp.json" + export STUB_UNINSTALL_KEEP=cursor + setup_run --uninstall --only cursor + [ "$status" -eq 2 ] + [[ "$output" == *"armis-appsec is still registered in $HOME/.cursor/mcp.json"* ]] +} + +@test "a JetBrains config that cannot be edited on uninstall is reported as failed" { + make_clients + mkdir -p "$HOME/repo" + printf '{broken' > "$HOME/repo/.jb-mcp.json" + export ARMIS_JETBRAINS_PROJECTS="$HOME/repo" + setup_run --uninstall --only jetbrains + [ "$status" -eq 1 ] + [[ "$output" == *"could not remove armis-appsec from $HOME/repo/.jb-mcp.json"* ]] +} + +@test "uninstall with an ARMIS_CLIENTS subset removes only those clients" { + make_clients + export ARMIS_CLIENTS="cursor vscode" + setup_run --uninstall + [ "$status" -eq 0 ] + grep -q '^uninstall cursor vscode --format json$' "$STUB_LOG/armis-cli.argv" + ! grep -q -- '--force' "$STUB_LOG/armis-cli.argv" +} + +@test "sso mode and uninstall drop client credentials from the environment" { + make_clients + export STUB_ROOT=1 ARMIS_AUTH_MODE=sso ARMIS_TENANT_ID=acme ARMIS_SSO_LOGIN=skip + setup_run --only cursor + setup_run --uninstall --only cursor + [ ! -e "$STUB_LOG/env.flags" ] + ! grep -rq "$SECRET" "$LOG_DIR" + ! grep -q -- '--rotate-credentials' "$STUB_LOG/armis-cli.argv" +} + @test "the script runs under bash 3.2 without bash 4 features" { [ "$(/bin/bash -c 'echo ${BASH_VERSINFO[0]}')" -le 3 ] || skip "/bin/bash is not 3.x on this machine" make_clients diff --git a/test/scripts/stubs/armis-cli b/test/scripts/stubs/armis-cli index 03f0ea1..0beb0cb 100755 --- a/test/scripts/stubs/armis-cli +++ b/test/scripts/stubs/armis-cli @@ -81,7 +81,8 @@ do_install() { *) IFS='|' read -r file top <<< "$(target_cfg "$t")" mkdir -p "$(dirname "$file")" - osascript -l JavaScript "$DIR/merge.js" "$file" "$top" ;; + osascript -l JavaScript "$DIR/merge.js" "$file" "$top" + [ "${STUB_WIPE_SERVERS:-}" != "$t" ] || echo '{}' > "$file" ;; esac if [ "${STUB_HOOK_WARN:-}" = "$t" ]; then report "$t" ok "" warn "adapter missing"; failed=1; else report "$t" ok; fi done @@ -100,13 +101,19 @@ case "${1:-}" in install) shift; do_install "$@"; exit $? ;; uninstall) shift + [ "${STUB_UNINSTALL_NOJSON:-0}" != 1 ] || { echo "panic: boom" >&2; exit 2; } targets="" - for a in "$@"; do case $a in --*) ;; *) targets="$targets $a" ;; esac; done + prev="" + for a in "$@"; do + case $prev:$a in --format:*) ;; *:--*) ;; *) targets="$targets $a" ;; esac + prev=$a + done [ -n "$targets" ] || targets="cursor vscode copilot antigravity junie" clients="" for t in $targets; do IFS='|' read -r file top <<< "$(target_cfg "$t")" - [ -z "$file" ] || [ ! -f "$file" ] || osascript -l JavaScript "$DIR/merge.js" "$file" "$top" remove + [ "${STUB_UNINSTALL_KEEP:-}" = "$t" ] || [ -z "$file" ] || [ ! -f "$file" ] \ + || osascript -l JavaScript "$DIR/merge.js" "$file" "$top" remove report "$t" ok removed done printf '{"clients":[%s],"warnings":[]}\n' "$clients" From b638a33ddee3e614c98d5490e5c2d482c6349cbe Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Tue, 17 Nov 2026 10:25:51 +0200 Subject: [PATCH 6/7] Resolve latest armis-cli tag and harden enterprise setup profile handlin - Resolve "latest" from the github.com releases redirect and fetch the installer from that tag instead of main. Fail with exit 2 when it cannot be resolved or is older than the minimum supported version. - Drop the api.github.com preflight check, which is no longer needed. - Leave a profile unchanged and report a warning when its managed block has a begin marker but no end marker, so a hand-edited block cannot truncate the file. Tolerate trailing whitespace on marker lines. - Treat the JetBrains per-project hint as informational on a bare run, and as a warning only with --only jetbrains. - Share version_lt and valid_version helpers. - Add tests, extend the curl stub, and update the deployment docs. --- docs/ENTERPRISE-DEPLOYMENT.md | 8 +-- scripts/enterprise-setup.sh | 100 +++++++++++++++++++++++------ test/scripts/enterprise-setup.bats | 58 +++++++++++++++++ test/scripts/stubs/curl | 5 ++ 4 files changed, 148 insertions(+), 23 deletions(-) diff --git a/docs/ENTERPRISE-DEPLOYMENT.md b/docs/ENTERPRISE-DEPLOYMENT.md index 7ae06b0..8cc0391 100644 --- a/docs/ENTERPRISE-DEPLOYMENT.md +++ b/docs/ENTERPRISE-DEPLOYMENT.md @@ -37,7 +37,7 @@ A client that is not installed is reported as `skip (not installed)` and is not - Python 3.11 or later on each developer's `PATH` (the MCP server runs on it). If it is missing, the script reports it per user and exits 1; armis-cli still installs. Install it with `brew install python@3.12` or the python.org installer, then re-run. - Network access to the endpoints below, directly or through your proxy: - `moose.armis.com` (`eu.moose.armis.com` for region `eu1`) - - `api.github.com`, `github.com` and `raw.githubusercontent.com`. Set `ARMIS_INSTALLER_URL` to an internal mirror of `scripts/install.sh` if you cannot reach `raw.githubusercontent.com`. + - `github.com` and `raw.githubusercontent.com`. Set `ARMIS_INSTALLER_URL` to an internal mirror of `scripts/install.sh` if you cannot reach `raw.githubusercontent.com`. - A proxy or TLS inspection is supported through `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (upper or lower case) and `SSL_CERT_FILE` (a PEM file with your root CA). The script passes them, and `ARMIS_API_URL` when set, to `curl` and to every armis-cli command. - armis-cli 1.27.0 or later. The script reads the `install --format json` report and uses `--rotate-credentials`, and it exits 3 when `ARMIS_CLI_VERSION` is older. @@ -80,7 +80,7 @@ Every value can come from the environment, so an MDM can set them as script para | Variable | Default | Meaning | |---|---|---| | `ARMIS_CLI_VERSION` | none | armis-cli release to install, `1.27.0` or later. The installer is fetched from the same tag. | -| `ARMIS_ALLOW_LATEST` | `0` | `1` allows an unpinned install with `--non-interactive`. | +| `ARMIS_ALLOW_LATEST` | `0` | `1` allows an unpinned install with `--non-interactive`. The script resolves the latest release tag and downloads the installer from that tag, never from `main`. | | `ARMIS_MCP_VERSION` | latest | MCP server release to pin. A pin is saved and kept by `armis-cli mcp update` and `armis-cli mcp doctor --fix`. | | `ARMIS_TENANT_ID` | none | Tenant. Required for `sso`. | | `ARMIS_REGION` | default region | For example `eu1`. | @@ -123,7 +123,7 @@ For each user (the home directory is that user's): | `ARMIS_INSTALL_DIR/armis-cli` | The binary. | | `~/.armis/plugins/armis-appsec-mcp/` | The MCP server, its Python environment and `.env` (mode 0600). | | The client files in the [table above](#supported-clients) | One `armis-appsec` entry added. Other servers are kept. | -| `~/.zshenv`, `~/.profile` or `~/.bash_profile`, `~/.bashrc` | A block between `# >>> armis-cli (managed) >>>` and `# <<< armis-cli (managed) <<<` with `ARMIS_TENANT_ID`, `ARMIS_REGION`, `ARMIS_DEFAULT_AUTH_METHOD` (sso) and `PATH`. Written only when it has content. Everything outside the markers is untouched. | +| `~/.zshenv`, `~/.profile` or `~/.bash_profile`, `~/.bashrc` | A block between `# >>> armis-cli (managed) >>>` and `# <<< armis-cli (managed) <<<` with `ARMIS_TENANT_ID`, `ARMIS_REGION`, `ARMIS_DEFAULT_AUTH_METHOD` (sso) and `PATH`. Written only when it has content. Everything outside the markers is untouched. A file with the begin marker but no end marker is left unchanged and reported, so a hand-edited block cannot truncate it. | | `/.jb-mcp.json`, `/.git/hooks/pre-commit` | Only for the projects and repositories you list. | | `ARMIS_LOG_DIR` | `enterprise-setup-.log` and `.json`. | @@ -173,7 +173,7 @@ Junie is automatic (`junie` above). JetBrains AI Assistant reads a `.jb-mcp.json ARMIS_JETBRAINS_PROJECTS="$HOME/code/api,$HOME/code/web" ./scripts/enterprise-setup.sh --only jetbrains ``` -The script runs `armis-cli install jetbrains --project ` for each project that belongs to the user. The developer then enables the server in the IDE's AI Assistant MCP settings. Without a project list, the script reports `run 'armis-cli install jetbrains --project ' in each repo, or use Junie`. +The script runs `armis-cli install jetbrains --project ` for each project that belongs to the user. The developer then enables the server in the IDE's AI Assistant MCP settings. Without a project list, the script reports `run 'armis-cli install jetbrains --project ' in each repo, or use Junie`. On a run without `--only` this is a hint and does not change the exit code; with `--only jetbrains` it is a warning (exit 1). ## Commit gate diff --git a/scripts/enterprise-setup.sh b/scripts/enterprise-setup.sh index 6bb4a4d..02a0e42 100755 --- a/scripts/enterprise-setup.sh +++ b/scripts/enterprise-setup.sh @@ -212,6 +212,16 @@ split_list() { printf '%s' "$1" | tr ',' ' ' | tr -s ' '; } # lines_of_list "a,b c": one entry per line, splitting on commas only (paths may contain spaces). lines_of_list() { printf '%s' "$1" | tr ',' '\n' | sed '/^[[:space:]]*$/d'; } +# version_lt A B: is release A (prerelease suffix ignored) older than B? +version_lt() { + awk -v a="${1%%-*}" -v b="$2" 'BEGIN { + split(a, x, "."); split(b, y, ".") + for (i = 1; i <= 3; i++) if (x[i] + 0 != y[i] + 0) exit !(x[i] + 0 < y[i] + 0) + exit 1 }' +} + +valid_version() { printf '%s' "$1" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?$'; } + require_ident() { local name=$1 value=$2 printf '%s' "$value" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' \ @@ -679,7 +689,7 @@ stage_preflight() { fatal 3 "$dir is not writable by $(id -un)" fi - for url in "$(api_base)" "https://api.github.com" "https://github.com/$REPO/releases"; do + for url in "$(api_base)" "https://github.com/$REPO/releases"; do code=$(probe "$url") if [ "$code" = 000 ]; then fatal 3 "cannot reach $url (check the network, HTTPS_PROXY and SSL_CERT_FILE)" @@ -703,12 +713,46 @@ cli_version_ok() { # does the installed binary report exactly the wanted version [ -n "$got" ] && [ "$got" = "$ARMIS_CLI_VERSION" ] } +# resolve_latest: the version of the latest release, from the redirect of +# github.com/REPO/releases/latest, so "latest" installs a released tag's installer. +resolve_latest() { + local url tag + if [ -n "${SSL_CERT_FILE:-}" ]; then + url=$(curl -fsSL -o /dev/null -w '%{url_effective}' --connect-timeout 10 --max-time 30 \ + --cacert "$SSL_CERT_FILE" "https://github.com/$REPO/releases/latest" 2>/dev/null) || return 1 + else + url=$(curl -fsSL -o /dev/null -w '%{url_effective}' --connect-timeout 10 --max-time 30 \ + "https://github.com/$REPO/releases/latest" 2>/dev/null) || return 1 + fi + case $url in */releases/tag/*) tag=${url##*/releases/tag/} ;; *) return 1 ;; esac + tag=${tag#v} + valid_version "$tag" || return 1 + printf '%s' "$tag" +} + stage_cli() { - local ref installer_url version_arg + local installer_url latest log "armis-cli" CLI_BIN="$CLI_DIR/armis-cli" - if [ "$ARMIS_CLI_VERSION" != latest ] && cli_version_ok; then + if [ "$ARMIS_CLI_VERSION" = latest ]; then + if ! latest=$(resolve_latest); then + rec "-" armis-cli installed fail + rec "-" armis-cli action "could not resolve the latest release from https://github.com/$REPO/releases/latest; set ARMIS_CLI_VERSION" + FORCED_EXIT=2 + finish + fi + if version_lt "$latest" "$MIN_CLI_VERSION"; then + rec "-" armis-cli installed fail + rec "-" armis-cli action "the latest release $latest is older than $MIN_CLI_VERSION, which this script needs" + FORCED_EXIT=2 + finish + fi + log "latest armis-cli release is $latest" + ARMIS_CLI_VERSION=$latest + fi + + if cli_version_ok; then log "armis-cli $ARMIS_CLI_VERSION already installed at $CLI_BIN" rec "-" armis-cli detected yes rec "-" armis-cli installed ok @@ -716,8 +760,7 @@ stage_cli() { return 0 fi - if [ "$ARMIS_CLI_VERSION" = latest ]; then ref=main; version_arg=latest; else ref="v$ARMIS_CLI_VERSION"; version_arg="v$ARMIS_CLI_VERSION"; fi - installer_url="${ARMIS_INSTALLER_URL:-https://raw.githubusercontent.com/$REPO/$ref/scripts/install.sh}" + installer_url="${ARMIS_INSTALLER_URL:-https://raw.githubusercontent.com/$REPO/v$ARMIS_CLI_VERSION/scripts/install.sh}" if [ "$DRY_RUN" -eq 1 ]; then log "[dry-run] would download $installer_url and install armis-cli $ARMIS_CLI_VERSION to $CLI_DIR" @@ -741,7 +784,7 @@ stage_cli() { # CI=1 keeps the installer from editing the invoking account's shell rc; # profiles are managed per developer below. exec_cmd env CI=1 SHELL="${SHELL:-/bin/bash}" INSTALL_DIR="$CLI_DIR" VERIFY=true \ - PATH="$SAFE_PATH:$CLI_DIR:$PATH" bash "$WORK/install.sh" "$version_arg" + PATH="$SAFE_PATH:$CLI_DIR:$PATH" bash "$WORK/install.sh" "v$ARMIS_CLI_VERSION" show_out "$LAST_OUT" if grep -Eq "(Checksum|Signature) verification failed" "$LAST_OUT"; then rec "-" armis-cli installed fail @@ -759,7 +802,7 @@ stage_cli() { rec "-" armis-cli detected yes rec "-" armis-cli installed ok - if [ "$ARMIS_CLI_VERSION" != latest ] && ! cli_version_ok; then + if ! cli_version_ok; then rec "-" armis-cli verified fail rec "-" armis-cli action "installed binary does not report version $ARMIS_CLI_VERSION" FORCED_EXIT=2 @@ -781,8 +824,14 @@ stage_cli() { MANAGED_BLOCK_SH='f=$1 b=$2 e=$3 c=$4 tmp=$(mktemp "${TMPDIR:-/tmp}/armis-profile.XXXXXX") || exit 1 if [ -f "$f" ]; then - awk -v b="$b" -v e="$e" "\$0 == b { skip = 1; next } \$0 == e { skip = 0; next } !skip" "$f" > "$tmp" \ - || { rm -f "$tmp"; exit 1; } + # Exit 3, leaving FILE alone, when a begin marker has no end marker after it. + awk -v b="$b" -v e="$e" "{ l = \$0; sub(/[[:space:]]+\$/, \"\", l) } + !skip && l == b { skip = 1; next } + skip && l == e { skip = 0; next } + !skip { print } + END { exit skip ? 3 : 0 }" "$f" > "$tmp" + rc=$? + [ "$rc" -eq 0 ] || { rm -f "$tmp"; exit "$rc"; } fi if [ -n "$c" ]; then printf "%s\n%s\n%s\n" "$b" "$c" "$e" >> "$tmp"; fi cat "$tmp" > "$f" @@ -799,8 +848,18 @@ set_managed_block() { # set_managed_block FILE USER HOME CONTENT return 0 fi backup_file "$user" "$home" "$file" "$list" - as_user "$user" "$home" 0 0 /bin/sh -c "$MANAGED_BLOCK_SH" sh "$file" "$MARK_BEGIN" "$MARK_END" "$content" \ - || warn "[$user] could not update $file" + as_user "$user" "$home" 0 0 /bin/sh -c "$MANAGED_BLOCK_SH" sh "$file" "$MARK_BEGIN" "$MARK_END" "$content" + case $? in + 0) ;; + 3) + warn "[$user] $file has '$MARK_BEGIN' without '$MARK_END'; left it unchanged" + rec "$user" profile installed warn + rec "$user" profile action "$file has an unterminated armis-cli managed block; fix the markers by hand, then re-run" ;; + *) + warn "[$user] could not update $file" + rec "$user" profile installed warn + rec "$user" profile action "could not update $file" ;; + esac drop_unchanged "$user" "$home" "$list" } @@ -1118,7 +1177,11 @@ stage_jetbrains() { # stage_jetbrains USER HOME if [ -z "$ARMIS_JETBRAINS_PROJECTS" ]; then if ls -d "$home/Library/Application Support/JetBrains"/* >/dev/null 2>&1; then rec "$user" jetbrains detected yes - rec "$user" jetbrains installed warn + if [ "$JETBRAINS_HINT_ONLY" -eq 1 ]; then + rec "$user" jetbrains installed skip + else + rec "$user" jetbrains installed warn + fi rec "$user" jetbrains action "JetBrains AI Assistant is per project: run 'armis-cli install jetbrains --project ' in each repo, set ARMIS_JETBRAINS_PROJECTS, or use Junie" else rec "$user" jetbrains detected no @@ -1668,13 +1731,9 @@ if [ "$DO_UNINSTALL" -eq 0 ]; then fi if [ "$ARMIS_CLI_VERSION" != latest ]; then ARMIS_CLI_VERSION=${ARMIS_CLI_VERSION#v} - printf '%s' "$ARMIS_CLI_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?$' \ - || die_usage "ARMIS_CLI_VERSION must look like 1.27.0" + valid_version "$ARMIS_CLI_VERSION" || die_usage "ARMIS_CLI_VERSION must look like 1.27.0" # This script reads `install --format json`, added in this release. - if awk -v a="${ARMIS_CLI_VERSION%%-*}" -v b="$MIN_CLI_VERSION" 'BEGIN { - split(a, x, "."); split(b, y, ".") - for (i = 1; i <= 3; i++) if (x[i] + 0 != y[i] + 0) exit !(x[i] + 0 < y[i] + 0) - exit 1 }'; then + if version_lt "$ARMIS_CLI_VERSION" "$MIN_CLI_VERSION"; then die_usage "ARMIS_CLI_VERSION $ARMIS_CLI_VERSION is too old; this script needs $MIN_CLI_VERSION or later" fi fi @@ -1706,9 +1765,12 @@ for n in jetbrains hook; do ENABLED_EXTRAS="$ENABLED_EXTRAS $n" fi done -# A bare run (no --only) still reports on JetBrains, as a hint. +# A bare run (no --only) still reports on JetBrains, as a hint that does not +# count against the exit code. +JETBRAINS_HINT_ONLY=0 if [ -z "$ONLY" ] && ! in_list jetbrains "$SKIP" && ! in_list jetbrains "$ENABLED_EXTRAS"; then ENABLED_EXTRAS="$ENABLED_EXTRAS jetbrains" + JETBRAINS_HINT_ONLY=1 fi ENABLED_EXTRAS=${ENABLED_EXTRAS# } diff --git a/test/scripts/enterprise-setup.bats b/test/scripts/enterprise-setup.bats index a2203eb..5b4fefe 100644 --- a/test/scripts/enterprise-setup.bats +++ b/test/scripts/enterprise-setup.bats @@ -693,6 +693,64 @@ EOF ! grep -q -- '--rotate-credentials' "$STUB_LOG/armis-cli.argv" } +@test "an unpinned install uses the installer from the latest release tag" { + unset ARMIS_CLI_VERSION + export ARMIS_ALLOW_LATEST=1 STUB_LATEST=1.28.0 STUB_CLI_VERSION=1.28.0 + rm -f "$INSTALL_DIR/armis-cli" + setup_run --only cursor --report "$T/rep" + [ "$status" -eq 0 ] + grep -q 'armis-cli/v1.28.0/scripts/install.sh' "$STUB_LOG/curl.urls" + ! grep -q '/main/' "$STUB_LOG/curl.urls" + grep -q '"cli_version": "1.28.0"' "$T/rep.json" +} + +@test "an unpinned install fails when the latest release cannot be resolved" { + unset ARMIS_CLI_VERSION + export ARMIS_ALLOW_LATEST=1 STUB_LATEST=garbage + rm -f "$INSTALL_DIR/armis-cli" + setup_run --only cursor + [ "$status" -eq 2 ] + [[ "$output" == *"could not resolve the latest release"* ]] + ! grep -q 'install.sh' "$STUB_LOG/curl.urls" +} + +@test "preflight does not need api.github.com" { + make_clients + setup_run --only cursor + [ "$status" -eq 0 ] + ! grep -q 'api.github.com' "$STUB_LOG/curl.urls" +} + +@test "a JetBrains data directory on a bare run is a hint, not a warning" { + make_clients + mkdir -p "$HOME/Library/Application Support/JetBrains/IntelliJIdea2025.1" + setup_run + [ "$status" -eq 0 ] + [[ "$output" == *"install jetbrains --project"* ]] +} + +@test "a profile with an unterminated managed block is left unchanged" { + make_clients + printf 'export A=1\n# >>> armis-cli (managed) >>>\nexport OLD=1\nexport KEEP=me\n' > "$HOME/.zshenv" + before=$(shasum "$HOME/.zshenv") + export ARMIS_TENANT_ID=acme + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"unterminated armis-cli managed block"* ]] + [ "$before" = "$(shasum "$HOME/.zshenv")" ] +} + +@test "an end marker with trailing whitespace still closes the managed block" { + make_clients + printf 'export A=1\n# >>> armis-cli (managed) >>>\nexport OLD=1\n# <<< armis-cli (managed) <<< \nexport KEEP=me\n' > "$HOME/.zshenv" + export ARMIS_TENANT_ID=acme + setup_run --only cursor + [ "$status" -eq 0 ] + grep -q 'export KEEP=me' "$HOME/.zshenv" + ! grep -q 'export OLD=1' "$HOME/.zshenv" + [ "$(grep -c 'armis-cli (managed) >>>' "$HOME/.zshenv")" -eq 1 ] +} + @test "the script runs under bash 3.2 without bash 4 features" { [ "$(/bin/bash -c 'echo ${BASH_VERSINFO[0]}')" -le 3 ] || skip "/bin/bash is not 3.x on this machine" make_clients diff --git a/test/scripts/stubs/curl b/test/scripts/stubs/curl index bb952ea..c47af19 100755 --- a/test/scripts/stubs/curl +++ b/test/scripts/stubs/curl @@ -13,6 +13,11 @@ while [ $# -gt 0 ]; do done printf '%s\n' "$url" >> "$LOG/curl.urls" if [ "$probe" = 1 ]; then + case $url in + */releases/latest) + [ "${STUB_CURL_FAIL:-0}" != 1 ] || exit 7 + printf '%s' "${url%/latest}/tag/v${STUB_LATEST:-1.28.0}"; exit 0 ;; + esac if [ "${STUB_CURL_FAIL:-0}" = 1 ]; then printf '000'; exit 7; fi printf '200'; exit 0 fi From 8ce0ef558199a0d4aced37354abb5494b23feec5 Mon Sep 17 00:00:00 2001 From: Yiftach Cohen Date: Tue, 17 Nov 2026 11:06:32 +0200 Subject: [PATCH 7/7] Warn when another armis-cli shadows the installed one on a developer's P - Probe each developer's login shell for `command -v armis-cli`. Report a warning (exit 1) when the binary is missing from PATH or when a copy with a different version comes first, such as an older Homebrew install. Homebrew copies get `brew upgrade` advice. - Report an older existing armis-cli as "found, will be replaced" in dry runs, instead of "not installed". Record the replaced version after a real install. - Set `ARMIS_NO_UPDATE_CHECK` for version probes so they don't hit the network. - Add `ARMIS_LOGIN_SHELL` as a test hook, with a `loginshell` stub and bats tests for the shadowed, Homebrew, same-version and missing cases. - Document the new exit-1 cause in ENTERPRISE-DEPLOYMENT.md. --- docs/ENTERPRISE-DEPLOYMENT.md | 2 +- scripts/enterprise-setup.sh | 81 ++++++++++++++++++++++++------ test/scripts/enterprise-setup.bats | 56 +++++++++++++++++++++ test/scripts/stubs/loginshell | 5 ++ 4 files changed, 129 insertions(+), 15 deletions(-) create mode 100755 test/scripts/stubs/loginshell diff --git a/docs/ENTERPRISE-DEPLOYMENT.md b/docs/ENTERPRISE-DEPLOYMENT.md index 8cc0391..87440f2 100644 --- a/docs/ENTERPRISE-DEPLOYMENT.md +++ b/docs/ENTERPRISE-DEPLOYMENT.md @@ -149,7 +149,7 @@ The matrix has one row per endpoint, user and component, with these columns: End | Exit code | Meaning | |---|---| | 0 | Everything succeeded. | -| 1 | Partial: something needs attention (a client failed, Python is missing, sign-in is pending, a JetBrains project is not set up). | +| 1 | Partial: something needs attention (a client failed, Python is missing, sign-in is pending, a JetBrains project is not set up, or the developer's login shell runs a different `armis-cli` than the one installed). | | 2 | A verification failed (`mcp doctor`, the sample scan), or armis-cli could not be installed. | | 3 | Bad arguments, an unreadable credentials file, a checksum or signature mismatch, or a preflight failure. | diff --git a/scripts/enterprise-setup.sh b/scripts/enterprise-setup.sh index 02a0e42..f2de3e6 100755 --- a/scripts/enterprise-setup.sh +++ b/scripts/enterprise-setup.sh @@ -704,15 +704,22 @@ stage_preflight() { # ---- armis-cli -------------------------------------------------------------- -cli_version_ok() { # does the installed binary report exactly the wanted version? +# parse_version: the first x.y.z on stdin, without a leading v. +parse_version() { + awk '{ for (i = 1; i <= NF; i++) if ($i ~ /^v?[0-9]+\.[0-9]+\.[0-9]+/) { sub(/^v/, "", $i); print $i; exit } }' +} + +# installed_version: what CLI_BIN reports; "unknown" for a build without a +# version (dev); empty when there is no binary. +installed_version() { local got - [ -x "$CLI_BIN" ] || return 1 - got=$("$CLI_BIN" --version 2>/dev/null | awk '{ - for (i = 1; i <= NF; i++) if ($i ~ /^v?[0-9]+\.[0-9]+\.[0-9]+/) { sub(/^v/, "", $i); print $i; exit } - }') - [ -n "$got" ] && [ "$got" = "$ARMIS_CLI_VERSION" ] + [ -x "$CLI_BIN" ] || return 0 + got=$(ARMIS_NO_UPDATE_CHECK=1 "$CLI_BIN" --version 2>/dev/null | parse_version) + printf '%s' "${got:-unknown}" } +cli_version_ok() { [ "$(installed_version)" = "$ARMIS_CLI_VERSION" ]; } + # resolve_latest: the version of the latest release, from the redirect of # github.com/REPO/releases/latest, so "latest" installs a released tag's installer. resolve_latest() { @@ -731,7 +738,7 @@ resolve_latest() { } stage_cli() { - local installer_url latest + local installer_url latest have plan log "armis-cli" CLI_BIN="$CLI_DIR/armis-cli" @@ -752,21 +759,28 @@ stage_cli() { ARMIS_CLI_VERSION=$latest fi - if cli_version_ok; then + have=$(installed_version) + if [ "$have" = "$ARMIS_CLI_VERSION" ]; then log "armis-cli $ARMIS_CLI_VERSION already installed at $CLI_BIN" rec "-" armis-cli detected yes rec "-" armis-cli installed ok rec "-" armis-cli verified ok return 0 fi + if [ -n "$have" ]; then + rec "-" armis-cli detected yes + plan="replace armis-cli $have at $CLI_BIN with $ARMIS_CLI_VERSION" + else + rec "-" armis-cli detected no + plan="install armis-cli $ARMIS_CLI_VERSION to $CLI_DIR" + fi installer_url="${ARMIS_INSTALLER_URL:-https://raw.githubusercontent.com/$REPO/v$ARMIS_CLI_VERSION/scripts/install.sh}" if [ "$DRY_RUN" -eq 1 ]; then - log "[dry-run] would download $installer_url and install armis-cli $ARMIS_CLI_VERSION to $CLI_DIR" - rec "-" armis-cli detected no + log "[dry-run] would download $installer_url and $plan" rec "-" armis-cli installed skip - rec "-" armis-cli action "dry-run: would install armis-cli $ARMIS_CLI_VERSION" + rec "-" armis-cli action "dry-run: would $plan" return 0 fi @@ -780,7 +794,7 @@ stage_cli() { finish fi - log "Installing armis-cli $ARMIS_CLI_VERSION to $CLI_DIR" + log "Going to $plan" # CI=1 keeps the installer from editing the invoking account's shell rc; # profiles are managed per developer below. exec_cmd env CI=1 SHELL="${SHELL:-/bin/bash}" INSTALL_DIR="$CLI_DIR" VERIFY=true \ @@ -800,8 +814,8 @@ stage_cli() { fi if [ "$IS_ROOT" -eq 1 ]; then chmod 755 "$CLI_BIN"; fi - rec "-" armis-cli detected yes rec "-" armis-cli installed ok + [ -z "$have" ] || rec "-" armis-cli action "replaced $have with $ARMIS_CLI_VERSION" if ! cli_version_ok; then rec "-" armis-cli verified fail rec "-" armis-cli action "installed binary does not report version $ARMIS_CLI_VERSION" @@ -818,6 +832,44 @@ stage_cli() { fi } +# ---- the developer's PATH -------------------------------------------------- + +# ARMIS_LOGIN_SHELL exists for tests. +login_shell() { # login_shell USER: the account's shell, for a PATH probe + local sh + if [ -n "${ARMIS_LOGIN_SHELL:-}" ]; then printf '%s' "$ARMIS_LOGIN_SHELL"; return; fi + sh=$(dscl . -read "/Users/$1" UserShell 2>/dev/null | awk '{ print $2 }') + case $sh in */zsh | */bash | */sh) printf '%s' "$sh" ;; *) printf '/bin/zsh' ;; esac +} + +# check_cli_path USER HOME: which armis-cli the developer's login shell runs. +# Another copy earlier on PATH (often Homebrew's) shadows the one installed here. +check_cli_path() { + local user=$1 home=$2 sh found got + sh=$(login_shell "$user") + SEQ=$((SEQ + 1)) + LAST_OUT="$WORK/out.$SEQ" + # A minimal PATH, so only the developer's own profile and /etc/paths decide. + # shellcheck disable=SC2016 # expanded by the login shell + with_timeout 20 as_user "$user" "$home" 0 0 /usr/bin/env PATH=/usr/bin:/bin:/usr/sbin:/sbin \ + "$sh" -l -c 'command -v armis-cli' > "$LAST_OUT" 2>/dev/null + found=$(grep '^/' "$LAST_OUT" | tail -n 1) + if [ -z "$found" ]; then + [ "$DRY_RUN" -eq 1 ] && return 0 + rec "$user" cli-path installed warn + rec "$user" cli-path action "armis-cli is not on $user's PATH in a new $(basename "$sh") login shell; add $CLI_DIR to PATH" + return 0 + fi + [ "$found" != "$CLI_BIN" ] || return 0 + user_cmd "$user" "$home" 0 0 env ARMIS_NO_UPDATE_CHECK=1 "$found" --version + got=$(parse_version < "$LAST_OUT") + [ "${got:-unknown}" != "$ARMIS_CLI_VERSION" ] || return 0 + local fix="remove it or move $CLI_DIR earlier in PATH" + case $(readlink "$found" 2>/dev/null) in */Cellar/*) fix="run 'brew uninstall armis-cli' or 'brew upgrade armis-cli'" ;; esac + rec "$user" cli-path installed warn + rec "$user" cli-path action "$found (${got:-unknown}) comes before $CLI_BIN ($ARMIS_CLI_VERSION) on $user's PATH; $fix" +} + # ---- profiles --------------------------------------------------------------- # shellcheck disable=SC2016 # expanded by the inner shell @@ -1602,7 +1654,7 @@ build_table() { for (i = 1; i <= n; i++) { k = order[i] a = (u[k] in auth) ? auth[u[k]] : "" - if (c[k] == "armis-cli" || c[k] == "preflight" || det[k] == "no") a = "" + if (c[k] == "armis-cli" || c[k] == "preflight" || c[k] == "cli-path" || c[k] == "profile" || det[k] == "no") a = "" action = act[k] if (c[k] == "mcp-server" && uact[u[k]] != "") action = (action == "" ? uact[u[k]] : action "; " uact[u[k]]) printf "%s\037%s\037%s\037%s\037%s\037%s\037%s\n", u[k], c[k], det[k], ins[k], a, ver[k], action @@ -1866,6 +1918,7 @@ for u in $USERS; do network_check "$u" "$h" fi stage_auth "$u" "$h" + check_cli_path "$u" "$h" stage_mcp "$u" "$h" stage_jetbrains "$u" "$h" stage_hook "$u" "$h" diff --git a/test/scripts/enterprise-setup.bats b/test/scripts/enterprise-setup.bats index 5b4fefe..4c85d7e 100644 --- a/test/scripts/enterprise-setup.bats +++ b/test/scripts/enterprise-setup.bats @@ -23,6 +23,7 @@ setup() { export PATH="$STUBS:/usr/bin:/bin:/usr/sbin:/sbin" export ARMIS_SAFE_PATH="/usr/bin:/bin:/usr/sbin:/sbin" export ARMIS_EXTRA_PATH="$STUBS:$PYSTUB" + export ARMIS_LOGIN_SHELL="$STUBS/loginshell" export ARMIS_INSTALL_DIR="$INSTALL_DIR" export ARMIS_LOG_DIR="$LOG_DIR" export ARMIS_CLI_VERSION="1.27.0" @@ -751,6 +752,61 @@ EOF [ "$(grep -c 'armis-cli (managed) >>>' "$HOME/.zshenv")" -eq 1 ] } +# fake_brew_cli VERSION: an armis-cli in $T/brew reporting VERSION. +fake_brew_cli() { + mkdir -p "$T/brew" + printf '#!/bin/sh\necho "armis-cli version %s (commit: x, built: y)"\n' "$1" > "$T/brew/armis-cli" + chmod 755 "$T/brew/armis-cli" +} + +@test "a dry run with an older CLI reports it as found and to be replaced" { + make_clients + export STUB_CLI_VERSION=1.25.0 + setup_run --dry-run + [ "$status" -eq 0 ] + [[ "$output" == *"would replace armis-cli 1.25.0 at $INSTALL_DIR/armis-cli with 1.27.0"* ]] + ! printf '%s\n' "$output" | grep -q 'armis-cli .*skip (not installed)' +} + +@test "an older armis-cli earlier on the developer's PATH is reported" { + make_clients + fake_brew_cli 1.25.0 + export STUB_USER_PATH="$T/brew:$INSTALL_DIR" + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"$T/brew/armis-cli (1.25.0) comes before $INSTALL_DIR/armis-cli (1.27.0)"* ]] + [[ "$output" == *"remove it or move"* ]] +} + +@test "a shadowing Homebrew armis-cli gets brew advice" { + make_clients + fake_brew_cli 1.25.0 + mkdir -p "$T/Cellar/armis-cli/1.25.0/bin" "$T/hb/bin" + mv "$T/brew/armis-cli" "$T/Cellar/armis-cli/1.25.0/bin/armis-cli" + ln -s "../../Cellar/armis-cli/1.25.0/bin/armis-cli" "$T/hb/bin/armis-cli" + export STUB_USER_PATH="$T/hb/bin:$INSTALL_DIR" + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"brew upgrade armis-cli"* ]] +} + +@test "the same armis-cli version earlier on PATH is not reported" { + make_clients + fake_brew_cli 1.27.0 + export STUB_USER_PATH="$T/brew:$INSTALL_DIR" + setup_run --only cursor + [ "$status" -eq 0 ] + [[ "$output" != *"comes before"* ]] +} + +@test "armis-cli missing from the developer's PATH is reported" { + make_clients + export STUB_USER_PATH="$T/nowhere" + setup_run --only cursor + [ "$status" -eq 1 ] + [[ "$output" == *"armis-cli is not on"* ]] +} + @test "the script runs under bash 3.2 without bash 4 features" { [ "$(/bin/bash -c 'echo ${BASH_VERSINFO[0]}')" -le 3 ] || skip "/bin/bash is not 3.x on this machine" make_clients diff --git a/test/scripts/stubs/loginshell b/test/scripts/stubs/loginshell new file mode 100755 index 0000000..75a75ee --- /dev/null +++ b/test/scripts/stubs/loginshell @@ -0,0 +1,5 @@ +#!/bin/bash +# Fake login shell (ARMIS_LOGIN_SHELL): resolves the command against STUB_USER_PATH. +[ "$1" = -l ] && shift +[ "$1" = -c ] && shift +PATH="${STUB_USER_PATH:-$ARMIS_INSTALL_DIR}" exec /bin/sh -c "$1"