diff --git a/bin/dotfiles-azure-mcp-pilot b/bin/dotfiles-azure-mcp-pilot new file mode 100755 index 0000000..2f67373 --- /dev/null +++ b/bin/dotfiles-azure-mcp-pilot @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +# Optional ChatGPT tunnel recipe; never registered in global MCP surfaces. +set -euo pipefail +set +x + +mode=preview +mode_seen=false +tunnel_id='' +for arg in "$@"; do + case "$arg" in + --apply | --doctor | --status | --check | --dry-run) + [[ "$mode_seen" == false ]] || { + echo 'ERROR: choose one mode' >&2 + exit 1 + } + mode_seen=true + case "$arg" in + --apply) mode=apply ;; + --doctor | --status) mode=doctor ;; + *) mode=preview ;; + esac + ;; + -h | --help) + cat <<'HELP' +Usage: bin/dotfiles-azure-mcp-pilot [--check|--dry-run|--apply] [tunnel_ID] + bin/dotfiles-azure-mcp-pilot --doctor|--status +Default: read-only preview. --apply creates missing recipe files only; never +installs tools, writes keys, logs in, or starts services. Existing differences +are refused. See docs/ops/azure-mcp-pilot.md for manual key activation/start. +HELP + exit 0 + ;; + *) + [[ -z "$tunnel_id" && "$arg" =~ ^tunnel_[A-Za-z0-9_-]+$ ]] || { + echo 'ERROR: expected tunnel_ID (never pass a runtime key)' >&2 + exit 1 + } + tunnel_id=$arg + ;; + esac +done + +# A fixed OS PATH avoids inherited IDE paths, empty entries and systemd omissions. +export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin" +[[ "$HOME" =~ ^/[A-Za-z0-9_./-]+$ && "$HOME" != *'/../'* ]] || { + echo 'ERROR: HOME must be an absolute path using letters, digits, _, ., / or -' >&2 + exit 1 +} +name=ixatu-azure-mcp-pilot +launcher="$HOME/.local/share/$name/start.sh" +profile="$HOME/.config/tunnel-client/$name.yaml" +unit="$HOME/.config/systemd/user/$name.service" +keyfile="$HOME/.config/$name/runtime.env" + +# Refuse symlinks in all owned paths before reading or writing recipe files. +for target in "$launcher" "$profile" "$unit" "$keyfile"; do + ancestor=$target + while [[ "$ancestor" != / ]]; do + [[ ! -L "$ancestor" ]] || { + echo 'ERROR: pilot paths must not contain symlinks' >&2 + exit 1 + } + ancestor=${ancestor%/*} + [[ -n "$ancestor" ]] || break + done +done + +if [[ "$mode" == doctor || "$mode" == apply ]]; then + for tool in az uvx; do + command -v "$tool" >/dev/null || { + printf 'ERROR: missing %s; provision it manually in ~/.local/bin or OS PATH; retry --doctor\n' "$tool" >&2 + exit 1 + } + done + [[ -x "$HOME/.local/bin/tunnel-client" ]] || { + echo 'ERROR: missing ~/.local/bin/tunnel-client; provision manually, then retry --doctor' >&2 + exit 1 + } +fi + +if [[ "$mode" == doctor ]]; then + failed=0 + for target in "$launcher" "$profile" "$unit"; do + if [[ -f "$target" ]]; then + printf 'present: %s\n' "$target" + else + printf 'missing: %s (preview then --apply tunnel_ID)\n' "$target" + failed=1 + fi + done + # Metadata only: never source, parse, or display runtime.env. + if [[ -f "$keyfile" && -s "$keyfile" && -O "$keyfile" && "$(stat -c %a "$keyfile")" == 600 ]]; then + echo 'runtime key file: present, owner-only (contents not checked)' + else + echo 'runtime key file: missing/empty or unsafe; follow manual activation, chmod 0600' + failed=1 + fi + if command -v curl >/dev/null && curl --noproxy '*' -fsS --max-time 2 -o /dev/null http://127.0.0.1:49188/readyz 2>/dev/null; then + echo 'readyz: OK (does not prove Azure authentication or tool scope)' + else + echo 'readyz: unavailable; check pilot service locally (curl required)' + failed=1 + fi + exit "$failed" +fi + +if [[ -z "$tunnel_id" ]]; then + [[ "$mode" != apply ]] || { + echo 'ERROR: --apply requires a new PC09 tunnel_ID' >&2 + exit 1 + } + printf 'PREVIEW: generate %s, %s, %s with --apply tunnel_ID\n' "$launcher" "$profile" "$unit" + echo 'No key files or services will be changed. See --help.' + exit 0 +fi + +# Render in memory: preview makes no directories or temporary files. +launcher_text=$( + cat <<'LAUNCHER' +#!/usr/bin/env bash +set -euo pipefail +set +x +export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin" +export AZURE_TOKEN_CREDENTIALS=AzureCliCredential +export AZURE_MCP_COLLECT_TELEMETRY=false +export AZURE_MCP_COLLECT_TELEMETRY_MICROSOFT=false +export AZURE_EXTENSION_USE_DYNAMIC_INSTALL=no +export UV_NO_PROGRESS=1 +for tool in az uvx; do + command -v "$tool" >/dev/null || { printf 'ERROR: missing %s in pilot PATH\n' "$tool" >&2; exit 1; } +done +exec uvx --from msmcp-azure==3.0.0 azmcp server start --transport stdio --mode all \ + --namespace containerapps --namespace group --read-only +LAUNCHER +) +profile_text=$( + cat <&2 + exit 1 + fi + fi +done +for i in "${!paths[@]}"; do + target=${paths[$i]} + if [[ "$mode" == apply ]]; then + umask 077 + mkdir -p "${target%/*}" + if [[ ! -e "$target" ]]; then + ( + set -o noclobber + printf '%s\n' "${texts[$i]}" >"$target" + ) + [[ "$i" != 0 ]] || chmod 700 "$target" + fi + printf 'retained/created: %s\n' "$target" + else + printf '\nPREVIEW %s\n%s\n' "$target" "${texts[$i]}" + fi +done +echo 'Key activation and service start are separate manual steps; see docs/ops/azure-mcp-pilot.md.' diff --git a/docs/ops/azure-mcp-pilot.md b/docs/ops/azure-mcp-pilot.md new file mode 100644 index 0000000..5118615 --- /dev/null +++ b/docs/ops/azure-mcp-pilot.md @@ -0,0 +1,131 @@ +# Azure MCP + ChatGPT Secure MCP Tunnel: piloto WSL2 opt-in + +Receta pequeña para PC-IXATU-09, independiente de Desktop Commander. Ejecutar +manualmente desde el checkout; no se instala ni registra en Cursor/Codex, +Chezmoi o el MANIFEST global. `dotfiles-update` solo reporta versiones del piloto +si está presente. No requiere abrir Cursor. + +## Preparación y preview + +Provisionar por separado `az`, `uvx` y `~/.local/bin/tunnel-client`. No hay +instaladores, update checks ni login dentro de esta receta. Azure MCP se obtiene +con `uvx --from msmcp-azure==3.0.0`; el primer arranque puede descargar el paquete. +El tunnel-client existente no se actualiza: su versión y compatibilidad deben +verificarse manualmente en PC09 antes de activar. + +Crear **un túnel y runtime key nuevos para PC09** en ChatGPT Secure MCP Tunnel. +No copiar ni reutilizar el ID, perfil, runtime.env o credenciales de PC08 sin +autorización explícita. El ID es identificador; la runtime key es un secreto +distinto. No pasar la clave por argumentos CLI, chat o archivos del repo. + +```bash +bin/dotfiles-azure-mcp-pilot # resumen, sin escribir +bin/dotfiles-azure-mcp-pilot tunnel_REPLACE # preview completa +bin/dotfiles-azure-mcp-pilot --apply tunnel_REPLACE +``` + +`--apply` crea únicamente los archivos ausentes que muestra la preview: + +- `~/.local/share/ixatu-azure-mcp-pilot/start.sh` (0700) +- `~/.config/tunnel-client/ixatu-azure-mcp-pilot.yaml` (0600) +- `~/.config/systemd/user/ixatu-azure-mcp-pilot.service` (0600) + +Repetir con el mismo ID conserva archivos idénticos; cualquier diferencia se +rechaza antes de escribir. No sobreescribe archivos ajenos ni credenciales, +ni inicia/recarga servicios. Rechaza symlinks en las rutas del piloto. HOME debe +ser absoluto y usar letras, dígitos, `_`, `.`, `/` o `-` (sin espacios ni `%`). + +## Activación humana de la clave y del servicio + +En una terminal Bash local, sin tracing (`set +x`), introducir la runtime key con +entrada oculta. Este bloque se niega a reemplazar un runtime.env existente; +si existe, conservarlo y revisar su procedencia manualmente. No ejecutar el +bloque sobre rutas con symlinks. No guardar la clave en historial ni capturas. + +```bash +set +x +umask 077 +mkdir -p "$HOME/.config/ixatu-azure-mcp-pilot" +read -r -s -p 'PC09 runtime key: ' pilot_key; printf '\n' +if [[ -n "$pilot_key" && "$pilot_key" =~ ^[A-Za-z0-9_./+=:-]+$ ]]; then + (set -o noclobber + printf 'AZURE_MCP_CONTROL_PLANE_API_KEY=%s\n' "$pilot_key" > "$HOME/.config/ixatu-azure-mcp-pilot/runtime.env") +else + printf 'Clave vacía/formato inesperado; no se ha escrito.\n' >&2 +fi +unset pilot_key +``` + +El archivo recién creado tiene modo 0600 por `umask 077`. El perfil referencia +`env:AZURE_MCP_CONTROL_PLANE_API_KEY`; systemd carga el archivo dedicado mediante +`EnvironmentFile=%h/.config/ixatu-azure-mcp-pilot/runtime.env`. No se usa SOPS ni +el entorno de Desktop Commander. No hacer `cat`, `source` o commit de ese archivo. + +Antes de iniciar, comprobar manualmente la sesión CLI y sus permisos DEV en +PC09. Autenticación CLI ya preparada es prerrequisito; el script no ejecuta +`az login`, no cambia suscripciones y no consulta Azure. La identidad debe tener +acceso limitado a DEV: namespaces y `--read-only` **no son una frontera DEV/PROD**. +No activar con permisos PROD amplios. + +```bash +systemctl --user daemon-reload +systemctl --user start ixatu-azure-mcp-pilot.service +bin/dotfiles-azure-mcp-pilot --doctor # --status es alias; sin cambios +# Opcional, solo tras validar: +systemctl --user enable ixatu-azure-mcp-pilot.service +``` + +El doctor verifica herramientas, presencia de archivos, propietario/modo/tamaño +de runtime.env y HTTP en `127.0.0.1:49188/readyz`; nunca lee la clave ni invoca +Azure/uvx/tunnel-client. Sale distinto de cero si falta algo. Un HTTP OK no prueba +la autenticación Azure ni el catálogo MCP. Validar en ChatGPT que `tools/list` +contenga exactamente `containerapps_list`, `group_list`, `group_resource_list`, +y hacer una consulta DEV de lectura antes de dar por válido el piloto. La receta +reproduce `--transport stdio --mode all --namespace containerapps --namespace group +--read-only` de 3.0.0; no añadir namespaces ni operaciones. Si el catálogo difiere, +parar el piloto y revisar antes de usarlo. + +## Diagnóstico y parada + +### Versiones en dotfiles-update + +La sección `tools` lee el pin de +`~/.local/share/ixatu-azure-mcp-pilot/start.sh` y consulta el JSON de PyPI para +`msmcp-azure` (con timeouts de conexión/total de 5/15 segundos). Solo considera +versiones finales `x.y.z` con archivos no retirados; ignora beta/rc/dev. +El snapshot incluye `Azure MCP` con el pin antes/después idéntico, incluso si +PyPI falla o se ejecuta otra sección. `PINNED` representa configuración, no una +comprobación de la versión cargada en un proceso vivo ni de la caché uvx. + +Si aparece una estable posterior, emite `ACTIVATION_PENDING`: revisar manualmente +la compatibilidad, cambiar el pin del launcher dedicado y activar/reiniciar el +piloto en una terminal humana separada. El updater no descarga/ejecuta uvx, no +escribe el launcher ni modifica servicios, autenticación o túneles. `--apply` +de la receta seguirá rechazando un launcher con un pin distinto del generado. +Sin piloto: `SKIP`; sin versión remota válida: `WARN` y pin conservado. En mock +no hay consulta de red. Tunnel Client conserva su reporte separado existente. + +### Operación local + +PATH fijo en systemd y launcher: `$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin`. +Evita el 401 «Azure CLI not installed» cuando `az` viene de pipx en `.local/bin`. +Se fija `AZURE_TOKEN_CREDENTIALS=AzureCliCredential` para evitar intentos de broker +sin X/MSAL antes de CLI ([autenticación Microsoft](https://github.com/microsoft/mcp/blob/main/docs/Authentication.md)). +`AZURE_MCP_COLLECT_TELEMETRY=false` desactiva toda telemetría; también se desactiva +la de Microsoft explícitamente ([referencia Microsoft](https://github.com/microsoft/mcp/blob/main/servers/Azure.Mcp.Server/README.md)). + +El perfil usa `log.level: warn` para evitar ruido de polling. Para depurar, +cambiar **solo el perfil local dedicado** a `debug`, reiniciar este servicio, +inspeccionar logs localmente y volver a `warn`. Los logs debug pueden contener +datos sensibles; no compartirlos sin revisión. `--apply` rechazará el perfil +modificado hasta restaurar su contenido original. + +```bash +systemctl --user restart ixatu-azure-mcp-pilot.service +systemctl --user stop ixatu-azure-mcp-pilot.service +# Si se habilitó inicio automático: +systemctl --user disable ixatu-azure-mcp-pilot.service +``` + +No tocar servicios, perfiles ni puerto 49187 de Desktop Commander. Esta receta +no transfiere credenciales, crea recursos Azure ni valida remotamente producción. diff --git a/docs/ops/azure-tooling.md b/docs/ops/azure-tooling.md index 86d7276..5b4e60e 100644 --- a/docs/ops/azure-tooling.md +++ b/docs/ops/azure-tooling.md @@ -2,6 +2,9 @@ Esta guía describe la integración mínima de Azure tooling en `dotfiles` para trabajar desde Windows 11 Pro + WSL2 sin mezclar configuración local con despliegues reales. +Piloto opcional ChatGPT: [Azure MCP + Secure MCP Tunnel en PC09](azure-mcp-pilot.md) +(preview, generación explícita y doctor; separado del MANIFEST global). + ## Objetivo `dotfiles` prepara herramientas generales, aliases, checks y setup local. No crea recursos Azure, no guarda credenciales y no contiene nombres reales de recursos para proyectos. diff --git a/scripts/update/lib/azure_mcp.sh b/scripts/update/lib/azure_mcp.sh new file mode 100644 index 0000000..4f4b6af --- /dev/null +++ b/scripts/update/lib/azure_mcp.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Report the opt-in uvx launcher pin; never execute or activate the package. +azure_mcp_version() { + local launcher="$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" + [[ -r "$launcher" ]] || return 0 + sed -nE 's@^exec ([^[:space:]]*/)?uvx[[:space:]]+--from[[:space:]]+msmcp-azure==([0-9]+\.[0-9]+\.[0-9]+)([[:space:]].*)?$@\2@p' "$launcher" 2>/dev/null || true +} + +azure_mcp_snapshot() { + [[ -f "$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" ]] || return 0 + local current + current="$(azure_mcp_version)" + tool_snapshot_has "Azure MCP" || tool_snapshot_add "Azure MCP" "$current" "$current" +} + +azure_mcp_latest() { + # Only non-yanked, final x.y.z releases with distribution files qualify. + curl --fail --silent --show-error --connect-timeout 5 --max-time 15 --retry 0 \ + https://pypi.org/pypi/msmcp-azure/json 2>/dev/null | + python3 -c ' +import json, re, sys +try: + releases = json.load(sys.stdin)["releases"] + stable = [v for v, files in releases.items() + if re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", v) + and any(not f.get("yanked", False) for f in files)] + print(max(stable, key=lambda v: tuple(map(int, v.split("."))))) +except (ValueError, KeyError, TypeError, AttributeError): + sys.exit(1) +' 2>/dev/null +} + +update_azure_mcp() { + local current latest + azure_mcp_snapshot + if [[ ! -f "$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" ]]; then + result_skip "WSL" "Azure MCP" "Optional managed pilot absent; no changes made" + return 0 + fi + current="$(azure_mcp_version)" + if is_truthy "${DOTFILES_UPDATE_MOCK:-}"; then + result_skip "WSL" "Azure MCP" "PINNED ${current:-unknown}; latest stable not checked (mock)" + elif [[ ! "$current" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + result_warn "WSL" "Azure MCP" "Launcher pin unavailable; latest stable unknown; no changes made" + elif ! latest="$(azure_mcp_latest)" || [[ ! "$latest" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + result_warn "WSL" "Azure MCP" "PINNED $current; latest stable unknown (PyPI unavailable); unchanged" + elif [[ "$latest" != "$current" && "$(printf '%s\n%s\n' "$latest" "$current" | sort -V | tail -n 1)" == "$latest" ]]; then + result_warn "WSL" "Azure MCP" "PINNED $current; latest stable $latest; ACTIVATION_PENDING: human review/update of dedicated launcher pin and separate pilot restart required (not performed)" + else + result_info "WSL" "Azure MCP" "PINNED $current; latest stable $latest; unchanged" + fi +} diff --git a/scripts/update/update-wsl.sh b/scripts/update/update-wsl.sh index 8242781..ba6e8b1 100755 --- a/scripts/update/update-wsl.sh +++ b/scripts/update/update-wsl.sh @@ -13,6 +13,8 @@ source "${SCRIPT_DIR}/lib/results.sh" source "${SCRIPT_DIR}/lib/logging.sh" # shellcheck source=scripts/update/lib/dc_local.sh source "${SCRIPT_DIR}/lib/dc_local.sh" +# shellcheck source=scripts/update/lib/azure_mcp.sh +source "${SCRIPT_DIR}/lib/azure_mcp.sh" SECTION="all" if [[ "${1:-}" == "--section" ]]; then @@ -546,6 +548,7 @@ capture_workstation_snapshot() { snapshot_current_tool "Claude Code CLI" claude --version snapshot_current_tool "Cursor Agent CLI" agent --version dc_snapshot + azure_mcp_snapshot } ingest_agent_tools_results() { @@ -775,6 +778,7 @@ run_services() { want_section apt && run_apt want_section tools && run_tools want_section tools && ! is_truthy "${DOTFILES_UPDATE_MOCK:-}" && update_dc_local +want_section tools && update_azure_mcp want_section tools && run_opencode want_section tools && run_cursor_agent want_section tools && run_ai_workspace diff --git a/tests/Makefile.tests b/tests/Makefile.tests index a4b8ffe..bdd64f1 100644 --- a/tests/Makefile.tests +++ b/tests/Makefile.tests @@ -463,6 +463,8 @@ bats-system: bats-zsh @$(call run_bats,$(BATS_DIR)/system/excalidraw-docker.bats) @$(call run_bats,$(BATS_DIR)/system/dry-run-guard.bats) @$(call run_bats,$(BATS_DIR)/system/azure-tools.bats) + @$(call run_bats,$(BATS_DIR)/system/azure-mcp-pilot.bats) + @$(call run_bats,$(BATS_DIR)/system/azure-mcp-update.bats) @$(call run_bats,$(BATS_DIR)/system/ai-cursor-check.bats) @$(call run_bats,$(BATS_DIR)/system/secrets-check.bats) @$(call run_bats,$(BATS_DIR)/system/mcp-manifest.bats) @@ -532,6 +534,8 @@ test-ci: test-lint test-bats-ci test-chezmoi @echo "$(GREEN)==>$(NC) CI tests completed" test-bats-ci: bats-dc-activate bats-helpers bats-filesystem bats-chezmoi-mcp-launchers bats-mcp-launcher-contract bats-git bats-governance bats-chezmoi bats-skills bats-git-flow bats-gitnexus bats-git-hooks bats-docs + @$(call run_bats,$(BATS_DIR)/system/azure-mcp-pilot.bats) + @$(call run_bats,$(BATS_DIR)/system/azure-mcp-update.bats) # ============================================ # Combined tests diff --git a/tests/bats/system/azure-mcp-pilot.bats b/tests/bats/system/azure-mcp-pilot.bats new file mode 100644 index 0000000..9fb074c --- /dev/null +++ b/tests/bats/system/azure-mcp-pilot.bats @@ -0,0 +1,155 @@ +#!/usr/bin/env bats + +setup() { + bats_require_minimum_version 1.5.0 + REPO="$(cd "$BATS_TEST_DIRNAME/../../.." && pwd)" + CLI="$REPO/bin/dotfiles-azure-mcp-pilot" + export HOME="$BATS_TEST_TMPDIR/home" + mkdir -p "$HOME/.local/bin" + export PILOT_CALLS="$BATS_TEST_TMPDIR/calls" + for tool in az uvx tunnel-client curl systemctl; do + cat >"$HOME/.local/bin/$tool" <<'MOCK' +#!/usr/bin/env bash +printf '%s %s\n' "${0##*/}" "$*" >> "$PILOT_CALLS" +if [[ "${0##*/}" == uvx ]]; then + printf '%s\n' "$PATH" "$AZURE_TOKEN_CREDENTIALS" "$AZURE_MCP_COLLECT_TELEMETRY" >> "$PILOT_CALLS" +fi +MOCK + chmod +x "$HOME/.local/bin/$tool" + done + LAUNCHER="$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" + PROFILE="$HOME/.config/tunnel-client/ixatu-azure-mcp-pilot.yaml" + UNIT="$HOME/.config/systemd/user/ixatu-azure-mcp-pilot.service" + KEY="$HOME/.config/ixatu-azure-mcp-pilot/runtime.env" +} + +@test "default and explicit previews are read-only and do not execute tools" { + for flags in '' '--check' '--dry-run'; do + read -r -a flag_args <<<"$flags" + run "$CLI" "${flag_args[@]}" tunnel_pc09 + [ "$status" -eq 0 ] + [[ "$output" == *PREVIEW* ]] + done + [ ! -e "$HOME/.config" ] + [ ! -e "$HOME/.local/share" ] + [ ! -e "$PILOT_CALLS" ] +} + +@test "apply is idempotent, isolated and does not create a secret or start service" { + mkdir -p "$HOME/.config/tunnel-client" + printf 'DC sentinel\n' >"$HOME/.config/tunnel-client/default.yaml" + run "$CLI" --apply tunnel_pc09 + [ "$status" -eq 0 ] + local before + before="$(sha256sum "$LAUNCHER" "$PROFILE" "$UNIT")" + run "$CLI" --apply tunnel_pc09 + [ "$status" -eq 0 ] + [ "$before" = "$(sha256sum "$LAUNCHER" "$PROFILE" "$UNIT")" ] + [ "$(cat "$HOME/.config/tunnel-client/default.yaml")" = 'DC sentinel' ] + [ ! -e "$KEY" ] + [ ! -e "$PILOT_CALLS" ] + [ "$(stat -c %a "$PROFILE")" = 600 ] + [ "$(stat -c %a "$LAUNCHER")" = 700 ] + [ "$(find "$HOME/.config" -type f | wc -l)" -eq 3 ] +} + +@test "launcher pins stable package, CLI auth, safe PATH and read-only namespaces" { + run "$CLI" --apply tunnel_pc09 + [ "$status" -eq 0 ] + run env PATH=/usr/bin:/bin "$LAUNCHER" + [ "$status" -eq 0 ] + grep -Fxq 'uvx --from msmcp-azure==3.0.0 azmcp server start --transport stdio --mode all --namespace containerapps --namespace group --read-only' "$PILOT_CALLS" + grep -Fxq "$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin" "$PILOT_CALLS" + grep -Fxq AzureCliCredential "$PILOT_CALLS" + grep -Fxq false "$PILOT_CALLS" + grep -Fq 'Environment="PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin"' "$UNIT" + grep -Fq 'api_key: "env:AZURE_MCP_CONTROL_PLANE_API_KEY"' "$PROFILE" + grep -Fq 'level: warn' "$PROFILE" + grep -Fq '127.0.0.1:49188' "$PROFILE" + run ! grep -Eq '@latest|beta|49187|desktop-commander|/home/jesus' "$PROFILE" "$UNIT" "$LAUNCHER" +} + +@test "doctor uses metadata only, never executes az or uvx, and probes only pilot health" { + run "$CLI" --apply tunnel_pc09 + [ "$status" -eq 0 ] + mkdir -p "${KEY%/*}" + printf 'do-not-source; touch %s/leaked\n' "$HOME" >"$KEY" + chmod 600 "$KEY" + local before + before="$(sha256sum "$KEY" "$LAUNCHER" "$PROFILE" "$UNIT")" + run "$CLI" --doctor + [ "$status" -eq 0 ] + [[ "$output" != *do-not-source* ]] + [ ! -e "$HOME/leaked" ] + [ "$before" = "$(sha256sum "$KEY" "$LAUNCHER" "$PROFILE" "$UNIT")" ] + grep -Fq 'http://127.0.0.1:49188/readyz' "$PILOT_CALLS" + run ! grep -Eq '^(az|uvx|systemctl|tunnel-client) ' "$PILOT_CALLS" + chmod 644 "$KEY" + run "$CLI" --status + [ "$status" -ne 0 ] + [[ "$output" == *unsafe* ]] +} + +@test "missing tooling fails actionably without writes or network" { + for tool in az uvx tunnel-client; do + mv "$HOME/.local/bin/$tool" "$HOME/.local/bin/$tool.saved" + # OS installations may satisfy az/uvx; hide them with an explicit failing executable check below. + if ! PATH=/usr/local/bin:/usr/bin:/bin command -v "$tool" >/dev/null; then + run "$CLI" --apply tunnel_pc09 + [ "$status" -ne 0 ] + [[ "$output" == *missing*"$tool"* ]] + fi + mv "$HOME/.local/bin/$tool.saved" "$HOME/.local/bin/$tool" + done + [ ! -e "$HOME/.config" ] + [ ! -e "$PILOT_CALLS" ] +} + +@test "conflicts, symlinks, different IDs and CLI keys never overwrite files" { + mkdir -p "${UNIT%/*}" + printf unrelated >"$UNIT" + run "$CLI" --apply tunnel_pc09 + [ "$status" -ne 0 ] + [ "$(cat "$UNIT")" = unrelated ] + [ ! -e "$LAUNCHER" ] + rm "$UNIT" + run "$CLI" --apply tunnel_pc09 + [ "$status" -eq 0 ] + run "$CLI" --apply tunnel_other + [ "$status" -ne 0 ] + run "$CLI" --runtime-key secret-canary + [ "$status" -ne 0 ] + [[ "$output" != *secret-canary* ]] + mkdir -p "${KEY%/*}" + ln -s "$BATS_TEST_TMPDIR/unrelated" "$KEY" + run "$CLI" --apply tunnel_pc09 + [ "$status" -ne 0 ] + [ ! -e "$BATS_TEST_TMPDIR/unrelated" ] +} + +@test "conflicting modes cannot turn a requested preview into apply" { + for flags in '--check --apply' '--apply --dry-run' '--status --apply'; do + read -r -a flag_args <<<"$flags" + run "$CLI" "${flag_args[@]}" tunnel_pc09 + [ "$status" -ne 0 ] + done + [ ! -e "$HOME/.config" ] +} + +@test "apply preserves an existing runtime key and doctor fails unavailable health" { + mkdir -p "${KEY%/*}" + printf 'test-secret-canary\n' >"$KEY" + chmod 600 "$KEY" + local before + before="$(sha256sum "$KEY")" + run "$CLI" --apply tunnel_pc09 + [ "$status" -eq 0 ] + [[ "$output" != *test-secret-canary* ]] + [ "$before" = "$(sha256sum "$KEY")" ] + run ! grep -q test-secret-canary "$PROFILE" "$UNIT" "$LAUNCHER" + printf '#!/bin/sh\nexit 1\n' >"$HOME/.local/bin/curl" + run "$CLI" --status + [ "$status" -ne 0 ] + [[ "$output" == *'readyz: unavailable'* ]] + [[ "$output" != *test-secret-canary* ]] +} diff --git a/tests/bats/system/azure-mcp-update.bats b/tests/bats/system/azure-mcp-update.bats new file mode 100644 index 0000000..4c72d08 --- /dev/null +++ b/tests/bats/system/azure-mcp-update.bats @@ -0,0 +1,154 @@ +#!/usr/bin/env bats + +setup() { + DOTFILES_DIR="$(cd "$BATS_TEST_DIRNAME/../../.." && pwd)" + export DOTFILES_DIR + export HOME="$BATS_TEST_TMPDIR/home" + export MOCK_BIN="$BATS_TEST_TMPDIR/bin" CALLS="$BATS_TEST_TMPDIR/calls" + export PYPI_JSON="$BATS_TEST_TMPDIR/pypi.json" + export DOTFILES_UPDATE_RUN_DIR="$BATS_TEST_TMPDIR/run" + unset DOTFILES_UPDATE_MOCK + mkdir -p "$HOME/.local/share/ixatu-azure-mcp-pilot" "$MOCK_BIN" + export LAUNCHER="$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" + printf 'exec uvx --from msmcp-azure==3.0.0 azmcp server start --transport stdio\n' >"$LAUNCHER" + printf '{"info":{"version":"4.0.0b1"},"releases":{"3.0.0":[{}],"4.0.0b1":[{}],"5.0.0rc1":[{}],"6.0.0.dev1":[{}],"7.0.0":[{"yanked":true}],"8.0.0":[]}}' >"$PYPI_JSON" + # Restricted PATH: snapshots cannot invoke any workstation CLI. + for cmd in bash mkdir dirname sed awk head tr sort tail date python3 cat; do + ln -s "$(command -v "$cmd")" "$MOCK_BIN/$cmd" + done + cat >"$MOCK_BIN/curl" <<'CURL' +#!/usr/bin/env bash +printf 'curl %s\n' "$*" >> "$CALLS" +[[ "${CURL_FAIL:-0}" == 0 ]] || { echo private-network-error >&2; exit 28; } +cat "$PYPI_JSON" +CURL + for cmd in uvx uv systemctl tunnel-client; do + cat >"$MOCK_BIN/$cmd" <<'GUARD' +#!/usr/bin/env bash +printf 'FORBIDDEN %s\n' "$0 $*" >> "$CALLS" +exit 99 +GUARD + done + chmod +x "$MOCK_BIN/curl" "$MOCK_BIN/uvx" "$MOCK_BIN/uv" "$MOCK_BIN/systemctl" "$MOCK_BIN/tunnel-client" +} + +report() { + run env PATH="$MOCK_BIN" bash -c ' + set -euo pipefail + source "$DOTFILES_DIR/scripts/update/lib/environment.sh" + source "$DOTFILES_DIR/scripts/update/lib/results.sh" + source "$DOTFILES_DIR/scripts/update/lib/azure_mcp.sh" + tool_snapshot_has() { [[ -f "$TOOL_SNAPSHOT_FILE" ]] && awk -F "\t" '\''$1 == "Azure MCP" {found=1} END {exit !found}'\'' "$TOOL_SNAPSHOT_FILE"; } + result_init "$DOTFILES_UPDATE_RUN_DIR/results.tsv" + tool_snapshot_init "$DOTFILES_UPDATE_RUN_DIR/snapshot.tsv" + update_azure_mcp + azure_mcp_snapshot + cat "$RESULTS_FILE" "$TOOL_SNAPSHOT_FILE" + ' + [ "$status" -eq 0 ] + if [[ -f "$CALLS" ]]; then + ! grep -q FORBIDDEN "$CALLS" + fi +} + +@test "Azure MCP pin and stable latest ignore beta rc dev yanked and empty releases" { + report + [[ "$output" == *'PINNED 3.0.0; latest stable 3.0.0; unchanged'* ]] + [[ "$output" == *$'Azure MCP\t3.0.0\t3.0.0\tunchanged'* ]] + [ "$(grep -c '^Azure MCP' "$DOTFILES_UPDATE_RUN_DIR/snapshot.tsv")" -eq 1 ] + grep -q -- '--connect-timeout 5 --max-time 15 --retry 0 https://pypi.org/pypi/msmcp-azure/json' "$CALLS" +} + +@test "Azure MCP detects original PC08 launcher with an absolute uvx path" { + printf 'exec /home/jesus/.local/bin/uvx --from msmcp-azure==3.0.0 \\\n azmcp server start --read-only\n' >"$LAUNCHER" + report + [[ "$output" == *'PINNED 3.0.0; latest stable 3.0.0; unchanged'* ]] +} + +@test "Azure MCP newer stable reports manual activation without changing launcher" { + printf '{"releases":{"3.9.0":[{}],"3.10.0":[{}],"4.0.0b1":[{}]}}' >"$PYPI_JSON" + cp "$LAUNCHER" "$BATS_TEST_TMPDIR/before" + report + [[ "$output" == *'PINNED 3.0.0; latest stable 3.10.0; ACTIVATION_PENDING'* ]] + [[ "$output" == *$'Azure MCP\t3.0.0\t3.0.0\tunchanged'* ]] + cmp "$LAUNCHER" "$BATS_TEST_TMPDIR/before" +} + +@test "Azure MCP different configured pin is reported and never downgraded" { + sed -i 's/3.0.0/9.1.2/' "$LAUNCHER" + report + [[ "$output" == *'PINNED 9.1.2; latest stable 3.0.0; unchanged'* ]] + [[ "$output" == *$'Azure MCP\t9.1.2\t9.1.2\tunchanged'* ]] +} + +@test "Azure MCP network failure warns gracefully retaining snapshot without raw errors" { + export CURL_FAIL=1 + report + [[ "$output" == *'WARN'*'PINNED 3.0.0; latest stable unknown'* ]] + [[ "$output" != *private-network-error* ]] + [[ "$output" == *$'Azure MCP\t3.0.0\t3.0.0\tunchanged'* ]] +} + +@test "Azure MCP invalid JSON or no stable release yields unknown latest" { + for payload in 'invalid' '{"releases":{"4.0.0b1":[{}]}}' '{"info":{"version":"3.0.0"}}'; do + printf '%s' "$payload" >"$PYPI_JSON" + report + [[ "$output" == *'latest stable unknown'* ]] + done +} + +@test "Azure MCP absent optional pilot skips without network" { + rm "$LAUNCHER" + report + [[ "$output" == *'SKIP'*'Optional managed pilot absent'* ]] + [ ! -e "$CALLS" ] +} + +@test "Azure MCP unrecognized launcher warns without executing or disclosing content" { + printf 'echo private-launcher-content\nexec uvx --from msmcp-azure==4.0.0b1 azmcp server start --transport stdio\n' >"$LAUNCHER" + report + [[ "$output" == *'WARN'*'Launcher pin unavailable'* ]] + [[ "$output" != *private-launcher-content* ]] + [ ! -e "$CALLS" ] +} + +@test "Azure MCP missing curl or Python warns and preserves pin" { + for cmd in curl python3; do + mv "$MOCK_BIN/$cmd" "$BATS_TEST_TMPDIR/$cmd" + report + [[ "$output" == *'WARN'*'PINNED 3.0.0; latest stable unknown'* ]] + mv "$BATS_TEST_TMPDIR/$cmd" "$MOCK_BIN/$cmd" + done +} + +@test "Azure MCP mock reports pin without network" { + export DOTFILES_UPDATE_MOCK=1 + report + [[ "$output" == *'PINNED 3.0.0; latest stable not checked (mock)'* ]] + [ ! -e "$CALLS" ] +} + +@test "Azure MCP mock with unrecognized launcher skips without workstation warnings" { + export DOTFILES_UPDATE_MOCK=1 + printf '# custom launcher\n' >"$LAUNCHER" + report + [[ "$output" == *'SKIP'*'PINNED unknown; latest stable not checked (mock)'* ]] + [[ "$output" != *WARN* ]] + [ ! -e "$CALLS" ] +} + +@test "Azure MCP snapshot integrated outside tools and mock tools never query PyPI" { + # Permit only inert version probes already used by the existing updater. + printf '#!/usr/bin/env bash\nexit 0\n' >"$MOCK_BIN/uv" + for section in none tools; do + run env PATH="$MOCK_BIN" DOTFILES_UPDATE_MOCK=1 bash "$DOTFILES_DIR/scripts/update/update-wsl.sh" --section "$section" + [ "$status" -eq 0 ] + grep -q $'^Azure MCP\t3.0.0\t3.0.0\tunchanged$' "$DOTFILES_UPDATE_RUN_DIR/tool-snapshot.tsv" + [ ! -e "$CALLS" ] + if [[ "$section" == tools ]]; then + grep -q 'latest stable not checked (mock)' "$DOTFILES_UPDATE_RUN_DIR/wsl-results.tsv" + else + ! grep -q 'Azure MCP' "$DOTFILES_UPDATE_RUN_DIR/wsl-results.tsv" + fi + done +}