From 0e7f0d64d3e05239af096a897d22595c5e898ebf Mon Sep 17 00:00:00 2001 From: jesus Date: Wed, 18 Nov 2026 15:23:04 +0100 Subject: [PATCH] feat(update): safely autoactivate compatible DC and Azure MCP releases --- bin/dotfiles-dc-activate | 31 ++- docs/MCP_QUICKREF.md | 9 + docs/UPDATE.md | 43 ++-- docs/ops/azure-mcp-pilot.md | 57 ++++- scripts/update/azure-mcp-activate.py | 266 +++++++++++++++++++++ scripts/update/lib/azure_mcp.sh | 32 ++- scripts/update/lib/dc_local.sh | 23 +- tests/Makefile.tests | 4 +- tests/bats/system/azure-mcp-update.bats | 66 ++++- tests/bats/system/dc-activate.bats | 120 +++++++++- tests/bats/system/mcp-auto-activate.bats | 178 ++++++++++++++ tests/bats/system/update-node-runtime.bats | 2 +- 12 files changed, 780 insertions(+), 51 deletions(-) create mode 100644 scripts/update/azure-mcp-activate.py create mode 100644 tests/bats/system/mcp-auto-activate.bats diff --git a/bin/dotfiles-dc-activate b/bin/dotfiles-dc-activate index f1d863ac..840b2f2f 100755 --- a/bin/dotfiles-dc-activate +++ b/bin/dotfiles-dc-activate @@ -1,9 +1,10 @@ #!/usr/bin/env bash -# Human-only activation. Updaters and agents must never invoke --apply on a live HOME. +# Verified activation; updater mode additionally enforces conservative compatibility. set -euo pipefail umask 077 repo="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)" validator="$repo/scripts/dc/validate.cjs" +updater=0 mode=dry-run version= health_url='http://127.0.0.1:49187/readyz' @@ -16,11 +17,17 @@ Usage: dotfiles-dc-activate [--status|--dry-run|--apply] [VERSION] [--health-url Default: read-only status, or preflight/dry-run when VERSION is supplied. VERSION must be exact stable semver. --apply requires VERSION; default readiness endpoint is http://127.0.0.1:49187/readyz. Health URL must be HTTP loopback without credentials or query parameters. -HUMAN ONLY: invoke --apply from a separate WSL terminal; disconnects the tunnel. -Never invoke --apply from updater/agent sessions. Failed candidates remain staged. +Manual --apply: use a separate WSL terminal; disconnects the tunnel. +--updater-apply: authorized daily updater; compatible versions only. +Failed candidates remain staged. Agents test only with fixtures. HELP exit 0 ;; + --updater-apply) + updater=1 + set -- --apply "${@:2}" + continue + ;; --apply | --dry-run | --status) ((for_arg_mode == 0)) || { echo 'ERROR: conflicting modes' >&2 @@ -69,6 +76,16 @@ if [[ "$version" == "$old" ]]; then exit 0 fi [[ "$(printf '%s\n%s\n' "$version" "$old" | sort -V | tail -n 1)" == "$version" ]] || fail 'version must be newer than active' +if ((updater)); then + [[ "${DOTFILES_MCP_AUTO_ACTIVATE:-1}" != 0 && "${DOTFILES_UPDATE_MOCK:-0}" == 0 ]] || fail 'updater activation disabled' + IFS=. read -r old_major old_minor _ <<<"$old" + IFS=. read -r new_major new_minor _ <<<"$version" + [[ "$old_major" == "$new_major" && ("$old_major" != 0 || "$old_minor" == "$new_minor") ]] || fail 'incompatible updater version' + # A CLI inside this service would be killed by stop; leave it staged instead. + if grep -Fq '/ixatu-wsl-mcp.service' /proc/self/cgroup; then + fail 'caller belongs to DC service; run updater in a separate WSL terminal' + fi +fi stage="$stages/$version" node "$validator" paths "$stage" "$active" node "$validator" stage "$stage" "$version" "$(command -v npm)" @@ -129,7 +146,7 @@ cleanup() { trap '' HUP INT TERM if ((transaction)); then # Do not move a possibly running candidate. Keep both copies if stopping fails. - if systemctl --user stop "$service" >/dev/null 2>&1; then + if timeout 45 systemctl --user stop "$service" >/dev/null 2>&1; then if [[ -d "$backup/node_modules" ]]; then if [[ -d "$active" ]]; then mv -T -- "$active" "$stage" || rc=1; fi if [[ ! -e "$active" ]]; then mv -T -- "$backup" "$active" || rc=1; fi @@ -137,7 +154,7 @@ cleanup() { else echo 'ERROR: rollback stop failed; copies retained for manual recovery' >&2 fi - if systemctl --user start "$service" >/dev/null 2>&1 && ready "$old"; then + if timeout 45 systemctl --user start "$service" >/dev/null 2>&1 && ready "$old"; then echo 'ROLLBACK: previous runtime restored' >&2 else echo 'ERROR: rollback requires manual service recovery; backup retained' >&2 @@ -154,10 +171,10 @@ trap 'exit 129' HUP trap 'exit 130' INT trap 'exit 143' TERM transaction=1 -systemctl --user stop "$service" >/dev/null 2>&1 || fail 'service stop failed' +timeout 45 systemctl --user stop "$service" >/dev/null 2>&1 || fail 'service stop failed' mv -T -- "$active" "$backup" mv -T -- "$stage" "$active" -systemctl --user start "$service" >/dev/null 2>&1 || fail 'service start failed' +timeout 45 systemctl --user start "$service" >/dev/null 2>&1 || fail 'service start failed' ready "$version" || fail 'readiness timed out; rolling back' # Success is committed before best-effort output (e.g. a closed terminal pipe). transaction=0 diff --git a/docs/MCP_QUICKREF.md b/docs/MCP_QUICKREF.md index bd6216bc..7a6bccff 100644 --- a/docs/MCP_QUICKREF.md +++ b/docs/MCP_QUICKREF.md @@ -233,3 +233,12 @@ npx/python/wrapper DSN/credentials/env 4. Run `make ai-mcp-validate`. 5. Regenerate Chezmoi MCP templates when needed: `make ai-mcp-generate APPLY=1` (after governance passes). 6. Run `make ai-mcp-governance` or `bin/validate-mcp-governance` before commit when touching MCP intent or templates. + +## Actualización de los MCP locales IXATU + +`dotfiles-update` activa DC compatible (0.x: mismo minor; 1+: mismo major) y Azure +MCP del mismo major, con preflight y rollback. Ejecutar desde terminal WSL +independiente. `DOTFILES_MCP_AUTO_ACTIVATE=0` desactiva ambas activaciones; +versiones incompatibles quedan pendientes. Tunnel Client sigue siendo manual. +Detalles: [DC](UPDATE.md#ixatu-desktop-commander-local) y +[Azure](ops/azure-mcp-pilot.md#versiones-en-dotfiles-update). diff --git a/docs/UPDATE.md b/docs/UPDATE.md index cd21caa1..6e8a6b17 100644 --- a/docs/UPDATE.md +++ b/docs/UPDATE.md @@ -355,25 +355,31 @@ under `~/.local/share/ixatu-mcp`) and **Tunnel Client** (the executable under `~/.local/bin`) in the `Tool snapshot`. The updater checks npm and GitHub's latest stable release respectively. A newer Desktop Commander is installed with its exact version, npm integrity verification, lockfile, and scripts disabled -into `~/.local/share/ixatu-mcp-staged/` only. The running MCP is never -replaced or restarted: a `STAGED`/`ACTIVATION_PENDING` warning describes the -manual activation command (`dotfiles-dc-activate --apply`). The snapshot continues to report the **active** -installed version, not the staged version. A newer Tunnel Client is reported -as available for separately verified, manual update; the running binary is -never overwritten by the updater. Network failures are warnings, never -reported as successful upgrades. No credentials are needed for these checks. - -#### Explicit activation (human only) - -`dotfiles-dc-activate` is published through the existing Chezmoi symlink -pattern. Before materialization, use `./bin/dotfiles-dc-activate` from the -checkout. The updater never calls activation. Agents must only test with -mocked commands and a temporary HOME; never activate the live tunnel. +into `~/.local/share/ixatu-mcp-staged/`. By default it then invokes +verified activation: DC 0.x accepts only patches within the same minor; DC 1+ +accepts minor/patch updates within the same major. Other versions remain +`PREPARED` / `ACTIVATION_PENDING`. `DOTFILES_MCP_AUTO_ACTIVATE=0` disables automatic +activation of both local MCPs (DC staging and version checks continue). +The snapshot reports the active version after successful activation. Tunnel +Client remains a separate manual, checksum-verified update; its shared binary +is never overwritten. Network/activation failures warn and leave the global +updater running. Activation logs live beside the existing per-run tool logs. + +#### Verified activation + +`dotfiles-dc-activate` is published through the existing Chezmoi symlink pattern; +the updater calls the activator from its own checkout. The explicit internal +`--updater-apply` mode enforces the conservative version policy and opt-out. +Ordinary `--apply` retains its existing manual, verified behavior. +Run the daily updater from an independent WSL terminal. When the caller belongs +to `ixatu-wsl-mcp.service`, automatic DC activation stays pending to avoid killing +the caller before its summary. No detached daemon or background job is added. +Agents exercise mutations only with mocked commands and a temporary HOME. ```bash dotfiles-dc-activate --status # default: read-only active/staged listing dotfiles-dc-activate 0.3.4 # validate staged candidate; dry-run -# HUMAN ONLY, from a separate WSL terminal: interrupts ChatGPT's tunnel. +# Manual activation from a separate WSL terminal: interrupts ChatGPT's tunnel. # Default health URL is http://127.0.0.1:49187/readyz dotfiles-dc-activate 0.3.4 --apply # Optional override if this computer uses a different tunnel port: @@ -401,7 +407,7 @@ ownership. Activation uses same-filesystem directory renames, an exclusive Dry-run/status create no locks, backups or logs. The lock serializes this CLI; do not run the updater or modify staging concurrently with human activation. -Only `--apply` stops the service, moves active to backup, moves staged to +`--apply` and authorized `--updater-apply` stop the service, moves active to backup, moves staged to active, and starts the service. For up to 30 seconds it retries service readiness, active metadata version, a Desktop Commander process under the service's MainPID (including nested descendants, with the active package path @@ -409,7 +415,7 @@ in its command), and HTTP health. The health URL must use literal HTTP loopback, without credentials, queries or fragments. Curl ignores `.curlrc`, bypasses proxies, accepts only HTTP 2xx, does not follow redirects and discards response bodies. Use a read-only `/health` or `/health/control-plane` endpoint; the script never invokes MCP tools or -prints service environment/health bodies. There is no guessed default port. +prints service environment/health bodies. The default is the dedicated DC port 49187; Azure uses 49188 independently. Failure or HUP/INT/TERM triggers rollback: stop the candidate before moving it back to staging, restore the backup and start/check the previous runtime. @@ -426,3 +432,6 @@ systemctl/curl/pgrep); also included in `make test-ci`. The Python CI quality step uses Ruff's correctness rules for the existing Python tree, and initially gates ty and Pyright on the winget log parser; expanding full-repository typing requires resolving older typing diagnostics. + +Azure MCP uses an independent pinned-launcher transaction, including offline MCP +catalog/schema preflight and rollback: [Azure pilot updates](ops/azure-mcp-pilot.md#versiones-en-dotfiles-update). diff --git a/docs/ops/azure-mcp-pilot.md b/docs/ops/azure-mcp-pilot.md index 51186158..05cc268f 100644 --- a/docs/ops/azure-mcp-pilot.md +++ b/docs/ops/azure-mcp-pilot.md @@ -2,8 +2,8 @@ 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. +Chezmoi o el MANIFEST global. `dotfiles-update` mantiene el piloto local existente +cuando está presente y activo (también PC08). No requiere abrir Cursor. ## Preparación y preview @@ -93,17 +93,48 @@ 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. +El snapshot incluye el pin antes/después; tras una activación verificada muestra +la nueva versión. Con versiones iguales no ejecuta uvx ni opera servicios. +`DOTFILES_MCP_AUTO_ACTIVATE=0` conserva solo el reporte (modo mantenimiento/CI). +Mock no consulta red ni ejecuta paquetes o servicios. + +Una estable posterior del mismo major activa por defecto con supervisión humana +en la actualización diaria. Un major distinto queda `ACTIVATION_PENDING`. +El helper `scripts/update/azure-mcp-activate.py`: + +1. Verifica propietario, modo, rutas reales sin symlinks, launcher conocido y + flags exactos: stdio, mode all, namespaces containerapps/group y read-only. + Acepta uvx en PATH o `$HOME/.local/bin/uvx` absoluto. Rechaza otros comandos, + scopes y flags. Adquiere `flock` exclusivo del directorio del piloto. +2. Exige servicio activo y valida el pin actual con initialize + tools/list + offline. Descarga el candidato fijado con `uvx --from msmcp-azure==X.Y.Z` + y `azmcp --help` (180 s máximo), sin cambiar el servicio. +3. Ejecuta el candidato desde caché (`--offline`), initialize + tools/list + (45 s máximo): exactamente `containerapps_list`, `group_list`, + `group_resource_list`, schemas de objeto válidos, sin readOnlyHint falso, + y schemas de entrada/salida idénticos al pin anterior. No hace tools/call. + Un fallo del contrato actual o candidato impide la activación. +4. Reporta `PREPARED`, reemplaza atómicamente solo el texto de la versión, + conservando propietario/grupo/modo y el resto del launcher, y reinicia + exclusivamente `ixatu-azure-mcp-pilot.service`. +5. Confirma servicio activo, pin del launcher y HTTP 2xx en + `127.0.0.1:49188/readyz` durante hasta 30 s. Cada operación systemd tiene + timeout de 45 s. Reporta `INSTALLED/ACTIVATED` o restaura atómicamente el + launcher previo, reinicia y comprueba su readiness: `ROLLBACK`. + +Errores parciales son WARN; el updater continúa. Los logs de activación del run +contienen estados, sin salida del servidor, cuerpos HTTP ni entorno. Si falla +la recuperación, reporta `ROLLBACK FAILED` y requiere recuperación manual del +servicio dedicado. No lee ni modifica perfil, runtime.env o credenciales; no +cambia el tunnel-client compartido, DC ni 49187. Tampoco reinicia si el caller +pertenece al propio servicio Azure. No hay daemon adicional. + +La caché uv del pin anterior debe existir para comprobar el contrato offline. +SIGKILL, pérdida de alimentación o disco no admiten rollback automático: revisar +el pin y servicio antes de reintentar. Las pruebas reales con versiones iguales +solo demuestran no-op; una actualización real compatible sigue pendiente de una +release futura. `--apply` de la receta inicial seguirá rechazando launchers +actualizados distintos del generado; no se usa para mantener instalaciones. ### Operación local diff --git a/scripts/update/azure-mcp-activate.py b/scripts/update/azure-mcp-activate.py new file mode 100644 index 00000000..507fd73b --- /dev/null +++ b/scripts/update/azure-mcp-activate.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +"""Conservative Azure pilot transaction. Never read tunnel profiles or credentials.""" +import contextlib +import fcntl +import json +import os +from pathlib import Path +import re +import selectors +import shlex +import signal +import stat +import subprocess +import sys +import tempfile +import time +import urllib.request + +SERVICE = 'ixatu-azure-mcp-pilot.service' +FLAGS = ['azmcp', 'server', 'start', '--transport', 'stdio', '--mode', 'all', + '--namespace', 'containerapps', '--namespace', 'group', '--read-only'] +TOOLS = {'containerapps_list', 'group_list', 'group_resource_list'} +STABLE = r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)' + + +def require(ok): + if not ok: + raise ValueError('preflight/contract validation failed') + + +def run(args, timeout=45, env=None): + proc = subprocess.Popen(args, env=env, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + try: + code = proc.wait(timeout=timeout) + if code: + raise subprocess.CalledProcessError(code, args) + finally: + if proc.poll() is None: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait(timeout=3) + + +def service(action): + run(['systemctl', '--user', action, SERVICE]) + + +def launcher(path): + home = Path(os.environ['HOME']) + require(home.is_absolute() and home.resolve() == home) + require(path == home / '.local/share/ixatu-azure-mcp-pilot/start.sh') + for item in [path, *path.parents]: + st = item.lstat() + require(not stat.S_ISLNK(st.st_mode)) + if item == home or home in item.parents: + require(st.st_uid == os.getuid() and not st.st_mode & 0o022) + if item == home: + break + st = path.stat() + require(stat.S_ISREG(st.st_mode) and st.st_nlink == 1 and st.st_mode & 0o100) + text = path.read_bytes().decode('utf-8') + require(text.splitlines()[0] in ('#!/usr/bin/env bash', '#!/bin/bash')) + # Accept only the known pilot shell preamble. Never source/evaluate it. + lines = text.replace('\\\n', '').splitlines() + allowed = { + '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', + } + guard = ['for tool in az uvx; do', + 'command -v "$tool" >/dev/null || { printf \'ERROR: missing %s in pilot PATH\\n\' "$tool" >&2; exit 1; }', + 'done'] + commands = [] + i = 0 + while i < len(lines): + line = lines[i].strip() + if line == guard[0]: + require([v.strip() for v in lines[i:i + 3]] == guard) + i += 3 + continue + if line and not line.startswith('#') and line not in allowed: + commands.append(shlex.split(line)) + i += 1 + require(len(commands) == 1) + cmd = commands[0] + require(len(cmd) >= 5 and cmd[0] == 'exec' and cmd[2] == '--from') + require(cmd[1] == 'uvx' or cmd[1] == str(home / '.local/bin/uvx')) + require(re.fullmatch('msmcp-azure==' + STABLE, cmd[3])) + require(cmd[4:] == FLAGS) + require(text.count(cmd[3]) == 1) + return text, st, cmd[1], cmd[3].split('==')[1] + + +def smoke(uvx, version, env): + """MCP newline JSON stdio; bounded buffer/deadline; no tools/call.""" + cmd = [uvx, '--offline', '--from', 'msmcp-azure==' + version, *FLAGS] + proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, env=env, start_new_session=True) + selector = selectors.DefaultSelector() + selector.register(proc.stdout, selectors.EVENT_READ) + buffer = b'' + deadline = time.monotonic() + 45 + + def send(value): + proc.stdin.write(json.dumps(value).encode() + b'\n') + proc.stdin.flush() + + def response(request_id): + nonlocal buffer + while time.monotonic() < deadline: + if b'\n' in buffer: + line, buffer = buffer.split(b'\n', 1) + value = json.loads(line) + if value.get('id') == request_id: + require('error' not in value and 'result' in value) + return value['result'] + continue + if selector.select(max(0, deadline - time.monotonic())): + chunk = os.read(proc.stdout.fileno(), 65536) + require(chunk) + buffer += chunk + require(len(buffer) <= 2_000_000) + raise TimeoutError('MCP timeout') + + try: + send({'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', 'params': { + 'protocolVersion': '2024-11-05', 'capabilities': {}, + 'clientInfo': {'name': 'dotfiles-preflight', 'version': '1'}}}) + initialized = response(1) + require(initialized.get('protocolVersion') == '2024-11-05') + require('tools' in initialized.get('capabilities', {})) + send({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + send({'jsonrpc': '2.0', 'id': 2, 'method': 'tools/list', 'params': {}}) + result = response(2) + tools = result['tools'] + require(not result.get('nextCursor') and len(tools) == 3) + require({tool['name'] for tool in tools} == TOOLS) + schemas = {} + for tool in tools: + schema = tool['inputSchema'] + require(schema.get('type') == 'object') + require(isinstance(schema.get('properties', {}), dict)) + require(isinstance(schema.get('required', []), list)) + require(set(schema.get('required', [])) <= set(schema.get('properties', {}))) + require(tool.get('annotations', {}).get('readOnlyHint', True) is True) + schemas[tool['name']] = (schema, tool.get('outputSchema')) + return schemas + finally: + selector.close() + # Reap the entire uvx/server process group, including startup failures. + try: + os.killpg(proc.pid, signal.SIGTERM) + proc.wait(timeout=3) + except (ProcessLookupError, subprocess.TimeoutExpired): + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + proc.wait(timeout=3) + proc.stdin.close() + proc.stdout.close() + + +def atomic(path, data, metadata): + fd, name = tempfile.mkstemp(prefix='.start-', dir=path.parent) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data.encode()) + os.fchown(stream.fileno(), metadata.st_uid, metadata.st_gid) + os.fchmod(stream.fileno(), stat.S_IMODE(metadata.st_mode)) + stream.flush() + os.fsync(stream.fileno()) + os.replace(name, path) + finally: + if os.path.exists(name): + os.unlink(name) + + +def ready(path, version): + deadline = time.monotonic() + 30 + # A redirect must not turn another endpoint's HTTP 200 into local readiness. + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + while time.monotonic() < deadline: + try: + service('is-active') + require(launcher(path)[3] == version) + with opener.open('http://127.0.0.1:49188/readyz', timeout=1) as reply: + require(200 <= reply.status < 300) + return + except (OSError, ValueError, subprocess.SubprocessError): + time.sleep(1) + raise TimeoutError('readiness timeout') + + +def main(): + require(os.environ.get('DOTFILES_MCP_AUTO_ACTIVATE', '1') != '0') + require(os.environ.get('DOTFILES_UPDATE_MOCK', '0') == '0') + version = sys.argv[1] + require(re.fullmatch(STABLE, version)) + path = Path(os.environ['HOME']) / '.local/share/ixatu-azure-mcp-pilot/start.sh' + text, metadata, uvx, old = launcher(path) + if version == old: + print('UNCHANGED ' + old) + return + current, candidate = tuple(map(int, old.split('.'))), tuple(map(int, version.split('.'))) + require(candidate > current and candidate[0] == current[0]) + # Lock directory inode, no lockfile or symlink opening. Covers entire preflight. + with contextlib.ExitStack() as stack: + lock = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + stack.callback(os.close, lock) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + require(launcher(path)[0] == text) + service('is-active') + require('/' + SERVICE not in Path('/proc/self/cgroup').read_text()) + env = {'HOME': os.environ['HOME'], + 'PATH': os.environ['HOME'] + '/.local/bin:/usr/local/bin:/usr/bin:/bin', + 'UV_NO_CONFIG': '1', 'UV_NO_PROGRESS': '1', + 'AZURE_TOKEN_CREDENTIALS': 'AzureCliCredential', + 'AZURE_MCP_COLLECT_TELEMETRY': 'false', + 'AZURE_MCP_COLLECT_TELEMETRY_MICROSOFT': 'false', + 'AZURE_EXTENSION_USE_DYNAMIC_INSTALL': 'no'} + baseline = smoke(uvx, old, env) + # Warm uv cache before touching the service; all later smoke is offline. + run([uvx, '--from', 'msmcp-azure==' + version, 'azmcp', '--help'], timeout=180, env=env) + require(smoke(uvx, version, env) == baseline) + print('PREPARED ' + version, flush=True) + require(launcher(path)[0] == text) + service('is-active') + try: + atomic(path, text.replace('msmcp-azure==' + old, 'msmcp-azure==' + version), metadata) + service('restart') + ready(path, version) + except BaseException: + for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM): + signal.signal(sig, signal.SIG_IGN) + try: + atomic(path, text, metadata) + service('restart') + ready(path, old) + print('ROLLBACK: previous launcher restored; service ready', flush=True) + except BaseException: + print('ROLLBACK FAILED: manual launcher/service recovery required', flush=True) + raise + print('INSTALLED/ACTIVATED ' + version, flush=True) + + +if __name__ == '__main__': + def interrupted(signum, _frame): + raise InterruptedError('activation interrupted') + + for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM): + signal.signal(sig, interrupted) + try: + main() + except Exception: + # No subprocess/launcher output, Azure data or environment in updater logs. + print('ACTIVATION_PENDING: validation or activation failed; inspect local service status', file=sys.stderr) + sys.exit(1) diff --git a/scripts/update/lib/azure_mcp.sh b/scripts/update/lib/azure_mcp.sh index 4f4b6af4..cbbcdbf8 100644 --- a/scripts/update/lib/azure_mcp.sh +++ b/scripts/update/lib/azure_mcp.sh @@ -1,7 +1,14 @@ #!/usr/bin/env bash -# Report the opt-in uvx launcher pin; never execute or activate the package. +# Opt-in Azure MCP pin, stable release discovery and verified activation. azure_mcp_version() { - local launcher="$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" + local launcher="$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" ancestor + # Version snapshots must not follow a launcher symlink into unrelated Home files. + ancestor="$launcher" + while [[ "$ancestor" != / ]]; do + [[ ! -L "$ancestor" ]] || return 0 + ancestor="${ancestor%/*}" + [[ -n "$ancestor" ]] || break + done [[ -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 } @@ -23,7 +30,7 @@ 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)] + and files and all(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) @@ -31,7 +38,7 @@ except (ValueError, KeyError, TypeError, AttributeError): } update_azure_mcp() { - local current latest + local current latest helper activation_log activation_status 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" @@ -45,7 +52,22 @@ update_azure_mcp() { 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)" + if [[ "${DOTFILES_MCP_AUTO_ACTIVATE:-1}" == 0 || "${current%%.*}" != "${latest%%.*}" ]]; then + result_warn "WSL" "Azure MCP" "PINNED $current; latest stable $latest; ACTIVATION_PENDING (disabled or incompatible)" + else + helper="${DOTFILES_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)}/scripts/update/azure-mcp-activate.py" + activation_log="${LOG_DIR:-$DOTFILES_UPDATE_RUN_DIR}/wsl-azure-mcp-activate.log" + if python3 "$helper" "$latest" >"$activation_log" 2>&1; then + tool_snapshot_add "Azure MCP" "$current" "$(azure_mcp_version)" + result_info "WSL" "Azure MCP" "INSTALLED/ACTIVATED $latest; verified; see activation log" + else + activation_status=ACTIVATION_PENDING + if grep -q 'ROLLBACK FAILED' "$activation_log"; then + activation_status='ROLLBACK FAILED: manual recovery required' + elif grep -q ROLLBACK "$activation_log"; then activation_status=ROLLBACK; fi + result_warn "WSL" "Azure MCP" "PINNED $(azure_mcp_version); $activation_status; see activation log" + fi + fi else result_info "WSL" "Azure MCP" "PINNED $current; latest stable $latest; unchanged" fi diff --git a/scripts/update/lib/dc_local.sh b/scripts/update/lib/dc_local.sh index cb580575..3c580244 100644 --- a/scripts/update/lib/dc_local.sh +++ b/scripts/update/lib/dc_local.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Local IXATU MCP versions; never replace a live service runtime. +# Local IXATU MCP staging and conservative verified activation. dc_local_version() { local file="$HOME/.local/share/ixatu-mcp/node_modules/@wonderwhy-er/desktop-commander/package.json" [[ -f "$file" ]] || return 0 @@ -29,7 +29,11 @@ dc_snapshot() { } update_dc_local() { - local installed latest tunnel_installed tunnel_latest stage tmp candidate + local installed latest tunnel_installed tunnel_latest stage tmp candidate activation_log activation_status + if [[ "${DOTFILES_UPDATE_MOCK:-0}" != 0 ]]; then + result_skip "WSL" "Desktop Commander" "Mock; no package or service operations" + return 0 + fi installed="$(dc_local_version)" tunnel_installed="$(dc_tunnel_version)" dc_snapshot @@ -57,7 +61,20 @@ update_dc_local() { [[ -d "$tmp" ]] && rm -rf "$tmp" fi if [[ -f "$candidate" ]] && [[ "$(node -p "require(process.argv[1]).version" "$candidate" 2>/dev/null)" == "$latest" ]]; then - result_warn "WSL" "Desktop Commander" "STAGED $latest; ACTIVE $installed; ACTIVATION_PENDING; human separate WSL terminal: dotfiles-dc-activate $latest --apply (not performed)" + activation_log="$LOG_DIR/wsl-dc-activate.log" + if [[ "${DOTFILES_MCP_AUTO_ACTIVATE:-1}" != 0 ]] && + "${DOTFILES_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)}/bin/dotfiles-dc-activate" "$latest" --updater-apply >"$activation_log" 2>&1; then + tool_snapshot_add "Desktop Commander" "$installed" "$(dc_local_version)" + result_info "WSL" "Desktop Commander" "INSTALLED/ACTIVATED $latest; verified; see activation log" + else + activation_status=ACTIVATION_PENDING + if [[ "${DOTFILES_MCP_AUTO_ACTIVATE:-1}" != 0 && -f "$activation_log" ]]; then + if grep -q 'manual.*recovery' "$activation_log"; then + activation_status='ROLLBACK FAILED: manual recovery required' + elif grep -q ROLLBACK "$activation_log"; then activation_status=ROLLBACK; fi + fi + result_warn "WSL" "Desktop Commander" "PREPARED $latest; ACTIVE $(dc_local_version); $activation_status; see activation log" + fi fi else result_info "WSL" "Desktop Commander" "Installed $installed; latest stable $latest; unchanged" diff --git a/tests/Makefile.tests b/tests/Makefile.tests index bdd64f1a..18bd58a4 100644 --- a/tests/Makefile.tests +++ b/tests/Makefile.tests @@ -464,7 +464,7 @@ bats-system: bats-zsh @$(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/azure-mcp-update.bats $(BATS_DIR)/system/mcp-auto-activate.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) @@ -535,7 +535,7 @@ test-ci: test-lint test-bats-ci test-chezmoi 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) + @$(call run_bats,$(BATS_DIR)/system/azure-mcp-update.bats $(BATS_DIR)/system/mcp-auto-activate.bats) # ============================================ # Combined tests diff --git a/tests/bats/system/azure-mcp-update.bats b/tests/bats/system/azure-mcp-update.bats index 4c72d082..23e6f24f 100644 --- a/tests/bats/system/azure-mcp-update.bats +++ b/tests/bats/system/azure-mcp-update.bats @@ -8,12 +8,13 @@ setup() { export PYPI_JSON="$BATS_TEST_TMPDIR/pypi.json" export DOTFILES_UPDATE_RUN_DIR="$BATS_TEST_TMPDIR/run" unset DOTFILES_UPDATE_MOCK + export DOTFILES_MCP_AUTO_ACTIVATE=0 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 + for cmd in bash mkdir dirname sed awk head tr sort tail date python3 cat grep; do ln -s "$(command -v "$cmd")" "$MOCK_BIN/$cmd" done cat >"$MOCK_BIN/curl" <<'CURL' @@ -65,7 +66,7 @@ report() { [[ "$output" == *'PINNED 3.0.0; latest stable 3.0.0; unchanged'* ]] } -@test "Azure MCP newer stable reports manual activation without changing launcher" { +@test "Azure MCP maintenance opt-out reports pending without changing launcher" { printf '{"releases":{"3.9.0":[{}],"3.10.0":[{}],"4.0.0b1":[{}]}}' >"$PYPI_JSON" cp "$LAUNCHER" "$BATS_TEST_TMPDIR/before" report @@ -152,3 +153,64 @@ report() { fi done } + +activation_boundary() { + export DOTFILES_MCP_AUTO_ACTIVATE=1 DOTFILES_ROOT="$BATS_TEST_TMPDIR/checkout" + mkdir -p "$DOTFILES_ROOT/scripts/update" + cat >"$DOTFILES_ROOT/scripts/update/azure-mcp-activate.py" <<'PY' +import os, pathlib, sys +p = pathlib.Path(os.environ['LAUNCHER']) +assert sys.argv[1] == '3.1.0' +if os.environ.get('ACTIVATION_FAIL'): + print('ROLLBACK: previous launcher restored; service ready') + sys.exit(1) +p.write_text(p.read_text().replace('3.0.0', sys.argv[1])) +print('INSTALLED/ACTIVATED ' + sys.argv[1]) +PY + printf '{"releases":{"3.1.0":[{}]}}' >"$PYPI_JSON" +} + +@test "Azure updater default activation boundary updates pin and final snapshot" { + activation_boundary + report + [[ "$output" == *'INSTALLED/ACTIVATED 3.1.0'* ]] + grep -q $'^Azure MCP\t3.0.0\t3.1.0\tupdated$' "$DOTFILES_UPDATE_RUN_DIR/snapshot.tsv" +} + +@test "Azure updater rollback warns and continues with previous pin" { + activation_boundary + export ACTIVATION_FAIL=1 + report + [[ "$output" == *ROLLBACK* ]] + [[ "$(cat "$LAUNCHER")" == *3.0.0* ]] +} + +@test "Azure updater major mismatch skips activation even with automation enabled" { + activation_boundary + printf '{"releases":{"4.0.0":[{}]}}' >"$PYPI_JSON" + report + [[ "$output" == *ACTIVATION_PENDING* ]] + [[ "$(cat "$LAUNCHER")" == *3.0.0* ]] +} + +@test "Azure partially yanked release is never an automatic candidate" { + printf '{"releases":{"3.0.0":[{}],"3.1.0":[{}, {"yanked":true}]}}' >"$PYPI_JSON" + report + [[ "$output" == *'latest stable 3.0.0; unchanged'* ]] +} + +@test "Azure pin reader refuses launcher symlink before opening its contents" { + mv "$LAUNCHER" "$BATS_TEST_TMPDIR/unrelated" + ln -s "$BATS_TEST_TMPDIR/unrelated" "$LAUNCHER" + report + [[ "$output" == *'Launcher pin unavailable'* ]] + [ ! -e "$CALLS" ] +} + +@test "Azure pin reader refuses symlinked runtime ancestors" { + mv "$HOME/.local/share/ixatu-azure-mcp-pilot" "$BATS_TEST_TMPDIR/unrelated" + ln -s "$BATS_TEST_TMPDIR/unrelated" "$HOME/.local/share/ixatu-azure-mcp-pilot" + report + [[ "$output" == *'Launcher pin unavailable'* ]] + [ ! -e "$CALLS" ] +} diff --git a/tests/bats/system/dc-activate.bats b/tests/bats/system/dc-activate.bats index ba524f47..d34c0c12 100644 --- a/tests/bats/system/dc-activate.bats +++ b/tests/bats/system/dc-activate.bats @@ -41,6 +41,14 @@ printf '%s\n' "$*" >> "$DC_TEST/curl" if [[ -f "$DC_TEST/fail-curl" ]]; then exit 1; fi if [[ -f "$DC_TEST/retry" ]]; then rm "$DC_TEST/retry"; exit 1; fi printf 200 +MOCK + cat >"$BATS_TEST_TMPDIR/bin/grep" <<'MOCK' +#!/usr/bin/env bash +if [[ "${*: -1}" == /proc/self/cgroup ]]; then + [[ "${DC_CALLER_IN_SERVICE:-0}" == 1 ]] +else + exec /usr/bin/grep "$@" +fi MOCK chmod +x "$BATS_TEST_TMPDIR/bin/"* } @@ -77,7 +85,7 @@ assert_old() { @test "activation help and status never mutate or contact service" { run "$CLI" --help [ "$status" -eq 0 ] - [[ "$output" == *'HUMAN ONLY'* ]] + [[ "$output" == *'--updater-apply'* ]] run "$CLI" --status [ "$status" -eq 0 ] [[ "$output" == *'ACTIVE 0.3.3'*'STAGED 0.3.4'* ]] @@ -290,3 +298,113 @@ MOCK [[ "$output" == *DRY-RUN* ]] assert_old } + +@test "updater mode activates compatible patch and is idempotent" { + run "$CLI" 0.3.4 --updater-apply + [ "$status" -eq 0 ] + [[ "$output" == *'ACTIVE 0.3.4'* ]] + run "$CLI" 0.3.4 --updater-apply + [ "$status" -eq 0 ] + [[ "$output" == *'already active'* ]] + [ "$(grep -c stop "$DC_TEST/systemctl")" -eq 1 ] +} + +@test "updater mode refuses zero major minor and major transitions" { + for version in 0.4.0 1.0.0; do + run "$CLI" "$version" --updater-apply + [ "$status" -ne 0 ] + [[ "$output" == *'incompatible updater version'* ]] + done + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "updater mode opt-out and mock prevent service mutation" { + for flag in DOTFILES_MCP_AUTO_ACTIVATE=0 DOTFILES_UPDATE_MOCK=1; do + run env "$flag" "$CLI" 0.3.4 --updater-apply + [ "$status" -ne 0 ] + [[ "$output" == *'disabled'* ]] + done + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "updater mode rolls back failed restart with service isolation" { + touch "$DC_TEST/fail-start" + run "$CLI" 0.3.4 --updater-apply + [ "$status" -ne 0 ] + [[ "$output" == *ROLLBACK* ]] + run ! grep -Eq 'azure|49188' "$DC_TEST/systemctl" "$DC_TEST/curl" + assert_old +} + +dc_updater() { + local latest="$1" + local semver + semver="$(node -e 'const fs=require("fs"),m=require("module"); console.log(require("path").dirname(m.createRequire(fs.realpathSync(process.argv[1])).resolve("semver/package.json")))' "$(command -v npm)")" + mkdir -p "$BATS_TEST_TMPDIR/bin/node_modules" + ln -s "$semver" "$BATS_TEST_TMPDIR/bin/node_modules/semver" + cat >"$BATS_TEST_TMPDIR/bin/npm" <<'MOCK' +#!/usr/bin/env bash +[[ "$1" == view ]] || { echo FORBIDDEN-package-operation >&2; exit 99; } +printf '%s\n' "$LATEST" +MOCK + chmod +x "$BATS_TEST_TMPDIR/bin/npm" + run env LATEST="$latest" DOTFILES_ROOT="$REPO" LOG_DIR="$DC_TEST" bash -c ' + set -euo pipefail + source "$DOTFILES_ROOT/scripts/update/lib/dc_local.sh" + result_info() { echo "$*"; } + result_warn() { echo "$*"; } + result_skip() { echo "$*"; } + tool_snapshot_has() { return 0; } + tool_snapshot_add() { echo "snapshot $*"; } + update_dc_local + ' + [ "$status" -eq 0 ] + [[ "$output" != *FORBIDDEN* ]] +} + +@test "DC updater invokes verified activation and records new active snapshot" { + dc_updater 0.3.4 + [[ "$output" == *'INSTALLED/ACTIVATED 0.3.4'* ]] + [[ "$output" == *'snapshot Desktop Commander 0.3.3 0.3.4'* ]] + run ! grep -q azure "$DC_TEST/systemctl" +} + +@test "DC updater equal stable version never invokes services or package install" { + dc_updater 0.3.3 + [[ "$output" == *unchanged* ]] + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "DC updater failure warns without aborting and old runtime is ready" { + touch "$DC_TEST/fail-start" + dc_updater 0.3.4 + [[ "$output" == *ROLLBACK* ]] + assert_old +} + +@test "DC updater incompatible version remains staged without restart" { + fixture "$HOME/.local/share/ixatu-mcp-staged/0.4.0" 0.4.0 + dc_updater 0.4.0 + [[ "$output" == *ACTIVATION_PENDING* ]] + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "DC updater inside live service leaves candidate pending without killing caller" { + run env DC_CALLER_IN_SERVICE=1 "$CLI" 0.3.4 --updater-apply + [ "$status" -ne 0 ] + [[ "$output" == *'caller belongs to DC service'* ]] + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "DC stable major permits compatible minor updates" { + fixture "$ACTIVE" 1.1.0 + fixture "$HOME/.local/share/ixatu-mcp-staged/1.2.0" 1.2.0 + run "$CLI" 1.2.0 --updater-apply + [ "$status" -eq 0 ] + [[ "$output" == *'ACTIVE 1.2.0'* ]] +} diff --git a/tests/bats/system/mcp-auto-activate.bats b/tests/bats/system/mcp-auto-activate.bats new file mode 100644 index 00000000..a03ee8ec --- /dev/null +++ b/tests/bats/system/mcp-auto-activate.bats @@ -0,0 +1,178 @@ +#!/usr/bin/env bats + +setup() { + umask 077 + REPO="$(cd "$BATS_TEST_DIRNAME/../../.." && pwd)" + export REPO + export HOME="$BATS_TEST_TMPDIR/home" + mkdir -p "$HOME/.local/share/ixatu-azure-mcp-pilot" + chmod 700 "$HOME" + export LAUNCHER="$HOME/.local/share/ixatu-azure-mcp-pilot/start.sh" + cat >"$LAUNCHER" <<'LAUNCHER' +#!/usr/bin/env bash +set -euo pipefail +export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin" +export AZURE_TOKEN_CREDENTIALS=AzureCliCredential +exec uvx --from msmcp-azure==3.0.0 \ + azmcp server start --transport stdio --mode all \ + --namespace containerapps --namespace group --read-only +LAUNCHER + chmod 700 "$LAUNCHER" + unset DOTFILES_UPDATE_MOCK DOTFILES_MCP_AUTO_ACTIVATE +} + +lifecycle() { + run python3 - "$1" <<'PY' +import importlib.util, os, pathlib, sys +from unittest.mock import patch +spec = importlib.util.spec_from_file_location('activate', os.environ['REPO'] + '/scripts/update/azure-mcp-activate.py') +a = importlib.util.module_from_spec(spec) +spec.loader.exec_module(a) +case = sys.argv[1] +p = pathlib.Path(os.environ['LAUNCHER']) +old = p.read_bytes() +mode = p.stat().st_mode +calls = [] +# Fail closed if this transaction ever tries to open a profile/credential path. +def audit(event, args): + if event == 'open' and isinstance(args[0], (str, bytes)): + name = os.fsdecode(args[0]) + assert '/.config/' not in name and not name.endswith('runtime.env'), name +sys.addaudithook(audit) + +def svc(action): + calls.append(action) + assert a.SERVICE == 'ixatu-azure-mcp-pilot.service' + if case == 'inactive' or (case == 'rollback' and action == 'restart' and calls.count('restart') == 1): + raise RuntimeError('mock service failure') + +def smoke(uvx, version, env): + calls.append('smoke:' + version) + assert env['UV_NO_CONFIG'] == '1' + assert not any('KEY' in k or 'SECRET' in k for k in env) + if case == 'invalid-baseline': + raise ValueError('unsafe baseline') + if case == 'invalid-contract' and version != '3.0.0': + return {'schemas': 'changed'} + return {'schemas': 'same'} + +def warm(args, **kwargs): + calls.append('download') + assert pathlib.Path(args[0]).name == 'uvx' + assert args[1:] == ['--from', 'msmcp-azure==3.1.0', 'azmcp', '--help'] + assert kwargs['timeout'] == 180 + if case == 'download-failure': + raise RuntimeError('mock download failure') + +def ready(path, version): + calls.append('ready:' + version) + assert a.launcher(path)[3] == version + if case == 'postflight-failure' and version != '3.0.0': + raise ValueError('mock health failure') + +version = '3.0.0' if case == 'noop' else '4.0.0' if case == 'major' else '3.1.0' +if case == 'symlink': + p.rename(p.with_name('original')) + p.symlink_to(p.with_name('original')) +if case == 'scope': + p.write_text(p.read_text().replace('--namespace group', '--namespace subscription')) + old = p.read_bytes() +if case == 'unexpected': + p.write_text('echo arbitrary-command\n' + p.read_text()) + old = p.read_bytes() +if case == 'absolute': + p.write_text(p.read_text().replace('exec uvx', 'exec ' + os.environ['HOME'] + '/.local/bin/uvx')) + old = p.read_bytes() +if case == 'optout': + os.environ['DOTFILES_MCP_AUTO_ACTIVATE'] = '0' +if case == 'mock': + os.environ['DOTFILES_UPDATE_MOCK'] = '1' +if case == 'lock': + lock = os.open(p.parent, os.O_RDONLY) + a.fcntl.flock(lock, a.fcntl.LOCK_EX | a.fcntl.LOCK_NB) +failed = False +with patch.object(a, 'service', svc), patch.object(a, 'run', warm), patch.object(a, 'smoke', smoke), patch.object(a, 'ready', ready), patch.object(sys, 'argv', ['activate', version]): + try: + a.main() + except Exception: + import traceback + traceback.print_exc() + failed = True +success = case in ('success', 'absolute') +assert failed == (not success and case != 'noop'), (case, calls, failed) +assert p.stat().st_mode == mode +if success: + assert p.read_bytes() == old.replace(b'msmcp-azure==3.0.0', b'msmcp-azure==3.1.0') + assert calls == ['is-active', 'smoke:3.0.0', 'download', 'smoke:3.1.0', 'is-active', 'restart', 'ready:3.1.0'], calls +else: + assert p.read_bytes() == old + if case in ('rollback', 'postflight-failure'): + assert calls.count('restart') == 2 and calls[-1] == 'ready:3.0.0', calls + else: + assert 'restart' not in calls +assert not list(p.parent.glob('.start-*')) +print('PASS', case) +PY + [ "$status" -eq 0 ] + [[ "$output" == *"PASS $1"* ]] +} + +@test "Azure compatible activation preserves launcher text mode and service isolation" { lifecycle success; } +@test "Azure activation accepts absolute uvx path" { lifecycle absolute; } +@test "Azure equal version is a genuine no-op without package or service operations" { lifecycle noop; } +@test "Azure major mismatch never downloads or restarts" { lifecycle major; } +@test "Azure inactive service never downloads or restarts" { lifecycle inactive; } +@test "Azure candidate contract failure retains launcher and live service" { lifecycle invalid-contract; } +@test "Azure failed download retains launcher and live service" { lifecycle download-failure; } +@test "Azure restart failure restores launcher atomically and verifies rollback" { lifecycle rollback; } +@test "Azure readiness failure restores launcher and restarts previous version" { lifecycle postflight-failure; } +@test "Azure rejects symlink launcher" { lifecycle symlink; } +@test "Azure rejects unauthorized namespaces" { lifecycle scope; } +@test "Azure rejects unexpected shell commands" { lifecycle unexpected; } +@test "Azure opt-out prevents package and service operations" { lifecycle optout; } +@test "Azure mock prevents package and service operations" { lifecycle mock; } +@test "Azure concurrent activation lock refuses mutation" { lifecycle lock; } + +@test "Azure MCP stdio verifies initialize and exact tools with object schemas without tools call" { + cat >"$BATS_TEST_TMPDIR/uvx" <<'PY' +#!/usr/bin/env python3 +import json, os, sys +assert sys.argv[1:4] == ['--offline', '--from', 'msmcp-azure==3.1.0'] +for line in sys.stdin: + req = json.loads(line) + method = req['method'] + assert method in ('initialize', 'notifications/initialized', 'tools/list') + if method == 'notifications/initialized': + continue + if method == 'initialize': + result = {'protocolVersion': '2024-11-05', 'capabilities': {'tools': {}}} + else: + names = ['containerapps_list', 'group_list', 'group_resource_list'] + if os.environ.get('BAD') == 'tools': + names.append('group_delete') + schema = {'type': 'object', 'properties': {}, 'required': []} + if os.environ.get('BAD') == 'schema': + schema['type'] = 'string' + result = {'tools': [{'name': n, 'inputSchema': schema, 'annotations': {'readOnlyHint': os.environ.get('BAD') != 'write'}} for n in names]} + print(json.dumps({'jsonrpc': '2.0', 'id': req['id'], 'result': result}), flush=True) +PY + chmod +x "$BATS_TEST_TMPDIR/uvx" + run python3 - "$BATS_TEST_TMPDIR/uvx" <<'PY' +import importlib.util, os, sys +s = importlib.util.spec_from_file_location('a', os.environ['REPO'] + '/scripts/update/azure-mcp-activate.py') +a = importlib.util.module_from_spec(s) +s.loader.exec_module(a) +for bad in ('', 'tools', 'schema', 'write'): + env = dict(os.environ, BAD=bad) + failed = False + try: + result = a.smoke(sys.argv[1], '3.1.0', env) + assert set(result) == a.TOOLS + except ValueError: + failed = True + assert failed == bool(bad), bad +PY + [ "$status" -eq 0 ] +} + +@test "Azure invalid current read-only contract prevents downloading or restarting" { lifecycle invalid-baseline; } diff --git a/tests/bats/system/update-node-runtime.bats b/tests/bats/system/update-node-runtime.bats index da9756b7..563107a4 100644 --- a/tests/bats/system/update-node-runtime.bats +++ b/tests/bats/system/update-node-runtime.bats @@ -352,7 +352,7 @@ EOF EOF chmod +x "${prefix}/bin/npm" - run env PATH="$shadow_bin" NODE_RUNTIME_TRACE="$trace" DOTFILES_MANAGED_NODE_BIN="$managed" bash -c "set -euo pipefail; set -- --section none; DOTFILES_UPDATE_RUN_DIR='${run_dir}'; source '${UPDATE_WSL}'; overlay=\$(node_runtime_create_overlay '${run_dir}' '${managed}'); export PATH=\"\$(node_runtime_controlled_path \"\$overlay\" '${prefix}' '${shadow_bin}')\"; unset NPM_CONFIG_PREFIX DOTFILES_NPM_PREFIX; test \"\$(user_npm_prefix)\" = '${prefix}'; node_runtime_cleanup_overlay \"\$overlay\"" + run env HOME="${TEST_TEMP_DIR}/home" PATH="$shadow_bin" NODE_RUNTIME_TRACE="$trace" DOTFILES_MANAGED_NODE_BIN="$managed" bash -c "set -euo pipefail; set -- --section none; DOTFILES_UPDATE_RUN_DIR='${run_dir}'; source '${UPDATE_WSL}'; overlay=\$(node_runtime_create_overlay '${run_dir}' '${managed}'); export PATH=\"\$(node_runtime_controlled_path \"\$overlay\" '${prefix}' '${shadow_bin}')\"; unset NPM_CONFIG_PREFIX DOTFILES_NPM_PREFIX; test \"\$(user_npm_prefix)\" = '${prefix}'; node_runtime_cleanup_overlay \"\$overlay\"" [[ "$status" -eq 0 ]] grep -q 'managed-node-ran:.*/npm' "$trace" assert_file_not_contains "$trace" 'shadow-node-ran'