diff --git a/deploy/nginx.conf.j2 b/deploy/nginx.conf.j2 index e98bad47..018342a8 100644 --- a/deploy/nginx.conf.j2 +++ b/deploy/nginx.conf.j2 @@ -9,11 +9,6 @@ server { default_type text/plain; try_files $uri =404; } - location ^~ /acme/powercell/ { - access_log off; - error_log /dev/null crit; - return 308 https://$host$request_uri; - } location / { return 308 https://$host$request_uri; } } @@ -28,19 +23,6 @@ server { add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; client_max_body_size 100m; - # The URL contains a per-enrollment capability, including on 4xx/5xx. - location ^~ /acme/powercell/ { - access_log off; - error_log /dev/null crit; - proxy_pass http://127.0.0.1:8000; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_connect_timeout 5s; - proxy_read_timeout 90s; - proxy_send_timeout 90s; - } - location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; diff --git a/deploy/powercell-renew.sh.j2 b/deploy/powercell-renew.sh.j2 deleted file mode 100644 index ed6a2ce9..00000000 --- a/deploy/powercell-renew.sh.j2 +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -set -eu -# Other sites have independent Certbot lineages and must not restart this API. -if [ "${RENEWED_LINEAGE:-}" = {{ powercell_tls_lineage | quote }} ]; then - exec /usr/bin/python3 /usr/local/sbin/throng-powercell-setup renew \ - --directory {{ powercell_directory | quote }} \ - --env-file {{ powercell_env_file | quote }} \ - --tls-lineage {{ powercell_tls_lineage | quote }} --restart -fi diff --git a/deploy/powercell_setup.py b/deploy/powercell_setup.py deleted file mode 100644 index 0a0b29c3..00000000 --- a/deploy/powercell_setup.py +++ /dev/null @@ -1,294 +0,0 @@ -"""Explicit administrator provisioning; never called by API startup or ordinary CI.""" - -import argparse -import fcntl -import grp -import hashlib -import json -import os -import re -import secrets -import shlex -import subprocess -import tempfile -from pathlib import Path -from urllib.parse import urlsplit - -PREFIX = "THRONG_POWERCELL_" -ASSIGNMENT = re.compile(r"^\s*(THRONG_POWERCELL_[A-Z_]+)\s*=(.*)$") - - -def openssl(*arguments): - result = subprocess.run(["openssl", *map(str, arguments)], capture_output=True, check=False) - if result.returncode: - # Never forward tool diagnostics or private configuration to CI/journald. - raise ValueError("Certificate validation/provisioning failed: openssl " + arguments[0]) - return result.stdout - - -def write_private(path, data, gid): - if path.exists() and path.read_bytes() == data: - os.chmod(path, 0o640) - os.chown(path, -1, gid) - return False - descriptor, name = tempfile.mkstemp(prefix=".powercell-", dir=path.parent) - try: - with os.fdopen(descriptor, "wb") as stream: - os.fchmod(stream.fileno(), 0o640) - os.fchown(stream.fileno(), -1, gid) - stream.write(data) - stream.flush() - os.fsync(stream.fileno()) - os.replace(name, path) - finally: - if os.path.exists(name): - os.unlink(name) - return True - - -def read_environment(path): - text = path.read_text() - values = {} - for line in text.splitlines(): - if match := ASSIGNMENT.match(line): - name, encoded = match.groups() - if name in values: - raise ValueError("Duplicate setting: " + name) - # Managed values use JSON-compatible double quotes, including - # escaped quotes/backslashes. Also accept existing simple .env values. - try: - pieces = ( - [json.loads(encoded)] - if encoded.lstrip().startswith('"') - else shlex.split(encoded, comments=False) - ) - except json.JSONDecodeError: - pieces = shlex.split(encoded, comments=False) - if ( - len(pieces) != 1 - or not isinstance(pieces[0], str) - or any(c in pieces[0] for c in "\r\n\x00") - ): - raise ValueError("Expected one quoted or unquoted value: " + name) - values[name] = pieces[0] - return text, values - - -def update_environment(text, values): - pending = dict(values) - lines = [] - for line in text.splitlines(): - match = ASSIGNMENT.match(line) - if match and match[1] in pending: - line = match[1] + "=" + json.dumps(pending.pop(match[1]), ensure_ascii=False) - lines.append(line) - lines.extend( - name + "=" + json.dumps(value, ensure_ascii=False) for name, value in pending.items() - ) - return "\n".join(lines) + "\n" - - -def endpoint(value, *, relay=False): - url = urlsplit(value) - if ( - url.scheme != "https" - or not url.hostname - or url.username is not None - or url.password is not None - or url.query - or url.fragment - or (relay and url.path not in ("", "/")) - ): - raise ValueError("Expected a public HTTPS " + ("relay origin" if relay else "ACME URL")) - if relay and not 1024 <= (url.port or 443) <= 65535: - raise ValueError("Use an unprivileged relay port, for example 8444") - return url - - -def check_pair(certificate, key, *, ca=False, hostname=None): - public = openssl("x509", "-in", certificate, "-pubkey", "-noout") - if public != openssl("pkey", "-in", key, "-pubout", "-passin", "pass:"): - raise ValueError("Certificate and private key do not match") - openssl("x509", "-in", certificate, "-checkend", "0", "-noout") - if ca: - description = openssl("x509", "-in", certificate, "-text", "-noout") - if b"CA:TRUE" not in description or b"id-ecPublicKey" not in description: - raise ValueError("An EC certificate authority is required") - if hostname: - verdict = openssl("x509", "-in", certificate, "-checkhost", hostname, "-noout") - # Older OpenSSL versions also exit zero when the hostname does not match. - if verdict.strip() != f"Hostname {hostname} does match certificate".encode(): - raise ValueError("Certificate does not match the relay hostname") - - -def issuer(directory, existing, gid, allow_create): - certificate = existing.get(PREFIX + "CA_CERTIFICATE") - key = existing.get(PREFIX + "CA_KEY") - if bool(certificate) != bool(key): - raise ValueError("Restore the complete existing CA configuration; refusing to replace it") - if certificate: - certificate, key = Path(certificate), Path(key) - if not certificate.is_absolute() or not key.is_absolute(): - raise ValueError("Existing CA paths must be absolute") - else: - target = directory / "issuer" - certificate, key = target / "ca.pem", target / "ca-key.pem" - if not target.exists(): - if not allow_create: - raise ValueError("Initial issuer provisioning requires --create-issuer") - with tempfile.TemporaryDirectory(prefix=".issuer-", dir=directory) as temporary: - temporary = Path(temporary) - openssl( - "req", - "-new", - "-x509", - "-newkey", - "ec", - "-pkeyopt", - "ec_paramgen_curve:P-256", - "-nodes", - "-sha256", - "-days", - "3650", - "-subj", - "/CN=Power Cell Device CA/O=Mutating", - "-addext", - "basicConstraints=critical,CA:TRUE", - "-addext", - "keyUsage=critical,keyCertSign,cRLSign", - "-addext", - "subjectKeyIdentifier=hash", - "-addext", - "authorityKeyIdentifier=keyid:always", - "-keyout", - temporary / "ca-key.pem", - "-out", - temporary / "ca.pem", - ) - for name in ("ca.pem", "ca-key.pem"): - write_private(temporary / name, (temporary / name).read_bytes(), gid) - os.chown(temporary, -1, gid) - os.chmod(temporary, 0o750) - # Publish the pair together. A partial existing issuer is never replaced. - temporary.rename(target) - check_pair(certificate, key, ca=True) - return str(certificate), str(key) - - -def install_tls(directory, lineage, relay_url, gid): - host = endpoint(relay_url, relay=True).hostname - certificate, key = lineage / "fullchain.pem", lineage / "privkey.pem" - check_pair(certificate, key, hostname=host) - content = (certificate.read_bytes(), key.read_bytes()) - digest = hashlib.sha256(b"\x00".join(content)).hexdigest() - version = directory / ("tls-" + digest) - if not version.exists(): - with tempfile.TemporaryDirectory(prefix=".tls-", dir=directory) as temporary: - temporary = Path(temporary) - for name, data in (("fullchain.pem", content[0]), ("privkey.pem", content[1])): - write_private(temporary / name, data, gid) - os.chown(temporary, -1, gid) - os.chmod(temporary, 0o750) - temporary.rename(version) - current = directory / "tls" - if current.is_symlink() and os.readlink(current) == version.name: - return False - if current.exists() and not current.is_symlink(): - raise ValueError("The managed TLS path must be a symlink; refusing to replace it") - link = directory / (".tls-link-" + secrets.token_hex(8)) - try: - link.symlink_to(version.name) - os.replace(link, current) - finally: - link.unlink(missing_ok=True) - return True - - -def provision(arguments, gid): - text, existing = read_environment(arguments.env_file) - endpoint(arguments.acme_url) - endpoint(arguments.relay_url, relay=True) - # Validate the externally issued server certificate before generating state. - check_pair( - arguments.tls_lineage / "fullchain.pem", - arguments.tls_lineage / "privkey.pem", - hostname=urlsplit(arguments.relay_url).hostname, - ) - secret_path = arguments.directory / "recovery.secret" - saved = secret_path.read_text().rstrip("\n") if secret_path.exists() else None - had_issuer = ( - bool(existing.get(PREFIX + "CA_CERTIFICATE")) or (arguments.directory / "issuer").exists() - ) - if had_issuer and not (existing.get(PREFIX + "SECRET") or saved): - raise ValueError("Restore the existing recovery secret; refusing to generate a replacement") - secret = existing.get(PREFIX + "SECRET") or saved or secrets.token_hex(32) - if len(secret) < 32 or (saved is not None and saved != secret): - raise ValueError("Restore the persistent recovery secret; refusing to rotate it") - certificate, key = issuer(arguments.directory, existing, gid, arguments.create_issuer) - changed = write_private(secret_path, (secret + "\n").encode(), gid) - changed |= install_tls(arguments.directory, arguments.tls_lineage, arguments.relay_url, gid) - values = { - PREFIX + "ACME_URL": arguments.acme_url, - PREFIX + "CA_CERTIFICATE": certificate, - PREFIX + "CA_KEY": key, - PREFIX + "SECRET": secret, - PREFIX + "RELAY_URL": arguments.relay_url, - PREFIX + "RELAY_CERTIFICATE": str(arguments.directory / "tls/fullchain.pem"), - PREFIX + "RELAY_KEY": str(arguments.directory / "tls/privkey.pem"), - PREFIX + "RELAY_HOST": arguments.relay_host, - } - changed |= write_private(arguments.env_file, update_environment(text, values).encode(), gid) - return changed - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("operation", choices=["configure", "renew"]) - parser.add_argument("--directory", type=Path, default=Path("/etc/throng/powercell")) - parser.add_argument("--env-file", type=Path, default=Path("/etc/throng/throng.env")) - parser.add_argument("--tls-lineage", type=Path, required=True) - parser.add_argument("--group", default="throng") - parser.add_argument("--acme-url", default="https://api.mutating.tech/acme/powercell") - parser.add_argument("--relay-url", default="https://api.mutating.tech:8444") - parser.add_argument("--relay-host", default="0.0.0.0") - parser.add_argument("--create-issuer", action="store_true") - parser.add_argument( - "--restart", - action="store_true", - help="Try restarting throng.service after TLS renewal", - ) - arguments = parser.parse_args() - if not all( - path.is_absolute() - for path in (arguments.directory, arguments.env_file, arguments.tls_lineage) - ): - raise ValueError("Directory, environment and TLS lineage paths must be absolute") - os.umask(0o077) - gid = grp.getgrnam(arguments.group).gr_gid - arguments.directory.mkdir(mode=0o750, parents=True, exist_ok=True) - os.chmod(arguments.directory, 0o750) - os.chown(arguments.directory, -1, gid) - with (arguments.directory / ".lock").open("a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - if arguments.operation == "configure": - changed = provision(arguments, gid) - else: - _, values = read_environment(arguments.env_file) - changed = install_tls( - arguments.directory, - arguments.tls_lineage, - values[PREFIX + "RELAY_URL"], - gid, - ) - # Retry the restart even if a previous renewal already published - # the files but systemd failed. Certbot calls this only on renewal. - if arguments.restart: - subprocess.run(["systemctl", "try-restart", "throng.service"], check=True) - print(json.dumps({"changed": changed})) - - -if __name__ == "__main__": - try: - main() - except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error: - raise SystemExit("Power Cell setup failed: " + str(error)) from None diff --git a/deploy/server.env.example b/deploy/server.env.example index 8cf49b27..d5ebbf48 100644 --- a/deploy/server.env.example +++ b/deploy/server.env.example @@ -6,14 +6,6 @@ THRONG_BROWSER_ORIGINS=["https://platform.mutating.tech"] THRONG_BROWSER_SECURE_COOKIE=true DASHBOARD_API_URL=https://api.mutating.tech/v1 -# Enable Power Cell with infra/playbooks/setup-powercell.yml after deploying. -# The administrator command preserves existing settings and provisions these -# values with persistent CA/recovery material; never put private values in Git. -# THRONG_POWERCELL_ACME_URL=https://api.mutating.tech/acme/powercell -# THRONG_POWERCELL_CA_CERTIFICATE=/etc/throng/powercell/issuer/ca.pem -# THRONG_POWERCELL_CA_KEY=/etc/throng/powercell/issuer/ca-key.pem -# THRONG_POWERCELL_SECRET= -# THRONG_POWERCELL_RELAY_URL=https://api.mutating.tech:8444 -# THRONG_POWERCELL_RELAY_CERTIFICATE=/etc/throng/powercell/tls/fullchain.pem -# THRONG_POWERCELL_RELAY_KEY=/etc/throng/powercell/tls/privkey.pem -# THRONG_POWERCELL_RELAY_HOST=0.0.0.0 +# Power Cell registration needs one persistent secret only to recover an +# idempotent finish response. Generate it once with: openssl rand -hex 32 +# THRONG_ENROLLMENT_SECRET= diff --git a/docs/deployment.md b/docs/deployment.md index e974f1f1..45109de3 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -387,644 +387,32 @@ nginx-конфиг `/etc/nginx/sites-available/throng`. Сертификат д ## Включение Power Cell на существующем сервере -Это отдельный административный шаг после обычного деплоя текущего кода. -Он добавляет настройки в существующий `/etc/throng/throng.env`, сохраняя БД, -CORS и остальные параметры. Обычный CI не создаёт и не заменяет CA/секреты. - -По умолчанию relay доступен по `https://api.mutating.tech:8444`: используется -тот же DNS и уже выпущенный публичный сертификат API. Адрес должен вести -на основной сервер непосредственно или через TCP-прокси с передачей порта 8444. -`setup-proxy.yml` сохраняет этот маршрут через новый VPS. Playbook Power Cell -открывает порт relay в активном UFW или firewalld и затем проверяет TCP-доступ -с машины, запускающей Ansible. Relay -обслуживает сам API, с TLS 1.3, HTTP/2 и проверкой клиентского -сертификата. HTTP-прокси не должен завершать TLS этого порта. - -Из корня репозитория, с административным SSH-доступом: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/setup-powercell.yml -u root -``` - -При необходимости добавьте `--ask-pass`; для административного пользователя -с sudo используйте `-u ADMIN --ask-become-pass`. Пароли вводятся в приглашениях -Ansible. Playbook сначала проверяет, что уже развёрнут supervisor с защитой -ACME-адресов в логах. Затем устанавливает защищённый nginx-конфиг, явно создаёт -постоянный EC CA и случайный секрет восстановления, копирует действующий TLS -сертификат/ключ relay с правами `0640 root:throng`, перезапускает `throng` и -проверяет обе capabilities: enrollment и relay. Перезапуск даёт короткий перерыв -в обслуживании API и кабинета. - -Порт берётся из `powercell_relay_url`, поэтому переопределение адреса меняет и -правило firewall. Существующие SSH/web-правила сохраняются; отключённый firewall -не включается. В firewalld исключение добавляется в runtime и постоянную -конфигурацию выбранной зоны без перезагрузки остальных правил. По умолчанию -используется default zone; при другой зоне внешнего интерфейса задайте -`powercell_firewalld_zone`. - -Проверка внешнего порта выполняется с Ansible-контроллера без sudo. Если порт -недоступен, playbook завершается ошибкой: возможны неверный DNS, bind-адрес, -собственные nftables/iptables-правила или фильтрация провайдера. Для собственных -firewall-ролей можно передать `-e powercell_manage_firewall=false`; они должны -сами разрешить порт. `-e powercell_verify_external=false` отключает только -внешнюю проверку, например для подготовки из закрытой сети. Внешний firewall -провайдера требует отдельного доступа к его API, если такая фильтрация включена. - -CA и ключ находятся в `/etc/throng/powercell/issuer/`, копия секрета восстановления — -в `/etc/throng/powercell/recovery.secret`. Их нужно включить в защищённые резервные -копии вместе с `/etc/throng/throng.env` и БД. Повторный запуск сохраняет существующие -CA и секрет, а при неполной или противоречивой конфигурации останавливается. -Автоматической ротации CA нет. Ранее настроенные внешние CA/ключ и секрет -подхватываются из env и сохраняются; пользователь `throng` должен иметь доступ -к этим внешним файлам. - -Hook `/etc/letsencrypt/renewal-hooks/deploy/throng-powercell` реагирует только -на выбранный Certbot lineage. Он публикует полную новую пару TLS через атомарную -ссылку `/etc/throng/powercell/tls` и перезапускает активный `throng`. Неактивный -сервис не запускается. Продление сертификатов других сайтов его не затрагивает. - -Адреса, каталог и lineage можно переопределить переменными -`powercell_acme_url`, `powercell_relay_url`, `powercell_relay_host`, -`powercell_directory`, `powercell_env_file`, `powercell_tls_lineage`. -Для другого домена relay сначала подготовьте DNS и публичный сертификат на -этот домен; helper проверяет имя, срок действия и соответствие ключа сертификату. - -После настройки проверьте публичную доступность: - -```sh -curl --fail https://api.mutating.tech/v1/agent-capabilities -``` - -В `extensions` должны присутствовать `powercell.enrollment.v1` и -`powercell.relay.v1`, а `attestation_required` — быть `true`. Окончательная -проверка выполняется на физическом Mac: вход, скачивание профиля, ручная -установка в системных настройках, аттестация Apple и завершение подключения. - -При дальнейшем деплое сохранённый production env и файлы `/etc/throng/powercell` -не заменяются. Для смены issuer или секрета требуется отдельная процедура -ротации с учётом уже выпущенных сертификатов и незавершённых подключений. -Playbook также обновляет root-owned activation wrapper: после включения Power Cell -он отклоняет релизы без `--no-access-log` в supervisor до остановки сервиса. -Поэтому обычные CI-релизы должны содержать это изменение `deploy/run.py`. - -## CI и SSH-секреты - -`.github/workflows/deploy.yml` запускается при **каждом push в main**, без фильтров -по файлам. Также есть ручной `workflow_dispatch`. Сборка и деплой запускаются -без ожидания результатов тестов. `.github/workflows/tests.yml` независимо запускает -все site-, API- и web-проверки, включая HTTPS и визуальные тесты, на push в любую -ветку (в том числе `main`) и на pull request. Ошибки тестов не блокируют деплой. -Все production-деплои сериализованы; выполняющийся деплой не отменяется следующим -push. Настройка `queue: max` сохраняет ожидающие запуски вместо замены новым push; -[GitHub Actions допускает до 100 запусков в очереди](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency#example-queueing-multiple-pending-runs). - -До загрузки и после активации релиза CI выполняет `bash deploy/verify-site.sh`. -Скрипт проверяет доступ по HTTP/1.1, доверие к TLS-сертификатам и имена обоих -хостов сайта, редиректы 308 с сохранением пути и запроса, HSTS и кэширование HTML. -В `setup-site.yml` HTTP/2 отключён на HTTPS-хостах `mutating.tech` и `www.mutating.tech`. - -Для сервера, настроенного с помощью `setup-site.yml`, тег `nginx_config` -обновляет конфигурацию виртуальных хостов сайта отдельно от выкладки релиза. - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/setup-site.yml -u root --tags nginx_config -``` - -Для просмотра изменений можно добавить `--check --diff`. - -В GitHub-репозитории добавьте Actions secrets: - -| Secret | Значение | -| --- | --- | -| `DEPLOY_HOST` | Публичный IPv4-адрес или DNS-имя сервера, доступное из GitHub | -| `DEPLOY_PORT` | SSH-порт, например `22` | -| `DEPLOY_USER` | Пользователь из playbook, по умолчанию `user` | -| `DEPLOY_PASSWORD` | Пароль этого SSH-пользователя, как в `site` | - -Достаточно четырёх прежних SSH-секретов. Дополнительный `DEPLOY_KNOWN_HOSTS` -не требуется: проверенный публичный SSH-ключ сервера сохранён в -`deploy/known_hosts`. Это публичный ключ, его можно хранить в Git. -CI использует `StrictHostKeyChecking=yes` и `HostKeyAlias=mutating-production`, -поэтому проверка сохраняется при использовании IP, DNS-имени или другого SSH-порта. -При пересоздании сервера сначала проверьте новый ключ через доверенный доступ, -затем обновите `deploy/known_hosts`. Пароль в репозитории не хранится. - -Deployment user записывает только исходники и окружения в `/opt/mutating/releases/` -и Python в `/opt/mutating/python/`. Секреты и база недоступны ему напрямую. Для -активации разрешён один root-owned скрипт `/usr/local/sbin/mutating-activate` через -sudo без пароля; миграции и SQLite backup внутри него выполняются от `throng`. - -## Что происходит при обновлении - -1. CI собирает Hugo в `site/public/` с origin `https://mutating.tech/` и интерфейс с `VITE_SITE_ORIGIN=https://mutating.tech` и передаёт - исходники API/веб-сервера, готовые `site/public/` и `platform/web/dist/` - через rsync в новый каталог релиза. Локальные - `.env`, виртуальные окружения, базы и тестовые данные исключены из передачи. -2. На сервере `uv sync --project platform/api --frozen --no-dev` готовит отдельное Python-окружение. - Ошибка сборки/установки не останавливает работающий сервис. -3. Скрипт активации получает файловую блокировку и останавливает общий сервис. -4. SQLite backup API сохраняет согласованную копию БД, включая данные из WAL, - в `/var/lib/throng/backups/-/throng.db` и проверяет её целостность. -5. Alembic применяет все неприменённые миграции до `head`. При ошибке до запуска - приложений копия БД восстанавливается и прежний активный сервис запускается снова. -6. Атомарно переключается `/opt/mutating/current`. Запускается единый systemd-сервис, - проверяется готовность API и наличие HTML кабинета. Повторная проверка миграций - при обычном старте не применяет уже выполненные миграции заново. -7. Скрипт синхронизирует `site/public/` в `/var/www/mutating.tech/`. CI проверяет - публичные HTTPS-адреса сайта, API и кабинета через nginx. - -В Actions загрузка, подготовка Python и активация показаны отдельными шагами. -Загрузка сверяет содержимое (`--checksum`) с зафиксированным текущим релизом -и использует `rsync --copy-dest`: неизменившиеся файлы копируются на сервере, -а по сети передаются изменения. Новые релизы имеют собственные файлы без общих -hard links. Это также работает при изменившихся после checkout временах файлов; -первый релиз без `/opt/mutating/current` загружается целиком. Из `site/` -передаётся только результат Hugo в `site/public/`: исходные картинки, темы, -контент и промежуточные ресурсы на сервере не нужны и не дублируют готовый сайт. - -Для CSS библиотеки с хешем в `/ui/styles/` nginx должен выдавать тот же -`Cache-Control: public, max-age=31536000, immutable`, что и для `/css/`. -Правило уже находится в `infra/playbooks/setup-site.yml`. Для существующего -сервера сохранена отдельная операция `infra/playbooks/update-site-ui-cache.yml`: -она добавляет `/ui/styles/` в действующее правило, сохраняя остальную конфигурацию. -Запускайте из корня репозитория с административным доступом: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/update-site-ui-cache.yml \ - -u root --ask-pass -``` - -Для предварительного просмотра добавьте `--check --diff`. При доступе по ключу -замените `--ask-pass` на `--private-key /private/path/to/key`; для sudo добавьте -`--ask-become-pass`. Проверенный SSH host key берётся из `deploy/known_hosts`. -Пароль вводится в приглашении Ansible и в файлы проекта не записывается. - -Playbook проверяет активный symlink и исходную конфигурацию, сохраняет резервную -копию рядом с TLS-конфигом, выполняет `nginx -t` и reload. При ошибке проверки -или reload восстанавливает копию и сообщает об ошибке. Повторный запуск не меняет -уже обновлённый конфиг и не перезагружает nginx. После применения Ansible -проверяет заголовки опубликованных CSS с контроллера; если новая UI-сборка ещё не -опубликована, сообщает о пропуске этой проверки. Параметры путей и домена доступны -через `nginx_ui_cache_config`, `nginx_ui_cache_enabled` и `nginx_ui_cache_origin`. -Обычный CI-пользователь может активировать релиз, но не менять конфигурацию nginx. - -При подготовке права на чтение выдаются только файлам deployment user; -чужие файлы и кеши `__pycache__` в общем Python не изменяются. - -CI выводит общий прогресс rsync, скорость, итоговую статистику, начало и конец -каждого этапа с длительностью. Долгие этапы каждые 15 секунд подтверждают, что -ещё выполняются. Ограничения: SSH preflight — 60 секунд, передача — 8 минут -и не более 60 секунд без I/O, подготовка Python — 10 минут, наблюдение за -активацией — 7 минут. SSH дополнительно проверяет соединение каждые 15 секунд -и прерывается после трёх пропущенных ответов. Общий предел job — 50 минут; -каждый из трёх этапов завершается раньше со своей ошибкой и кодом выхода. - -Активация запускается на сервере независимо от SSH-наблюдателя: отмена CI или -обрыв связи не прерывают SQLite backup, миграцию или восстановление БД. -Её журнал находится в `/opt/mutating/releases//.activation/output.log`, -а файл `status` в том же каталоге появляется атомарно после завершения -(содержимое `0` означает успех). Отсутствие `status` не означает успех. -Повторное выполнение `bash deploy/upload.sh activate` подключается -к журналу того же процесса и возвращает сохранённый код без повторной активации. -После таймаута наблюдения сначала проверьте этот журнал и `status`: серверный -процесс может продолжать работу. Для отдельной загрузки или подготовки доступны -фазы `upload` и `prepare`; вызов без фазы сохраняет прежний порядок всех операций. - -Во время остановки, миграций и запуска возможен короткий перерыв с `502` от nginx. -Если новое приложение не запускается после успешной миграции, сервис останавливается, -CI завершается ошибкой, а новая БД сохраняется для разбора. Автоматический откат -БД после запуска API мог бы удалить уже принятые новые записи и поэтому не выполняется. -Перед остановкой сервиса новый activation wrapper проверяет запас для копии SQLite: -число страниц БД × размер страницы плюс минимум 64 МиБ (либо 10% размера БД). -Сам backup повторяет проверку, пишет `throng.db.incomplete` и публикует `throng.db` -только после проверки целостности. При ошибке удаляется только каталог, созданный -этой попыткой; ранее завершённые копии и исходная БД сохраняются. -Wrapper использует root-owned helper `/usr/local/lib/mutating/sqlite_backup.py`, -устанавливаемый Ansible из `deploy/sqlite_backup.py`. Это позволяет проверять место -и сохранять атомарные копии при активации старых релизов, в которых ещё нет -`check-space`. Helper запускается от `throng` через Python выбранного релиза. -Точечное обновление helper/wrapper без изменения nginx и перезапуска приложений: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i '85.204.240.76,' infra/playbooks/update-deployment-tools.yml -u root --ask-pass -``` - -До замены wrapper playbook проверяет helper с текущим окружением Python. -Если процесс активации завершился, но полный диск помешал записать `status`, -новый наблюдатель завершает CI ошибкой сразу после обнаружения завершившегося -процесса, сохраняя журнал для диагностики. - -### Автоматическая ротация после GitHub-деплоя - -Последний шаг `Deploy production`, после успешной активации и публичных проверок -сайта, API, кабинета и CORS, запускает `deploy/rotate.py`. Он вызывает только -Ansible (`infra/playbooks/rotate-deployments.yml`) от обычного CI-пользователя. -Ansible проверяет оба статических сайта до и после очистки. Шаг имеет явный -`success()` и не выполняется после ошибки или отмены предыдущих этапов. - -Политика хранения: - -| История | Что сохраняется | -| --- | --- | -| Релизы | Текущий и три предыдущих с успешной активацией; порядок определяется завершением активации, а не mtime загруженных исходников | -| SQLite | Пять последних завершённых и проверенных резервных копий; копия текущего релиза дополнительно защищена при необычном порядке дат | -| Незавершённые загрузки и копии | Сохраняются первые 24 часа, затем могут удаляться при следующем успешном деплое | -| Используемые каталоги | Не удаляются, пока на них ссылается живой процесс | - -Симлинки и каталоги с неизвестным содержимым пропускаются. Очистка ограничена -`/opt/mutating/releases/` и `/var/lib/throng/backups/`; рабочая БД, артефакты, -nginx, сертификаты и файлы `pomponchik.org` в неё не входят. Если копий меньше -пяти, сохраняются все. Неполные и повреждённые копии в эти пять не засчитываются. -SQLite-копии с оставшимися journal/WAL/SHM также считаются незавершёнными: -они защищены первые 24 часа и затем могут удаляться без засчитывания в пять исправных. - -Новые backup сохраняют `.complete.json` после проверки целостности. Старые копии -при первом использовании проверяются через read-only `PRAGMA quick_check`; -результат кешируется по размеру и mtime файла, чтобы не сканировать сотни МБ при -каждом деплое. Проверяются только копии, необходимые для защищённого набора. -Ротация откажется удалять что-либо без исправной копии текущего деплоя, при -сменившемся `current`, неуспешном статусе активации или неработающем API/кабинете. -Планирование и удаление выполняются под `deploy.lock`. Операции удаления и записи -метаданных привязаны к открытым дескрипторам каталогов и не следуют подменённым -симлинкам. Прерванная очистка не удаляет текущую версию и защищённые копии. - -У CI остаётся существующее ограниченное sudo-право: -`mutating-activate RELEASE_ID rotate` вызывает только установленный root-owned -`/usr/local/lib/mutating/rotate_deployments.py` через системный Python. Код из -изменяемого каталога релиза от root не запускается. Установка/обновление этой -политики — административный Ansible-шаг `update-deployment-tools.yml`; он нужен -перед первым запуском нового workflow и уже включает helper в первоначальную -настройку `setup-platform.yml`. - -Для CI закреплены Python 3.13 и `ansible-core==2.21.2`. Пароль передаётся Ansible -через временный файл с правами 0600 в приватном каталоге runner, удаляемом и при -успехе, и при ошибке. В аргументы процесса и inventory пароль не попадает. -Первый проход по старым копиям может занять больше времени; предел шага — 10 минут, -общий предел job — 50 минут. Ошибка ротации делает шаг CI неуспешным, сохраняя -работающий релиз. Журнал перечисляет сохранённые/удалённые каталоги и свободные байты. - -Ручная проверка той же политики от deployment user (без удаления): - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i '85.204.240.76,' infra/playbooks/rotate-deployments.yml -u user --ask-pass \ - -e rotation_release_id=CURRENT_RELEASE -e rotation_apply=false -``` - -Для административной проверки ограниченного CI-права через root-подключение -используйте `-u root -e rotation_run_as=user`. `--check` также выполняет только -планирование. Для применения просмотренного плана повторите команду с -`-e rotation_apply=true`; ID должен по-прежнему совпадать с текущим релизом. -Новая политика запускается автоматически после публикации workflow в `main` -обычным PR из `develop`. - -**Проверка ротации 3 ноября 2026 (МСК).** Helper установлен через Ansible и -проверен с ограниченным sudo-правом пользователя `user`. Применён план для текущего -релиза `d14a69881df63e3140d9278374eed5ba030c53d6-41530526100-1`: удалены 10 старых -каталогов релизов (включая две незавершённые загрузки) и 35 резервных копий. -Освобождено 1 478 008 832 байта; `df` показывает 3,0 ГБ свободного места, 66% занято. -Сохранены текущий релиз с тремя предыдущими, пять проверенных копий и временно -защищённая незавершённая копия с journal от предыдущего сбоя. Повторный запуск -завершился с `changed=0`. API, кабинет и оба статических сайта отвечают 200, -`throng.service` остался `active/running` с тем же PID; все 23 отпечатка nginx -до и после очистки совпали. Новый шаг GitHub workflow покрыт локальными тестами; -сам шаг в GitHub начнёт работать после слияния изменений в `main`. - -### Диагностика и очистка диска - -Все серверные операции выполняйте через Ansible. Сначала получите размеры -каталогов, свободные блоки/inode, активный релиз и состояние сервиса: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i '85.204.240.76,' infra/playbooks/diagnose-disk.yml -u root --ask-pass -``` - -Playbook закрепляет host key из `deploy/known_hosts`. Временные файлы Ansible -размещаются в `/run`, чтобы диагностика работала при заполненном корневом диске. -Он не выводит environment приложения, содержимое БД или HTTP-журналы. -Для быстрой проверки без обхода размеров каталогов добавьте `--tags capacity,state`: -в отчёт попадут состояние сервиса и наиболее загруженные процессы без их аргументов. - -`cleanup-deployments.yml` принимает явный список старых релизов. Сначала -просмотрите план; подставьте проверенные ID из диагностики вместо `OLD_RELEASE`: +Power Cell больше не требует CA, ACME, профиля, relay или открытого порта +`8444`. Нужен только постоянный секрет для идемпотентного завершения +регистрации: ```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i '85.204.240.76,' infra/playbooks/cleanup-deployments.yml -u root --ask-pass \ - -e '{"cleanup_release_ids":["OLD_RELEASE"]}' - -# Применить тот же проверенный список. -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i '85.204.240.76,' infra/playbooks/cleanup-deployments.yml -u root --ask-pass \ - -e '{"cleanup_release_ids":["OLD_RELEASE"],"cleanup_apply":true}' +openssl rand -hex 32 ``` -Очистка захватывает тот же `deploy.lock`, что и активация. Сохраняются текущий -и три самых свежих каталога релизов, по умолчанию также все релизы моложе суток. -Параметры `cleanup_keep` и `cleanup_minimum_age_hours` допускают минимум 3 и 1. -Сначала проверяется весь список: текущие/свежие релизы, симлинки, выход за пределы -`/opt/mutating/releases/`, каталоги без собранного сайта/кабинета и релизы с живым -PID активации запрещены. `--check` всегда выполняет только планирование. -Playbook не удаляет БД, резервные копии, пользовательские артефакты, кеши Python, -файлы `pomponchik.org`, конфигурации nginx или сертификаты. После выполнения он -проверяет API, кабинет и оба публичных сайта, не перезапуская сервисы. +Добавьте результат в `/etc/throng/throng.env`: -Если платформа уже остановилась из-за полного диска, для этапа очистки задайте -`cleanup_verify_health=false`, затем восстановите конкретный подготовленный релиз: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i '85.204.240.76,' infra/playbooks/recover-release.yml -u root --ask-pass \ - -e recovery_release_id=PREPARED_RELEASE \ - -e recovery_expected_current_id=CURRENT_RELEASE +```dotenv +THRONG_ENROLLMENT_SECRET=<полученное значение> ``` -Recovery откажется дублировать живую активацию или заменять неожиданно изменившийся -текущий релиз. Проверяет запас места, вызывает установленный wrapper с новой копией -SQLite и миграциями, проверяет API/кабинет и `PRAGMA quick_check`, затем публикует -успешный `status`. В `verify-hosted-sites.yml` сохранены проверки обоих статических -сайтов на локальном TLS listener с настоящими доменами и проверкой сертификатов, -а также отпечатки конфигурационных файлов nginx без вывода их содержимого. +Секрет шифрует только восстановимую копию agent credential до подтверждения +ответа `finish`. Он не является trust anchor и не заменяет пароль или токен. +Храните его вместе с БД в защищённых резервных копиях; при потере незавершённые +повторные `finish` перестанут возвращать тот же credential. -На macOS для подключения мимо VPN можно привязать транспорт Ansible к физическому -интерфейсу: добавьте `-e disk_ssh_interface=en1` к этим playbook. Имя интерфейса -и шлюз предварительно проверьте через `route -n get default`. Если VPN перекрывает -доступ к его таблице маршрутов, администратор Mac может создать отдельный scoped -host route (пример для Wi-Fi `en1`, шлюза `192.168.1.1`): +После изменения перезапустите `throng` и проверьте capabilities: ```sh -sudo /sbin/route -n add -host 85.204.240.76 192.168.1.1 -ifscope en1 -# После обслуживания удалить только добавленный маршрут. -sudo /sbin/route -n delete -host 85.204.240.76 192.168.1.1 -ifscope en1 -``` - -Это не отключает VPN и не заменяет проверку SSH host key; маршрут используется -соединениями, явно привязанными к этому интерфейсу. Пароли вводите только в -приглашении Ansible/Терминала и не сохраняйте в репозиторий или журнал. - -**Восстановление 3 ноября 2026 (МСК).** Корневой ext4 раздел 9,1 ГБ был заполнен: -доступно 0 байт, сервис `throng.service` — `failed`. Удалены 30 явно выбранных -устаревших релизов 14–20 октября; текущий релиз, свежие версии, БД, все резервные -копии и артефакты сохранены. Стало доступно 1 987 919 872 байта. Затем через Ansible -успешно активирован прерванный релиз `6dc6e6c76ccb112eee5e4fa2587bb32b334ed518-41517259173-1` -с новой копией SQLite. После восстановления свободно 1,8 ГБ (80% занято), сервис -`active/running`, API и кабинет отвечают 200, SQLite quick check — `ok`. -`mutating.tech` и `pomponchik.org` отвечают 200; все 23 отпечатка файлов nginx -совпали с состоянием до очистки. Конфигурации, сертификаты и файлы блога не менялись. -Через `update-deployment-tools.yml` установлен общий backup helper и wrapper с -проверкой места до остановки сервиса; helper проверен с Python текущего релиза. -Повторная установка и проверка сайтов дали `changed=0`, сервисы не перезапускались. -Исправление наблюдателя в `deploy/deploy.sh` применяется к новым загрузкам после -публикации соответствующих изменений репозитория; существующие каталоги релизов -не переписывались. - -## Данные и управление - -| Путь | Содержимое | -| --- | --- | -| `/var/lib/throng/throng.db` | Рабочая SQLite; при работе также возможны `-wal` и `-shm` | -| `/var/lib/throng/artifacts/` | Артефакты, аватары и другие данные API | -| `/var/lib/throng/backups/` | Копии SQLite перед обновлениями; файлы артефактов не копируются | -| `/etc/throng/throng.env` | Настройки API, CORS и публичного адреса API для кабинета | -| `/opt/mutating/releases/` | Hugo, API, интерфейс и `platform/api/.venv` каждого релиза | -| `/opt/mutating/current` | Ссылка на релиз, соответствующий текущей схеме БД | - -Cookie `tmc_session` выдаётся самим API: Secure/HttpOnly, без Domain, -`Path=/v1/`, SameSite=Lax. Она содержит случайный API-токен; в БД сохраняется -только его хэш. Отдельного хранилища веб-сессий и ключа шифрования кабинета нет. -Для CORS и CSRF используется список точных origin `THRONG_BROWSER_ORIGINS`, -по умолчанию `["https://platform.mutating.tech"]`. В production -`THRONG_BROWSER_SECURE_COOKIE=true`. Кабинет получает публичный адрес из -`DASHBOARD_API_URL` (по умолчанию `https://api.mutating.tech/v1`). -Прежние `DASHBOARD_SESSION_KEY`, `DASHBOARD_SECURE_COOKIE` и -`DASHBOARD_PUBLIC_ORIGIN` больше не используются. -В SQLite одновременно работает один API/контроллер; не запускайте дополнительные -Uvicorn workers или старый независимый API поверх этой базы. - -Одна команда запускает оба приложения: - -```sh -sudo systemctl start throng -``` - -Остальные команды администратора: - -```sh -sudo systemctl restart throng -sudo systemctl stop throng -sudo systemctl status throng -sudo journalctl -u throng -f -``` - -Общий `infra/playbooks/setup-server.yml` последовательно запускает `setup-site.yml` -и `setup-platform.yml`; их можно применять отдельно по необходимости. - -При изменении systemd unit, root-owned скрипта активации или nginx-шаблона повторно -примените playbook. Обычный push обновляет приложения и миграции; изменение -административных настроек сервера выполняется явно. - -Актуальный nginx-шаблон передаёт все пути платформы приложению без переписывания -или перенаправления корня. На сервере со старой конфигурацией сначала примените -`setup-platform.yml`, затем обновите приложение. - -## Диагностика публичного доступа - -Проверки с контроллера и из разных стран выполняются через read-only playbook. -На контроллере нужны Ansible, `curl` и `dig`; административный доступ к серверу -для этих внешних проверок не требуется. Check-Host и Globalping получают только -публичные имена сайтов, без паролей, cookie и ключей. Результаты доступны через -их публичные отчёты; у Globalping срок хранения ограничен. - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i localhost, infra/playbooks/diagnose-public-access.yml \ - --tags dns,transport,global,globalping -``` - -Теги: `dns` — A/AAAA/NS/CAA через Cloudflare DNS и Google DNS; -`transport` — HTTP по имени и IP, TLS с SNI и без него, SSH banner и контрольный -`example.com`; `local` — подробные времена `curl` для четырёх доменов по -HTTP/HTTPS с `-4` и `-6`; `global` — DNS/HTTP/HTTPS/TCP через Check-Host; -`globalping` — независимые HTTPS-проверки Globalping с ASN источника, временем -TCP/TLS и проверкой сертификата. При отсутствии AAAA результат `curl -6` может -отражать IPv4-mapped адрес VPN; он не доказывает доступность настоящего IPv6. - -Можно передать `access_domain`, `access_address` (IP для обхода DNS в транспортной -проверке), `access_hosts`, `access_checks`, `access_probe_nodes` и -`access_check_host_nodes`. Для проверки Финляндии и США: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i localhost, infra/playbooks/diagnose-public-access.yml --tags globalping \ - -e '{"access_hosts":["mutating.tech"],"access_globalping_locations":[{"country":"FI","limit":6},{"country":"US","limit":8}]}' -``` - -Чтобы повторить проверку с тех же узлов, передайте ID предыдущего измерения -строкой: `-e '{"access_globalping_locations":"MEASUREMENT_ID"}'`. -Узлы, выбранные только по стране/ASN, могут меняться между запросами. -`access_globalping_type` и `access_globalping_options` позволяют менять тип -измерения и параметры согласно API Globalping. По умолчанию используется HEAD: -`405` кабинета и `404` корня API означают полученный HTTP-ответ, а не сетевой -тайм-аут. Для проверки страниц используйте -`-e '{"access_globalping_options":{"protocol":"HTTPS","request":{"method":"GET"}}}'`. - -Отказ отдельного публичного узла перепроверьте на `example.com` с того же узла: -неисправность пробника нельзя приписывать сайту. Доступный TCP-порт сам по себе -не доказывает успешный TLS/HTTP. При тайм-ауте после TCP сравните SNI и прямой IP, -другие домены сервера и контрольный сайт. Проверки firewall, nginx и захват -пакетов на production также выполняются только через Ansible. Разбор инцидента -23 октября 2026 года сохранён в `docs/public-access-2026-10-23.md`. - -Дополнительные транспортные проверки запускаются явно, поскольку включают -несколько повторных соединений: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i localhost, infra/playbooks/diagnose-public-access.yml --tags profiles -``` - -Они сравнивают TLS 1.2/1.3, минимальный HTTP-запрос, SSH с разным порядком -отправки banner и счётчики повторной передачи TCP в macOS. `access_profile_filter` -оставляет только имена проверок, содержащие заданную подстроку. Поле `mss` -показывает фактический размер сегмента: запрошенный TCP_MAXSEG может не примениться -после connect в macOS. Для этих проверок VPN отключать не требуется. Пробы -`physical_interface` по умолчанию выключены; они добавляются только при явном -задании `access_physical_interface` и создают отдельный сокет с привязкой к -этому интерфейсу. - -Действующий nginx, listeners, firewall и локальный HTTPS проверяет отдельный -read-only playbook с административным доступом. Пароль вводится в приглашении: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/diagnose-server-access.yml -u root --ask-pass \ - -e access_server_first_ssh=true -``` - -`access_server_first_ssh=true` включает ProxyCommand внутри транспорта Ansible: -он сначала получает SSH banner сервера, затем передаёт поток клиента. SSH -по-прежнему проверяет закреплённый host key из `deploy/known_hosts` и выполняет -аутентификацию и шифрование. Обход нужен для воспроизведённого случая, когда -соединение с немедленной отправкой client banner зависает. Настройки VPN и -production он не меняет. - -Для сопоставления запроса контроллера с пакетами на интерфейсе сервера: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/diagnose-server-access.yml -u root --ask-pass \ - -e access_server_first_ssh=true -e access_capture=true \ - -e access_probe_source=PROBLEM_PUBLIC_IPV4 --tags capture -``` - -Захват использует Python AF_PACKET, поэтому устанавливать tcpdump не нужно. -Он печатает только метаданные TCP портов 80/443: время, направление, адреса, -порты, seq/ack, флаги и длину данных; содержимое пакетов не печатается и не -записывается в pcap. По умолчанию окно — 45 секунд, задаётся -`access_capture_seconds`. Включать `access_capture_all_sources=true` следует -только при необходимости сравнить проблемный поток с независимым контрольным -источником. Временные метки запроса и захвата позволяют проверить их пересечение. - -Чтобы локализовать потери после установления TCP, запустите TTL-пробы вместе -с серверным захватом. Один TCP-поток последовательно отправляет данные с разным -TTL; ICMP Time Exceeded сопоставляется по портам и seq. Для HTTPS используется -настоящий TLS ClientHello, для HTTP — короткие части запроса: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/diagnose-server-access.yml -u root --ask-pass \ - -e access_server_first_ssh=true -e access_capture=true \ - -e access_probe_source=PROBLEM_PUBLIC_IPV4 -e access_capture_edge=true \ - -e access_edge_port=443 -e access_capture_seconds=15 \ - -e access_capture_max_packets=400 --tags capture -``` - -`access_edge_port=80` выбирает HTTP. Пробы меняют TTL только своих сокетов, -не маршруты и не VPN. Отсутствие ICMP-ответа само по себе не доказывает потерю -на конкретном узле; наличие ответа доказывает достижение этого узла пакетом. -Серверный захват позволяет проверить, пришли ли эти данные на VM. - -Без административного доступа доступны отдельные локальные TTL-пробы и -ICMP/UDP traceroute через текущий VPN: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i localhost, infra/playbooks/diagnose-public-access.yml --tags edge \ - -e access_edge_fixed_flow=true -e access_edge_port=443 -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i localhost, infra/playbooks/diagnose-public-access.yml --tags trace -``` - -TCP traceroute в macOS может потребовать прав для BPF; TTL-пробы `edge` -используют ICMP datagram socket и этого доступа не требуют. - -## Проверки - -```sh -uv run --project platform/api pytest -c platform/api/pyproject.toml -q tests/platform/api/deployment -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook --syntax-check \ - -i localhost, infra/playbooks/setup-server.yml -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook --syntax-check \ - -i localhost, infra/playbooks/setup-proxy.yml -bash -n deploy/upload.sh deploy/deploy.sh deploy/activate.sh -``` - -Проверки используют временную SQLite и реальные API, кабинет и nginx с отдельными -портами и временным TLS-сертификатом. Они проверяют выбор приложения по Host, -статику, CSRF/cookie, сохранение данных и сессии после перезапуска и остановку -обоих компонентов при завершении одного. Системный nginx и рабочая база не -затрагиваются. Для сетевой проверки нужен собранный `platform/web/dist/`, nginx и -OpenSSL; она запускается в группе web общего CI после сборки. - -## GitHub App через Ansible - -Секреты GitHub устанавливаются playbook, исходный JSON хранится вне checkout: - -```sh -LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ansible-playbook \ - -i 'SERVER_IP,' infra/playbooks/setup-github-actions.yml -u root \ - -e github_credentials_file=/private/path/github-app.json +curl --fail https://api.mutating.tech/v1/agent-capabilities ``` -Схема JSON: `app_id`, `slug`, `client_id`, `client_secret`, `webhook_secret`, -`token_key`, `private_key_path` (локальный PEM), `public_api_url`, `dashboard_url`. -Для текущего стенда файл находится в защищённом локальном каталоге -`~/.config/mutating/server-dev/github-app.json`, права `0600`. -Пароль подключения можно передать через `--ask-pass` либо отдельный приватный -vars-файл; он не входит в репозиторий. - -Playbook сначала требует релиз с GitHub API, затем копирует App key в -`/etc/throng/github/app.pem` (`root:throng`, `0640`), добавляет управляемый блок в -существующий `/etc/throng/throng.env` с резервной копией и перезапускает сервис -только при изменении конфигурации. Параметры БД и Power Cells сохраняются. -Несовпадение уже установленного App ID или постоянного Fernet key останавливает -playbook: их замена требует отдельной миграции OAuth credentials. Все операции -с секретами выполняются с `no_log` и без diff. Повторный запуск должен быть -идемпотентным. - -Для подготовленного локально архива релиза предусмотрен -`infra/playbooks/deploy-platform.yml`. В архив входят код и собранный -`platform/web/dist`, исключаются `.git`, `.env*`, виртуальные окружения, -node_modules, данные и тестовые результаты. Передайте `release_archive` и новый -`release_id`; он должен соответствовать `[A-Za-z0-9][A-Za-z0-9._-]{0,127}`. -При обновлении только API/кабинета можно передать `release_reuse_static_site=true`: -в архиве тогда не должно быть `site/public`, и playbook сохранит статическую -сборку действующего релиза. В архиве должен присутствовать каталог `site`. - -Playbook распаковывает код в новый каталог, готовит окружение от deployment user -и вызывает существующий root-owned activation wrapper. Wrapper сохраняет SQLite -backup, применяет миграции, проверяет готовность и не активирует релиз, если за -время подготовки изменился `/opt/mutating/current`. Установку credentials App -выполняйте после успешного обновления кода. - -16 октября 2026 года этими playbook развёрнут релиз -`github-ci-20261016-163116` и установлен тестовый App `mutating-power-cells-dev`. -Повторное применение `setup-github-actions.yml` завершилось с `changed=0`, без -перезапуска сервиса. GitHub подтвердил HTTP 202 при повторной доставке `ping` -и `workflow_run`. Подробности живой проверки и оставшееся ограничение GitHub -billing — в [инструкции стенда](github-actions-dev-setup.md). +В `extensions` должны быть `powercell.enrollment.v1` и `powercell.device.v1`; +поля `attestation_required` и `powercell.relay.v1` больше нет. Окончательная +проверка: вход в приложении, регистрация компьютера без профиля macOS, запуск +задачи после привязки к пулу и отвязка. diff --git a/infra/playbooks/setup-powercell.yml b/infra/playbooks/setup-powercell.yml deleted file mode 100644 index c78df06f..00000000 --- a/infra/playbooks/setup-powercell.yml +++ /dev/null @@ -1,140 +0,0 @@ ---- -# Explicit one-time administrator action after deploying the current release. -# Uses the API domain's existing public TLS certificate; exposes TCP 8444 directly. -- name: Enable Power Cell enrollment and authenticated relay - hosts: all - become: true - gather_facts: true - vars: - ansible_python_interpreter: /usr/bin/python3 - project_source: "{{ playbook_dir }}/../.." - certificate_path: /etc/letsencrypt/live/throng-mutating.tech - powercell_tls_lineage: "{{ certificate_path }}" - powercell_directory: /etc/throng/powercell - powercell_env_file: /etc/throng/throng.env - powercell_acme_url: https://api.mutating.tech/acme/powercell - powercell_relay_url: https://api.mutating.tech:8444 - powercell_relay_host: 0.0.0.0 - powercell_manage_firewall: true - powercell_firewalld_zone: "" - powercell_verify_external: true - handlers: - - name: Validate nginx - ansible.builtin.command: nginx -t - changed_when: false - listen: powercell nginx changed - - name: Reload nginx - ansible.builtin.service: - name: nginx - state: reloaded - listen: powercell nginx changed - tasks: - - name: Require Debian or Ubuntu - ansible.builtin.assert: - that: ansible_facts.distribution in ['Debian', 'Ubuntu'] - - - name: Read the deployed supervisor - ansible.builtin.slurp: - src: /opt/mutating/current/deploy/run.py - register: deployed_supervisor - - - name: Require the release that protects ACME capability URLs - ansible.builtin.assert: - that: "'--no-access-log' in (deployed_supervisor.content | b64decode)" - fail_msg: Deploy the current release first; the old API supervisor logs secret ACME URLs. - - - name: Install issuer provisioning tools - ansible.builtin.apt: - name: [openssl, python3] - state: present - update_cache: true - cache_valid_time: 3600 - - - name: Install the root-owned provisioning helper - ansible.builtin.copy: - src: "{{ project_source }}/deploy/powercell_setup.py" - dest: /usr/local/sbin/throng-powercell-setup - owner: root - group: root - mode: '0750' - - - name: Keep future activations from restoring unsafe ACME logging - ansible.builtin.copy: - src: "{{ project_source }}/deploy/activate.sh" - dest: /usr/local/sbin/mutating-activate - owner: root - group: root - mode: '0755' - - - name: Install ACME log protection in the existing nginx hosts - ansible.builtin.template: - src: "{{ project_source }}/deploy/nginx.conf.j2" - dest: /etc/nginx/sites-available/throng - owner: root - mode: '0644' - notify: powercell nginx changed - - - name: Provision the persistent issuer, recovery secret and relay TLS pair - ansible.builtin.command: - argv: - - /usr/bin/python3 - - /usr/local/sbin/throng-powercell-setup - - configure - - --create-issuer - - --directory - - "{{ powercell_directory }}" - - --env-file - - "{{ powercell_env_file }}" - - --tls-lineage - - "{{ powercell_tls_lineage }}" - - --acme-url - - "{{ powercell_acme_url }}" - - --relay-url - - "{{ powercell_relay_url }}" - - --relay-host - - "{{ powercell_relay_host }}" - register: provisioning - changed_when: (provisioning.stdout | from_json).changed - - - name: Install certificate renewal and relay restart hook - ansible.builtin.template: - src: "{{ project_source }}/deploy/powercell-renew.sh.j2" - dest: /etc/letsencrypt/renewal-hooks/deploy/throng-powercell - owner: root - group: root - mode: '0750' - - - name: Apply protected nginx routing - ansible.builtin.meta: flush_handlers - - # This explicit administrative command also retries a previous failed - # activation when the files already contain their intended values. - - name: Activate the configured enrollment and relay - ansible.builtin.systemd_service: - name: throng.service - state: restarted - - - name: Require both enrollment and relay capabilities from the running API - ansible.builtin.uri: - url: http://127.0.0.1:8000/v1/agent-capabilities - return_content: true - register: capabilities - until: - - capabilities.status == 200 - - "'powercell.enrollment.v1' in capabilities.json.extensions" - - "'powercell.relay.v1' in capabilities.json.extensions" - - capabilities.json.attestation_required - retries: 30 - delay: 2 - - - name: Allow the relay in the active host firewall - ansible.builtin.include_tasks: tasks/powercell-firewall.yml - when: powercell_manage_firewall | bool - - - name: Verify the public relay port from the Ansible controller - ansible.builtin.include_tasks: tasks/powercell-connectivity.yml - when: powercell_verify_external | bool - - - name: Report the remaining enrollment check - ansible.builtin.debug: - msg: "Power Cell enabled at {{ powercell_relay_url }}. Host firewall management={{ powercell_manage_firewall | bool }}, external TCP check={{ powercell_verify_external | bool }}. Finish enrollment on a physical Mac." diff --git a/infra/playbooks/tasks/powercell-connectivity.yml b/infra/playbooks/tasks/powercell-connectivity.yml deleted file mode 100644 index 4bc4c4da..00000000 --- a/infra/playbooks/tasks/powercell-connectivity.yml +++ /dev/null @@ -1,18 +0,0 @@ ---- -- name: Check relay TCP reachability from outside the VPS - block: - - name: Connect from the Ansible controller to the public relay address - ansible.builtin.wait_for: - host: "{{ powercell_relay_url | ansible.builtin.urlsplit('hostname') }}" - port: "{{ (powercell_relay_url | ansible.builtin.urlsplit('port')) | default(443, true) | int }}" - state: started - connect_timeout: 3 - timeout: "{{ powercell_relay_probe_timeout | default(30) }}" - delegate_to: localhost - become: false - vars: - ansible_python_interpreter: "{{ ansible_playbook_python }}" - rescue: - - name: Explain an unreachable relay instead of reporting successful setup - ansible.builtin.fail: - msg: "Relay {{ powercell_relay_url }} is unreachable from the Ansible controller. Check DNS, the relay bind address, custom nftables/iptables rules, or provider filtering." diff --git a/infra/playbooks/tasks/powercell-firewall.yml b/infra/playbooks/tasks/powercell-firewall.yml deleted file mode 100644 index 8e68f87b..00000000 --- a/infra/playbooks/tasks/powercell-firewall.yml +++ /dev/null @@ -1,109 +0,0 @@ ---- -# Add only the relay exception to an already active firewall. Enabling/resetting -# a firewall here could change the operator's SSH and unrelated service policy. -- name: Derive the TCP port from the configured relay URL - ansible.builtin.set_fact: - powercell_relay_port: "{{ (powercell_relay_url | ansible.builtin.urlsplit('port')) | default(443, true) | int }}" - -- name: Validate the unprivileged relay port - ansible.builtin.assert: - that: - - powercell_relay_port | int >= 1024 - - powercell_relay_port | int <= 65535 - -- name: Locate UFW - ansible.builtin.shell: "command -v {{ powercell_ufw_binary | default('ufw') | quote }}" - register: powercell_ufw_binary_status - changed_when: false - # bash returns 1 for a missing command; Debian's dash returns 127. - failed_when: powercell_ufw_binary_status.rc not in [0, 1, 127] - check_mode: false - -- name: Locate firewalld - ansible.builtin.shell: "command -v {{ powercell_firewalld_binary | default('firewall-cmd') | quote }}" - register: powercell_firewalld_binary_status - changed_when: false - failed_when: powercell_firewalld_binary_status.rc not in [0, 1, 127] - check_mode: false - -- name: Inspect UFW without changing its state - ansible.builtin.command: - argv: ["{{ powercell_ufw_binary | default('ufw') }}", status] - environment: - LC_ALL: C - register: powercell_ufw_status - changed_when: false - failed_when: powercell_ufw_status.rc != 0 - check_mode: false - when: powercell_ufw_binary_status.rc == 0 - -- name: Inspect firewalld without changing its state - ansible.builtin.command: - argv: ["{{ powercell_firewalld_binary | default('firewall-cmd') }}", --state] - environment: - LC_ALL: C - register: powercell_firewalld_status - changed_when: false - failed_when: powercell_firewalld_status.rc not in [0, 252] - check_mode: false - when: powercell_firewalld_binary_status.rc == 0 - -- name: Identify the active host firewall - ansible.builtin.set_fact: - powercell_ufw_active: "{{ powercell_ufw_status.rc | default(-1) == 0 and 'Status: active' in (powercell_ufw_status.stdout | default('')) }}" - powercell_firewalld_active: "{{ powercell_firewalld_status.rc | default(-1) == 0 }}" - -- name: Require one firewall manager - ansible.builtin.assert: - that: not (powercell_ufw_active and powercell_firewalld_active) - fail_msg: Both UFW and firewalld are active. Select one manager before applying the relay exception. - -- name: Allow inbound TCP to the relay with UFW - ansible.builtin.command: - argv: ["{{ powercell_ufw_binary | default('ufw') }}", allow, "{{ powercell_relay_port }}/tcp", comment, Power Cell relay] - environment: - LC_ALL: C - register: powercell_ufw_rule - changed_when: "'Rule added' in powercell_ufw_rule.stdout or 'Rules updated' in powercell_ufw_rule.stdout" - when: powercell_ufw_active - -- name: Read the default firewalld zone - ansible.builtin.command: - argv: ["{{ powercell_firewalld_binary | default('firewall-cmd') }}", --get-default-zone] - register: powercell_default_zone - changed_when: false - check_mode: false - when: - - powercell_firewalld_active - - (powercell_firewalld_zone | default('')) | length == 0 - -- name: Choose the relay firewalld zone - ansible.builtin.set_fact: - powercell_selected_zone: "{{ powercell_firewalld_zone | default('') or powercell_default_zone.stdout | default('') | trim }}" - when: powercell_firewalld_active - -- name: Query the firewalld runtime and persistent relay exception - ansible.builtin.command: - argv: "{{ [powercell_firewalld_binary | default('firewall-cmd')] + (['--permanent'] if item else []) + ['--zone=' + powercell_selected_zone, '--query-port=' + (powercell_relay_port | string) + '/tcp'] }}" - loop: [false, true] - register: powercell_firewalld_queries - changed_when: false - failed_when: powercell_firewalld_queries.rc not in [0, 1] - check_mode: false - when: powercell_firewalld_active - -- name: Add missing firewalld runtime and persistent relay exceptions - ansible.builtin.command: - argv: "{{ [powercell_firewalld_binary | default('firewall-cmd')] + (['--permanent'] if item.item else []) + ['--zone=' + powercell_selected_zone, '--add-port=' + (powercell_relay_port | string) + '/tcp'] }}" - loop: "{{ powercell_firewalld_queries.results | default([]) }}" - loop_control: - label: "{{ 'persistent' if item.item else 'runtime' }}" - when: - - powercell_firewalld_active - - item.rc == 1 - changed_when: true - -- name: Report an unmanaged or disabled host firewall - ansible.builtin.debug: - msg: No active UFW or firewalld detected; the playbook leaves the existing policy in place and checks public TCP reachability next. - when: not powercell_ufw_active and not powercell_firewalld_active diff --git a/platform/api/.env.example b/platform/api/.env.example index 97cf9919..7666693a 100644 --- a/platform/api/.env.example +++ b/platform/api/.env.example @@ -12,18 +12,9 @@ THRONG_PLATFORM_ORIGIN=http://127.0.0.1:8001 THRONG_BROWSER_ORIGINS=["http://127.0.0.1:8001","http://127.0.0.1:5173"] THRONG_BROWSER_SECURE_COOKIE=false -# Optional Power Cell issuer. Set all four together; no development CA is generated. -# THRONG_POWERCELL_ACME_URL=https://example.org/acme/powercell -# THRONG_POWERCELL_CA_CERTIFICATE=/run/secrets/powercell-ca.pem -# THRONG_POWERCELL_CA_KEY=/run/secrets/powercell-ca-key.pem -# THRONG_POWERCELL_SECRET= - -# Native macOS relay: same process as the API, separate TLS listener with mTLS. -# Expose this port directly (no TLS termination at the HTTP reverse proxy). -# THRONG_POWERCELL_RELAY_URL=https://relay.example.org:8444 -# THRONG_POWERCELL_RELAY_CERTIFICATE=/run/secrets/relay-fullchain.pem -# THRONG_POWERCELL_RELAY_KEY=/run/secrets/relay-key.pem -# THRONG_POWERCELL_RELAY_HOST=0.0.0.0 +# Power Cell registration. The secret encrypts only the recoverable credential +# for an exact enrollment-finish retry; it is not a trust anchor. +# THRONG_ENROLLMENT_SECRET= # Optional GitHub App integration. Set all seven credentials together. # OAuth/setup callbacks, repository discovery and CI routing; see docs/github.md. diff --git a/platform/api/docs/agent-protocol.md b/platform/api/docs/agent-protocol.md index d1cb7d96..2cfa6631 100644 --- a/platform/api/docs/agent-protocol.md +++ b/platform/api/docs/agent-protocol.md @@ -179,8 +179,8 @@ whether a command is currently running. ## Power Cell extensions -Power Cell uses the same task/result transport with additional attested enrollment, +Power Cell uses the same task/result transport with client-device registration, capacity policies and confirmed cleanup. See [powercell.md](powercell.md) for the -wire contract, deployment settings and trust boundary. Existing generic workers -retain their original credential protocol; the `powercell-ubuntu-arm64-v1` runtime -can only be registered through verified enrollment. +wire contract and deployment settings. Existing generic workers retain their +original credential protocol; the `powercell-ubuntu-arm64-v1` runtime is created +through `POST /v1/agent-enrollments` and authenticates with its agent credential. diff --git a/platform/api/docs/powercell.md b/platform/api/docs/powercell.md index 4de0f2d2..48ffa2ec 100644 --- a/platform/api/docs/powercell.md +++ b/platform/api/docs/powercell.md @@ -1,341 +1,63 @@ # Power Cell server protocol -The agent extension is implemented in migration `0006`. Run `throng-api migrate` -before starting an updated API/controller. SQLite and PostgreSQL use the existing -serialized write transaction for scheduling, capacity, cleanup and replay guards. -Older generic agents keep their existing bearer/session protocol. The Power Cell -runtime cannot be created using the legacy `/computers` endpoint. +Power Cell registration is a client-generated installation id plus a normal +agent credential. Migration `0028` removes device certificates, ACME +enrollments, request nonces and the native relay. ## Deployment -For the existing native systemd deployment, first deploy the current release, -then run `infra/playbooks/setup-powercell.yml` with administrative SSH access. -It explicitly provisions the persistent issuer/recovery secret, updates the -existing environment without replacing unrelated settings, installs the relay's -TLS renewal hook, and checks discovery. See `docs/deployment.md` in the repository -root. Its default relay is `https://api.mutating.tech:8444`, using the API's -existing public TLS certificate; expose that port directly and preserve TLS. -The following settings describe the equivalent manual configuration. - -Configure all four values together: +Run `throng-api migrate` before starting an updated API/controller. The only +Power Cell-specific setting is the persistent secret used to recover a +credential after an uncertain finish response: ```dotenv -THRONG_POWERCELL_ACME_URL=https://example.org/acme/powercell -THRONG_POWERCELL_CA_CERTIFICATE=/run/secrets/powercell-ca.pem -THRONG_POWERCELL_CA_KEY=/run/secrets/powercell-ca-key.pem -THRONG_POWERCELL_SECRET= +THRONG_ENROLLMENT_SECRET= ``` -The certificate must be an EC CA with its matching unencrypted PEM private key. -Provision and protect this issuer separately; the application never silently -creates a development CA. The HTTPS endpoint must be reachable by macOS and its -TLS certificate must be trusted by that Mac. Route `/acme/powercell/*` to this -application, preserving paths. A URL prefix stripped by a reverse proxy may be -included in the configured public URL. Do not log directory secrets, signed -bodies, credentials or issuer key material. Directory capabilities expire with -the enrollment (one hour by default). - -`THRONG_POWERCELL_SECRET` encrypts the credential recovery material needed after -an uncertain enrollment response. Back it up with the database and CA keys. -Changing it makes unfinished credential recovery unavailable; plan rotation -rather than generating a new value every startup. Agent credentials themselves -remain hashed in `agent_credentials`. - -Without these settings the API still serves generic workers and all execution -extensions, but does not advertise `powercell.enrollment.v1` and refuses to enroll -Power Cell devices. Partial or invalid issuer configuration fails startup. - -For the native macOS agent, also configure the authenticated network relay: - -```dotenv -THRONG_POWERCELL_RELAY_URL=https://relay.example.org:8444 -THRONG_POWERCELL_RELAY_CERTIFICATE=/run/secrets/relay-fullchain.pem -THRONG_POWERCELL_RELAY_KEY=/run/secrets/relay-key.pem -THRONG_POWERCELL_RELAY_HOST=0.0.0.0 -``` +Generate it once with `openssl rand -hex 32`, back it up with the database, and +keep it stable across restarts. Changing it makes unfinished idempotent finish +retries unavailable. Agent credentials remain hashed in `agent_credentials`; +the secret never becomes a trust anchor. -The URL must be an HTTPS origin (no credentials, path, query or fragment). Its -port is the listener port; the bind address defaults to `127.0.0.1`. Use a TLS -certificate trusted by macOS, and expose this listener directly or through TCP -passthrough. Ordinary HTTP reverse proxies must not terminate its TLS: the API -must verify the actual client certificate. Run one API process per relay address -and port. TLS 1.3, HTTP/2 and a client certificate issued by the Power Cell CA are -mandatory; partial configuration or unusable TLS material fails startup. -`deploy/run.py --env-file ` keeps that file selected in its child services; -standalone processes can select it with `THRONG_ENV_FILE=`. An explicitly -selected file does not inherit settings from a different local `.env`. - -The relay accepts TCP CONNECT only to its own virtual API destination. It does -not proxy arbitrary hosts. Each connection's verified TLS certificate is attached -to the API request internally; no public certificate/fingerprint header is trusted. -There is no additional loopback HTTP listener accepting trusted identity headers. +Without the secret the API serves generic workers and scheduling, but +`POST /agent-enrollments/{id}/finish` returns `503`. Existing credentials keep +working. There is no CA, profile, relay listener or certificate renewal hook to +configure. Additional limits: `THRONG_ENROLLMENT_SECONDS` (3600), -`THRONG_DEVICE_CERTIFICATE_DAYS` (365), `THRONG_DEVICE_PROOF_SECONDS` (300), `THRONG_AGENT_MUTATION_SECONDS` (86400), `THRONG_MAX_DIAGNOSTIC_BYTES` (8 MiB), `THRONG_MAX_COMPUTER_DIAGNOSTICS_BYTES` (64 MiB), -`THRONG_DIAGNOSTIC_RETENTION_DAYS` (30). Expired protocol nonces, cleanup retry -records and diagnostics are removed by the controller. Diagnostic reads enforce -expiry even when the controller is stopped. - -## Discovery and enrollment - -Public `GET /v1/agent-capabilities` returns `protocol_version: 1`, runtime -`powercell-ubuntu-arm64-v1`, image list `["ubuntu:24.04"]`, -`attestation_required: true`, and supported extensions: -`powercell.enrollment.v1`, `powercell.capacity.v1`, `powercell.eviction.v1`, -`powercell.diagnostics.v1`, `powercell.isolation.v1`. -When the relay is configured, discovery also advertises `powercell.relay.v1`. - -With a personal `manage` token, POST `/v1/agent-enrollments` and -`Idempotency-Key`: - -```json -{"installation_id":"uuid","name":"My Mac","company_id":null,"os":"linux","architecture":"arm64","runtime":"powercell-ubuntu-arm64-v1","isolation_modes":["vm","shared"],"cpu_millis":4000,"memory_bytes":4294967296,"disk_bytes":8589934592} -``` - -Company enrollment requires its administrator role, rechecked when finishing. -Responses and GET `/v1/agent-enrollments/{id}` contain -`id,status,expires_at,certificate_sha256,relay`. Status is `pending_attestation`, -`verified` or `expired`. The certificate hash is absent until a matching CSR has -been signed after successful attestation. Only the initiating user can read or -finish an enrollment. At most 20 live enrollments per initiating user are allowed. - -GET `.../{id}/profile` returns `application/x-apple-aspen-config`. It contains a -ACME identity payload, no MDM/root/restriction payloads. -It requests hardware-bound, nonextractable P-256 with `Attest=true`, -`AllowAllAppsAccess=false`, digital-signature usage and client-auth EKU. - -With a relay configured, the profile also contains `com.apple.relay.managed`. -It uses `PayloadScope=System`: the built-in relay requires its hardware-bound -ACME identity in the system data protection keychain. Installation requires -manual administrator consent. Without a relay, the profile remains user scoped. -It routes only its own virtual `.powercell-.invalid` hostname and refers -to the **same ACME payload UUID** for client authentication. macOS uses the -nonextractable attested key itself; the app neither exports that key nor needs -access to the system-only identity. Other computer traffic is unaffected. -The `relay` response field contains `url` and `api_origin`; without this feature -it is null. The agent keeps the original server URL as its credential origin and -rewrites device request URLs to `api_origin`, preserving paths, queries and bodies. -The virtual hostname cannot resolve to a public fallback without the profile. -Routes differ between enrollment attempts, so a previously installed profile -cannot select the wrong identity for a new connection or another account. - -After installation, authenticated GET `.../{id}/verification` through the relay -checks the enrollment owner's token and possession of its exact certificate. It -returns the enrollment status, or 409 for a pending/expired unbound attempt and -401 for an invalid device proof. The agent probes this endpoint before finishing. - -The ACME service implements newNonce, newAccount, newOrder, POST-as-GET polling, -`device-attest-01`, CSR finalization and PEM chain retrieval. Each enrollment has -one account/order/certificate. ES256 and RS256 account signatures are supported; -the attested identity/CSR must use P-256. JWS URL, account, algorithm and nonce are -checked. A finalized order cannot change key or CSR. Requests cannot obtain DNS -certificates or arbitrary CSR extensions. - -Apple attestation verification uses OpenSSL path validation against the bundled, -SHA-256-pinned Apple Enterprise Attestation Root, validity intervals, challenge -freshness, nonempty certified serial/UDID and Mac/Secure Enclave properties. The -freshness extension must contain **SHA256(challenge token)**, as documented by -Apple. The issued CSR must prove possession of the exact attested public key. -No client UUID, serial, self-signed key or forwarded proxy header substitutes for -attestation. Certificate SAN/subject and EKU are generated by the server. - -POST `.../{id}/finish` with an empty JSON object, personal `manage` token, -`Idempotency-Key` and a device proof returns: - -```json -{"computer_id":"uuid","credential":"agt_...","device_id":"uuid","certificate_sha256":"hex","relay":{"url":"https://relay.example.org:8444","api_origin":"http://.powercell-.invalid"}} -``` - -An exact retry using a new proof nonce recovers the same credential. A different -finish key, rotated/revoked credential or revoked certificate cannot recover it. -Physical identity is SHA-256 of a domain-separated Apple-certified UDID. Different -installations and accounts can bind the same physical device; deleting a binding -preserves its billing identity. Enrollment IDs, installation IDs and physical -IDs are separate records. - -On the relay transport, the TLS certificate provides the device proof. Each API -request rechecks its exact enrollment/computer binding, validity interval and -revocation, including on an already-established TLS connection. Bearer tokens, -organization authorization, sessions and mutation idempotency still apply. -Registration and stable physical-device verification do not impose license or -computer-count limits. - -## Request signatures - -Every endpoint under `/agent/v1` requires a possession proof for enrolled Power -Cell computers, including session discovery, session creation and late uploads. -The server rechecks credential binding/revocation in the handler after proof -verification. Rotating a bearer token never removes its device-key requirement. -Generic legacy agents without an attested binding are unchanged. +`THRONG_DIAGNOSTIC_RETENTION_DAYS` (30). -The following signature protocol remains available for clients that can access -their attested key directly. The native relay transport above does not require -these per-request signatures. +## Device login -`X-PowerCell-Proof` contains base64 of exact UTF-8 JSON bytes; -`X-PowerCell-Signature` contains base64 of their ECDSA P-256/SHA-256 DER signature: +`POST /api/v1/auth/login` accepts `device_id` (UUID). The server stores it in +`devices` and associates it with the authenticated user in `device_accounts`. +The id may be reused by another account on the same computer; it is an +installation identifier, not a hardware proof. -```json -{"version":1,"certificate_sha256":"hex","method":"POST","target":"/agent/v1/heartbeat","timestamp":1791576000,"nonce":"uuid","body_sha256":"hex","authorization_sha256":"hex","session":"uuid","idempotency_key":null} -``` - -`target` is the original percent-encoded path plus query. Hashes cover raw body -bytes (empty if absent) and the exact Authorization header. Session and idempotency -fields must match their headers, or be null when absent. Reject unknown/duplicate -JSON fields, wrong context, invalid signatures, expired/revoked certificates, -stale timestamps and replayed per-certificate nonces. Nonce consumption is atomic -across API processes and survives restarts. Sign every transport retry afresh; -retain the original mutation body and idempotency key. - -Proofs also operate over explicitly configured HTTP API endpoints. HTTP does not -encrypt credentials/data or authenticate responses; the ACME profile endpoint -still requires HTTPS. Optional TLS client-certificate verification may be applied -by the deployment, but forwarded certificate headers never bypass request proofs. -Only the API's own relay listener can supply the authenticated TLS identity. - -## Capacity and isolation - -Optional extension `powercell.images.v1` adds -`image_families: ["ghcr.io/actions/actions-runner"]` to discovery and capacity -reports. Discovery `images` continues to list the built-in `ubuntu:24.04`. -Only advertise the family after installing the host/guest runtime with OCI -support. The scheduler sends public runner images with an explicit tag or -`@sha256:<64 lowercase hex>` only to Power Cells advertising the family in -their current session with networking enabled. Missing/empty families preserve -old agents' Ubuntu-only behavior. Session clean-start clears the advertisement. -The optional field lives in `capacity_report`, so no database migration is needed. - -For `POST /v1/isolates` with `runtime: "powercell-ubuntu-arm64-v1"`, `image` -accepts these aliases in addition to full image references: - -| Alias | Full image reference | -| --- | --- | -| `ubuntu` | `ubuntu:24.04` | -| `actions` | `ghcr.io/actions/actions-runner:latest` | - -Omitting `image` selects `ubuntu` (`ubuntu:24.04`). Explicit `null` or empty -strings are rejected. An omitted image, `ubuntu` and `ubuntu:24.04` are equivalent -for idempotency checks. - -Aliases are case-sensitive and expanded before storage, scheduling and -idempotency checks. Isolate responses and agent tasks contain the full reference; -retrying with the equivalent alias/full reference and the same idempotency key -returns the same isolate. Discovery exposes this mapping as `image_aliases`. -Other runtimes continue to interpret image names literally. -`actions` follows the mutable `latest` tag; use a full reference with a version -tag or digest when pinning is required. It requires the same advertised image -support and enabled networking as an explicit runner reference. - -The updated Mac agent downloads the Linux ARM64 image with an anonymous, -size-bounded, checksum-verified GHCR transport, then imports it with guest umoci -inside the isolate's disk quota. Image user/working-directory/environment are -honored; mounts/hooks/capabilities never override Power Cell security policy. -Image commands use `cwd` relative to the image's working directory, while state -archives and snapshots still cover `/workspace` only. The official runner image -does not enable privileged commands or Docker service/container actions. -Preparing the image does not register a GitHub runner or implement CI autoscaling. - -POST `/agent/v1/capacity` requires a live session and Idempotency-Key: - -```json -{"revision":7,"accepting_work":true,"mode":"idle","reason":null,"cpu_millis":4000,"memory_bytes":4294967296,"disk_bytes":8589934592,"default_isolation":"vm","network_enabled":false,"internet_only":true,"running_commands":2,"cpu_used_millis":320,"memory_used_bytes":150994944} -``` +## Registration -Returns `{"revision":7,"accepted":true}`. Revisions are monotonic per session; -identical retries are safe, conflicts/stale revisions return 409. Reports do not -renew the lease. New Power Cell sessions accept no work until their first report. +`POST /api/v1/agent-enrollments` requires that the device already signed in for +the same account. The response is immediately verified; no profile challenge +exists. `finish` returns `{computer_id, credential, device_id}`. The +idempotency key recovers the same credential; a different key conflicts. -The offered target is separate from inventory and reservation accounting. A report -may offer zero or less than occupied capacity; it cannot free reservations. -Increases expand the stored inventory envelope. Scheduling uses both inventory -and target bounds; `free=max(0,min(inventory,target)-reserved)`. Computer responses -include targets, latest telemetry and `free_cpu/free_memory/free_disk`. -`only_available` summaries and availability history use the current offered budget. -Regular inventory/history continues to describe inventory and reservations. - -When `accepting_work=false`, or existing reservations exceed the new target, no -new create/run/snapshot may be delivered or started. Cancels/destroys and completion -of already running commands remain available. Snapshot API calls return 409 while -draining. Controller and agent admission both enforce the policy under the same -transaction lock. A claim that sees only paused create/run/snapshot work stays -read-only. Each poll rereads policy, while cancel/destroy delivery keeps its -priority and the final write transaction rechecks every admission condition. - -Isolate creation accepts `isolation_mode: "vm"|"shared"|null` and -`retry_allowed: true` by default. A plugin value takes priority; null resolves to -the chosen agent's default. The effective mode and network policy are fixed at -assignment and included in the create payload. Unadvertised modes are not scheduled. -Later capacity reports affect new isolates only. - -## Confirmed cleanup and deferred diagnostics - -POST `/agent/v1/isolates/{id}/evict` with live session/Idempotency-Key: - -```json -{"reason":"capacity_reduced","cleanup_confirmed":true,"retry_allowed":true} -``` - -Reasons: `capacity_reduced`, `isolate_lost`, `disabled`, `battery`, `thermal`, -`user_switched`, `sleep`, `disk_unavailable`, `agent_quit`, `logout`, -`lease_expired`, `memory_pressure`. Confirmation means the agent has already -stopped all relevant processes/VMs. The transaction fails remaining commands as -`isolate_failed`, obsoletes assignments and releases reservations exactly once. -Terminal results are immutable. Plugin retry prohibition cannot be relaxed by the -agent. No command or stateful history is automatically replayed. - -POST `/agent/v1/disconnect` takes `cleanup_confirmed:true,reason` and a live session; -it settles all work and immediately marks the computer unavailable. Its exact -retry succeeds after disconnection. Credential remains usable for a clean start. - -POST `/agent/v1/unbind` takes `cleanup_confirmed:true`; no live session or user -token is required. It settles work, removes ownership, revokes credential and -certificate. For 24 hours, the revoked token plus device proof can retry only that -exact unbind. It never authorizes a new operation. Physical identity is retained. - -If the device key/profile is lost or its certificate has expired, the owner can -log in again and POST `/v1/computers/{computer_id}/unbind` with a user token -having `manage` scope, `Idempotency-Key` and `{"cleanup_confirmed":true}`. The -client must stop its sandboxes before confirming. Current personal ownership or -company administration is required. This performs the same cleanup and revokes -the old credential/certificate without requiring their possession; it does not -authorize execution or issue replacement credentials. Computer, execution and -physical-device history are retained. An exact retry with the same authenticated -account/key (including a fresh login token) succeeds for 24 hours after detachment. Reconnecting requires a new -attested enrollment. - -PUT `/agent/v1/diagnostics/{uuid}` requires agent credential/proof, no live session. -Send `application/octet-stream` containing the Swift agent's UTF-8 JSON record: - -```json -{"id":"uuid","created":"2026-10-10T12:00:00Z","message":"failure","session_id":null,"task_id":null,"uploaded":false} -``` +`assign_pool` defaults to false. Without it the computer has no +`ComputerOwnership`: it is visible to its account, cannot receive tasks, and can +be assigned later from the app or dashboard. Set `assign_pool` and `company_id` +to bind personal (`null`) or an organization pool at registration. -The URL and body IDs must match. Task metadata must belong to that computer and, -if supplied, the original session. Session-only metadata is an untrusted label. -Return `{id,sha256}`. Exact bytes deduplicate; conflicting bytes return 409. Bounded -records, checksum, original owner and retention are stored atomically in the DB. -GET `/v1/computers/{id}/diagnostics/{uuid}` requires authenticated computer -administration and original log ownership. Transferring the computer does not -transfer private logs. Storage quota exhaustion returns 409; oversize returns 413. -These logs never update execution results. stdout/stderr retain the existing live -task artifact protocol and the existing throng result shape. +## Agent authentication -## Validation and references +Agent endpoints accept the `agt_` bearer credential plus the live +`X-Agent-Session` and idempotency headers where required. There are no request +signatures, certificates, nonces or relay connections. -Tests use the repository's real Uvicorn TCP server, migrated temporary database, -native HTTPX clients, generated certificate chains and real signatures. Test -fixtures substitute an isolated trust root; production has no trust-root override. -They cover malformed/replayed attestations, signature/context substitution, -physical identity deduplication, concurrent nonce/revision/completion races, -credential recovery/revocation, cleanup, diagnostics and migration compatibility. -A physical Mac/Apple attestation round trip requires the deployed HTTPS issuer and -manual installation of the profile; generated PKI tests do not claim to validate -that external Apple service or macOS keychain access. +## Data migration -- [Apple Managed Device Attestation](https://support.apple.com/guide/security/managed-device-attestation-sec8a37b4cb2/web) -- [Apple ACME payload specification](https://github.com/apple/device-management/blob/release/mdm/profiles/com.apple.security.acme.yaml) -- [Apple Private PKI](https://www.apple.com/certificateauthority/private/) -- [Apple native ACME client](https://github.com/apple-oss-distributions/Security/blob/main/OSX/sec/Security/SecCertificateRequest.m) -- [RFC 8555](https://www.rfc-editor.org/rfc/rfc8555) +`0028` renames `physical_devices` to `devices`, keeps existing device ids, +backfills account associations from connected computers, preserves pending +enrollment installation ids as device keys, and drops certificate/nonce tables +and certificate columns. Existing computers keep their credentials and become +normal credential-authenticated workers. diff --git a/platform/api/throng_api/accounts.py b/platform/api/throng_api/accounts.py index 213c835e..16d951d9 100644 --- a/platform/api/throng_api/accounts.py +++ b/platform/api/throng_api/accounts.py @@ -16,6 +16,8 @@ AccessToken, Company, CompanyInvitation, + Device, + DeviceAccount, GitHubAccount, GitHubOAuthFlow, LegacyCredential, @@ -106,6 +108,36 @@ async def create_user(data: UserCreate, request: Request): return await saved(session, User(**values)) +async def remember_device(session, user, device_id, now): + """Persist a client-generated installation id and its account association. + + Login is the only place a new installation announces itself. Repeating the + same id is idempotent and adds a fresh account association instead of + replacing the previous one, so switching accounts keeps billing history. + """ + if device_id is None: + return None + client_key = str(device_id).lower() + device = await session.scalar(select(Device).where(Device.client_key == client_key)) + if device is None: + device = Device(client_key=client_key) + session.add(device) + await session.flush() + association = await session.get(DeviceAccount, (device.id, user.id)) + if association is None: + session.add( + DeviceAccount( + device_id=device.id, + user_id=user.id, + first_seen_at=now, + last_seen_at=now, + ) + ) + else: + association.last_seen_at = now + return device + + async def issue_login(data: Login, request: Request): async with request.app.state.db.read() as session: identifier = data.login.casefold() @@ -121,14 +153,15 @@ async def issue_login(data: Login, request: Request): user = await session.get(User, user_id) if not user or user.password_hash != encoded: raise HTTPException(401, "Credentials changed; retry login") + now = request.app.state.clock() + await remember_device(session, user, data.device_id, now) raw = secret("thr_") token = LoginSession( user_id=user.id, name="login", scopes=sorted(SCOPES), session_hash=digest(raw), - expires_at=request.app.state.clock() - + timedelta(seconds=request.app.state.settings.login_token_seconds), + expires_at=now + timedelta(seconds=request.app.state.settings.login_token_seconds), ) session.add(token) await session.flush() diff --git a/platform/api/throng_api/acme.py b/platform/api/throng_api/acme.py deleted file mode 100644 index 16e31652..00000000 --- a/platform/api/throng_api/acme.py +++ /dev/null @@ -1,299 +0,0 @@ -"""Restricted RFC 8555 service: one account/order/Apple identity per enrollment. - -No DNS issuance, arbitrary CSR extensions, caller-supplied CAs or proxy trust headers. -The enrollment's random directory capability authorizes only its single identity. -""" - -import base64 -import binascii -import hashlib -import secrets -from datetime import timedelta -from uuid import UUID - -import cbor2 -from cryptography import x509 -from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa, utils -from fastapi import APIRouter, Request -from fastapi.responses import JSONResponse, Response -from OpenSSL.crypto import X509StoreContextError - -from throng_api.device_security import public_key_bytes, strict_json, validate_attestation -from throng_api.enrollment import authority, record_certificate -from throng_api.models import AgentEnrollment, DeviceCertificate, ProtocolNonce -from throng_api.powercell import bounded_body - -router = APIRouter(prefix="/acme/powercell", tags=["Power Cell ACME"]) - - -class AcmeError(Exception): - def __init__(self, detail, code="malformed", status=400): - self.detail, self.code, self.status = detail, code, status - - -def unb64(value): - if not isinstance(value, str) or len(value) > 512 * 1024: - raise ValueError("Invalid base64url value") - return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True) - - -def jwk_key(jwk, algorithm): - if ( - algorithm == "ES256" - and set(jwk) == {"kty", "crv", "x", "y"} - and jwk["kty"] == "EC" - and jwk["crv"] == "P-256" - ): - return ec.EllipticCurvePublicNumbers( - int.from_bytes(unb64(jwk["x"]), "big"), - int.from_bytes(unb64(jwk["y"]), "big"), - ec.SECP256R1(), - ).public_key() - if algorithm == "RS256" and set(jwk) == {"kty", "n", "e"} and jwk["kty"] == "RSA": - key = rsa.RSAPublicNumbers( - int.from_bytes(unb64(jwk["e"]), "big"), int.from_bytes(unb64(jwk["n"]), "big") - ).public_key() - if not 2048 <= key.key_size <= 4096: - raise ValueError("Unsupported RSA account key size") - return key - raise ValueError("Unsupported account algorithm or JWK") - - -async def authenticate_jws(session, request, row, issuer, operation, content): - try: - envelope = strict_json(content) - if set(envelope) != {"protected", "payload", "signature"}: - raise ValueError("Expected flattened JWS") - protected = strict_json(unb64(envelope["protected"])) - identity = "jwk" if operation == "new-account" else "kid" - if set(protected) != {"alg", "nonce", "url", identity} or protected[ - "url" - ] != issuer.endpoint(row, operation): - raise ValueError("JWS protected headers do not match this endpoint") - if identity == "kid" and ( - not row.account_jwk or protected["kid"] != issuer.endpoint(row, "account") - ): - raise ValueError("Unknown ACME account") - if not isinstance(protected["nonce"], str) or not 1 <= len(protected["nonce"]) <= 64: - raise ValueError("Invalid nonce") - jwk = protected["jwk"] if identity == "jwk" else row.account_jwk - key = jwk_key(jwk, protected["alg"]) - signature = unb64(envelope["signature"]) - signed = (envelope["protected"] + "." + envelope["payload"]).encode() - if isinstance(key, ec.EllipticCurvePublicKey): - if len(signature) != 64: - raise ValueError("Invalid ES256 signature size") - signature = utils.encode_dss_signature( - int.from_bytes(signature[:32], "big"), int.from_bytes(signature[32:], "big") - ) - key.verify(signature, signed, ec.ECDSA(hashes.SHA256())) - else: - key.verify(signature, signed, padding.PKCS1v15(), hashes.SHA256()) - nonce = await session.get(ProtocolNonce, ("acme:" + row.id, protected["nonce"])) - if not nonce or nonce.expires_at <= request.app.state.clock(): - raise AcmeError("Fetch a new replay nonce", "badNonce") - await session.delete(nonce) - payload = unb64(envelope["payload"]) - return (strict_json(payload) if payload else None), jwk - except ( - ValueError, - TypeError, - KeyError, - AttributeError, - binascii.Error, - InvalidSignature, - ) as error: - raise AcmeError("Invalid ACME signed request", "unauthorized", 401) from error - - -def challenge(row, issuer): - result = { - "type": "device-attest-01", - "url": issuer.endpoint(row, "challenge"), - "status": "valid" if row.attested_key else "pending", - "token": row.challenge_token, - } - return result - - -def order(row, issuer): - return { - "status": "valid" if row.certificate_sha256 else "ready" if row.attested_key else "pending", - "expires": row.expires_at.isoformat(), - "identifiers": [{"type": "permanent-identifier", "value": row.id}], - "authorizations": [issuer.endpoint(row, "authorization")], - "finalize": issuer.endpoint(row, "finalize"), - **({"certificate": issuer.endpoint(row, "certificate")} if row.certificate_sha256 else {}), - } - - -async def dispatch(session, request, row, issuer, operation, payload, jwk): - if operation == "new-account": - if not isinstance(payload, dict) or set(payload) - { - "termsOfServiceAgreed", - "contact", - "onlyReturnExisting", - }: - raise AcmeError("Invalid account request") - if row.account_jwk and row.account_jwk != jwk: - raise AcmeError("Enrollment already has an account", "unauthorized", 401) - if payload.get("onlyReturnExisting") and not row.account_jwk: - raise AcmeError("Account not found", "accountDoesNotExist") - created = row.account_jwk is None - row.account_jwk = jwk - return ( - {"status": "valid", "orders": issuer.endpoint(row, "orders")}, - 201 if created else 200, - {"Location": issuer.endpoint(row, "account")}, - ) - if operation == "new-order": - if payload != {"identifiers": [{"type": "permanent-identifier", "value": row.id}]}: - raise AcmeError("Order identifier must match this enrollment", "rejectedIdentifier") - row.order_created = True - return order(row, issuer), 201, {"Location": issuer.endpoint(row, "order")} - if operation == "account": - if payload not in (None, {}): - raise AcmeError("Account updates are not supported") - return {"status": "valid", "orders": issuer.endpoint(row, "orders")}, 200, {} - if operation == "orders": - if payload is not None: - raise AcmeError("Use POST-as-GET") - return {"orders": [issuer.endpoint(row, "order")] if row.order_created else []}, 200, {} - if not row.order_created: - raise AcmeError("Order not found", "unauthorized", 401) - if operation in {"order", "authorization", "certificate"} and payload is not None: - raise AcmeError("Use POST-as-GET") - if operation == "order": - return order(row, issuer), 200, {} - if operation == "authorization": - return ( - { - "status": "valid" if row.attested_key else "pending", - "expires": row.expires_at.isoformat(), - "identifier": {"type": "permanent-identifier", "value": row.id}, - "challenges": [challenge(row, issuer)], - }, - 200, - {}, - ) - if operation == "challenge": - if payload is None: - return challenge(row, issuer), 200, {} - if not isinstance(payload, dict) or set(payload) != {"attObj"}: - raise AcmeError("Apple attObj is required", "badAttestationStatement") - try: - identity, key = validate_attestation( - unb64(payload["attObj"]), row.challenge_token, request.app.state.clock() - ) - except ( - ValueError, - TypeError, - KeyError, - AttributeError, - x509.ExtensionNotFound, - cbor2.CBORDecodeError, - X509StoreContextError, - ) as error: - raise AcmeError( - "Apple attestation validation failed", "badAttestationStatement" - ) from error - if row.attested_key and (row.attested_key != key or row.identity_hash != identity): - raise AcmeError("Attestation already bound to another key", "badAttestationStatement") - row.attested_key, row.identity_hash = key, identity - return challenge(row, issuer), 200, {} - if operation == "finalize": - if not row.attested_key: - raise AcmeError("Complete attestation before finalizing", "orderNotReady") - try: - if not isinstance(payload, dict) or set(payload) != {"csr"}: - raise ValueError("CSR required") - encoded = unb64(payload["csr"]) - csr = x509.load_der_x509_csr(encoded) - if not csr.is_signature_valid or public_key_bytes(csr.public_key()) != row.attested_key: - raise ValueError("CSR key must be the attested key") - checksum = hashlib.sha256(encoded).hexdigest() - if row.csr_sha256 and row.csr_sha256 != checksum: - raise ValueError("Order was finalized with a different CSR") - if not row.certificate_sha256: - certificate = issuer.issue(row, csr, request.app.state.clock()) - await record_certificate(session, row, certificate) - row.csr_sha256 = checksum - except (ValueError, TypeError, KeyError) as error: - raise AcmeError("Invalid CSR or unavailable issuer", "badCSR") from error - return order(row, issuer), 200, {"Location": issuer.endpoint(row, "order")} - if operation == "certificate" and row.certificate_sha256: - certificate = await session.get(DeviceCertificate, row.certificate_sha256) - return certificate.pem + issuer.cert.public_bytes(serialization.Encoding.PEM), 200, {} - raise AcmeError("Unknown or unavailable ACME operation") - - -@router.get("/{enrollment_id}/{directory_secret}/{operation}") -@router.head("/{enrollment_id}/{directory_secret}/{operation}") -@router.post("/{enrollment_id}/{directory_secret}/{operation}") -async def acme(enrollment_id: UUID, directory_secret: str, operation: str, request: Request): - issuer = authority(request) - content = await bounded_body(request, 512 * 1024) - async with request.app.state.db.write() as session: - row = await session.get(AgentEnrollment, str(enrollment_id)) - now = request.app.state.clock() - if ( - not row - or not secrets.compare_digest(row.acme_secret, directory_secret) - or row.expires_at <= now - ): - return JSONResponse( - { - "type": "urn:ietf:params:acme:error:unauthorized", - "detail": "Unknown or expired enrollment", - }, - status_code=401, - media_type="application/problem+json", - ) - nonce = secrets.token_urlsafe(32) - session.add( - ProtocolNonce( - namespace="acme:" + row.id, value=nonce, expires_at=now + timedelta(minutes=10) - ) - ) - headers = { - "Replay-Nonce": nonce, - "Cache-Control": "no-store", - "Link": "<" + issuer.endpoint(row, "directory") + '>;rel="index"', - } - try: - if request.method == "GET" and operation == "directory": - body = { - "newNonce": issuer.endpoint(row, "nonce"), - "newAccount": issuer.endpoint(row, "new-account"), - "newOrder": issuer.endpoint(row, "new-order"), - } - return JSONResponse(body, headers=headers) - if request.method in {"HEAD", "GET"} and operation == "nonce": - return Response( - status_code=200 if request.method == "HEAD" else 204, headers=headers - ) - if request.method != "POST": - raise AcmeError("Use POST with a signed JWS", status=405) - payload, jwk = await authenticate_jws(session, request, row, issuer, operation, content) - body, status, extra = await dispatch( - session, request, row, issuer, operation, payload, jwk - ) - headers.update(extra) - if isinstance(body, bytes): - return Response( - body, - status_code=status, - media_type="application/pem-certificate-chain", - headers=headers, - ) - return JSONResponse(body, status_code=status, headers=headers) - except AcmeError as error: - # Commit consumed request nonce even when a validly signed operation is rejected. - return JSONResponse( - {"type": "urn:ietf:params:acme:error:" + error.code, "detail": error.detail}, - status_code=error.status, - media_type="application/problem+json", - headers=headers, - ) diff --git a/platform/api/throng_api/agents.py b/platform/api/throng_api/agents.py index 65977381..5b2851f0 100644 --- a/platform/api/throng_api/agents.py +++ b/platform/api/throng_api/agents.py @@ -17,7 +17,6 @@ receive_file, ) from throng_api.availability import sync_capacity -from throng_api.device_security import agent_device_proof from throng_api.execution import ( TASK_TERMINAL, check_new_work, @@ -50,7 +49,7 @@ router = APIRouter( prefix="/agent/v1", tags=["agent protocol v1"], - dependencies=[Depends(agent_credential_scheme), Depends(agent_device_proof)], + dependencies=[Depends(agent_credential_scheme)], ) # The runtime guard stays in agent_auth(), preserving 401 for invalid credentials @@ -115,8 +114,6 @@ def confirm_connected_account(computer, credential): if credential.pending_connected_user_id is not None: computer.connected_user_id = credential.pending_connected_user_id credential.pending_connected_user_id = None - computer.legacy_transfer_user_id = None - computer.legacy_transfer_pending = False @router.post("/connection/confirm", status_code=204) @@ -124,8 +121,8 @@ async def confirm_connection(data: ComputerConnectionConfirmation, request: Requ """Confirm the persisted key without starting a worker or a lease.""" async with request.app.state.db.write() as session: computer, credential = await authenticated_agent(session, request, require_session=False) - if computer.id != str(data.computer_id) or not computer.certificate_sha256: - raise HTTPException(404, "Attested computer not found") + if computer.id != str(data.computer_id): + raise HTTPException(404, "Computer not found") confirm_connected_account(computer, credential) @@ -166,12 +163,12 @@ async def current_session(request: Request, include_pool: bool = False): "session_id": computer.session_id, "server_time": now, "lease_expires_at": computer.lease_expires_at, - "transfer_pending": computer.legacy_transfer_pending, + "transfer_pending": False, "active": bool( computer.online and computer.lease_expires_at and computer.lease_expires_at > now ), } - if include_pool and computer.certificate_sha256 and not computer.legacy_transfer_pending: + if include_pool: state["pool_owner"] = ( ( await session.execute( diff --git a/platform/api/throng_api/app.py b/platform/api/throng_api/app.py index a37fcaa9..6620d0a5 100644 --- a/platform/api/throng_api/app.py +++ b/platform/api/throng_api/app.py @@ -13,7 +13,6 @@ from throng_api import ( __version__, accounts, - acme, agents, api_tokens, artifacts, @@ -33,7 +32,6 @@ jobs, organization_directory, powercell, - relay, resources, token_checks, ) @@ -53,13 +51,9 @@ async def lifespan(app): app.state.db = Database(settings.database_url) task = None ci_task = None - relay_server = None stop = asyncio.Event() try: await app.state.db.check() - if app.state.powercell_relay: - relay_server = relay.RelayServer(app, settings, app.state.powercell_relay) - await relay_server.start() if settings.controller_enabled: task = asyncio.create_task(controller.run(app, stop), name="throng-controller") ci_task = asyncio.create_task( @@ -67,8 +61,6 @@ async def lifespan(app): ) yield finally: - if relay_server: - await relay_server.close() if task: # Finish the current transaction before disposing connections. # Cancelling an in-flight SQLite statement can retain its write lock. @@ -112,8 +104,7 @@ async def lifespan(app): "Плагин Throng, исполняющий агент, веб-интерфейс и админка реализуются отдельно." ), ) - app.state.powercell_authority = enrollment.configure_authority(settings) - app.state.powercell_relay = relay.configuration(settings) + app.state.enrollment_cipher = enrollment.cipher(settings) app.state.settings = settings app.state.github = github.configure(settings) app.state.clock = clock @@ -243,7 +234,6 @@ async def ready(request: Request): github_catalog.router, ci.public_router, github_webhook.router, - acme.router, resources.router, ): app.include_router(router) diff --git a/platform/api/throng_api/benchmarks.py b/platform/api/throng_api/benchmarks.py index 6fbd6b74..00d5896a 100644 --- a/platform/api/throng_api/benchmarks.py +++ b/platform/api/throng_api/benchmarks.py @@ -13,7 +13,6 @@ semver_key, ) from throng_api.computers import computer_for_user -from throng_api.device_security import agent_device_proof from throng_api.models import ( BenchmarkAggregateInvalidation, BenchmarkResult, @@ -36,7 +35,7 @@ agent_router = APIRouter( prefix="/agent/v1", tags=["agent protocol v1"], - dependencies=[Depends(agent_credential_scheme), Depends(agent_device_proof)], + dependencies=[Depends(agent_credential_scheme)], ) diff --git a/platform/api/throng_api/computers.py b/platform/api/throng_api/computers.py index 44f8f8d0..7d59a28e 100644 --- a/platform/api/throng_api/computers.py +++ b/platform/api/throng_api/computers.py @@ -84,22 +84,21 @@ def computer_view(computer, now): def connected_to_account(user_id): + """Computers connected to an account, including installations not yet pooled.""" return ( select(Computer, ComputerOwnership) - .join(ComputerOwnership, ComputerOwnership.computer_id == Computer.id) + .outerjoin(ComputerOwnership, ComputerOwnership.computer_id == Computer.id) .where( Computer.connected_user_id == user_id, - or_(ComputerOwnership.user_id.is_(None), ComputerOwnership.user_id == user_id), + or_( + ComputerOwnership.id.is_(None), + ComputerOwnership.user_id.is_(None), + ComputerOwnership.user_id == user_id, + ), ) ) -def legacy_transfer_pending(computer, credential): - return bool( - computer.certificate_sha256 and (credential is None or computer.legacy_transfer_pending) - ) - - @router.get("/connected-computers", response_model=out.ConnectedComputers) async def list_connected_computers( request: Request, @@ -146,16 +145,20 @@ async def list_connected_computers( .offset(offset) ) items = [] - for computer, owner, company_name, membership_id, role, permissions, credential in rows: + for computer, owner, company_name, membership_id, role, permissions, _credential in rows: pool = None can_move = False - if owner.user_id == user_id: + revision = 0 + if owner is None: + can_move = computer.registered_by_user_id == user_id + elif owner.user_id == user_id: pool = {"company_id": None, "name": None} can_move = True + revision = owner.revision elif company_name is not None: pool = {"company_id": owner.company_id, "name": company_name} can_move = "resources.manage" in effective_permissions(role, permissions) - pending = legacy_transfer_pending(computer, credential) + revision = owner.revision items.append( { "id": computer.id, @@ -166,9 +169,9 @@ async def list_connected_computers( "online": active_computer_session(computer, now), "pool": pool, "pool_membership_id": membership_id, - "pool_revision": owner.revision, - "can_move": can_move and "manage" in principal.scopes and not pending, - "transfer_pending": pending, + "pool_revision": revision, + "can_move": can_move and "manage" in principal.scopes, + "transfer_pending": False, } ) response.headers[COMPUTER_POOL_CHECK_REVISION_HEADER] = str(await current_revision(session)) @@ -211,11 +214,7 @@ async def can_recover_connected_computer( .join(ComputerOwnership, ComputerOwnership.computer_id == Computer.id) .where( Computer.id == str(computer_id), - Computer.certificate_sha256.is_not(None), - or_( - Computer.connected_user_id == user_id, - Computer.legacy_transfer_user_id == user_id, - ), + Computer.connected_user_id == user_id, owned_filter(ComputerOwnership, principal), ) ) @@ -243,9 +242,7 @@ async def recover_connected_computer_key( .join(ComputerOwnership, ComputerOwnership.computer_id == Computer.id) .where( Computer.id == str(computer_id), - Computer.certificate_sha256.is_not(None), - Computer.legacy_transfer_pending.is_(True), - Computer.legacy_transfer_user_id == user_id, + Computer.connected_user_id == user_id, owned_filter(ComputerOwnership, principal), ) ) @@ -372,8 +369,8 @@ async def apply_connected_pool_move( if row is None: raise HTTPException(404, "Connected computer not found") computer, owner = row - member = await owner_access(session, principal, owner, admin=True) - before = (owner.user_id, owner.company_id) + member = await owner_access(session, principal, owner, admin=True) if owner else None + before = (owner.user_id, owner.company_id) if owner else (None, None) after = before if previous is None: check_expected_owner(owner, None, None, data.expected_revision) @@ -384,22 +381,25 @@ async def apply_connected_pool_move( member = await company_access(session, principal, data.company_id, admin=True) after = (None, member.company_id) if before != after: - current = UUID(owner.company_id) if owner.company_id is not None else None + current = UUID(owner.company_id) if owner and owner.company_id is not None else None if current != data.expected_company_id: raise HTTPException(409, "Computer pool changed") - credential = await session.scalar( - select(AgentCredential).where(AgentCredential.computer_id == computer.id) - ) - if legacy_transfer_pending(computer, credential): - raise HTTPException(409, "Computer has an unfinished native transfer") if computer.reserved_disk or any(resource.occupied for resource in computer.resources): raise HTTPException(409, "Computer has reserved resources") - owner.user_id, owner.company_id = after - owner.revision = await current_revision(session) + if owner is None: + owner = ComputerOwnership( + computer_id=computer.id, + user_id=after[0], + company_id=after[1], + revision=await current_revision(session), + ) + session.add(owner) + else: + owner.user_id, owner.company_id = after + owner.revision = await current_revision(session) await session.flush() now = request.app.state.clock() - # The agent still belongs to this account and holds the same certified - # device key. Update the owner and capacity ledger in one transaction. + # The installation keeps its credential; only the pool ledger changes. await transfer_resources(session, computer, before, after, now, principal.actor_id) await sync_capacity(session, computer, now) if idempotency_key is not None and previous is None: @@ -457,7 +457,7 @@ async def create_computer(data: ComputerCreate, request: Request): async with request.app.state.db.write() as session: principal = await authenticate(session, request, "manage") if data.runtime == "powercell-ubuntu-arm64-v1": - raise HTTPException(422, "Computers require attested enrollment") + raise HTTPException(422, "Use agent enrollment for Power Cell computers") owner = await owner_values(session, principal, data.company_id, admin=True) computer = Computer( **data.model_dump(exclude={"company_id", "cpu_millis", "memory_bytes"}), @@ -636,23 +636,9 @@ async def replace_computer_credential(session, principal, computer, owner, now): await invalidate_computer(session, computer, now, "credential_rotated") computer.session_id = None computer.lease_expires_at = None - if computer.certificate_sha256: - computer.legacy_transfer_pending = True - owner.revision = await current_revision(session) await session.execute(delete(AgentCredential).where(AgentCredential.computer_id == computer.id)) - pending = ( - principal.user_id - if principal.password_login and computer.legacy_transfer_user_id == principal.user_id - else None - ) raw = secret("agt_") - session.add( - AgentCredential( - computer_id=computer.id, - token_hash=digest(raw), - pending_connected_user_id=pending, - ) - ) + session.add(AgentCredential(computer_id=computer.id, token_hash=digest(raw))) return {"computer_id": computer.id, "token": raw} @@ -727,17 +713,10 @@ async def update_owner( computer = await session.get(Computer, row.computer_id) now = request.app.state.clock() await disconnect_idle(session, computer, now) - computer.legacy_transfer_pending = bool(computer.certificate_sha256) before = (row.user_id, row.company_id) for key, value in values.items(): setattr(row, key, value) row.revision = await current_revision(session) - if before != (row.user_id, row.company_id): - computer.legacy_transfer_user_id = ( - principal.user_id - if computer.certificate_sha256 and principal.password_login - else None - ) await session.flush() await transfer_resources( session, @@ -753,6 +732,10 @@ async def update_owner( def check_expected_owner(owner, company_id, user_id, revision): if company_id is not None and user_id is not None: raise HTTPException(422, "Specify a single expected computer owner") + if owner is None: + if company_id is not None or user_id is not None or revision not in (None, 0): + raise ProtocolError("computer_pool_changed", "Computer pool changed") + return if ( (company_id is not None and owner.company_id != str(company_id)) or (user_id is not None and owner.user_id != str(user_id)) @@ -769,9 +752,6 @@ async def delete_owner(ownership_id: UUID, request: Request): computer = await session.get(Computer, row.computer_id) now = request.app.state.clock() await disconnect_idle(session, computer, now) - computer.connected_user_id = None - computer.legacy_transfer_user_id = None - computer.legacy_transfer_pending = False await transfer_resources( session, computer, diff --git a/platform/api/throng_api/config.py b/platform/api/throng_api/config.py index f72e8c07..cf842481 100644 --- a/platform/api/throng_api/config.py +++ b/platform/api/throng_api/config.py @@ -34,19 +34,9 @@ class Settings(BaseSettings): long_poll_max_seconds: float = Field(default=25, ge=0, le=30) long_poll_interval: float = Field(default=0.25, ge=0.01, le=5) - # Provision explicitly; startup never creates an untrusted development CA. - powercell_acme_url: str | None = None - powercell_ca_certificate: Path | None = None - powercell_ca_key: Path | None = None - powercell_secret: str | None = Field(default=None, min_length=32, repr=False) - powercell_relay_url: str | None = None - powercell_relay_certificate: Path | None = None - powercell_relay_key: Path | None = None - powercell_relay_host: str = "127.0.0.1" - powercell_relay_keep_alive_seconds: int = Field(default=30, ge=5, le=300) + # Encrypts only the recoverable credential for an idempotent enrollment finish. + enrollment_secret: str | None = Field(default=None, min_length=32, repr=False) enrollment_seconds: int = Field(default=3600, ge=60, le=86400) - device_certificate_days: int = Field(default=365, ge=1, le=3650) - device_proof_seconds: int = Field(default=300, ge=30, le=600) agent_mutation_seconds: int = Field(default=86400, ge=60, le=604800) max_diagnostic_bytes: int = Field(default=8 * 1024 * 1024, ge=1, le=8 * 1024 * 1024) max_computer_diagnostics_bytes: int = Field(default=64 * 1024 * 1024, ge=1) diff --git a/platform/api/throng_api/device_security.py b/platform/api/throng_api/device_security.py deleted file mode 100644 index ee7f2a04..00000000 --- a/platform/api/throng_api/device_security.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Apple trust validation and request possession proofs. No client-selected trust anchors.""" - -import base64 -import binascii -import hashlib -import io -import json -from datetime import timedelta -from pathlib import Path -from uuid import UUID - -import cbor2 -from cryptography import x509 -from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec -from fastapi import HTTPException, Request -from OpenSSL import crypto -from sqlalchemy import select - -from throng_api.models import ( - AgentCredential, - AgentMutation, - Computer, - DeviceCertificate, - ProtocolNonce, -) -from throng_api.security import bearer, digest - -APPLE_ROOT = Path(__file__).with_name("certificates") / "apple-enterprise-attestation.pem" -APPLE_ROOT_SHA256 = "ccf59ef8fcb3017d97f8b5fa6fa90e7a3f9283f76b55ac6cf6eda8b8b949f05b" -SERIAL_OID = x509.ObjectIdentifier("1.2.840.113635.100.8.9.1") -UDID_OID = x509.ObjectIdentifier("1.2.840.113635.100.8.9.2") -NONCE_OID = x509.ObjectIdentifier("1.2.840.113635.100.8.11.1") -SEP_OID = x509.ObjectIdentifier("1.2.840.113635.100.8.10.2") -SIP_OID = x509.ObjectIdentifier("1.2.840.113635.100.8.13.1") - - -def strict_json(data): - def unique(pairs): - result = {} - for key, value in pairs: - if key in result: - raise ValueError("Duplicate JSON member") - result[key] = value - return result - - return json.loads( - data, - object_pairs_hook=unique, - parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)), - ) - - -def public_key_bytes(key): - return key.public_bytes( - serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo - ) - - -def validate_attestation(encoded, token, now): - """Validate Apple's ACME attestation envelope using OpenSSL's full path validator. - - Apple uses SHA256(token), unlike the generic draft's keyAuthorization construction. - Apple extension values here are raw bytes, not nested App Attest ASN.1 objects. - """ - stream = io.BytesIO(encoded) - envelope = cbor2.CBORDecoder(stream).decode() - if stream.read(1) or not isinstance(envelope, dict) or envelope.get("fmt") != "apple": - raise ValueError("Expected an Apple attestation") - chain = envelope.get("attStmt", {}).get("x5c") - if not isinstance(chain, list) or not 2 <= len(chain) <= 5: - raise ValueError("Invalid attestation chain") - certificates = [x509.load_der_x509_certificate(item) for item in chain] - root = x509.load_pem_x509_certificate(APPLE_ROOT.read_bytes()) - if root.fingerprint(hashes.SHA256()).hex() != APPLE_ROOT_SHA256: - raise ValueError("Apple trust anchor integrity failure") - store = crypto.X509Store() - store.add_cert(crypto.X509.from_cryptography(root)) - store.set_time(now) - context = crypto.X509StoreContext( - store, - crypto.X509.from_cryptography(certificates[0]), - [crypto.X509.from_cryptography(cert) for cert in certificates[1:]], - ) - context.verify_certificate() - leaf = certificates[0] - key = leaf.public_key() - if not isinstance(key, ec.EllipticCurvePublicKey) or not isinstance(key.curve, ec.SECP256R1): - raise ValueError("Expected an attested P-256 key") - - def extension(oid): - return leaf.extensions.get_extension_for_oid(oid).value.value - - if extension(NONCE_OID) != hashlib.sha256(token.encode()).digest(): - raise ValueError("Attestation freshness does not match this enrollment") - udid, serial = extension(UDID_OID), extension(SERIAL_OID) - if not udid or not serial or len(udid) > 128 or len(serial) > 128: - raise ValueError("Missing certified hardware identity") - # A Mac attestation has SIP and Secure Enclave properties. No claims from the request are used. - if not extension(SEP_OID) or not extension(SIP_OID): - raise ValueError("Missing Mac/Secure Enclave properties") - identity = hashlib.sha256(b"powercell.apple.udid.v1\x00" + udid).hexdigest() - return identity, public_key_bytes(key) - - -async def verify_proof(session, request, certificate_hash, *, allow_revoked=False): - """Recheck TLS possession, or durably consume signed-proof nonces under the write lock.""" - now = request.app.state.clock() - from throng_api.relay import RelayPeer - - peer = request.scope.get("powercell.relay_peer") - if isinstance(peer, RelayPeer): - certificate = await session.get(DeviceCertificate, certificate_hash) - if ( - peer.certificate_sha256 != certificate_hash - or not certificate - or certificate.expires_at <= now - or (certificate.revoked_at and not allow_revoked) - or x509.load_pem_x509_certificate(certificate.pem).not_valid_before_utc > now - ): - raise HTTPException(401, "Invalid device proof") - request.state.device_certificate = certificate_hash - return - window = request.app.state.settings.device_proof_seconds - try: - raw = base64.b64decode(request.headers.get("x-powercell-proof", ""), validate=True) - signature = base64.b64decode( - request.headers.get("x-powercell-signature", ""), validate=True - ) - if not raw or len(raw) > 8192 or not signature or len(signature) > 128: - raise ValueError("Missing or oversized proof") - proof = strict_json(raw) - target = request.scope.get("raw_path", request.url.path.encode()).decode("ascii") - if request.scope["query_string"]: - target += "?" + request.scope["query_string"].decode("ascii") - if not isinstance(proof, dict) or set(proof) != { - "version", - "certificate_sha256", - "method", - "target", - "timestamp", - "nonce", - "body_sha256", - "authorization_sha256", - "session", - "idempotency_key", - }: - raise ValueError("Unexpected proof fields") - if ( - type(proof["version"]) is not int - or proof["version"] != 1 - or proof["certificate_sha256"] != certificate_hash - or proof["method"] != request.method - or proof["target"] != target - or type(proof["timestamp"]) is not int - or abs(now.timestamp() - proof["timestamp"]) > window - or proof["body_sha256"] != hashlib.sha256(await request.body()).hexdigest() - or proof["authorization_sha256"] != digest(request.headers.get("authorization", "")) - or proof["session"] != request.headers.get("x-agent-session") - or proof["idempotency_key"] != request.headers.get("idempotency-key") - ): - raise ValueError("Proof does not match this request") - nonce = str(UUID(proof["nonce"])) - certificate = await session.get(DeviceCertificate, certificate_hash) - if ( - not certificate - or certificate.expires_at <= now - or (certificate.revoked_at and not allow_revoked) - ): - raise ValueError("Certificate is expired or revoked") - cert = x509.load_pem_x509_certificate(certificate.pem) - if cert.not_valid_before_utc > now: - raise ValueError("Certificate not yet valid") - cert.public_key().verify(signature, raw, ec.ECDSA(hashes.SHA256())) - except ( - ValueError, - TypeError, - KeyError, - AttributeError, - binascii.Error, - InvalidSignature, - ) as error: - raise HTTPException(401, "Invalid device proof") from error - identity = (certificate_hash, nonce) - previous = await session.get(ProtocolNonce, identity) - if previous and previous.expires_at > now: - raise HTTPException(401, "Device proof nonce has already been used") - if previous: - await session.delete(previous) - await session.flush() - # Keep until this timestamp can no longer be accepted, including future-skewed proofs. - session.add( - ProtocolNonce( - namespace=certificate_hash, - value=nonce, - expires_at=now + timedelta(seconds=2 * window + 1), - ) - ) - request.state.device_certificate = certificate_hash - - -async def agent_device_proof(request: Request): - """FastAPI dependency shared by every agent operation, including session-free uploads.""" - from throng_api.powercell import bounded_body - - certificate_hash = None - tombstone = False - async with request.app.state.db.read() as session: - credential_hash = digest(bearer(request)) - credential = await session.scalar( - select(AgentCredential).where(AgentCredential.token_hash == credential_hash) - ) - if credential: - computer = await session.get(Computer, credential.computer_id) - certificate_hash = computer.certificate_sha256 if computer else None - elif request.url.path == "/agent/v1/unbind": - row = await session.get( - AgentMutation, - (credential_hash, "unbind", request.headers.get("idempotency-key", "")), - ) - if row and row.expires_at > request.app.state.clock(): - certificate_hash, tombstone = row.certificate_sha256, True - if certificate_hash: - from throng_api.relay import RelayPeer - - limit = request.app.state.settings.max_artifact_bytes - if "/diagnostics/" in request.url.path: - limit = request.app.state.settings.max_diagnostic_bytes - await bounded_body(request, limit) - # TLS possession checks have no nonce to consume. Signed HTTP proofs - # still require the durable write lock for their replay protection. - context = ( - request.app.state.db.read - if isinstance(request.scope.get("powercell.relay_peer"), RelayPeer) - else request.app.state.db.write - ) - async with context() as session: - await verify_proof(session, request, certificate_hash, allow_revoked=tombstone) diff --git a/platform/api/throng_api/enrollment.py b/platform/api/throng_api/enrollment.py index 30d79a73..6c832b50 100644 --- a/platform/api/throng_api/enrollment.py +++ b/platform/api/throng_api/enrollment.py @@ -1,22 +1,20 @@ -"""User-authorized, single-certificate enrollment and ACME identity profiles.""" +"""User-authorized computer registration with a client-generated device id. + +There is no hardware attestation, ACME profile or possession proof here. The +installation announces its opaque id at login and reuses it when registering a +computer. The server only has to keep that association and issue one durable +agent credential per registration. +""" import base64 import hashlib -import plistlib -import secrets from datetime import timedelta -from urllib.parse import urlsplit -from uuid import NAMESPACE_URL, UUID, uuid5 +from uuid import UUID -from cryptography import x509 from cryptography.fernet import Fernet -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID -from fastapi import APIRouter, Depends, Header, HTTPException, Request, Response +from fastapi import APIRouter, Depends, Header, HTTPException, Request from sqlalchemy import select -from throng_api.device_security import public_key_bytes, verify_proof from throng_api.execution import remember, replay from throng_api.models import ( CPU_RESOURCE_ID, @@ -25,13 +23,12 @@ AgentEnrollment, Computer, ComputerOwnership, - DeviceCertificate, - PhysicalDevice, + Device, + DeviceAccount, new_id, ) from throng_api.powercell import bounded_body from throng_api.powercell_schemas import Binding, EnrollmentCreate, EnrollmentStatus -from throng_api.relay import enrollment_configuration from throng_api.resource_ledger import add_resource from throng_api.security import ( access_token_scheme, @@ -49,6 +46,7 @@ public_router = APIRouter(tags=["Power Cell capabilities"]) EXTENSIONS = [ "powercell.enrollment.v1", + "powercell.device.v1", "powercell.capacity.v1", "powercell.eviction.v1", "powercell.diagnostics.v1", @@ -57,132 +55,39 @@ ] -class Authority: - """Load operator-managed signing material once; never include it in responses or logs.""" - - def __init__(self, settings): - url = urlsplit(settings.powercell_acme_url) - if ( - url.scheme != "https" - or not url.hostname - or url.query - or url.fragment - or url.username - or url.password - ): - raise ValueError( - "THRONG_POWERCELL_ACME_URL must be an absolute HTTPS URL without credentials/query/fragment" - ) - self.base = settings.powercell_acme_url.rstrip("/") - self.cert = x509.load_pem_x509_certificate(settings.powercell_ca_certificate.read_bytes()) - self.key = serialization.load_pem_private_key( - settings.powercell_ca_key.read_bytes(), password=None - ) - if ( - not isinstance(self.key, ec.EllipticCurvePrivateKey) - or public_key_bytes(self.key.public_key()) != public_key_bytes(self.cert.public_key()) - or not self.cert.extensions.get_extension_for_class(x509.BasicConstraints).value.ca - ): - raise ValueError("Power Cell CA requires a matching EC CA certificate and private key") - self.fernet = Fernet( - base64.urlsafe_b64encode(hashlib.sha256(settings.powercell_secret.encode()).digest()) - ) - self.days = settings.device_certificate_days - - def endpoint(self, enrollment, operation): - return f"{self.base}/{enrollment.id}/{enrollment.acme_secret}/{operation}" - - def issue(self, enrollment, csr, now): - if not self.cert.not_valid_before_utc <= now < self.cert.not_valid_after_utc: - raise ValueError("Power Cell CA is not currently valid") - identifier = enrollment.id.encode() - permanent = x509.OtherName( - x509.ObjectIdentifier("1.3.6.1.5.5.7.8.3"), - b"\x30" - + bytes([len(identifier) + 2]) - + b"\x0c" - + bytes([len(identifier)]) - + identifier, - ) - return ( - x509.CertificateBuilder() - .subject_name( - x509.Name( - [x509.NameAttribute(NameOID.COMMON_NAME, f"Mutating Compute {enrollment.id}")] - ) - ) - .issuer_name(self.cert.subject) - .public_key(csr.public_key()) - .serial_number(x509.random_serial_number()) - .not_valid_before(now - timedelta(minutes=5)) - .not_valid_after(min(now + timedelta(days=self.days), self.cert.not_valid_after_utc)) - .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) - .add_extension( - x509.KeyUsage(True, False, False, False, False, False, False, False, False), - critical=True, - ) - .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False) - .add_extension(x509.SubjectAlternativeName([permanent]), critical=False) - .add_extension( - x509.SubjectKeyIdentifier.from_public_key(csr.public_key()), critical=False - ) - .add_extension( - x509.AuthorityKeyIdentifier.from_issuer_public_key(self.cert.public_key()), - critical=False, - ) - .sign(self.key, hashes.SHA256()) - ) - - -def configure_authority(settings): - fields = ( - settings.powercell_acme_url, - settings.powercell_ca_certificate, - settings.powercell_ca_key, - settings.powercell_secret, - ) - if not any(fields): +def cipher(settings): + """Build the at-rest cipher used only to recover an idempotent finish reply.""" + if not settings.enrollment_secret: return None - if not all(fields): - raise ValueError( - "Configure all four THRONG_POWERCELL_ACME_URL/CA_CERTIFICATE/CA_KEY/SECRET settings" - ) - return Authority(settings) + key = hashlib.sha256(settings.enrollment_secret.encode()).digest() + return Fernet(base64.urlsafe_b64encode(key)) -def authority(request): - if request.app.state.powercell_authority is None: - raise HTTPException(503, "Mutating Compute certificate authority is not configured") - return request.app.state.powercell_authority +def credential_cipher(request): + value = request.app.state.enrollment_cipher + if value is None: + raise HTTPException(503, "Computer enrollment is not configured") + return value @public_router.get("/v1/agent-capabilities") async def capabilities(request: Request): - configured = request.app.state.powercell_authority is not None return { "protocol_version": 1, - "extensions": (EXTENSIONS if configured else EXTENSIONS[1:]) - + (["powercell.relay.v1"] if request.app.state.powercell_relay else []) - + ["powercell.images.v1"], + "extensions": EXTENSIONS + ["powercell.images.v1"], "runtime": "powercell-ubuntu-arm64-v1", "images": ["ubuntu:24.04"], "image_families": ["ghcr.io/actions/actions-runner"], "image_aliases": IMAGE_ALIASES, - "attestation_required": True, + "device_registration": "client-uuid-v1", } -def enrollment_status(row, now, relay=None): - status = "verified" if row.certificate_sha256 else "pending_attestation" +def enrollment_status(row, now): + status = "verified" if row.expires_at <= now and not row.computer_id: status = "expired" - return { - "id": row.id, - "status": status, - "expires_at": row.expires_at, - "certificate_sha256": row.certificate_sha256, - "relay": enrollment_configuration(relay, row.id), - } + return {"id": row.id, "status": status, "expires_at": row.expires_at} async def enrollment_for_user(session, request, enrollment_id, scope="read"): @@ -194,6 +99,14 @@ async def enrollment_for_user(session, request, enrollment_id, scope="read"): return row, principal +async def registered_device(session, user_id, client_id): + """Resolve a device announced by this account, rejecting unregistered claims.""" + device = await session.scalar(select(Device).where(Device.client_key == str(client_id).lower())) + if device is None or await session.get(DeviceAccount, (device.id, user_id)) is None: + raise HTTPException(409, "Sign in with this device before registering it") + return device + + @router.post("/agent-enrollments", status_code=201, response_model=EnrollmentStatus) async def create_enrollment( data: EnrollmentCreate, request: Request, idempotency_key: str = Header() @@ -201,15 +114,27 @@ async def create_enrollment( async with request.app.state.db.write() as session: principal = await authenticate(session, request, "manage") actor_id = personal(principal) - authority(request) - await owner_values(session, principal, data.company_id, admin=True) payload = data.model_dump(mode="json") previous = await replay(session, principal.key, "enrollment", idempotency_key, payload) now = request.app.state.clock() if previous: - return enrollment_status( - await session.get(AgentEnrollment, previous), now, request.app.state.powercell_relay + return enrollment_status(await session.get(AgentEnrollment, previous), now) + device = await registered_device(session, actor_id, data.client_device_id) + if row := await session.scalar( + select(AgentEnrollment).where( + AgentEnrollment.device_id == device.id, + AgentEnrollment.actor_id == actor_id, + AgentEnrollment.computer_id.is_(None), + AgentEnrollment.expires_at > now, ) + ): + # A lost reply can be recovered with a fresh key only when the + # immutable request is identical. An explicit restart replaces the + # unfinished attempt instead of stranding this device for an hour. + if row.request == payload: + return enrollment_status(row, now) + await session.delete(row) + await session.flush() count = await session.scalars( select(AgentEnrollment).where( AgentEnrollment.actor_id == actor_id, AgentEnrollment.expires_at > now @@ -220,97 +145,22 @@ async def create_enrollment( row = AgentEnrollment( id=new_id(), actor_id=actor_id, - installation_id=str(data.installation_id), + device_id=device.id, request=payload, - acme_secret=secrets.token_urlsafe(32), - challenge_token=secrets.token_urlsafe(32), created_at=now, expires_at=now + timedelta(seconds=request.app.state.settings.enrollment_seconds), ) session.add(row) await session.flush() remember(session, principal.key, "enrollment", idempotency_key, payload, row.id) - return enrollment_status(row, now, request.app.state.powercell_relay) + return enrollment_status(row, now) @router.get("/agent-enrollments/{enrollment_id}", response_model=EnrollmentStatus) async def get_enrollment(enrollment_id: UUID, request: Request): async with request.app.state.db.read() as session: row, _ = await enrollment_for_user(session, request, enrollment_id) - return enrollment_status(row, request.app.state.clock(), request.app.state.powercell_relay) - - -@router.get("/agent-enrollments/{enrollment_id}/profile", response_class=Response) -async def profile(enrollment_id: UUID, request: Request): - async with request.app.state.db.read() as session: - row, _ = await enrollment_for_user(session, request, enrollment_id) - issuer = authority(request) - if row.expires_at <= request.app.state.clock() or row.computer_id: - raise HTTPException(409, "Enrollment is no longer pending") - prefix = f"tech.mutating.powercell.{row.id}" - acme = { - "PayloadType": "com.apple.security.acme", - "PayloadVersion": 1, - "PayloadIdentifier": prefix + ".identity", - "PayloadUUID": str(uuid5(NAMESPACE_URL, prefix + ".identity")), - "PayloadDisplayName": "Mutating Compute device identity", - "DirectoryURL": issuer.endpoint(row, "directory"), - "ClientIdentifier": row.id, - "Subject": [[["CN", f"Mutating Compute {row.id}"]]], - "KeyType": "ECSECPrimeRandom", - "KeySize": 256, - "HardwareBound": True, - "Attest": True, - "KeyIsExtractable": False, - "AllowAllAppsAccess": False, - "ExtendedKeyUsage": ["1.3.6.1.5.5.7.3.2"], - "UsageFlags": 1, - } - document = { - "PayloadType": "Configuration", - "PayloadVersion": 1, - "PayloadIdentifier": prefix, - "PayloadUUID": row.id, - "PayloadDisplayName": "Mutating Compute device verification", - "PayloadScope": "User", - "PayloadContent": [acme], - } - if relay := enrollment_configuration(request.app.state.powercell_relay, row.id): - # The built-in relay requires its ACME key in the system keychain. - document["PayloadScope"] = "System" - document["PayloadContent"].append( - { - "PayloadType": "com.apple.relay.managed", - "PayloadVersion": 1, - "PayloadIdentifier": prefix + ".relay", - "PayloadUUID": str(uuid5(NAMESPACE_URL, prefix + ".relay")), - "PayloadDisplayName": "Mutating Compute authenticated API connection", - "MatchDomains": [urlsplit(relay["api_origin"]).hostname], - "Relays": [ - { - "HTTP2RelayURL": relay["url"], - "PayloadCertificateUUID": acme["PayloadUUID"], - } - ], - } - ) - return Response( - plistlib.dumps(document), - media_type="application/x-apple-aspen-config", - headers={"Cache-Control": "no-store"}, - ) - - -@router.get("/agent-enrollments/{enrollment_id}/verification", response_model=EnrollmentStatus) -async def verify_enrolled_device(enrollment_id: UUID, request: Request): - """Confirm that this connection holds the key certified for this user's enrollment.""" - async with request.app.state.db.write() as session: - row, _ = await enrollment_for_user(session, request, enrollment_id) - now = request.app.state.clock() - if not row.certificate_sha256 or (not row.computer_id and row.expires_at <= now): - raise HTTPException(409, "Enrollment requires a fresh verified attestation") - await verify_proof(session, request, row.certificate_sha256) - return enrollment_status(row, now, request.app.state.powercell_relay) + return enrollment_status(row, request.app.state.clock()) @router.post("/agent-enrollments/{enrollment_id}/finish", response_model=Binding) @@ -318,37 +168,34 @@ async def finish_enrollment(enrollment_id: UUID, request: Request, idempotency_k content = await bounded_body(request, 1024) async with request.app.state.db.write() as session: row, principal = await enrollment_for_user(session, request, enrollment_id, "manage") - issuer = authority(request) if content not in (b"", b"{}"): raise HTTPException(422, "Enrollment finish accepts only an empty object") now = request.app.state.clock() - if not row.certificate_sha256 or (not row.computer_id and row.expires_at <= now): - raise HTTPException(409, "Enrollment requires a fresh verified attestation") - await verify_proof(session, request, row.certificate_sha256) + if not row.computer_id and row.expires_at <= now: + raise HTTPException(409, "Enrollment has expired") if not idempotency_key.strip() or len(idempotency_key) > 128: raise HTTPException(422, "Idempotency-Key of 1 to 128 characters is required") - certificate = await session.get(DeviceCertificate, row.certificate_sha256) + issuer = credential_cipher(request) + device = await session.get(Device, row.device_id) if row.computer_id: if row.finish_key != idempotency_key: raise HTTPException(409, "Enrollment has already been bound") - credential = issuer.fernet.decrypt(row.credential_encrypted).decode() + credential = issuer.decrypt(row.credential_encrypted).decode() current = await session.scalar( select(AgentCredential).where(AgentCredential.computer_id == row.computer_id) ) if not current or current.token_hash != digest(credential): raise HTTPException(409, "Enrollment credential has been replaced or revoked") else: - owner = await owner_values(session, principal, row.request["company_id"], admin=True) - values = { - key: row.request[key] - for key in ( - "name", - "os", - "architecture", - "runtime", - "disk_bytes", - "isolation_modes", + request_values = row.request + owner = None + if request_values.get("assign_pool"): + owner = await owner_values( + session, principal, request_values.get("company_id"), admin=True ) + values = { + key: request_values[key] + for key in ("name", "os", "architecture", "runtime", "disk_bytes", "isolation_modes") } computer = Computer( **values, @@ -356,46 +203,24 @@ async def finish_enrollment(enrollment_id: UUID, request: Request, idempotency_k connected_user_id=principal.user_id if principal.password_login else None, resources=[], accepting_work=False, - device_id=certificate.device_id, - certificate_sha256=certificate.sha256, + device_id=device.id, ) session.add(computer) await session.flush() - session.add(ComputerOwnership(computer_id=computer.id, **owner)) - await session.flush() + if owner is not None: + session.add(ComputerOwnership(computer_id=computer.id, **owner)) + await session.flush() for type_id, amount in ( - (CPU_RESOURCE_ID, row.request["cpu_millis"]), - (MEMORY_RESOURCE_ID, row.request["memory_bytes"]), + (CPU_RESOURCE_ID, request_values["cpu_millis"]), + (MEMORY_RESOURCE_ID, request_values["memory_bytes"]), ): await add_resource(session, computer, type_id, amount, now, principal.actor_id) credential = secret("agt_") session.add(AgentCredential(computer_id=computer.id, token_hash=digest(credential))) row.computer_id, row.finish_key = computer.id, idempotency_key - row.credential_encrypted = issuer.fernet.encrypt(credential.encode()) + row.credential_encrypted = issuer.encrypt(credential.encode()) return { "computer_id": row.computer_id, "credential": credential, - "device_id": certificate.device_id, - "certificate_sha256": certificate.sha256, - "relay": enrollment_configuration(request.app.state.powercell_relay, row.id), + "device_id": device.id, } - - -async def record_certificate(session, row, certificate): - device = await session.scalar( - select(PhysicalDevice).where(PhysicalDevice.identity_hash == row.identity_hash) - ) - if not device: - device = PhysicalDevice(identity_hash=row.identity_hash) - session.add(device) - await session.flush() - row.certificate_sha256 = certificate.fingerprint(hashes.SHA256()).hex() - session.add( - DeviceCertificate( - sha256=row.certificate_sha256, - device_id=device.id, - enrollment_id=row.id, - pem=certificate.public_bytes(serialization.Encoding.PEM), - expires_at=certificate.not_valid_after_utc, - ) - ) diff --git a/platform/api/throng_api/execution.py b/platform/api/throng_api/execution.py index 60db6f27..8dc30946 100644 --- a/platform/api/throng_api/execution.py +++ b/platform/api/throng_api/execution.py @@ -261,8 +261,7 @@ async def clean_start(session, computer, now, settings): isolate.destroyed_at = now computer.capacity_revision = -1 computer.capacity_report = None - # An attested agent must publish policy before the first assignment in every session. - computer.accepting_work = computer.certificate_sha256 is None + computer.accepting_work = True computer.target_cpu = computer.target_memory = computer.target_disk = None computer.session_id = new_id() computer.online = True diff --git a/platform/api/throng_api/github_oidc.py b/platform/api/throng_api/github_oidc.py index 7627c660..928acf28 100644 --- a/platform/api/throng_api/github_oidc.py +++ b/platform/api/throng_api/github_oidc.py @@ -8,9 +8,8 @@ from cryptography.hazmat.primitives.asymmetric import padding from fastapi import HTTPException -from throng_api.acme import jwk_key, unb64 -from throng_api.device_security import strict_json from throng_api.github_client import GitHubError +from throng_api.jsonutil import jwk_key, strict_json, unb64 ISSUER = "https://token.actions.githubusercontent.com" JWKS_URL = ISSUER + "/.well-known/jwks" diff --git a/platform/api/throng_api/github_webhook.py b/platform/api/throng_api/github_webhook.py index c6e66e12..4db364f5 100644 --- a/platform/api/throng_api/github_webhook.py +++ b/platform/api/throng_api/github_webhook.py @@ -11,8 +11,8 @@ from throng_api.ci import ACTIVE from throng_api.ci_controller import close_github, mark_running from throng_api.ci_policy import record_revision -from throng_api.device_security import strict_json from throng_api.github import disconnect_user, service +from throng_api.jsonutil import strict_json from throng_api.models import CIReservation, CIRoute, GitHubAccount, GitHubDelivery from throng_api.powercell import bounded_body diff --git a/platform/api/throng_api/jsonutil.py b/platform/api/throng_api/jsonutil.py new file mode 100644 index 00000000..4c768f8b --- /dev/null +++ b/platform/api/throng_api/jsonutil.py @@ -0,0 +1,54 @@ +"""Strict JSON and JOSE primitives shared by signed protocol adapters.""" + +import base64 +import json + +from cryptography.hazmat.primitives.asymmetric import ec, rsa + + +def strict_json(data): + """Reject duplicate members and non-standard numeric constants.""" + + def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate JSON member") + result[key] = value + return result + + return json.loads( + data, + object_pairs_hook=unique, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)), + ) + + +def unb64(value): + """Decode unpadded base64url with a bounded input.""" + if not isinstance(value, str) or len(value) > 512 * 1024: + raise ValueError("Invalid base64url value") + return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True) + + +def jwk_key(jwk, algorithm): + """Build an EC P-256 or RSA public key from a minimal JWK.""" + if ( + algorithm == "ES256" + and set(jwk) == {"kty", "crv", "x", "y"} + and jwk["kty"] == "EC" + and jwk["crv"] == "P-256" + ): + return ec.EllipticCurvePublicNumbers( + int.from_bytes(unb64(jwk["x"]), "big"), + int.from_bytes(unb64(jwk["y"]), "big"), + ec.SECP256R1(), + ).public_key() + if algorithm == "RS256" and set(jwk) == {"kty", "n", "e"} and jwk["kty"] == "RSA": + key = rsa.RSAPublicNumbers( + int.from_bytes(unb64(jwk["e"]), "big"), int.from_bytes(unb64(jwk["n"]), "big") + ).public_key() + if not 2048 <= key.key_size <= 4096: + raise ValueError("Unsupported RSA account key size") + return key + raise ValueError("Unsupported account algorithm or JWK") diff --git a/platform/api/throng_api/migrations/versions/0028_client_devices.py b/platform/api/throng_api/migrations/versions/0028_client_devices.py new file mode 100644 index 00000000..c81db579 --- /dev/null +++ b/platform/api/throng_api/migrations/versions/0028_client_devices.py @@ -0,0 +1,203 @@ +"""Replace hardware attestation with client-generated device identities. + +Revision ID: 0028 +Revises: 0027 + +Existing certified computers keep their device row and gain an account +association. Pending enrollments keep their installation UUID as a device key +so they can still finish after the upgrade. +""" + +from uuid import uuid4 + +import sqlalchemy as sa +from alembic import op + +revision = "0028" +down_revision = "0027" +branch_labels = None +depends_on = None + + +def upgrade(): + connection = op.get_bind() + op.drop_table("device_certificates") + op.drop_table("protocol_nonces") + op.rename_table("physical_devices", "devices") + with op.batch_alter_table("devices") as batch: + batch.alter_column("identity_hash", new_column_name="client_key") + + op.create_table( + "device_accounts", + sa.Column("device_id", sa.Uuid(as_uuid=False), sa.ForeignKey("devices.id"), primary_key=True), + sa.Column("user_id", sa.Uuid(as_uuid=False), sa.ForeignKey("users.id"), primary_key=True), + sa.Column("first_seen_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=False, index=True), + ) + + with op.batch_alter_table("computers") as batch: + batch.drop_column("certificate_sha256") + batch.drop_column("legacy_transfer_user_id") + batch.drop_column("legacy_transfer_pending") + + with op.batch_alter_table("agent_mutations") as batch: + batch.drop_column("certificate_sha256") + + with op.batch_alter_table("agent_enrollments") as batch: + batch.add_column(sa.Column("device_id", sa.Uuid(as_uuid=False))) + + # The installation id was the durable local key in the old protocol. Keep + # it as the device key so an offline client can finish its pending attempt. + seen = {} + rows = connection.execute( + sa.text("SELECT id, actor_id, installation_id FROM agent_enrollments") + ).all() + for row in rows: + installation = str(row.installation_id or "").lower() + if not installation: + continue + device = seen.get(installation) + if device is None: + device = connection.execute( + sa.text("SELECT id FROM devices WHERE client_key = :key"), + {"key": installation}, + ).scalar_one_or_none() + if device is None: + device = str(uuid4()) + connection.execute( + sa.text( + "INSERT INTO devices (id, client_key, created_at) " + "VALUES (:id, :key, CURRENT_TIMESTAMP)" + ), + {"id": device, "key": installation}, + ) + seen[installation] = device + connection.execute( + sa.text("UPDATE agent_enrollments SET device_id = :device WHERE id = :id"), + {"device": device, "id": row.id}, + ) + exists = connection.execute( + sa.text( + "SELECT 1 FROM device_accounts " + "WHERE device_id = :device AND user_id = :user" + ), + {"device": device, "user": row.actor_id}, + ).first() + if not exists: + connection.execute( + sa.text( + "INSERT INTO device_accounts " + "(device_id, user_id, first_seen_at, last_seen_at) " + "VALUES (:device, :user, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" + ), + {"device": device, "user": row.actor_id}, + ) + + # Preserve the account link for already connected computers. + computers = sa.table( + "computers", + sa.column("id", sa.Uuid(as_uuid=False)), + sa.column("device_id", sa.Uuid(as_uuid=False)), + sa.column("registered_by_user_id", sa.Uuid(as_uuid=False)), + sa.column("connected_user_id", sa.Uuid(as_uuid=False)), + schema=None, + ) + accounts = sa.table( + "device_accounts", + sa.column("device_id", sa.Uuid(as_uuid=False)), + sa.column("user_id", sa.Uuid(as_uuid=False)), + sa.column("first_seen_at", sa.DateTime(timezone=True)), + sa.column("last_seen_at", sa.DateTime(timezone=True)), + schema=None, + ) + seen_accounts = set() + for row in connection.execute( + sa.select( + computers.c.device_id, + computers.c.registered_by_user_id, + computers.c.connected_user_id, + ).where(computers.c.device_id.is_not(None)) + ): + for user_id in {row.registered_by_user_id, row.connected_user_id} - {None}: + key = (row.device_id, user_id) + if key in seen_accounts: + continue + seen_accounts.add(key) + connection.execute( + accounts.insert().values( + device_id=row.device_id, + user_id=user_id, + first_seen_at=sa.func.now(), + last_seen_at=sa.func.now(), + ) + ) + + with op.batch_alter_table("agent_enrollments") as batch: + for name in ( + "installation_id", + "acme_secret", + "account_jwk", + "order_created", + "challenge_token", + "attested_key", + "identity_hash", + "certificate_sha256", + "csr_sha256", + ): + batch.drop_column(name) + batch.alter_column("device_id", nullable=False) + batch.create_foreign_key( + "fk_agent_enrollments_device_id_devices", "devices", ["device_id"], ["id"] + ) + + +def downgrade(): + # Recreating the removed trust material is intentionally impossible. The + # downgrade restores the schema shape with nullable legacy fields so an + # operator can restore a pre-0028 backup when attestation is required. + with op.batch_alter_table("agent_enrollments") as batch: + batch.drop_constraint("fk_agent_enrollments_device_id_devices", type_="foreignkey") + batch.drop_column("device_id") + batch.add_column(sa.Column("installation_id", sa.Uuid(as_uuid=False))) + batch.add_column(sa.Column("acme_secret", sa.String(length=64))) + batch.add_column(sa.Column("account_jwk", sa.JSON())) + batch.add_column(sa.Column("order_created", sa.Boolean())) + batch.add_column(sa.Column("challenge_token", sa.String(length=64))) + batch.add_column(sa.Column("attested_key", sa.LargeBinary())) + batch.add_column(sa.Column("identity_hash", sa.String(length=64))) + batch.add_column(sa.Column("certificate_sha256", sa.String(length=64))) + batch.add_column(sa.Column("csr_sha256", sa.String(length=64))) + op.drop_table("device_accounts") + with op.batch_alter_table("devices") as batch: + batch.alter_column("client_key", new_column_name="identity_hash") + op.rename_table("devices", "physical_devices") + with op.batch_alter_table("computers") as batch: + batch.add_column(sa.Column("certificate_sha256", sa.String(length=64))) + batch.add_column(sa.Column("legacy_transfer_user_id", sa.Uuid(as_uuid=False))) + batch.add_column( + sa.Column("legacy_transfer_pending", sa.Boolean(), nullable=False, server_default=sa.false()) + ) + batch.create_foreign_key( + "fk_computers_legacy_transfer_user_id_users", + "users", + ["legacy_transfer_user_id"], + ["id"], + ondelete="SET NULL", + ) + with op.batch_alter_table("agent_mutations") as batch: + batch.add_column(sa.Column("certificate_sha256", sa.String(length=64))) + op.create_table( + "device_certificates", + sa.Column("sha256", sa.String(length=64), primary_key=True), + sa.Column("device_id", sa.Uuid(as_uuid=False), sa.ForeignKey("physical_devices.id")), + sa.Column("enrollment_id", sa.Uuid(as_uuid=False), nullable=False, unique=True), + sa.Column("pem", sa.LargeBinary(), nullable=False), + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("revoked_at", sa.DateTime(timezone=True)), + ) + op.create_table( + "protocol_nonces", + sa.Column("namespace", sa.String(length=80), primary_key=True), + sa.Column("value", sa.String(length=64), primary_key=True), + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False, index=True), + ) diff --git a/platform/api/throng_api/models.py b/platform/api/throng_api/models.py index 98b04f31..8eeb04c1 100644 --- a/platform/api/throng_api/models.py +++ b/platform/api/throng_api/models.py @@ -335,12 +335,6 @@ class Computer(Identity, Base): connected_user_id: Mapped[str | None] = mapped_column( ForeignKey("users.id", ondelete="SET NULL") ) - legacy_transfer_user_id: Mapped[str | None] = mapped_column( - ForeignKey("users.id", ondelete="SET NULL") - ) - legacy_transfer_pending: Mapped[bool] = mapped_column( - Boolean, default=False, server_default="0" - ) os: Mapped[str] = mapped_column(String(40)) architecture: Mapped[str] = mapped_column(String(40)) runtime: Mapped[str] = mapped_column(String(80)) @@ -362,8 +356,7 @@ class Computer(Identity, Base): isolation_modes: Mapped[list | None] = mapped_column(JSON) network_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0") internet_only: Mapped[bool] = mapped_column(Boolean, default=True, server_default="1") - device_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False), index=True) - certificate_sha256: Mapped[str | None] = mapped_column(String(64)) + device_id: Mapped[str | None] = mapped_column(ForeignKey("devices.id"), index=True) resources: Mapped[list["ComputerResource"]] = relationship( lazy="selectin", cascade="all, delete-orphan", passive_deletes=True ) @@ -627,49 +620,32 @@ class Isolate(Identity, Ownership, Base): internet_only: Mapped[bool | None] = mapped_column(Boolean) -class PhysicalDevice(Identity, Base): - """Billing identity survives installation, account and computer deletion.""" +class Device(Identity, Base): + """Client-generated installation identity; survives account and computer deletion.""" - __tablename__ = "physical_devices" - identity_hash: Mapped[str] = mapped_column(String(64), unique=True) + __tablename__ = "devices" + client_key: Mapped[str] = mapped_column(String(64), unique=True) + + +class DeviceAccount(Base): + __tablename__ = "device_accounts" + device_id: Mapped[str] = mapped_column(ForeignKey("devices.id"), primary_key=True) + user_id: Mapped[str] = mapped_column(ForeignKey("users.id"), primary_key=True) + first_seen_at: Mapped[datetime] = mapped_column(UTCDateTime()) + last_seen_at: Mapped[datetime] = mapped_column(UTCDateTime(), index=True) class AgentEnrollment(Identity, Base): __tablename__ = "agent_enrollments" actor_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), index=True) - installation_id: Mapped[str] = mapped_column(Uuid(as_uuid=False)) + device_id: Mapped[str] = mapped_column(ForeignKey("devices.id")) request: Mapped[dict] = mapped_column(JSON) expires_at: Mapped[datetime] = mapped_column(UTCDateTime(), index=True) - acme_secret: Mapped[str] = mapped_column(String(64)) - account_jwk: Mapped[dict | None] = mapped_column(JSON) - order_created: Mapped[bool] = mapped_column(Boolean, default=False) - challenge_token: Mapped[str] = mapped_column(String(64)) - attested_key: Mapped[bytes | None] = mapped_column(LargeBinary) - identity_hash: Mapped[str | None] = mapped_column(String(64)) - certificate_sha256: Mapped[str | None] = mapped_column(String(64)) - csr_sha256: Mapped[str | None] = mapped_column(String(64)) computer_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) credential_encrypted: Mapped[bytes | None] = mapped_column(LargeBinary) finish_key: Mapped[str | None] = mapped_column(String(128)) -class DeviceCertificate(Base): - __tablename__ = "device_certificates" - sha256: Mapped[str] = mapped_column(String(64), primary_key=True) - device_id: Mapped[str] = mapped_column(ForeignKey("physical_devices.id")) - enrollment_id: Mapped[str] = mapped_column(ForeignKey("agent_enrollments.id"), unique=True) - pem: Mapped[bytes] = mapped_column(LargeBinary) - expires_at: Mapped[datetime] = mapped_column(UTCDateTime()) - revoked_at: Mapped[datetime | None] = mapped_column(UTCDateTime()) - - -class ProtocolNonce(Base): - __tablename__ = "protocol_nonces" - namespace: Mapped[str] = mapped_column(String(80), primary_key=True) - value: Mapped[str] = mapped_column(String(64), primary_key=True) - expires_at: Mapped[datetime] = mapped_column(UTCDateTime(), index=True) - - class AgentMutation(Base): """Exact bounded retries, including disconnect and revoked-credential unbinding.""" @@ -679,7 +655,6 @@ class AgentMutation(Base): key: Mapped[str] = mapped_column(String(128), primary_key=True) request_hash: Mapped[str] = mapped_column(String(64)) session_id: Mapped[str | None] = mapped_column(Uuid(as_uuid=False)) - certificate_sha256: Mapped[str | None] = mapped_column(String(64)) response: Mapped[dict] = mapped_column(JSON) expires_at: Mapped[datetime] = mapped_column(UTCDateTime(), index=True) diff --git a/platform/api/throng_api/outputs.py b/platform/api/throng_api/outputs.py index 535d12e3..9e18a69e 100644 --- a/platform/api/throng_api/outputs.py +++ b/platform/api/throng_api/outputs.py @@ -210,7 +210,6 @@ class Computer(Identity): network_enabled: bool internet_only: bool device_id: str | None - certificate_sha256: str | None enabled: bool online: bool session_active: bool @@ -367,7 +366,7 @@ class AgentPoolOwner(BaseModel): class CurrentAgentSession(BaseModel): - transfer_pending: bool + transfer_pending: bool = False pool_owner: AgentPoolOwner | None = None computer_id: str session_id: str | None diff --git a/platform/api/throng_api/powercell.py b/platform/api/throng_api/powercell.py index 9e49746f..197083b9 100644 --- a/platform/api/throng_api/powercell.py +++ b/platform/api/throng_api/powercell.py @@ -14,7 +14,6 @@ from throng_api.artifacts import BINARY_UPLOAD_DOCS from throng_api.availability import sync_capacity from throng_api.computers import computer_for_user -from throng_api.device_security import agent_device_proof from throng_api.execution import fail_isolate, fingerprint, invalidate_computer, release_reservation from throng_api.models import ( CPU_RESOURCE_ID, @@ -24,9 +23,7 @@ AgentMutation, AgentTask, ComputerOwnership, - DeviceCertificate, Isolate, - ProtocolNonce, ) from throng_api.powercell_schemas import ( Capacity, @@ -53,7 +50,7 @@ router = APIRouter( prefix="/agent/v1", tags=["Power Cell"], - dependencies=[Depends(agent_credential_scheme), Depends(agent_device_proof)], + dependencies=[Depends(agent_credential_scheme)], ) user_router = APIRouter( prefix="/v1", tags=["Power Cell management"], dependencies=[Depends(access_token_scheme)] @@ -101,7 +98,6 @@ def mutation_save( key=identity[2], request_hash=fingerprint(payload), session_id=request.headers.get("x-agent-session"), - certificate_sha256=computer.certificate_sha256, response=jsonable_encoder(response), expires_at=request.app.state.clock() + timedelta(seconds=request.app.state.settings.agent_mutation_seconds), @@ -206,12 +202,7 @@ async def detach_computer(session, computer, now, actor_id=None): session, computer, (owner.user_id, owner.company_id), (None, None), now, actor_id ) await session.delete(owner) - if computer.certificate_sha256: - certificate = await session.get(DeviceCertificate, computer.certificate_sha256) - certificate.revoked_at = now computer.connected_user_id = None - computer.legacy_transfer_user_id = None - computer.legacy_transfer_pending = False computer.session_id = None await session.execute(delete(AgentCredential).where(AgentCredential.computer_id == computer.id)) @@ -379,5 +370,5 @@ async def read_diagnostic(computer_id: UUID, diagnostic_id: UUID, request: Reque async def prune_protocol(session, now): - for model in (ProtocolNonce, AgentMutation, AgentDiagnostic): + for model in (AgentMutation, AgentDiagnostic): await session.execute(delete(model).where(model.expires_at <= now)) diff --git a/platform/api/throng_api/powercell_schemas.py b/platform/api/throng_api/powercell_schemas.py index 7072d49c..1993d7e9 100644 --- a/platform/api/throng_api/powercell_schemas.py +++ b/platform/api/throng_api/powercell_schemas.py @@ -4,7 +4,7 @@ from typing import Annotated, Literal from uuid import UUID -from pydantic import AwareDatetime, Field +from pydantic import AwareDatetime, Field, model_validator from throng_api.schemas import ComputerCreate, Input @@ -27,32 +27,35 @@ class EnrollmentCreate(ComputerCreate): - installation_id: UUID + device_id: UUID | None = None + installation_id: UUID | None = None + assign_pool: bool = False os: Literal["linux"] = "linux" architecture: Literal["arm64"] = "arm64" runtime: Literal["powercell-ubuntu-arm64-v1"] = "powercell-ubuntu-arm64-v1" isolation_modes: list[Isolation] = Field(min_length=1, max_length=2) + @model_validator(mode="after") + def identify_device(self): + if self.device_id is None and self.installation_id is None: + raise ValueError("device_id is required") + return self -class RelayConfiguration(Input): - url: str - api_origin: str + @property + def client_device_id(self) -> UUID: + return self.device_id or self.installation_id class EnrollmentStatus(Input): id: str - status: Literal["pending_attestation", "verified", "expired"] + status: Literal["verified", "expired"] expires_at: datetime - certificate_sha256: str | None - relay: RelayConfiguration | None = None class Binding(Input): computer_id: str credential: str device_id: str - certificate_sha256: str - relay: RelayConfiguration | None = None class Capacity(Input): diff --git a/platform/api/throng_api/relay.py b/platform/api/throng_api/relay.py deleted file mode 100644 index 91255197..00000000 --- a/platform/api/throng_api/relay.py +++ /dev/null @@ -1,343 +0,0 @@ -"""Native macOS HTTP/2 relay terminating into this API, never an open proxy. - -Each CONNECT stream gets an in-process HTTP connection with its TLS peer bound -into the ASGI scope. No network listener or forwarded identity header can enter -this path. The original Apple-attested certificate remains the device identity. -""" - -import asyncio -import hashlib -import logging -import socket -import ssl -from dataclasses import dataclass -from urllib.parse import urlsplit -from uuid import UUID - -import uvicorn -from h2.config import H2Configuration -from h2.connection import H2Connection -from h2.errors import ErrorCodes -from h2.events import ( - ConnectionTerminated, - DataReceived, - RemoteSettingsChanged, - RequestReceived, - StreamEnded, - StreamReset, - WindowUpdated, -) -from h2.exceptions import H2Error -from h2.settings import SettingCodes -from uvicorn.protocols.http.h11_impl import H11Protocol -from uvicorn.server import ServerState - -logger = logging.getLogger("throng.transport") - - -class RelayHTTPProtocol(H11Protocol): - def timeout_keep_alive_handler(self): - logger.info('{"event":"relay_close","reason":"idle_timeout"}') - super().timeout_keep_alive_handler() - - -@dataclass(frozen=True) -class RelayPeer: - certificate_sha256: str - - -def configuration(settings): - """Require an explicit HTTPS endpoint and complete operator-owned TLS/CA material.""" - values = ( - settings.powercell_relay_url, - settings.powercell_relay_certificate, - settings.powercell_relay_key, - ) - if not any(values): - return None - if not all(values) or not settings.powercell_ca_certificate: - raise ValueError( - "Power Cell relay requires its HTTPS URL, TLS certificate/key and device CA" - ) - url = urlsplit(settings.powercell_relay_url) - if ( - url.scheme != "https" - or not url.hostname - or url.username - or url.password - or url.query - or url.fragment - or url.path not in ("", "/") - or (url.port is not None and not 1 <= url.port <= 65535) - ): - raise ValueError("Power Cell relay URL must be an HTTPS origin without credentials") - # This virtual destination exists only inside the relay. Without the installed - # profile it cannot resolve or fall back to an unauthenticated public endpoint. - identifier = hashlib.sha256(settings.powercell_relay_url.encode()).hexdigest()[:24] - return { - "url": settings.powercell_relay_url, - "api_origin": f"http://powercell-{identifier}.invalid", - } - - -def enrollment_configuration(info, enrollment_id): - """Give each installed profile its own route so old profiles cannot select another key.""" - if info is None: - return None - host = urlsplit(info["api_origin"]).hostname - return {"url": info["url"], "api_origin": f"http://{UUID(enrollment_id).hex}.{host}"} - - -class RelayServer: - def __init__(self, app, settings, info): - self.app, self.settings, self.info = app, settings, info - self.listener = None - self.connections = set() - self.closing = False - self.http_state = ServerState() - - async def start(self): - context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) - context.minimum_version = ssl.TLSVersion.TLSv1_3 - context.load_cert_chain( - self.settings.powercell_relay_certificate, self.settings.powercell_relay_key - ) - context.load_verify_locations(self.settings.powercell_ca_certificate) - context.verify_mode = ssl.CERT_REQUIRED - context.set_alpn_protocols(["h2"]) - context.options |= ssl.OP_NO_TICKET - context.num_tickets = 0 - self.listener = await asyncio.start_server( - self.connected, - self.settings.powercell_relay_host, - urlsplit(self.info["url"]).port or 443, - ssl=context, - ssl_handshake_timeout=10, - limit=65536, - ) - - def connected(self, reader, writer): - # Accept ownership before scheduling: close() may race a queued callback, - # and cancellation before the first coroutine step cannot run finally. - if self.closing: - writer.transport.abort() - return - task = asyncio.create_task(self.handle_connection(reader, writer)) - self.connections.add(task) - - def finished(task): - writer.transport.abort() - self.connections.discard(task) - - task.add_done_callback(finished) - return task - - async def handle_connection(self, reader, writer): - try: - tls = writer.get_extra_info("ssl_object") - if tls.selected_alpn_protocol() != "h2": - return - peer = RelayPeer(hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest()) - await _Connection(self, reader, writer, peer).run() - except asyncio.CancelledError: - # Server shutdown must not wait for a remote TLS close_notify. - writer.transport.abort() - raise - finally: - writer.close() - try: - await writer.wait_closed() - except (OSError, ssl.SSLError): - pass - - async def close(self): - self.closing = True - if self.listener: - self.listener.close() - tasks = list(self.connections) - for task in tasks: - task.cancel() - await asyncio.gather(*tasks, return_exceptions=True) - if self.listener: - await self.listener.wait_closed() - # Disconnect transports first, then let already-started API transactions - # drain before the parent lifespan closes its database. - await asyncio.gather(*list(self.http_state.tasks), return_exceptions=True) - - -class _Connection: - def __init__(self, server, reader, writer, peer): - self.server, self.reader, self.writer, self.peer = server, reader, writer, peer - self.h2 = H2Connection(H2Configuration(client_side=False, header_encoding="ascii")) - self.streams = {} - self.window = asyncio.Event() - - def flush(self): - self.writer.write(self.h2.data_to_send()) - - async def run(self): - self.h2.initiate_connection() - self.h2.update_settings( - {SettingCodes.MAX_CONCURRENT_STREAMS: 128, SettingCodes.MAX_HEADER_LIST_SIZE: 16384} - ) - self.flush() - try: - while data := await self.reader.read(65536): - for event in self.h2.receive_data(data): - if isinstance(event, RequestReceived): - await self.open(event) - elif isinstance(event, DataReceived): - # Return connection capacity immediately so a stalled - # upload cannot prevent another stream's heartbeat. - if not event.flow_controlled_length: - continue - self.h2.increment_flow_control_window(event.flow_controlled_length) - stream = self.streams.get(event.stream_id) - if stream: - stream.incoming.put_nowait((event.data, event.flow_controlled_length)) - elif isinstance(event, StreamEnded): - if stream := self.streams.get(event.stream_id): - stream.incoming.put_nowait(None) - elif isinstance(event, StreamReset): - if stream := self.streams.pop(event.stream_id, None): - stream.close() - elif isinstance(event, (WindowUpdated, RemoteSettingsChanged)): - self.window.set() - elif isinstance(event, ConnectionTerminated): - return - self.flush() - await self.writer.drain() - except (H2Error, UnicodeError, OSError): - pass - finally: - streams = list(self.streams.values()) - for stream in streams: - stream.close() - await asyncio.gather( - *(task for s in streams for task in s.tasks), return_exceptions=True - ) - - async def open(self, event): - headers = dict(event.headers) - authority = headers.get(":authority", "") - prefix, _, destination = authority.partition(".") - expected = urlsplit(self.server.info["api_origin"]).hostname + ":80" - status = None - if headers.get(":method") != "CONNECT" or ":protocol" in headers: - status = "405" - elif ( - destination != expected - or len(prefix) != 32 - or any(c not in "0123456789abcdef" for c in prefix) - ): - status = "403" - if status: - self.h2.send_headers(event.stream_id, [(":status", status)], end_stream=True) - return - - async def application(scope, receive, send): - scope = {**scope, "powercell.relay_peer": self.peer} - await self.server.app(scope, receive, send) - - config = uvicorn.Config( - application, - lifespan="off", - proxy_headers=False, - access_log=False, - log_level="critical", - server_header=False, - date_header=False, - timeout_keep_alive=self.server.settings.powercell_relay_keep_alive_seconds, - ) - config.load() - left, right = socket.socketpair() - left.setblocking(False) - right.setblocking(False) - transport = None - try: - transport, _ = await asyncio.get_running_loop().connect_accepted_socket( - lambda: RelayHTTPProtocol(config, self.server.http_state, {}), left - ) - reader, writer = await asyncio.open_connection(sock=right) - except BaseException: - if transport: - transport.close() - else: - left.close() - right.close() - raise - stream = _Stream(self, event.stream_id, reader, writer) - self.streams[event.stream_id] = stream - self.h2.send_headers(event.stream_id, [(":status", "200")]) - self.flush() - stream.tasks = [ - asyncio.create_task(stream.upload()), - asyncio.create_task(stream.download()), - ] - - async def send(self, stream_id, data): - while data: - while self.h2.local_flow_control_window(stream_id) <= 0: - self.window.clear() - await self.window.wait() - count = min( - len(data), - self.h2.local_flow_control_window(stream_id), - self.h2.max_outbound_frame_size, - ) - self.h2.send_data(stream_id, data[:count]) - data = data[count:] - self.flush() - await self.writer.drain() - - -class _Stream: - def __init__(self, connection, stream_id, reader, writer): - self.connection, self.id = connection, stream_id - self.reader, self.writer = reader, writer - # HTTP/2's unacknowledged per-stream receive window bounds this queue. - self.incoming = asyncio.Queue() - self.tasks = [] - - def close(self): - self.writer.close() - for task in self.tasks: - task.cancel() - - def reset(self): - """Report abnormal backend closure without disturbing other tunnels.""" - try: - self.connection.h2.reset_stream(self.id, ErrorCodes.CONNECT_ERROR) - self.connection.flush() - except (H2Error, OSError): - pass # The peer may have reset this stream or closed the connection. - - async def upload(self): - try: - while item := await self.incoming.get(): - data, size = item - self.writer.write(data) - await self.writer.drain() - self.connection.h2.increment_flow_control_window(size, self.id) - self.connection.flush() - self.writer.write_eof() - except (H2Error, OSError): - logger.info('{"event":"relay_close","reason":"backend_upload_error"}') - self.reset() - self.writer.close() - - async def download(self): - try: - while data := await self.reader.read(16384): - await self.connection.send(self.id, data) - self.connection.h2.end_stream(self.id) - self.connection.flush() - except (H2Error, OSError): - logger.info('{"event":"relay_close","reason":"backend_download_error"}') - self.reset() - finally: - self.writer.close() - # The receive task may be awaiting another chunk when the backend - # closes a keep-alive connection or rejects a request early. - self.tasks[0].cancel() - self.connection.streams.pop(self.id, None) diff --git a/platform/api/throng_api/schemas.py b/platform/api/throng_api/schemas.py index bd5cb043..33d0194b 100644 --- a/platform/api/throng_api/schemas.py +++ b/platform/api/throng_api/schemas.py @@ -88,6 +88,7 @@ class Login(Input): min_length=1, max_length=320, validation_alias=AliasChoices("login", "email") ) password: Password = Field(max_length=1024) + device_id: UUID | None = None class CompanyInput(Input): diff --git a/platform/api/throng_api/security.py b/platform/api/throng_api/security.py index 32dc3045..8152a473 100644 --- a/platform/api/throng_api/security.py +++ b/platform/api/throng_api/security.py @@ -17,7 +17,6 @@ AccessToken, AgentCredential, Computer, - DeviceCertificate, LegacyCredential, LoginSession, Membership, @@ -375,17 +374,6 @@ async def authenticated_agent(session, request, require_session=True): computer = await session.get(Computer, credential.computer_id) if not computer: raise HTTPException(401, "Invalid agent credential") - if computer.runtime == "powercell-ubuntu-arm64-v1" and not computer.certificate_sha256: - raise HTTPException(401, "Mutating Compute requires attested enrollment") - if computer.certificate_sha256: - certificate = await session.get(DeviceCertificate, computer.certificate_sha256) - if ( - getattr(request.state, "device_certificate", None) != computer.certificate_sha256 - or not certificate - or certificate.revoked_at - or certificate.expires_at <= request.app.state.clock() - ): - raise HTTPException(401, "A current device possession proof is required") # Disabled computers may finish and clean up work, but receive no new isolates. if require_session: if ( diff --git a/tests/platform/api/deployment/test_powercell_firewall.py b/tests/platform/api/deployment/test_powercell_firewall.py deleted file mode 100644 index c4915af1..00000000 --- a/tests/platform/api/deployment/test_powercell_firewall.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Run the real Ansible tasks against disposable firewall command adapters.""" - -import json -import os -import re -import shutil -import socket -import subprocess -import sys -from pathlib import Path - -import pytest - -ROOT = Path(__file__).resolve().parents[4] -TASKS = ROOT / "infra/playbooks/tasks" -pytestmark = pytest.mark.skipif( - not shutil.which("ansible-playbook"), - reason="Requires Ansible; installed in native deployment CI", -) - - -@pytest.fixture -def firewall(tmp_path): - """Keep firewall state and existing SSH/web rules outside the machine's policy.""" - state = tmp_path / "firewall.json" - state.write_text( - json.dumps( - { - "ufw": False, - "firewalld": False, - "calls": [], - "ufw_rules": ["22/tcp", "443/tcp"], - "runtime": ["22/tcp", "443/tcp"], - "permanent": ["22/tcp", "443/tcp"], - } - ) - ) - source = """import json,pathlib,sys -p=pathlib.Path(STATE) -s=json.loads(p.read_text());cmd=pathlib.Path(sys.argv[0]).name;a=sys.argv[1:] -s['calls'].append([cmd,*a]);p.write_text(json.dumps(s)) -if cmd=='ufw': - if a==['status']: - if s.get('error'):print('Cannot read firewall',file=sys.stderr);sys.exit(1) - print('Status: active' if s['ufw'] else 'Status: inactive');sys.exit(0) - assert s['ufw'] and a[0]=='allow' and a[2:]==['comment','Power Cell relay'],a - if a[1] in s['ufw_rules']:print('Skipping adding existing rule');sys.exit(0) - s['ufw_rules'].append(a[1]);p.write_text(json.dumps(s));print('Rule added');sys.exit(0) -if a==['--state']:print('running' if s['firewalld'] else 'not running');sys.exit(0 if s['firewalld'] else 252) -assert s['firewalld'],a -if a==['--get-default-zone']:print('public');sys.exit(0) -zone=next(x for x in a if x.startswith('--zone=')) -key='permanent' if '--permanent' in a else 'runtime' -query=next((x for x in a if x.startswith('--query-port=')),None) -if query:sys.exit(0 if zone+':'+query.split('=',1)[1] in s[key] else 1) -port=next(x for x in a if x.startswith('--add-port=')).split('=',1)[1] -assert len(a)==(3 if key=='permanent' else 2),a -s[key].append(zone+':'+port);p.write_text(json.dumps(s));print('success') -""".replace("STATE", repr(str(state))) - binaries = {} - for name in ["ufw", "firewall-cmd"]: - path = tmp_path / name - path.write_text("#!" + sys.executable + "\n" + source) - path.chmod(0o755) - binaries[name] = str(path) - return state, binaries - - -def run_playbook(tmp_path, task, variables, *, success=True): - """Execute the actual task include with Ansible's real command/wait modules.""" - wrapper = tmp_path / "review.yml" - wrapper.write_text( - json.dumps( - [ - { - "hosts": "all", - "gather_facts": False, - "become": False, - "vars": { - "ansible_connection": "local", - "ansible_python_interpreter": sys.executable, - **variables, - }, - "tasks": [{"ansible.builtin.include_tasks": str(TASKS / task)}], - } - ] - ) - ) - result = subprocess.run( - [shutil.which("ansible-playbook"), "-i", "localhost,", str(wrapper)], - env={**os.environ, "LC_ALL": "en_US.UTF-8", "LANG": "en_US.UTF-8", "ANSIBLE_NOCOLOR": "1"}, - capture_output=True, - text=True, - timeout=45, - check=False, - ) - assert (result.returncode == 0) == success, result.stdout + result.stderr - return result.stdout - - -@pytest.mark.parametrize( - ("manager", "zone"), [("ufw", ""), ("firewalld", ""), ("firewalld", "external")] -) -def test_relay_rule_is_persistent_and_idempotent_without_changing_ssh( - firewall, tmp_path, manager, zone -): - """Open the configured port twice while preserving other rules and firewall state.""" - state, binaries = firewall - initial = json.loads(state.read_text()) - initial[manager] = True - state.write_text(json.dumps(initial)) - variables = { - "powercell_relay_url": "https://api.example:18443", - "powercell_firewalld_zone": zone, - "powercell_ufw_binary": binaries["ufw"], - "powercell_firewalld_binary": binaries["firewall-cmd"], - } - first = run_playbook(tmp_path, "powercell-firewall.yml", variables) - assert re.search(r"changed=[12]\b", first) - second = run_playbook(tmp_path, "powercell-firewall.yml", variables) - assert re.search(r"changed=0\b", second) - final = json.loads(state.read_text()) - assert final[manager] and not final["ufw" if manager == "firewalld" else "firewalld"] - if manager == "ufw": - assert final["ufw_rules"] == ["22/tcp", "443/tcp", "18443/tcp"] - assert final["runtime"] == initial["runtime"] and final["permanent"] == initial["permanent"] - else: - for key in ["runtime", "permanent"]: - assert final[key] == initial[key] + ["--zone=" + (zone or "public") + ":18443/tcp"] - assert final["ufw_rules"] == initial["ufw_rules"] - - -@pytest.mark.parametrize("missing", [False, "absolute", "name"]) -def test_absent_or_inactive_firewalls_are_not_enabled(firewall, tmp_path, missing): - """Accept absent utilities, including dash's 127, without enabling a policy.""" - state, binaries = firewall - if missing: - for path in binaries.values(): - Path(path).unlink() - if missing == "name": - binaries = { - "ufw": "powercell-audit-absent-ufw", - "firewall-cmd": "powercell-audit-absent-firewalld", - } - output = run_playbook( - tmp_path, - "powercell-firewall.yml", - { - "powercell_relay_url": "https://api.example:8444", - "powercell_ufw_binary": binaries["ufw"], - "powercell_firewalld_binary": binaries["firewall-cmd"], - }, - ) - assert "changed=0" in output - final = json.loads(state.read_text()) - assert not final["ufw"] and not final["firewalld"] - assert final["ufw_rules"] == final["runtime"] == final["permanent"] == ["22/tcp", "443/tcp"] - - -@pytest.mark.parametrize("case", ["two_managers", "status_error", "invalid_port"]) -def test_unsafe_detection_stops_before_changing_firewall(firewall, tmp_path, case): - """Reject ambiguity, command errors and invalid relay ports without edits.""" - state, binaries = firewall - initial = json.loads(state.read_text()) - if case == "two_managers": - initial["ufw"] = initial["firewalld"] = True - if case == "status_error": - initial["error"] = True - state.write_text(json.dumps(initial)) - run_playbook( - tmp_path, - "powercell-firewall.yml", - { - "powercell_relay_url": "https://api.example" - if case == "invalid_port" - else "https://api.example:8444", - "powercell_ufw_binary": binaries["ufw"], - "powercell_firewalld_binary": binaries["firewall-cmd"], - }, - success=False, - ) - final = json.loads(state.read_text()) - for key in ["ufw", "firewalld", "ufw_rules", "runtime", "permanent"]: - assert final[key] == initial[key] - - -@pytest.mark.parametrize("reachable", [True, False]) -def test_external_tcp_probe_rejects_an_unreachable_relay(tmp_path, reachable): - """Use real sockets so a blocked/unavailable relay cannot produce success.""" - with socket.socket() as listener: - listener.bind(("127.0.0.1", 0)) - port = listener.getsockname()[1] - if reachable: - listener.listen() - output = run_playbook( - tmp_path, - "powercell-connectivity.yml", - { - "powercell_relay_url": f"https://127.0.0.1:{port}", - "powercell_relay_probe_timeout": 1, - }, - success=reachable, - ) - if not reachable: - assert "unreachable from the Ansible controller" in output diff --git a/tests/platform/api/deployment/test_powercell_setup.py b/tests/platform/api/deployment/test_powercell_setup.py deleted file mode 100644 index 3eeca5bf..00000000 --- a/tests/platform/api/deployment/test_powercell_setup.py +++ /dev/null @@ -1,357 +0,0 @@ -"""Exercise administrator provisioning with real OpenSSL, files and API startup.""" - -import grp -import json -import os -import shutil -import socket -import ssl -import subprocess -import sys -from datetime import UTC, datetime, timedelta -from pathlib import Path -from types import SimpleNamespace -from urllib.parse import urlsplit -from uuid import uuid4 - -import pytest -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.x509.oid import NameOID -from dotenv import dotenv_values -from fastapi.testclient import TestClient - -from throng_api.app import create_app -from throng_api.cli import migrate -from throng_api.config import Settings - -ROOT = Path(__file__).resolve().parents[4] - - -def tls_pair(directory, *, host="api.example", expired=False, ca=False): - """Issue an actual X.509 certificate and private key for OpenSSL validation.""" - directory.mkdir(parents=True, exist_ok=True) - key = ec.generate_private_key(ec.SECP256R1()) - name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, host)]) - now = datetime.now(UTC) - certificate = ( - x509.CertificateBuilder() - .subject_name(name) - .issuer_name(name) - .public_key(key.public_key()) - .serial_number(x509.random_serial_number()) - .not_valid_before(now - timedelta(days=2)) - .not_valid_after(now + timedelta(days=-1 if expired else 365)) - .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) - .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) - .add_extension( - x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()), critical=False - ) - .add_extension(x509.SubjectAlternativeName([x509.DNSName(host)]), critical=False) - .sign(key, hashes.SHA256()) - ) - (directory / "fullchain.pem").write_bytes(certificate.public_bytes(serialization.Encoding.PEM)) - (directory / "privkey.pem").write_bytes( - key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - - -@pytest.fixture -def provisioner(tmp_path): - """Run the administrator CLI against isolated files and a real TLS lineage.""" - lineage = tmp_path / "letsencrypt" - tls_pair(lineage) - env = tmp_path / "server.env" - env.write_text( - "# Existing production settings must survive.\n" - f'THRONG_DATABASE_URL="sqlite+aiosqlite:///{tmp_path}/audit.db"\n' - f'THRONG_STORAGE_PATH="{tmp_path}/artifacts"\n' - "THRONG_CONTROLLER_ENABLED=false\n" - "DASHBOARD_API_URL=https://api.example/v1\n" - ) - directory = tmp_path / "powercell" - with socket.socket() as listener: - listener.bind(("127.0.0.1", 0)) - port = listener.getsockname()[1] - base = [ - sys.executable, - str(ROOT / "deploy/powercell_setup.py"), - "--directory", - str(directory), - "--env-file", - str(env), - "--tls-lineage", - str(lineage), - "--group", - grp.getgrgid(os.getgid()).gr_name, - "--acme-url", - "https://api.example/acme/powercell", - "--relay-url", - f"https://api.example:{port}", - "--relay-host", - "127.0.0.1", - ] - - def run(*arguments, success=True, environment=None): - result = subprocess.run( - [*base, *arguments], - capture_output=True, - text=True, - env=environment, - check=False, - ) - assert (result.returncode == 0) == success, result.stderr - for private in (directory / "recovery.secret", directory / "issuer/ca-key.pem"): - if private.exists(): - assert private.read_text().strip() not in result.stdout + result.stderr - return result - - return directory, env, lineage, run - - -def test_explicit_setup_is_idempotent_and_enables_the_actual_api(provisioner): - """Keep identity across retries and boot a mutually authenticated relay.""" - directory, env, lineage, run = provisioner - run("configure", success=False) - assert not (directory / "issuer").exists() - assert json.loads(run("configure", "--create-issuer").stdout)["changed"] - paths = [ - env, - directory / "issuer/ca.pem", - directory / "issuer/ca-key.pem", - directory / "recovery.secret", - ] - before = [p.read_bytes() for p in paths] - assert not json.loads(run("configure", "--create-issuer").stdout)["changed"] - assert [p.read_bytes() for p in paths] == before - assert env.read_text().startswith("# Existing production settings must survive.\n") - for path in [*paths, directory / "tls/privkey.pem"]: - assert path.stat().st_mode & 0o777 == 0o640 - settings = Settings(_env_file=env) - migrate(settings) - app = create_app(settings) - with TestClient(app) as client: - response = client.get("/v1/agent-capabilities") - assert response.status_code == 200 - assert {"powercell.enrollment.v1", "powercell.relay.v1"} <= set( - response.json()["extensions"] - ) - assert response.json()["attestation_required"] - # Check the provisioned CA over TLS; Apple attestation has separate tests. - key = ec.generate_private_key(ec.SECP256R1()) - csr = ( - x509.CertificateSigningRequestBuilder() - .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "TLS test identity")])) - .sign(key, hashes.SHA256()) - ) - certificate = app.state.powercell_authority.issue( - SimpleNamespace(id=str(uuid4())), csr, datetime.now(UTC) - ) - (directory / "client.pem").write_bytes( - certificate.public_bytes(serialization.Encoding.PEM) - + (directory / "issuer/ca.pem").read_bytes() - ) - (directory / "client.key").write_bytes( - key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - context = ssl.create_default_context(cafile=str(lineage / "fullchain.pem")) - context.set_alpn_protocols(["h2"]) - context.load_cert_chain(directory / "client.pem", directory / "client.key") - with socket.create_connection( - ("127.0.0.1", urlsplit(settings.powercell_relay_url).port), timeout=3 - ) as connection: - with context.wrap_socket(connection, server_hostname="api.example") as authenticated: - assert authenticated.version() == "TLSv1.3" - assert authenticated.selected_alpn_protocol() == "h2" - - -def test_repairing_environment_reuses_the_persistent_issuer_and_secret(provisioner): - """Recover removed settings without changing the issuer or encryption secret.""" - directory, env, _, run = provisioner - run("configure", "--create-issuer") - before = [ - (directory / name).read_bytes() - for name in ["issuer/ca.pem", "issuer/ca-key.pem", "recovery.secret"] - ] - env.write_text( - "\n".join( - line - for line in env.read_text().splitlines() - if not line.startswith("THRONG_POWERCELL_") - ) - + "\n" - ) - run("configure", "--create-issuer") - assert before == [ - (directory / name).read_bytes() - for name in ["issuer/ca.pem", "issuer/ca-key.pem", "recovery.secret"] - ] - secret = dotenv_values(env)["THRONG_POWERCELL_SECRET"] - env.write_text(env.read_text().replace(secret, "different-secret-" + "a" * 64)) - result = run("configure", "--create-issuer", success=False) - assert "refusing to rotate" in result.stderr - assert (directory / "recovery.secret").read_text().strip() == secret - - -@pytest.mark.parametrize("damage", ["missing_key", "partial_environment", "missing_secret"]) -def test_partial_issuer_state_is_not_silently_replaced(provisioner, damage): - """Refuse to recreate missing identity material or lose credential recovery.""" - directory, env, _, run = provisioner - run("configure", "--create-issuer") - certificate = (directory / "issuer/ca.pem").read_bytes() - if damage == "missing_key": - (directory / "issuer/ca-key.pem").unlink() - elif damage == "missing_secret": - (directory / "recovery.secret").unlink() - env.write_text( - "\n".join( - line - for line in env.read_text().splitlines() - if not line.startswith("THRONG_POWERCELL_SECRET=") - ) - + "\n" - ) - else: - env.write_text( - "\n".join( - line - for line in env.read_text().splitlines() - if not line.startswith("THRONG_POWERCELL_CA_KEY=") - ) - + "\n" - ) - before = env.read_bytes() - run("configure", "--create-issuer", success=False) - assert (directory / "issuer/ca.pem").read_bytes() == certificate - assert env.read_bytes() == before - if damage == "missing_key": - assert not (directory / "issuer/ca-key.pem").exists() - - -@pytest.mark.parametrize("damage", ["wrong_key", "wrong_hostname", "expired"]) -def test_bad_tls_material_does_not_replace_a_working_pair(provisioner, damage): - """Keep the active pair when renewal offers the wrong key, name or lifetime.""" - directory, env, lineage, run = provisioner - run("configure", "--create-issuer") - before = [(directory / "tls" / name).read_bytes() for name in ["fullchain.pem", "privkey.pem"]] - environment = env.read_bytes() - old = (lineage / "fullchain.pem").read_bytes() - tls_pair( - lineage, - host="wrong.example" if damage == "wrong_hostname" else "api.example", - expired=damage == "expired", - ) - if damage == "wrong_key": - (lineage / "fullchain.pem").write_bytes(old) - run("renew", success=False) - assert before == [ - (directory / "tls" / name).read_bytes() for name in ["fullchain.pem", "privkey.pem"] - ] - assert env.read_bytes() == environment - - -@pytest.mark.parametrize("output", ["native", "empty"]) -def test_hostname_validation_checks_the_result_with_legacy_openssl(provisioner, tmp_path, output): - """Reject a mismatched or missing hostname verdict even when OpenSSL exits zero.""" - directory, env, lineage, run = provisioner - run("configure", "--create-issuer") - before = [(directory / "tls" / name).read_bytes() for name in ["fullchain.pem", "privkey.pem"]] - environment = env.read_bytes() - tls_pair(lineage, host="wrong.example") - binary = tmp_path / "bin" - binary.mkdir() - command = binary / "openssl" - command.write_text( - f"#!{sys.executable}\n" - "import subprocess, sys\n" - f"result = subprocess.run([{shutil.which('openssl')!r}, *sys.argv[1:]], capture_output=True)\n" - "checking_host = '-checkhost' in sys.argv\n" - f"hide_output = checking_host and {output == 'empty'!r}\n" - "sys.stdout.buffer.write(b'' if hide_output else result.stdout)\n" - "sys.stderr.buffer.write(result.stderr)\n" - "sys.exit(0 if checking_host else result.returncode)\n" - ) - command.chmod(0o755) - run( - "renew", - success=False, - environment={**os.environ, "PATH": str(binary) + os.pathsep + os.environ["PATH"]}, - ) - assert before == [ - (directory / "tls" / name).read_bytes() for name in ["fullchain.pem", "privkey.pem"] - ] - assert env.read_bytes() == environment - - -def test_renewal_restarts_with_a_complete_pair_and_retries_a_failed_restart(provisioner, tmp_path): - """Publish both files atomically and retry after systemd rejects restart.""" - directory, env, lineage, run = provisioner - run("configure", "--create-issuer") - old = (directory / "tls").resolve() - preserved = [ - env.read_bytes(), - (directory / "issuer/ca.pem").read_bytes(), - (directory / "recovery.secret").read_bytes(), - ] - tls_pair(lineage) - binary = tmp_path / "bin" - binary.mkdir() - calls = tmp_path / "systemctl.calls" - failed = tmp_path / "fail-systemctl" - failed.touch() - command = binary / "systemctl" - command.write_text(f'#!/bin/sh\nprintf "%s\\n" "$*" >> "{calls}"\ntest ! -e "{failed}"\n') - command.chmod(0o755) - environment = {**os.environ, "PATH": str(binary) + os.pathsep + os.environ["PATH"]} - run("renew", "--restart", environment=environment, success=False) - assert (directory / "tls").resolve() != old - failed.unlink() - run("renew", "--restart", environment=environment) - assert calls.read_text().splitlines() == ["try-restart throng.service"] * 2 - ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain( - directory / "tls/fullchain.pem", directory / "tls/privkey.pem" - ) - assert preserved == [ - env.read_bytes(), - (directory / "issuer/ca.pem").read_bytes(), - (directory / "recovery.secret").read_bytes(), - ] - - -@pytest.mark.parametrize( - "secret", - [ - "existing-operator-secret-" + "b" * 64, - 'секрет с "кавычками", # и \\ обратной чертой ' + "c" * 32, - "1234567890" * 6, - ], -) -def test_existing_operator_issuer_and_secret_are_preserved(provisioner, tmp_path, secret): - """Adopt operator-provided material without changing its bytes or secret.""" - directory, env, _, run = provisioner - external = tmp_path / "external-issuer" - tls_pair(external, ca=True) - with env.open("a") as stream: - stream.write( - f'THRONG_POWERCELL_CA_CERTIFICATE="{external}/fullchain.pem"\nTHRONG_POWERCELL_CA_KEY="{external}/privkey.pem"\nTHRONG_POWERCELL_SECRET=' - + json.dumps(secret, ensure_ascii=False) - + "\n" - ) - before = (external / "privkey.pem").read_bytes() - run("configure") - values = dotenv_values(env) - assert values["THRONG_POWERCELL_CA_CERTIFICATE"] == str(external / "fullchain.pem") - assert values["THRONG_POWERCELL_SECRET"] == secret - assert Settings(_env_file=env).powercell_secret == secret - run("configure") - assert (external / "privkey.pem").read_bytes() == before - assert not (directory / "issuer").exists() diff --git a/tests/platform/api/e2e/auth/conftest.py b/tests/platform/api/e2e/auth/conftest.py index cfe4bb61..b3670392 100644 --- a/tests/platform/api/e2e/auth/conftest.py +++ b/tests/platform/api/e2e/auth/conftest.py @@ -481,8 +481,6 @@ def api_requests( }, ), ("GET", "/v1/agent-enrollments/{enrollment_id}", "read", {}), - ("GET", "/v1/agent-enrollments/{enrollment_id}/profile", "read", {}), - ("GET", "/v1/agent-enrollments/{enrollment_id}/verification", "read", {}), ("POST", "/v1/agent-enrollments/{enrollment_id}/finish", "manage", {}), ("GET", "/v1/computers/{computer_id}/diagnostics/{diagnostic_id}", "read", {}), ] diff --git a/tests/platform/api/e2e/auth/test_authentication.py b/tests/platform/api/e2e/auth/test_authentication.py index 3388609f..89df33c6 100644 --- a/tests/platform/api/e2e/auth/test_authentication.py +++ b/tests/platform/api/e2e/auth/test_authentication.py @@ -38,12 +38,7 @@ async def test_authentication_matrix_covers_all_protected_operations( covered = {(case["method"], case["template"]) for case in cases} assert len(covered) == len(cases), "Duplicate HTTP cases hide gaps in the route inventory" assert covered.isdisjoint(public) - # ACME uses its own JWS/account/nonce authentication, exercised end to end in powercell/. - acme = { - (method, "/acme/powercell/{enrollment_id}/{directory_secret}/{operation}") - for method in ["GET", "HEAD", "POST"] - } - assert actual == covered | public | acme + assert actual == covered | public @pytest.mark.parametrize("settings", [{"agent_lease_seconds": 3600}], indirect=True) diff --git a/tests/platform/api/e2e/powercell/conftest.py b/tests/platform/api/e2e/powercell/conftest.py index e2974cdc..2e7b2737 100644 --- a/tests/platform/api/e2e/powercell/conftest.py +++ b/tests/platform/api/e2e/powercell/conftest.py @@ -1,354 +1,115 @@ -"""A real test CA and HTTP ACME client; cryptographic verification is never bypassed.""" +"""Shared Power Cell registration fixtures without hardware attestation.""" -import base64 -import hashlib -import json -import plistlib -from datetime import timedelta from types import SimpleNamespace -from urllib.parse import urlsplit from uuid import uuid4 -import cbor2 import pytest -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec, utils -from cryptography.x509.oid import NameOID from throng_api.app import create_app -from throng_api.device_security import NONCE_OID, SEP_OID, SERIAL_OID, SIP_OID, UDID_OID - - -def b64(data): - """Encode the RFC 7515 wire representation without padding.""" - return base64.urlsafe_b64encode(data).rstrip(b"=").decode() - - -def jwk(key): - """Describe a real EC account key using its public coordinates only.""" - numbers = key.public_key().public_numbers() - return { - "kty": "EC", - "crv": "P-256", - "x": b64(numbers.x.to_bytes(32, "big")), - "y": b64(numbers.y.to_bytes(32, "big")), - } - - -def jws(key, url, nonce, payload, *, kid=None, patch=None): - """Sign request bytes without sending or wrapping HTTP calls.""" - protected = { - "alg": "ES256", - "url": url, - "nonce": nonce, - **({"kid": kid} if kid else {"jwk": jwk(key)}), - **(patch or {}), - } - encoded = b64(json.dumps(protected).encode()) - body = "" if payload is None else b64(json.dumps(payload).encode()) - signature = key.sign((encoded + "." + body).encode(), ec.ECDSA(hashes.SHA256())) - r, s = utils.decode_dss_signature(signature) - return { - "protected": encoded, - "payload": body, - "signature": b64(r.to_bytes(32, "big") + s.to_bytes(32, "big")), - } - - -def proof_headers(key, certificate, method, target, body, headers, now, *, patch=None): - """Produce the exact signed envelope used by Swift, allowing explicit adversarial mutations.""" - proof = { - "version": 1, - "certificate_sha256": certificate.fingerprint(hashes.SHA256()).hex(), - "method": method, - "target": target, - "timestamp": int(now.timestamp()), - "nonce": str(uuid4()), - "body_sha256": hashlib.sha256(body).hexdigest(), - "authorization_sha256": hashlib.sha256( - headers.get("Authorization", "").encode() - ).hexdigest(), - "session": headers.get("X-Agent-Session"), - "idempotency_key": headers.get("Idempotency-Key"), - **(patch or {}), - } - raw = json.dumps(proof).encode() - return { - **headers, - "X-PowerCell-Proof": base64.b64encode(raw).decode(), - "X-PowerCell-Signature": base64.b64encode( - key.sign(raw, ec.ECDSA(hashes.SHA256())) - ).decode(), - } - - -def certificate(key, issuer_key, subject, issuer, now, *, ca=False, extensions=()): - """Issue a real X.509 chain with proper CA constraints and key usage.""" - builder = ( - x509.CertificateBuilder() - .subject_name(subject) - .issuer_name(issuer) - .public_key(key.public_key()) - .serial_number(x509.random_serial_number()) - .not_valid_before(now - timedelta(days=1)) - .not_valid_after(now + timedelta(days=3650)) - .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) - .add_extension( - x509.KeyUsage(True, False, False, False, False, ca, ca, False, False), critical=True - ) - .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) - .add_extension( - x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_key.public_key()), - critical=False, - ) - ) - for oid, value in extensions: - builder = builder.add_extension(x509.UnrecognizedExtension(oid, value), critical=False) - return builder.sign(issuer_key, hashes.SHA256()) - - -def attestation( - pki, key, token, now, *, udid=b"00006000-0012345678901234", nonce=None, extensions=None -): - """Create an Apple-shaped certificate under the isolated test trust root.""" - values = ( - extensions - if extensions is not None - else [ - (UDID_OID, udid), - (SERIAL_OID, b"MAC-SERIAL"), - (SEP_OID, b"1.0"), - (SIP_OID, b"\x01"), - (NONCE_OID, nonce if nonce is not None else hashlib.sha256(token.encode()).digest()), - ] - ) - leaf = certificate( - key, - pki.intermediate_key, - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Attested Mac")]), - pki.intermediate.subject, - now, - extensions=values, - ) - return b64( - cbor2.dumps( - { - "fmt": "apple", - "attStmt": { - "x5c": [ - leaf.public_bytes(serialization.Encoding.DER), - pki.intermediate.public_bytes(serialization.Encoding.DER), - ] - }, - } - ) - ) @pytest.fixture -def pki(tmp_path, clock): - """Generate separate issuer and attestation roots; no private fixture keys leave the test directory.""" - root_key, intermediate_key, issuer_key = [ - ec.generate_private_key(ec.SECP256R1()) for _ in range(3) - ] - root_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Test attestation root")]) - intermediate_name = x509.Name( - [x509.NameAttribute(NameOID.COMMON_NAME, "Test attestation intermediate")] - ) - issuer_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Test Power Cell CA")]) - root = certificate(root_key, root_key, root_name, root_name, clock.now, ca=True) - intermediate = certificate( - intermediate_key, root_key, intermediate_name, root_name, clock.now, ca=True - ) - issuer = certificate(issuer_key, issuer_key, issuer_name, issuer_name, clock.now, ca=True) - root_file, issuer_file, key_file = [ - tmp_path / name for name in ["root.pem", "issuer.pem", "issuer.key"] - ] - root_file.write_bytes(root.public_bytes(serialization.Encoding.PEM)) - issuer_file.write_bytes(issuer.public_bytes(serialization.Encoding.PEM)) - key_file.write_bytes( - issuer_key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - return SimpleNamespace( - root=root, - root_key=root_key, - intermediate=intermediate, - intermediate_key=intermediate_key, - root_file=root_file, - issuer=issuer, - issuer_file=issuer_file, - key_file=key_file, - ) - - -@pytest.fixture -def app(settings, clock, pki, monkeypatch): - """Run the actual application with an explicit disposable PKI trust root.""" - from throng_api import device_security - - monkeypatch.setattr(device_security, "APPLE_ROOT", pki.root_file) - monkeypatch.setattr( - device_security, "APPLE_ROOT_SHA256", pki.root.fingerprint(hashes.SHA256()).hex() - ) +def app(settings, clock): + """Run the real API with an explicit deployment-style enrollment secret.""" configured = settings.model_copy( - update={ - "powercell_acme_url": "https://enroll.example/acme/powercell", - "powercell_ca_certificate": pki.issuer_file, - "powercell_ca_key": pki.key_file, - "powercell_secret": "test-only-recovery-secret-" + str(uuid4()), - } + update={"enrollment_secret": "test-enrollment-secret-" + uuid4().hex} ) return create_app(configured, clock=lambda: clock.now) -@pytest.fixture -async def enrollment(api): - """Obtain a pending enrollment and the exact restricted profile over authenticated HTTP.""" +def proof_headers(_key, _certificate, _method, _target, _body, headers, _now, **_kwargs): + """Legacy callers now send ordinary bearer requests; no proof headers exist.""" + return dict(headers) + + +async def register_device(api, device_id, **overrides): + """Create and finish a registration for a device already linked at login.""" + key = str(uuid4()) payload = { - "installation_id": str(uuid4()), + "device_id": str(device_id), "name": "My Mac", "cpu_millis": 2000, "memory_bytes": 2048, "disk_bytes": 8192, "isolation_modes": ["vm", "shared"], + **overrides, } - key = str(uuid4()) response = await api.post( "/v1/agent-enrollments", headers={"Idempotency-Key": key}, json=payload ) assert response.status_code == 201, response.text - row = response.json() - response = await api.get(f"/v1/agent-enrollments/{row['id']}/profile") + enrollment = response.json() + target = f"/v1/agent-enrollments/{enrollment['id']}/finish" + headers = {"Idempotency-Key": "finish-" + enrollment["id"]} + response = await api.post(target, headers=headers, json={}) assert response.status_code == 200, response.text - profile = plistlib.loads(response.content) - url = profile["PayloadContent"][0]["DirectoryURL"] return SimpleNamespace( - row=row, - payload=payload, - key=key, - profile=profile, - base=url.rsplit("/", 1)[0], - path=urlsplit(url).path.rsplit("/", 1)[0], + enrollment=enrollment, + binding=response.json(), + target=target, + headers=headers, + device_id=str(device_id), + identity=SimpleNamespace(key=None, certificate=None), ) @pytest.fixture -async def acme_order(client, enrollment): - """Register a real JWS account and order through the live ACME service.""" - key = ec.generate_private_key(ec.SECP256R1()) - response = await client.get(enrollment.path + "/directory") - assert response.status_code == 200, response.text - response = await client.post( - enrollment.path + "/new-account", - json=jws( - key, - enrollment.base + "/new-account", - response.headers["Replay-Nonce"], - {"termsOfServiceAgreed": True}, - ), - ) - assert response.status_code == 201, response.text - account = response.headers["Location"] - response = await client.post( - enrollment.path + "/new-order", - json=jws( - key, - enrollment.base + "/new-order", - response.headers["Replay-Nonce"], - {"identifiers": [{"type": "permanent-identifier", "value": enrollment.row["id"]}]}, - kid=account, - ), - ) - assert response.status_code == 201, response.text - response = await client.post( - enrollment.path + "/authorization", - json=jws( - key, - enrollment.base + "/authorization", - response.headers["Replay-Nonce"], - None, - kid=account, - ), +async def enrollment(api): + """Create a pending registration whose device was announced by the account.""" + device_id = uuid4() + response = await api.post( + "/v1/auth/login", + json={ + "login": "alice", + "password": " correct horse battery staple ", + "device_id": str(device_id), + }, ) assert response.status_code == 200, response.text - return SimpleNamespace( - enrollment=enrollment, - key=key, - account=account, - nonce=response.headers["Replay-Nonce"], - token=response.json()["challenges"][0]["token"], + payload = { + "device_id": str(device_id), + "name": "My Mac", + "cpu_millis": 2000, + "memory_bytes": 2048, + "disk_bytes": 8192, + "isolation_modes": ["vm", "shared"], + } + key = str(uuid4()) + response = await api.post( + "/v1/agent-enrollments", headers={"Idempotency-Key": key}, json=payload ) + assert response.status_code == 201, response.text + return SimpleNamespace(row=response.json(), payload=payload, key=key, device_id=device_id) @pytest.fixture -async def verified_enrollment(client, acme_order, pki, clock): - """Validate a real certificate chain/freshness and finalize a CSR with its attested key.""" - order = acme_order - e = order.enrollment - key = ec.generate_private_key(ec.SECP256R1()) - statement = attestation(pki, key, order.token, clock.now) - response = await client.post( - e.path + "/challenge", - json=jws( - order.key, e.base + "/challenge", order.nonce, {"attObj": statement}, kid=order.account - ), - ) - assert response.status_code == 200, response.text - csr = ( - x509.CertificateSigningRequestBuilder() - .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, e.row["id"])])) - .sign(key, hashes.SHA256()) - ) - response = await client.post( - e.path + "/finalize", - json=jws( - order.key, - e.base + "/finalize", - response.headers["Replay-Nonce"], - {"csr": b64(csr.public_bytes(serialization.Encoding.DER))}, - kid=order.account, - ), - ) - assert response.status_code == 200, response.text - response = await client.post( - e.path + "/certificate", - json=jws( - order.key, - e.base + "/certificate", - response.headers["Replay-Nonce"], - None, - kid=order.account, - ), +async def bound_device(api, user): + """Register one computer for Alice and put it in her personal pool. + + Most session, CI and pool tests predate the explicit unassigned state and + describe an installation that already chose a pool. The registration tests + exercise the unassigned default separately. + """ + device_id = uuid4() + response = await api.post( + "/v1/auth/login", + json={ + "login": "alice", + "password": " correct horse battery staple ", + "device_id": str(device_id), + }, ) assert response.status_code == 200, response.text - return SimpleNamespace( - order=order, - key=key, - certificate=x509.load_pem_x509_certificate(response.content), - nonce=response.headers["Replay-Nonce"], - csr=csr, + device = await register_device(api, device_id) + moved = await api.patch( + f"/v1/connected-computers/{device.binding['computer_id']}/pool", + json={"company_id": None, "expected_company_id": None}, ) + assert moved.status_code == 200, moved.text + return device @pytest.fixture -async def bound_device(api, verified_enrollment, user, clock): - """Finish user enrollment with a genuine possession signature and preserve the issuance retry key.""" - identity = verified_enrollment - target = f"/v1/agent-enrollments/{identity.order.enrollment.row['id']}/finish" - headers = {**user["headers"], "Idempotency-Key": str(uuid4())} - response = await api.post( - target, - headers=proof_headers( - identity.key, identity.certificate, "POST", target, b"{}", headers, clock.now - ), - content=b"{}", - ) - assert response.status_code == 200, response.text - return SimpleNamespace( - identity=identity, binding=response.json(), target=target, headers=headers - ) +async def verified_enrollment(bound_device): + """Compatibility alias for tests written around the old verified step.""" + return bound_device diff --git a/tests/platform/api/e2e/powercell/test_acme_protocol.py b/tests/platform/api/e2e/powercell/test_acme_protocol.py deleted file mode 100644 index 966ad3eb..00000000 --- a/tests/platform/api/e2e/powercell/test_acme_protocol.py +++ /dev/null @@ -1,201 +0,0 @@ -"""ACME error transitions, polling and exact retries exercised over TCP.""" - -import json - -import pytest -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa - -from .conftest import attestation, b64, jws - -pytestmark = pytest.mark.anyio - - -async def test_account_nonce_and_preorder_contract(client, enrollment): - """Nonce retrieval, account retries and polling have the status semantics expected by native ACME clients.""" - e = enrollment - key = ec.generate_private_key(ec.SECP256R1()) - for method, operation, status in [ - ("HEAD", "nonce", 200), - ("GET", "nonce", 204), - ("GET", "order", 405), - ]: - response = await client.request(method, e.path + "/" + operation) - assert response.status_code == status - assert response.headers["Replay-Nonce"] - nonce = response.headers["Replay-Nonce"] - for payload, status in [ - (None, 400), - ({"unknown": True}, 400), - ({"onlyReturnExisting": True}, 400), - ({}, 201), - ({}, 200), - ]: - response = await client.post( - e.path + "/new-account", json=jws(key, e.base + "/new-account", nonce, payload) - ) - assert response.status_code == status, response.text - nonce = response.headers["Replay-Nonce"] - account = e.base + "/account" - for operation, payload, status in [ - ("account", None, 200), - ("account", {"status": "deactivated"}, 400), - ("orders", None, 200), - ("orders", {}, 400), - ("order", None, 401), - ]: - response = await client.post( - e.path + "/" + operation, - json=jws(key, e.base + "/" + operation, nonce, payload, kid=account), - ) - assert response.status_code == status, response.text - nonce = response.headers["Replay-Nonce"] - other = ec.generate_private_key(ec.SECP256R1()) - response = await client.post( - e.path + "/new-account", json=jws(other, e.base + "/new-account", nonce, {}) - ) - assert response.status_code == 401 - - -@pytest.mark.parametrize( - "operation,payload,status", - [ - ("challenge", None, 200), - ("challenge", {}, 400), - ("finalize", {}, 400), - ("order", {}, 400), - ("certificate", None, 400), - ("unknown", None, 400), - ("orders", None, 200), - ], -) -async def test_order_requires_correct_sequence_and_post_as_get( - client, acme_order, operation, payload, status -): - """Out-of-sequence issuance and polling with mutation bodies are rejected without changing the order.""" - order = acme_order - e = order.enrollment - response = await client.post( - e.path + "/" + operation, - json=jws(order.key, e.base + "/" + operation, order.nonce, payload, kid=order.account), - ) - assert response.status_code == status, response.text - - -async def test_finalized_order_retries_and_attestation_immutability( - client, verified_enrollment, pki, clock -): - """A finalized order returns the same certificate and cannot be rebound through a second attestation or CSR.""" - identity = verified_enrollment - order = identity.order - e = order.enrollment - nonce = identity.nonce - for payload, status in [ - (None, 400), - ({"csr": b64(identity.csr.public_bytes(serialization.Encoding.DER))}, 200), - ]: - response = await client.post( - e.path + "/finalize", - json=jws(order.key, e.base + "/finalize", nonce, payload, kid=order.account), - ) - assert response.status_code == status, response.text - nonce = response.headers["Replay-Nonce"] - other_csr = ( - x509.CertificateSigningRequestBuilder() - .subject_name(x509.Name([])) - .sign(identity.key, hashes.SHA256()) - ) - response = await client.post( - e.path + "/finalize", - json=jws( - order.key, - e.base + "/finalize", - nonce, - {"csr": b64(other_csr.public_bytes(serialization.Encoding.DER))}, - kid=order.account, - ), - ) - assert response.status_code == 400 - nonce = response.headers["Replay-Nonce"] - for key, status in [(identity.key, 200), (ec.generate_private_key(ec.SECP256R1()), 400)]: - response = await client.post( - e.path + "/challenge", - json=jws( - order.key, - e.base + "/challenge", - nonce, - {"attObj": attestation(pki, key, order.token, clock.now)}, - kid=order.account, - ), - ) - assert response.status_code == status, response.text - nonce = response.headers["Replay-Nonce"] - response = await client.post( - e.path + "/authorization", - json=jws(order.key, e.base + "/authorization", nonce, None, kid=order.account), - ) - assert response.status_code == 200 and response.json()["status"] == "valid" - - -@pytest.mark.parametrize( - "mutation", - [ - "wrong_kid", - "short_signature", - "unsupported_alg", - "bad_nonce_type", - "bad_base64_type", - "duplicate_json", - ], -) -async def test_malformed_signed_envelopes_are_controlled_errors(client, acme_order, mutation): - """JWS parsing rejects malformed values before database binding or state changes.""" - order = acme_order - e = order.enrollment - patch = {} - if mutation == "wrong_kid": - patch["kid"] = e.base + "/another-account" - if mutation == "unsupported_alg": - patch["alg"] = "none" - if mutation == "bad_nonce_type": - patch["nonce"] = [] - payload = jws(order.key, e.base + "/order", order.nonce, None, kid=order.account, patch=patch) - if mutation == "short_signature": - payload["signature"] = b64(b"1") - if mutation == "bad_base64_type": - payload["signature"] = 123 - if mutation == "duplicate_json": - payload["protected"] = b64(b'{"alg":"ES256","alg":"none"}') - response = await client.post(e.path + "/order", json=payload) - assert response.status_code == 401, response.text - - -async def test_rsa_account_support_is_separate_from_attested_device_key(client, enrollment): - """A standard RS256 account can create its order, while small account keys are rejected.""" - e = enrollment - response = await client.head(e.path + "/nonce") - nonce = response.headers["Replay-Nonce"] - for size, status in [(1024, 401), (2048, 201)]: - key = rsa.generate_private_key(public_exponent=65537, key_size=size) - numbers = key.public_key().public_numbers() - public = { - "kty": "RSA", - "n": b64(numbers.n.to_bytes(size // 8, "big")), - "e": b64(numbers.e.to_bytes(3, "big")), - } - protected = b64( - json.dumps( - {"alg": "RS256", "url": e.base + "/new-account", "nonce": nonce, "jwk": public} - ).encode() - ) - payload = b64(b"{}") - signature = key.sign( - (protected + "." + payload).encode(), padding.PKCS1v15(), hashes.SHA256() - ) - response = await client.post( - e.path + "/new-account", - json={"protected": protected, "payload": payload, "signature": b64(signature)}, - ) - assert response.status_code == status, response.text - nonce = response.headers["Replay-Nonce"] diff --git a/tests/platform/api/e2e/powercell/test_benchmark_proof_review.py b/tests/platform/api/e2e/powercell/test_benchmark_proof_review.py deleted file mode 100644 index 6e0ad741..00000000 --- a/tests/platform/api/e2e/powercell/test_benchmark_proof_review.py +++ /dev/null @@ -1,193 +0,0 @@ -"""Session-free benchmark uploads retain real device possession verification.""" - -import asyncio -import json -from uuid import uuid4 - -import pytest -from cryptography.hazmat.primitives.asymmetric import ec - -from .conftest import proof_headers - -pytestmark = pytest.mark.anyio - -TARGET = "/agent/v1/benchmark-results" -BODY = json.dumps( - { - "benchmarker_version": "0.0.2", - "run_id": str(uuid4()), - "results": [ - {"benchmark_name": "single_core", "number": 15}, - {"benchmark_name": "multi_core", "number": 40}, - ], - } -).encode() - - -def headers_for(device): - """Build test authorization headers for an enrolled device.""" - return { - "Authorization": "Bearer " + device.binding["credential"], - "Content-Type": "application/json", - } - - -async def test_attested_benchmark_upload_before_session_requires_fresh_proof_on_retry( - api, client, bound_device, clock -): - """An attested Mac can upload before an agent session, but retrying a measurement requires fresh possession proof while retaining row identity.""" - device = bound_device - signed = proof_headers( - device.identity.key, - device.identity.certificate, - "PUT", - TARGET, - BODY, - headers_for(device), - clock.now, - ) - responses = await asyncio.gather( - *(client.put(TARGET, headers=signed, content=BODY) for _ in range(2)) - ) - assert sorted(response.status_code for response in responses) == [200, 401], [ - response.text for response in responses - ] - rows = next(response.json() for response in responses if response.status_code == 200) - assert len(rows) == 2 - assert {row["computer_id"] for row in rows} == {device.binding["computer_id"]} - replay = next(response for response in responses if response.status_code == 401) - assert replay.json() == {"detail": "Device proof nonce has already been used"} - - response = await client.put( - TARGET, - headers=proof_headers( - device.identity.key, - device.identity.certificate, - "PUT", - TARGET, - BODY, - headers_for(device), - clock.now, - ), - content=BODY, - ) - assert response.status_code == 200, response.text - assert response.json() == rows - state = (await api.get(f"/v1/computers/{device.binding['computer_id']}")).json() - assert state["online"] is False - assert state["session_id"] is None - response = await api.get(f"/v1/computers/{device.binding['computer_id']}/benchmark-results") - assert response.status_code == 200, response.text - assert {row["id"] for row in response.json()} == {row["id"] for row in rows} - - -@pytest.mark.parametrize("attack", ["missing_proof", "unrelated_private_key", "altered_results"]) -async def test_session_free_upload_rejects_stolen_credential_or_modified_measurement( - api, client, bound_device, clock, attack -): - """A stolen credential, unrelated signing key, or body altered after signing cannot upload results or create stored measurements.""" - device = bound_device - headers = headers_for(device) - body = BODY - if attack != "missing_proof": - key = ( - ec.generate_private_key(ec.SECP256R1()) - if attack == "unrelated_private_key" - else device.identity.key - ) - headers = proof_headers( - key, device.identity.certificate, "PUT", TARGET, BODY, headers, clock.now - ) - if attack == "altered_results": - body = BODY.replace(b'"number": 15', b'"number": 999') - assert body != BODY - response = await client.put(TARGET, headers=headers, content=body) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid device proof"} - response = await api.get( - f"/v1/computers/{device.binding['computer_id']}/benchmark-results", - params={"latest_only": False}, - ) - assert response.status_code == 200, response.text - assert response.json() == [] - - -async def test_owner_unbind_rejects_signed_benchmark_upload_and_retains_old_measurements( - api, client, bound_device, clock -): - """Unbinding disables further device uploads, including correctly signed requests, while preserving previously stored scores.""" - device = bound_device - response = await client.put( - TARGET, - headers=proof_headers( - device.identity.key, - device.identity.certificate, - "PUT", - TARGET, - BODY, - headers_for(device), - clock.now, - ), - content=BODY, - ) - assert response.status_code == 200, response.text - original = response.json() - response = await api.post( - f"/v1/computers/{device.binding['computer_id']}/unbind", - headers={"Idempotency-Key": str(uuid4())}, - json={"cleanup_confirmed": True}, - ) - assert response.status_code == 200, response.text - altered = BODY.replace(b'"number": 15', b'"number": 999') - response = await client.put( - TARGET, - headers=proof_headers( - device.identity.key, - device.identity.certificate, - "PUT", - TARGET, - altered, - headers_for(device), - clock.now, - ), - content=altered, - ) - assert response.status_code == 401, response.text - response = await api.get(f"/v1/computers/{device.binding['computer_id']}/benchmark-results") - assert response.status_code == 200, response.text - assert {row["id"]: row for row in response.json()} == {row["id"]: row for row in original} - - -async def test_expired_certificate_cannot_upload_with_current_signed_proof( - api, client, bound_device, clock -): - """A fresh signature cannot restore upload authority after the device certificate expires, and no result is saved.""" - device = bound_device - clock.now = device.identity.certificate.not_valid_after_utc - response = await client.put( - TARGET, - headers=proof_headers( - device.identity.key, - device.identity.certificate, - "PUT", - TARGET, - BODY, - headers_for(device), - clock.now, - ), - content=BODY, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid device proof"} - # The owner token expired too; obtain a current owner token to inspect durable state. - response = await client.post( - "/v1/auth/login", - json={"email": "alice@example.com", "password": " correct horse battery staple "}, - ) - assert response.status_code == 200, response.text - response = await api.get( - f"/v1/computers/{device.binding['computer_id']}/benchmark-results", - headers={"Authorization": "Bearer " + response.json()["access_token"]}, - ) - assert response.status_code == 200, response.text - assert response.json() == [] diff --git a/tests/platform/api/e2e/powercell/test_ci.py b/tests/platform/api/e2e/powercell/test_ci.py index 60c0560d..13384abc 100644 --- a/tests/platform/api/e2e/powercell/test_ci.py +++ b/tests/platform/api/e2e/powercell/test_ci.py @@ -280,7 +280,7 @@ def auth_flow(self, request): @pytest.fixture async def powercell(client, bound_device, clock): - """Use the real ACME/device enrollment and proof-checked HTTP agent protocol.""" + """Use the real device registration and credential-authenticated agent protocol.""" device = bound_device.identity headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} async with httpx.AsyncClient( diff --git a/tests/platform/api/e2e/powercell/test_ci_chain.py b/tests/platform/api/e2e/powercell/test_ci_chain.py index 68ccd393..be3a03b8 100644 --- a/tests/platform/api/e2e/powercell/test_ci_chain.py +++ b/tests/platform/api/e2e/powercell/test_ci_chain.py @@ -162,6 +162,10 @@ async def test_workflow_cancelled_during_preparation_stops_the_whole_chain(chain chain.agent = powercell async def cancel(): + # The first pump runs before the routing job calls reserve. Cancelling + # then would only create a tombstone; wait for the actual reservation. + if await chain.state() is None: + return chain.on_pump = None await chain.webhook( "workflow_run", diff --git a/tests/platform/api/e2e/powercell/test_connected_computers.py b/tests/platform/api/e2e/powercell/test_connected_computers.py index 9795db21..18f4a038 100644 --- a/tests/platform/api/e2e/powercell/test_connected_computers.py +++ b/tests/platform/api/e2e/powercell/test_connected_computers.py @@ -8,12 +8,10 @@ import anyio import pytest from alembic import command -from httpx import AsyncClient -from sqlalchemy import update from sqlalchemy.ext.asyncio import AsyncSession from throng_api.cli import migration_config -from throng_api.models import AgentCredential, AvailabilityBaseline, Computer +from throng_api.models import AvailabilityBaseline, Computer from .conftest import proof_headers @@ -23,7 +21,7 @@ @pytest.fixture async def connected_worker(client, bound_device, clock): - """Open an attested agent session and publish available resources.""" + """Open an agent session and publish available resources.""" device = bound_device identity = device.identity headers = { @@ -77,24 +75,23 @@ async def test_inventory_is_account_scoped_and_reports_leases( reply = await api.get(PATH, params={"limit": 1}) assert int(reply.headers["x-computer-pool-check-revision"]) >= 0 assert reply.status_code == 200, reply.text - assert reply.json() == { - "items": [ - { - "id": session["computer_id"], - "name": "My Mac", - "os": "linux", - "architecture": "arm64", - "runtime": "powercell-ubuntu-arm64-v1", - "online": True, - "pool": {"company_id": None, "name": None}, - "pool_membership_id": None, - "pool_revision": 0, - "can_move": True, - "transfer_pending": False, - } - ], - "total": 1, - "online": 1, + page = reply.json() + assert page["total"] == 1 and page["online"] == 1 + row = page["items"][0] + assert row["pool_revision"] >= 0 + row["pool_revision"] = 0 + assert row == { + "id": session["computer_id"], + "name": "My Mac", + "os": "linux", + "architecture": "arm64", + "runtime": "powercell-ubuntu-arm64-v1", + "online": True, + "pool": {"company_id": None, "name": None}, + "pool_membership_id": None, + "pool_revision": 0, + "can_move": True, + "transfer_pending": False, } assert computer["id"] != session["computer_id"] assert (await api.get(PATH, params={"offset": 1})).json() == { @@ -146,6 +143,12 @@ async def pause_inventory(session, statement, *args, **kwargs): return rows monkeypatch.setattr(AsyncSession, "scalars", pause_inventory) + # Start in the personal pool so /v1/computers has a row to move. + personal = await api.patch( + f"{PATH}/{computer_id}/pool", + json={"company_id": None, "expected_company_id": None}, + ) + assert personal.status_code == 200, personal.text params = {"user_id": user["id"], "only_available": "false", "limit": 3} reading = asyncio.create_task(api.get("/v1/computers", params=params)) try: @@ -218,7 +221,7 @@ async def test_lookup_confirms_management_for_the_connected_account_without_pool async def test_pool_manager_can_check_the_pool_using_the_bound_device_key( api, other_api, other_user, company, client, connected_worker, bound_device, clock ): - """Return the verified pool to the attested agent while preserving account-scoped recovery.""" + """Return the verified pool to the credential-bearing agent while preserving scoped recovery.""" session, _ = connected_worker computer_id = session["computer_id"] member = await api.post( @@ -265,7 +268,6 @@ async def get_session(path): assert basic.status_code == 200, basic.text assert "pool_owner" not in basic.json() details = "/agent/v1/session?include_pool=true" - assert (await client.get(details, headers=agent_headers)).status_code == 401 checked = await get_session(details) assert checked.status_code == 200, checked.text assert checked.json()["session_id"] == session["session_id"] @@ -313,7 +315,8 @@ async def test_reconciliation_serializes_with_a_pool_change_whose_response_was_l delayed = await api.patch(path, json=payload, headers=headers) assert delayed.status_code == 409, delayed.text assert delayed.json()["detail"] == "Computer pool change was cancelled" - assert (await api.get(PATH)).json()["items"][0]["pool"]["company_id"] is None + row = (await api.get(PATH)).json()["items"][0] + assert row["pool"]["company_id"] is None later = await api.post(f"{path}/reconcile", json=payload, headers=headers) assert later.json() is move_arrived_first if move_arrived_first: @@ -415,52 +418,62 @@ async def grant(permissions): assert access_header not in unavailable.headers -async def test_transfer_receipt_checks_read_access_after_unlinking(api, company, connected_worker): - """An unlinked computer still has a readable card for its registering account.""" +async def test_unlinking_an_ownership_returns_the_computer_to_the_unassigned_state( + api, company, connected_worker +): + """Removing a pool keeps the registering account's computer visible and assignable.""" session, _ = connected_worker computer_id = session["computer_id"] path = f"{PATH}/{computer_id}/pool" payload = {"company_id": company["id"], "expected_company_id": None} - headers = {"Idempotency-Key": str(uuid4())} - assert (await api.patch(path, json=payload, headers=headers)).status_code == 200 + assert (await api.patch(path, json=payload)).status_code == 200 ownerships = await api.get("/v1/computer-ownerships") owner = next(row for row in ownerships.json() if row["computer_id"] == computer_id) assert (await api.delete(f"/v1/computer-ownerships/{owner['id']}")).status_code == 204 - assert (await api.get(PATH, params={"computer_id": computer_id})).json()["total"] == 0 + page = (await api.get(PATH, params={"computer_id": computer_id})).json() + assert page["total"] == 1 and page["items"][0]["pool"] is None assert (await api.get(f"/v1/computers/{computer_id}")).status_code == 200 - confirmed = await api.post(f"{path}/reconcile", json=payload, headers=headers) - assert confirmed.status_code == 200 and confirmed.json() is True - assert confirmed.headers["x-computer-read-allowed"] == "true" - assert confirmed.headers["x-computer-pool-assigned"] == "false" - assert "x-organization-id" not in confirmed.headers + confirmed = await api.patch(path, json={"company_id": company["id"], "expected_company_id": None}) + assert confirmed.status_code == 200 and confirmed.json()["company_id"] == company["id"] -async def test_enrollment_completed_with_an_api_token_is_excluded( - api, user, verified_enrollment, clock -): +async def test_enrollment_completed_with_an_api_token_is_excluded(api, user, client): """Limit the personal connected inventory to accounts that used password sign-in.""" + device_id = uuid4() + response = await client.post( + "/v1/auth/login", + json={ + "login": "alice", + "password": user["password"], + "device_id": str(device_id), + }, + ) + assert response.status_code == 200, response.text issued = await api.post( "/v1/api-tokens", json={"user_id": user["id"], "name": "Enrollment", "scopes": ["manage"]}, ) assert issued.status_code == 201, issued.text - identity = verified_enrollment - path = f"/v1/agent-enrollments/{identity.order.enrollment.row['id']}/finish" - response = await api.post( - path, - content=b"{}", - headers=proof_headers( - identity.key, - identity.certificate, - "POST", - path, - b"{}", - { - "Authorization": "Bearer " + issued.json()["token"], - "Idempotency-Key": str(uuid4()), - }, - clock.now, - ), + token = issued.json()["token"] + headers = {"Authorization": "Bearer " + token, "Idempotency-Key": str(uuid4())} + payload = { + "device_id": str(device_id), + "name": "API worker", + "cpu_millis": 2000, + "memory_bytes": 2048, + "disk_bytes": 8192, + "isolation_modes": ["vm", "shared"], + } + response = await client.post("/v1/agent-enrollments", headers=headers, json=payload) + assert response.status_code == 201, response.text + enrollment = response.json() + response = await client.post( + f"/v1/agent-enrollments/{enrollment['id']}/finish", + headers={ + "Authorization": "Bearer " + token, + "Idempotency-Key": "finish-" + enrollment["id"], + }, + json={}, ) assert response.status_code == 200, response.text assert (await api.get(PATH)).json() == {"items": [], "total": 0, "online": 0} @@ -537,953 +550,6 @@ async def start_replacement_session(client, bound_device, token, clock, *, publi return response.json() -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -async def test_upgrade_imports_existing_attested_binding(api, bound_device, computer, settings): - """Import the account of a previously enrolled and attested computer.""" - await reapply_connection_migration(settings) - page = (await api.get(PATH)).json() - assert [item["id"] for item in page["items"]] == [bound_device.binding["computer_id"]] - assert computer["id"] != page["items"][0]["id"] - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("key_issued_before_upgrade", [False, True]) -async def test_legacy_personal_transfer_preserves_new_account_after_migration( - api, - other_api, - other_user, - company, - bound_device, - settings, - client, - clock, - key_issued_before_upgrade, -): - """Associate a confirmed personal handoff with the new account.""" - computer_id = bound_device.binding["computer_id"] - grant = await api.post( - "/v1/memberships", - json={ - "company_id": company["id"], - "user_id": other_user["id"], - "role": "admin", - }, - ) - assert grant.status_code == 201, grant.text - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - owner_path = f"/v1/computer-ownerships/{owner['id']}" - company_owner = {"company_id": company["id"]} - assert (await api.patch(owner_path, json=company_owner)).status_code == 200 - personal = await other_api.patch(owner_path, json={"user_id": other_user["id"]}) - assert personal.status_code == 200, personal.text - credentials = f"/v1/computers/{computer_id}/credentials" - received = await other_api.post(credentials) if key_issued_before_upgrade else None - await reapply_connection_migration(settings) - assert (await api.get(PATH)).json()["items"] == [] - assert (await other_api.get(PATH)).json()["items"] == [] - if received is None: - received = await other_api.post(credentials) - assert received.status_code == 201, received.text - await start_replacement_session( - client, - bound_device, - received.json()["token"], - clock, - publish_capacity=True, - ) - personal_items = (await other_api.get(PATH)).json()["items"] - assert [row["id"] for row in personal_items] == [computer_id] - assert personal_items[0]["pool"] == {"company_id": None, "name": None} - - returned = await other_api.patch(owner_path, json=company_owner) - assert returned.status_code == 200, returned.text - await reapply_connection_migration(settings) - move_path = f"{PATH}/{computer_id}/pool" - payload = {"company_id": None, "expected_company_id": company["id"]} - assert (await api.get(PATH)).json()["items"] == [] - assert (await api.patch(move_path, json=payload)).status_code == 404 - assert [row["id"] for row in (await other_api.get(PATH)).json()["items"]] == [computer_id] - restored = await other_api.post(credentials) - assert restored.status_code == 201, restored.text - await start_replacement_session(client, bound_device, restored.json()["token"], clock) - shifted = await other_api.patch(move_path, json=payload) - assert shifted.status_code == 200, shifted.text - shifted_back = await other_api.patch( - move_path, json={**company_owner, "expected_company_id": None} - ) - assert shifted_back.status_code == 200, shifted_back.text - assert (await other_api.get(PATH)).json()["items"][0]["pool"] == shifted_back.json() - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("previous_pool", ["unconfirmed_personal", "confirmed_organization"]) -async def test_migration_recovers_previous_signed_account_when_legacy_target_was_changed( - api, - other_api, - other_user, - company, - bound_device, - settings, - client, - clock, - previous_pool, -): - """Keep the last verified account visible while a later transfer awaits proof.""" - computer_id = bound_device.binding["computer_id"] - grant = await api.post( - "/v1/memberships", - json={ - "company_id": company["id"], - "user_id": other_user["id"], - "role": "admin", - }, - ) - assert grant.status_code == 201, grant.text - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - ownership = f"/v1/computer-ownerships/{owner['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - first_pool = {"company_id": company["id"]} - assert (await api.patch(ownership, json=first_pool)).status_code == 200 - if previous_pool == "unconfirmed_personal": - target = {"user_id": other_user["id"]} - expected_account, other_account = api, other_api - else: - new_pool = await other_api.post("/v1/companies", json={"name": "Other organization"}) - assert new_pool.status_code == 201, new_pool.text - target = {"company_id": new_pool.json()["id"]} - expected_account, other_account = other_api, api - assert (await other_api.patch(ownership, json=target)).status_code == 200 - if previous_pool == "confirmed_organization": - key = await other_api.post(credentials) - assert key.status_code == 201, key.text - await start_replacement_session( - client, bound_device, key.json()["token"], clock, publish_capacity=True - ) - assert (await other_api.patch(ownership, json=first_pool)).status_code == 200 - key = await other_api.post(credentials) - assert key.status_code == 201, key.text - await reapply_connection_migration(settings) - rows = (await expected_account.get(PATH)).json()["items"] - assert [row["id"] for row in rows] == [computer_id] - assert rows[0]["transfer_pending"] and not rows[0]["can_move"] - assert (await other_account.get(PATH)).json()["items"] == [] - await start_replacement_session(client, bound_device, key.json()["token"], clock) - assert (await api.get(PATH)).json()["items"] == [] - assert [row["id"] for row in (await other_api.get(PATH)).json()["items"]] == [computer_id] - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize( - "legacy_stage", - ["before_issuance", "after_issuance", "after_issuance_retry", "archived_resources"], -) -async def test_legacy_organization_transfer_with_replacement_key_preserves_new_account( - api, - other_api, - app, - user, - other_user, - client, - company, - bound_device, - settings, - clock, - legacy_stage, -): - """Promote the account of an organization transfer after its key is confirmed.""" - computer_id = bound_device.binding["computer_id"] - grant = await api.post( - "/v1/memberships", - json={ - "company_id": company["id"], - "user_id": other_user["id"], - "role": "admin", - }, - ) - assert grant.status_code == 201, grant.text - target = await other_api.post("/v1/companies", json={"name": "New owner"}) - assert target.status_code == 201, target.text - target_id = target.json()["id"] - shared = await other_api.post( - "/v1/memberships", - json={"company_id": target_id, "user_id": user["id"], "role": "admin"}, - ) - assert shared.status_code == 201, shared.text - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - owner_path = f"/v1/computer-ownerships/{owner['id']}" - credentials_path = f"/v1/computers/{computer_id}/credentials" - assert (await api.patch(owner_path, json={"company_id": company["id"]})).status_code == 200 - # An administrator who did not perform the handoff can replace a key without - # adopting the computer into their account. - assert (await other_api.post(credentials_path)).status_code == 201 - assert (await other_api.get(PATH)).json()["items"] == [] - - if legacy_stage == "archived_resources": - resources = await api.get(f"/v1/computers/{computer_id}/resources") - assert resources.status_code == 200 and len(resources.json()) == 2, resources.text - for resource in resources.json(): - assert resource["computer_id"] == computer_id - result = await api.delete(f"/v1/computer-resources/{resource['id']}") - assert result.status_code == 204, result.text - moved = await other_api.patch(owner_path, json={"company_id": target_id}) - assert moved.status_code == 200, moved.text - saved_token = None - if legacy_stage.startswith("after_issuance"): - issued = await other_api.post(credentials_path) - assert issued.status_code == 201, issued.text - saved_token = issued.json()["token"] - if legacy_stage == "after_issuance": - # The ledger can keep a timestamp beyond wall time after a correction. - async with app.state.db.write() as database: - await database.execute( - update(AgentCredential) - .where(AgentCredential.computer_id == computer_id) - .values(created_at=clock.now - timedelta(minutes=10)) - ) - if legacy_stage != "archived_resources": - await reapply_connection_migration(settings) - assert (await other_api.get(PATH)).json()["items"] == [] - path = f"{PATH}/{computer_id}/pool" - payload = {"company_id": None, "expected_company_id": target_id} - pending_row = (await api.get(PATH)).json()["items"][0] - assert pending_row["transfer_pending"] and not pending_row["can_move"] - blocked = await api.patch(path, json=payload) - assert ( - blocked.status_code == 409 - and blocked.json()["detail"] == "Computer has an unfinished native transfer" - ) - if saved_token is None or legacy_stage == "after_issuance_retry": - replacement = await other_api.post(credentials_path) - assert replacement.status_code == 201, replacement.text - retried = await other_api.post(credentials_path) - assert retried.status_code == 201, retried.text - saved_token = retried.json()["token"] - unsigned = await client.post( - "/agent/v1/session", - json={"clean_start": True}, - headers={ - "Authorization": "Bearer " + saved_token, - "Idempotency-Key": str(uuid4()), - }, - ) - assert unsigned.status_code == 401, unsigned.text - assert (await other_api.get(PATH)).json()["items"] == [] - assert (await api.get(PATH)).json()["items"][0]["transfer_pending"] - assert (await api.patch(path, json=payload)).status_code == 409 - await start_replacement_session(client, bound_device, saved_token, clock) - if legacy_stage == "before_issuance": - await reapply_connection_migration(settings) - assert (await api.get(PATH)).json()["items"] == [] - current = (await other_api.get(PATH)).json()["items"][0] - assert current["id"] == computer_id and current["online"] and current["can_move"] - assert not current["transfer_pending"] - back = await other_api.patch(path, json=payload) - assert back.status_code == 200, back.text - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("key_confirmed_before_upgrade", [False, True]) -async def test_migration_uses_newer_verified_history_after_return_to_an_old_pool( - api, - other_api, - other_user, - company, - bound_device, - client, - clock, - settings, - key_confirmed_before_upgrade, -): - """Prefer newer signed evidence when the computer returns to an earlier pool.""" - computer_id = bound_device.binding["computer_id"] - membership = await api.post( - "/v1/memberships", - json={ - "company_id": company["id"], - "user_id": other_user["id"], - "role": "admin", - }, - ) - assert membership.status_code == 201, membership.text - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - ownership = f"/v1/computer-ownerships/{owner['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - resources_path = f"/v1/computers/{computer_id}/resources" - - async def archive(http): - before = await http.get(resources_path) - assert before.status_code == 200 and len(before.json()) == 2, before.text - for resource in before.json(): - result = await http.delete(f"/v1/computer-resources/{resource['id']}") - assert result.status_code == 204, result.text - return before.json() - - async def issue(http): - result = await http.post(credentials) - assert result.status_code == 201, result.text - return result.json()["token"] - - pool = {"company_id": company["id"]} - assert (await api.patch(ownership, json=pool)).status_code == 200 - await start_replacement_session( - client, bound_device, await issue(api), clock, publish_capacity=True - ) - clock.now += timedelta(minutes=1) - resources = await archive(api) - assert (await other_api.patch(ownership, json={"user_id": other_user["id"]})).status_code == 200 - for resource in resources: - restored = await other_api.post( - resources_path, - json={ - "resource_type_id": resource["resource_type_id"], - "total": resource["total"], - }, - ) - assert restored.status_code == 201, restored.text - await start_replacement_session( - client, bound_device, await issue(other_api), clock, publish_capacity=True - ) - clock.now += timedelta(minutes=1) - await archive(other_api) - assert (await other_api.patch(ownership, json=pool)).status_code == 200 - key = await issue(other_api) - if key_confirmed_before_upgrade: - await start_replacement_session(client, bound_device, key, clock) - - await reapply_connection_migration(settings) - rebuilt = (await other_api.get(PATH)).json()["items"] - assert [row["id"] for row in rebuilt] == [computer_id] - assert rebuilt[0]["transfer_pending"] is not key_confirmed_before_upgrade - if not key_confirmed_before_upgrade: - await start_replacement_session(client, bound_device, key, clock) - assert (await api.get(PATH)).json()["items"] == [] - assert [row["id"] for row in (await other_api.get(PATH)).json()["items"]] == [computer_id] - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("scenario", ["repeated_pool", "deleted_active", "deleted_before_pending"]) -async def test_migration_preserves_the_latest_signed_pool_account( - client, api, other_api, other_user, company, bound_device, clock, settings, scenario -): - """Identify the last signed actor through repeated visits and account deletion.""" - profile = { - "email": "carol@example.com", - "password": "long test password", - "first_name": "Carol", - "last_name": "Example", - "nickname": "carol", - } - registered = await client.post("/v1/users", json=profile) - assert registered.status_code == 201, registered.text - login = await client.post( - "/v1/auth/login", json={key: profile[key] for key in ("email", "password")} - ) - assert login.status_code == 200, login.text - async with AsyncClient( - base_url=client.base_url, - timeout=10, - trust_env=False, - headers={"Authorization": "Bearer " + login.json()["access_token"]}, - ) as third_api: - second = await other_api.post("/v1/companies", json={"name": "Second pool"}) - final = await api.post("/v1/companies", json={"name": "Final pool"}) - assert second.status_code == final.status_code == 201 - third_user_id = registered.json()["id"] - third_pool_id = company["id"] if scenario == "repeated_pool" else final.json()["id"] - third_memberships = [] - for manager, pool_id, user_id in [ - (api, company["id"], other_user["id"]), - (api, third_pool_id, third_user_id), - (other_api, second.json()["id"], third_user_id), - ]: - granted = await manager.post( - "/v1/memberships", - json={ - "company_id": pool_id, - "user_id": user_id, - "role": "admin", - }, - ) - assert granted.status_code == 201, granted.text - if user_id == third_user_id: - third_memberships.append(granted.json()["id"]) - computer_id = bound_device.binding["computer_id"] - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - ownership = f"/v1/computer-ownerships/{owner['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - for actor, pool_id in [ - (api, company["id"]), - (other_api, second.json()["id"]), - (third_api, third_pool_id), - ]: - moved = await actor.patch(ownership, json={"company_id": pool_id}) - assert moved.status_code == 200, moved.text - issued = await actor.post(credentials) - assert issued.status_code == 201, issued.text - await start_replacement_session( - client, - bound_device, - issued.json()["token"], - clock, - publish_capacity=True, - ) - clock.now += timedelta(seconds=10) - - assert [row["id"] for row in (await third_api.get(PATH)).json()["items"]] == [computer_id] - if scenario != "repeated_pool": - for membership_id in third_memberships: - left = await third_api.delete(f"/v1/memberships/{membership_id}") - assert left.status_code == 204, left.text - deleted = await third_api.delete(f"/v1/users/{third_user_id}") - assert deleted.status_code == 204, deleted.text - if scenario == "deleted_active": - await reapply_connection_migration(settings) - assert (await api.get(PATH)).json()["items"] == [] - assert (await other_api.get(PATH)).json()["items"] == [] - return - - destination = final.json()["id"] if scenario == "repeated_pool" else company["id"] - pending = await api.patch(ownership, json={"company_id": destination}) - assert pending.status_code == 200, pending.text - issued = await api.post(credentials) - assert issued.status_code == 201, issued.text - await reapply_connection_migration(settings) - assert (await api.get(PATH)).json()["items"] == [] - assert (await other_api.get(PATH)).json()["items"] == [] - if scenario == "repeated_pool": - rows = (await third_api.get(PATH)).json()["items"] - assert [row["id"] for row in rows] == [computer_id] - assert rows[0]["transfer_pending"] and not rows[0]["online"] - await start_replacement_session(client, bound_device, issued.json()["token"], clock) - if scenario == "repeated_pool": - assert (await third_api.get(PATH)).json()["items"] == [] - assert [row["id"] for row in (await api.get(PATH)).json()["items"]] == [computer_id] - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("resource_change", ["unchanged", "archived_one", "replaced"]) -async def test_migration_recognizes_a_signed_session_before_capacity_was_published( - api, - other_api, - user, - other_user, - company, - client, - bound_device, - clock, - settings, - resource_change, -): - """Use verified presence when a device entered the pool while paused.""" - other_pool = await other_api.post("/v1/companies", json={"name": "Paused pool"}) - assert other_pool.status_code == 201, other_pool.text - other_pool_id = other_pool.json()["id"] - for manager, pool_id, guest in [ - (api, company["id"], other_user), - (other_api, other_pool_id, user), - ]: - member = await manager.post( - "/v1/memberships", - json={ - "company_id": pool_id, - "user_id": guest["id"], - "role": "admin", - }, - ) - assert member.status_code == 201, member.text - computer_id = bound_device.binding["computer_id"] - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - ownership = f"/v1/computer-ownerships/{owner['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - for manager, pool_id, publish_capacity in [ - (api, company["id"], True), - (other_api, other_pool_id, False), - ]: - moved = await manager.patch(ownership, json={"company_id": pool_id}) - assert moved.status_code == 200, moved.text - key = await manager.post(credentials) - assert key.status_code == 201, key.text - if not publish_capacity and resource_change != "unchanged": - resources_path = f"/v1/computers/{computer_id}/resources" - resources = (await manager.get(resources_path)).json() - assert len(resources) == 2 - first, second = resources - archived = await manager.delete(f"/v1/computer-resources/{first['id']}") - assert archived.status_code == 204, archived.text - if resource_change == "replaced": - restored = await manager.post( - resources_path, - json={ - "resource_type_id": first["resource_type_id"], - "total": first["total"], - }, - ) - assert restored.status_code == 201, restored.text - archived = await manager.delete(f"/v1/computer-resources/{second['id']}") - assert archived.status_code == 204, archived.text - clock.now += timedelta(seconds=10) - await start_replacement_session( - client, - bound_device, - key.json()["token"], - clock, - publish_capacity=publish_capacity, - ) - clock.now += timedelta(seconds=10) - - pending = await api.patch(ownership, json={"company_id": company["id"]}) - assert pending.status_code == 200, pending.text - key = await api.post(credentials) - assert key.status_code == 201, key.text - for upgraded in (False, True): - if upgraded: - await reapply_connection_migration(settings) - assert (await api.get(PATH)).json()["items"] == [] - rows = (await other_api.get(PATH)).json()["items"] - assert [row["id"] for row in rows] == [computer_id] - assert rows[0]["transfer_pending"] and not rows[0]["online"] - await start_replacement_session(client, bound_device, key.json()["token"], clock) - assert (await other_api.get(PATH)).json()["items"] == [] - assert [row["id"] for row in (await api.get(PATH)).json()["items"]] == [computer_id] - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("previously_shared", [False, True]) -async def test_migrated_archive_still_blocks_a_browser_move_until_the_new_key_connects( - api, - other_api, - other_user, - company, - bound_device, - settings, - client, - clock, - previously_shared, -): - """Keep an archived native transfer pending until its replacement key is confirmed.""" - computer_id = bound_device.binding["computer_id"] - target = await api.post("/v1/companies", json={"name": "Next organization"}) - assert target.status_code == 201, target.text - target_id = target.json()["id"] - for company_id in [company["id"], target_id]: - access = await api.post( - "/v1/memberships", - json={ - "company_id": company_id, - "user_id": other_user["id"], - "role": "admin", - }, - ) - assert access.status_code == 201, access.text - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - ownership = f"/v1/computer-ownerships/{owner['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - assert (await api.patch(ownership, json={"company_id": company["id"]})).status_code == 200 - issued = await api.post(credentials) - assert issued.status_code == 201, issued.text - if previously_shared: - await start_replacement_session( - client, bound_device, issued.json()["token"], clock, publish_capacity=True - ) - resources = await api.get(f"/v1/computers/{computer_id}/resources") - assert resources.status_code == 200 and resources.json(), resources.text - for resource in resources.json(): - archived = await api.delete(f"/v1/computer-resources/{resource['id']}") - assert archived.status_code == 204, archived.text - moved = await other_api.patch(ownership, json={"company_id": target_id}) - assert moved.status_code == 200, moved.text - replacement = await other_api.post(credentials) - assert replacement.status_code == 201, replacement.text - await reapply_connection_migration(settings) - pending = (await api.get(PATH)).json()["items"][0] - assert pending["transfer_pending"] and not pending["can_move"] - move_path = f"{PATH}/{computer_id}/pool" - payload = {"company_id": None, "expected_company_id": target_id} - blocked = await api.patch(move_path, json=payload) - assert blocked.status_code == 409, blocked.text - token = replacement.json()["token"] - if previously_shared: - await start_replacement_session(client, bound_device, token, clock) - else: - path = "/agent/v1/connection/confirm" - content = json.dumps({"computer_id": computer_id}).encode() - signed = await client.post( - path, - content=content, - headers=proof_headers( - bound_device.identity.key, - bound_device.identity.certificate, - "POST", - path, - content, - { - "Authorization": "Bearer " + token, - "Content-Type": "application/json", - }, - clock.now, - ), - ) - assert signed.status_code == 204, signed.text - verified = (await api.get(PATH)).json()["items"][0] - assert not verified["transfer_pending"] - assert verified["online"] == previously_shared - assert (await api.patch(move_path, json=payload)).status_code == 200 - - -@pytest.mark.parametrize("same_account", [False, True]) -async def test_saved_key_can_be_checked_by_legacy_transfer_account_without_exposing_inventory( - api, - other_api, - user, - other_user, - company, - bound_device, - client, - clock, - same_account, - access_token, -): - """Verify and recover the signed key with narrow resource management access.""" - computer_id = bound_device.binding["computer_id"] - original = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - ownership = f"/v1/computer-ownerships/{original['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - recovery = f"{PATH}/{computer_id}/recovery" - login, manager, account = ( - (api, other_api, user) if same_account else (other_api, api, other_user) - ) - if not same_account: - joined = await api.post( - "/v1/memberships", - json={ - "company_id": company["id"], - "user_id": other_user["id"], - "role": "admin", - }, - ) - assert joined.status_code == 201, joined.text - assert (await api.patch(ownership, json={"company_id": company["id"]})).status_code == 200 - source_key = await api.post(credentials) - assert source_key.status_code == 201, source_key.text - await start_replacement_session(client, bound_device, source_key.json()["token"], clock) - - target = await manager.post("/v1/companies", json={"name": "Manage-only target"}) - assert target.status_code == 201, target.text - target_id = target.json()["id"] - membership_data = { - "company_id": target_id, - "user_id": account["id"], - "role": "user", - "permissions": ["resources.manage"], - } - membership = await manager.post("/v1/memberships", json=membership_data) - assert membership.status_code == 201, membership.text - move = await login.patch(ownership, json={"company_id": target_id}) - assert move.status_code == 200, move.text - repeated = await manager.patch(ownership, json={"company_id": target_id}) - assert repeated.status_code == 200, repeated.text - issued = await login.post(credentials) - assert issued.status_code == 201, issued.text - key = issued.json()["token"] - assert all( - row["computer_id"] != computer_id - for row in (await login.get("/v1/computer-ownerships")).json() - ) - inventory = (await login.get(PATH)).json()["items"] - if same_account: - assert inventory[0]["transfer_pending"] and not inventory[0]["can_move"] - assert (await manager.get(recovery)).json() is False - else: - assert inventory == [] - assert (await login.get(recovery)).json() is True - revision = (await login.get(recovery, params={"snapshot": "true"})).json()["revision"] - assert revision > move.json()["revision"] - - removed = await manager.delete(f"/v1/memberships/{membership.json()['id']}") - assert removed.status_code == 204, removed.text - assert (await login.get(recovery)).json() is False - assert (await login.get(recovery, params={"snapshot": "true"})).json() == {"revision": None} - assert (await manager.post("/v1/memberships", json=membership_data)).status_code == 201 - - session_path = "/agent/v1/session?include_pool=true" - checked = await client.get( - session_path, - headers=proof_headers( - bound_device.identity.key, - bound_device.identity.certificate, - "GET", - session_path, - b"", - {"Authorization": "Bearer " + key}, - clock.now, - ), - ) - assert checked.status_code == 200, checked.text - assert checked.json()["session_id"] is None and checked.json()["transfer_pending"] - assert "pool_owner" not in checked.json() - intent = { - "expected_user_id": account["id"], - "expected_company_id": target_id, - "expected_revision": revision, - } - wrong_account = await manager.post(recovery, json=intent) - assert wrong_account.status_code == 403, wrong_account.text - if same_account: - from_token = await client.post( - recovery, json=intent, headers={"Authorization": "Bearer " + access_token["token"]} - ) - assert from_token.status_code == 403, from_token.text - assert from_token.json()["detail"] == "The account must sign in to recover a transfer" - stale_intent = await login.post(recovery, json={**intent, "expected_company_id": None}) - assert stale_intent.status_code == 409, stale_intent.text - replacement = await login.post(recovery, json=intent) - assert replacement.status_code == 201, replacement.text - recovered_key = replacement.json()["token"] - assert recovered_key != key - confirmed_owner = replacement.json()["ownership"] - assert ( - confirmed_owner["computer_id"] == computer_id and confirmed_owner["company_id"] == target_id - ) - assert confirmed_owner["revision"] > revision - duplicate = await login.post(recovery, json=intent) - assert duplicate.status_code == 409 and duplicate.json()["code"] == "computer_pool_changed" - - confirm_path = "/agent/v1/connection/confirm" - - async def confirm(token, target_computer=computer_id, *, signed=True): - body = json.dumps({"computer_id": target_computer}).encode() - headers = { - "Authorization": "Bearer " + token, - "Content-Type": "application/json", - } - if signed: - headers = proof_headers( - bound_device.identity.key, - bound_device.identity.certificate, - "POST", - confirm_path, - body, - headers, - clock.now, - ) - return await client.post(confirm_path, content=body, headers=headers) - - assert (await confirm(recovered_key, signed=False)).status_code == 401 - assert (await confirm(recovered_key, str(uuid4()))).status_code == 404 - assert (await confirm(key)).status_code == 401 - personal_pool = {"company_id": None, "expected_company_id": target_id} - blocked = await login.patch(f"{PATH}/{computer_id}/pool", json=personal_pool) - assert blocked.status_code == (409 if same_account else 404), blocked.text - if same_account: - assert blocked.json()["detail"] == "Computer has an unfinished native transfer" - assert (await confirm(recovered_key)).status_code == 204 - assert (await confirm(recovered_key)).status_code == 204 - checked = await client.get( - session_path, - headers=proof_headers( - bound_device.identity.key, - bound_device.identity.certificate, - "GET", - session_path, - b"", - {"Authorization": "Bearer " + recovered_key}, - clock.now, - ), - ) - assert checked.status_code == 200, checked.text - assert checked.json()["session_id"] is None - assert not checked.json()["transfer_pending"] and not checked.json()["active"] - assert checked.json()["pool_owner"] == {"user_id": None, "company_id": target_id} - current = (await login.get(PATH)).json()["items"][0] - assert ( - current["id"] == computer_id - and current["can_move"] - and not current["transfer_pending"] - and not current["online"] - ) - assert (await manager.get(recovery)).json() is False - assert (await login.post(recovery, json=intent)).status_code == 404 - moved = await login.patch(f"{PATH}/{computer_id}/pool", json=personal_pool) - assert moved.status_code == 200, moved.text - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -async def test_web_move_waits_for_same_account_native_recovery( - api, client, company, bound_device, settings, clock -): - """Serialize a browser move with recovery of an interrupted transfer by the same account.""" - computer_id = bound_device.binding["computer_id"] - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - legacy_path = f"/v1/computer-ownerships/{owner['id']}" - credentials = f"/v1/computers/{computer_id}/credentials" - assert (await api.patch(legacy_path, json={"company_id": company["id"]})).status_code == 200 - # The server issued a key, but the old app may still be recovering a lost reply. - assert (await api.post(credentials)).status_code == 201 - path = f"{PATH}/{computer_id}/pool" - payload = {"company_id": None, "expected_company_id": company["id"]} - assert (await api.patch(path, json=payload)).status_code == 409 - await reapply_connection_migration(settings) - row = (await api.get(PATH)).json()["items"][0] - assert row["transfer_pending"] and not row["can_move"] - assert (await api.patch(path, json=payload)).status_code == 409 - retried = await api.post(credentials) - assert retried.status_code == 201, retried.text - await start_replacement_session(client, bound_device, retried.json()["token"], clock) - assert (await api.patch(path, json=payload)).status_code == 200 - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize( - ("detach_route", "action_after_detach"), - [ - ("unbind", "reattach_only"), - ("delete_owner", "reattach_only"), - ("delete_owner", "issue_key"), - ("delete_owner", "change_owner"), - ], -) -async def test_detach_removes_connection_even_if_an_owner_is_added_again( - api, - user, - connected_worker, - settings, - detach_route, - action_after_detach, - client, - access_token, - company, - clock, -): - """Keep a detached device out of the account inventory after owner recreation and upgrade.""" - session, _ = connected_worker - computer_id = session["computer_id"] - assert (await api.get(PATH)).json()["total"] == 1 - clock.now += timedelta(seconds=1) - if detach_route == "unbind": - detached = await api.post( - f"/v1/computers/{computer_id}/unbind", - json={"cleanup_confirmed": True}, - headers={"Idempotency-Key": str(uuid4())}, - ) - assert detached.status_code == 200, detached.text - else: - owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - detached = await api.delete(f"/v1/computer-ownerships/{owner['id']}") - assert detached.status_code == 204, detached.text - reattached = await api.post( - "/v1/computer-ownerships", - json={"computer_id": computer_id, "user_id": user["id"]}, - ) - assert reattached.status_code == 201, reattached.text - token_headers = {"Authorization": "Bearer " + access_token["token"]} - if action_after_detach == "issue_key": - reissued = await client.post( - f"/v1/computers/{computer_id}/credentials", - headers=token_headers, - ) - assert reissued.status_code == 201, reissued.text - if action_after_detach == "change_owner": - changed = await client.patch( - f"/v1/computer-ownerships/{reattached.json()['id']}", - json={"company_id": company["id"]}, - headers=token_headers, - ) - assert changed.status_code == 200, changed.text - assert (await api.get(PATH)).json()["items"] == [] - await reapply_connection_migration(settings) - assert (await api.get(PATH)).json()["items"] == [] - move = await api.patch( - f"{PATH}/{computer_id}/pool", - json={"company_id": None, "expected_company_id": None}, - ) - assert move.status_code == 404 - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -@pytest.mark.parametrize("confirmed", [False, True]) -async def test_migration_preserves_a_post_detach_handoff_when_the_clock_moves_back( - api, user, company, bound_device, connected_worker, settings, client, clock, confirmed -): - """Preserve post-detach signed sessions and recoverable handoffs across a clock correction.""" - session, _ = connected_worker - computer_id = session["computer_id"] - old_owner = next( - row - for row in (await api.get("/v1/computer-ownerships")).json() - if row["computer_id"] == computer_id - ) - clock.now += timedelta(seconds=15) - detached = await api.delete(f"/v1/computer-ownerships/{old_owner['id']}") - assert detached.status_code == 204, detached.text - reattached = await api.post( - "/v1/computer-ownerships", json={"computer_id": computer_id, "user_id": user["id"]} - ) - assert reattached.status_code == 201, reattached.text - handed_off = await api.patch( - f"/v1/computer-ownerships/{reattached.json()['id']}", json={"company_id": company["id"]} - ) - assert handed_off.status_code == 200, handed_off.text - issued = await api.post(f"/v1/computers/{computer_id}/credentials") - assert issued.status_code == 201, issued.text - token = issued.json()["token"] - if confirmed: - clock.now -= timedelta(seconds=5) - current = await start_replacement_session(client, bound_device, token, clock) - assert current["session_id"] != session["session_id"] - - before = (await api.get(PATH)).json() - assert before["total"] == before["online"] == int(confirmed) - await reapply_connection_migration(settings) - after = (await api.get(PATH)).json() - assert after["total"] == after["online"] == int(confirmed) - if not confirmed: - await start_replacement_session(client, bound_device, token, clock) - connected = (await api.get(PATH)).json() - assert connected["total"] == connected["online"] == 1 - assert connected["items"][0]["id"] == computer_id - assert connected["items"][0]["pool"]["company_id"] == company["id"] - - async def test_move_preserves_signed_session_and_transfers_capacity( api, other_api, connected_worker, company, user, clock, app ): @@ -1491,6 +557,7 @@ async def test_move_preserves_signed_session_and_transfers_capacity( session, agent_post = connected_worker computer_id = session["computer_id"] path = f"{PATH}/{computer_id}/pool" + assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200 before = clock.now async with app.state.db.write() as database: baseline = await database.get(AvailabilityBaseline, 1) @@ -1542,6 +609,7 @@ async def test_move_respects_live_permissions_and_busy_worker( """Revalidate source and destination roles and the current resource reservations.""" session, agent_post = connected_worker path = f"{PATH}/{session['computer_id']}/pool" + assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200 created = await other_api.post("/v1/companies", json={"name": "Read-only pool"}) other_company = created.json() joined = await other_api.post( @@ -1598,6 +666,8 @@ async def test_stale_native_mutation_cannot_revoke_key_or_overwrite_a_browser_mo """Use ownership revisions to protect a committed browser transfer from stale native writes.""" live, _ = connected_worker computer_id = live["computer_id"] + path = f"{PATH}/{computer_id}/pool" + assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200 owner = next( row for row in (await api.get("/v1/computer-ownerships")).json() @@ -1652,6 +722,7 @@ async def test_delayed_browser_move_cannot_reapply_after_the_computer_returned_t agent, _ = connected_worker id_ = agent["computer_id"] path = f"{PATH}/{id_}/pool" + assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200 initial = (await api.get(PATH, params={"computer_id": id_})).json()["items"][0] next_pool = {"company_id": company["id"], "expected_company_id": None} assert ( diff --git a/tests/platform/api/e2e/powercell/test_device_registration.py b/tests/platform/api/e2e/powercell/test_device_registration.py new file mode 100644 index 00000000..a182f0d9 --- /dev/null +++ b/tests/platform/api/e2e/powercell/test_device_registration.py @@ -0,0 +1,271 @@ +"""Client-generated device identity replaces hardware attestation. + +These tests pin the externally visible contract after the attestation cut: +login records a device, enrollment is a plain idempotent registration, the +computer starts without a pool, and agents authenticate with their credential +only. They deliberately avoid the old ACME/profile/proof fixtures so a +regression cannot hide behind compatibility helpers. +""" + +from uuid import uuid4 + +import pytest +from httpx import AsyncClient + +pytestmark = pytest.mark.anyio + + +def registration(device_id, **overrides): + """Return the minimal valid Power Cell registration payload.""" + return { + "device_id": str(device_id), + "name": "My Mac", + "cpu_millis": 2000, + "memory_bytes": 2048, + "disk_bytes": 8192, + "isolation_modes": ["vm", "shared"], + **overrides, + } + + +async def login_with_device(client, user, device_id): + """Sign in again with the same password, now identifying this installation.""" + response = await client.post( + "/v1/auth/login", + json={ + "email": user["email"], + "password": user["password"], + "device_id": str(device_id), + }, + ) + assert response.status_code == 200, response.text + return {"Authorization": "Bearer " + response.json()["access_token"]} + + +async def register(api, device_id, key=None, **overrides): + """Create and finish one enrollment, returning the binding and exact retry key.""" + key = key or str(uuid4()) + response = await api.post( + "/v1/agent-enrollments", + headers={"Idempotency-Key": key}, + json=registration(device_id, **overrides), + ) + assert response.status_code == 201, response.text + enrollment = response.json() + assert enrollment["status"] == "verified" + assert "certificate_sha256" not in enrollment + assert "relay" not in enrollment + response = await api.post( + f"/v1/agent-enrollments/{enrollment['id']}/finish", + headers={"Idempotency-Key": "finish-" + enrollment["id"]}, + json={}, + ) + assert response.status_code == 200, response.text + return enrollment, response.json(), key + + +async def start_agent(client, binding): + """Open a normal agent session using only the issued bearer credential.""" + headers = {"Authorization": "Bearer " + binding["credential"]} + response = await client.post( + "/agent/v1/session", + headers={**headers, "Idempotency-Key": str(uuid4())}, + json={"clean_start": True}, + ) + assert response.status_code == 200, response.text + session = response.json() + return {**headers, "X-Agent-Session": session["session_id"]}, session + + +async def test_login_registers_device_and_enrollment_needs_no_attestation(client, api, user): + """A device id supplied at login authorizes a plain, immediately verified registration.""" + device_id = uuid4() + headers = await login_with_device(client, user, device_id) + async with AsyncClient( + base_url=str(client.base_url), headers=headers, timeout=10, trust_env=False + ) as device_api: + enrollment, binding, _ = await register(device_api, device_id) + assert binding["device_id"] + assert "certificate_sha256" not in binding + assert "relay" not in binding + assert binding["computer_id"] + + response = await api.get(f"/v1/agent-enrollments/{enrollment['id']}") + assert response.status_code == 200 + assert response.json()["status"] == "verified" + for retired in ("profile", "verification"): + response = await api.get(f"/v1/agent-enrollments/{enrollment['id']}/{retired}") + assert response.status_code in {404, 405} + + +async def test_enrollment_requires_the_device_to_have_signed_in(client, api, user): + """A caller cannot register an arbitrary UUID that never authenticated.""" + device_id = uuid4() + response = await api.post( + "/v1/agent-enrollments", + headers={"Idempotency-Key": str(uuid4())}, + json=registration(device_id), + ) + assert response.status_code == 409 + assert "sign in" in response.json()["detail"].lower() + + +async def test_registration_is_unassigned_until_a_pool_is_explicitly_chosen( + client, api, user, company +): + """A new computer is visible to its account with no owner and can be assigned later.""" + device_id = uuid4() + headers = await login_with_device(client, user, device_id) + async with AsyncClient( + base_url=str(client.base_url), headers=headers, timeout=10, trust_env=False + ) as device_api: + _, binding, _ = await register(device_api, device_id) + computer_id = binding["computer_id"] + + response = await api.get("/v1/connected-computers") + assert response.status_code == 200, response.text + row = next(item for item in response.json()["items"] if item["id"] == computer_id) + assert row["pool"] is None + assert row["can_move"] is True + + response = await api.patch( + f"/v1/connected-computers/{computer_id}/pool", + headers={"Idempotency-Key": str(uuid4())}, + json={"company_id": company["id"], "expected_company_id": None}, + ) + assert response.status_code == 200, response.text + assert response.json()["company_id"] == company["id"] + + response = await api.get("/v1/connected-computers") + row = next(item for item in response.json()["items"] if item["id"] == computer_id) + assert row["pool"]["company_id"] == company["id"] + + +async def test_finish_is_idempotent_and_agent_uses_only_its_credential(client, api, user): + """The stored finish key recovers the same credential; unsigned agent requests work.""" + device_id = uuid4() + headers = await login_with_device(client, user, device_id) + async with AsyncClient( + base_url=str(client.base_url), headers=headers, timeout=10, trust_env=False + ) as device_api: + enrollment, binding, _ = await register(device_api, device_id) + retry = await device_api.post( + f"/v1/agent-enrollments/{enrollment['id']}/finish", + headers={"Idempotency-Key": "finish-" + enrollment["id"]}, + json={}, + ) + assert retry.status_code == 200 + assert retry.json() == binding + different = await device_api.post( + f"/v1/agent-enrollments/{enrollment['id']}/finish", + headers={"Idempotency-Key": str(uuid4())}, + json={}, + ) + assert different.status_code == 409 + + agent_headers, session = await start_agent(client, binding) + response = await client.post("/agent/v1/heartbeat", headers=agent_headers) + assert response.status_code == 200, response.text + assert response.json()["computer_id"] == binding["computer_id"] + assert response.json()["session_id"] == session["session_id"] + + response = await client.post("/agent/v1/heartbeat") + assert response.status_code == 401 + + +async def test_unassigned_computer_receives_no_work_until_pool_assignment( + client, api, user, artifact +): + """The device is the routing unit only after an explicit pool binding.""" + device_id = uuid4() + headers = await login_with_device(client, user, device_id) + async with AsyncClient( + base_url=str(client.base_url), headers=headers, timeout=10, trust_env=False + ) as device_api: + _, binding, _ = await register(device_api, device_id) + agent_headers, _ = await start_agent(client, binding) + response = await client.post( + "/agent/v1/capacity", + headers={**agent_headers, "Idempotency-Key": str(uuid4())}, + json={ + "revision": 0, + "accepting_work": True, + "mode": "idle", + "cpu_millis": 2000, + "memory_bytes": 2048, + "disk_bytes": 8192, + "running_commands": 0, + "cpu_used_millis": 0, + "memory_used_bytes": 0, + }, + ) + assert response.status_code == 200, response.text + response = await api.post( + "/v1/isolates", + headers={"Idempotency-Key": str(uuid4())}, + json={ + "state_artifact_id": artifact["id"], + "image": "ubuntu:24.04", + "os": "linux", + "architecture": "arm64", + "runtime": "powercell-ubuntu-arm64-v1", + "cpu_millis": 1000, + "memory_bytes": 1024, + "disk_bytes": 4096, + }, + ) + assert response.status_code == 202, response.text + response = await client.post( + "/agent/v1/tasks/claim", headers=agent_headers, json={"wait_seconds": 1} + ) + assert response.status_code == 200, response.text + assert response.json()["tasks"] == [] + + assigned = await api.patch( + f"/v1/connected-computers/{binding['computer_id']}/pool", + headers={"Idempotency-Key": str(uuid4())}, + json={"company_id": None, "expected_company_id": None}, + ) + assert assigned.status_code == 200, assigned.text + response = await client.post( + "/agent/v1/tasks/claim", headers=agent_headers, json={"wait_seconds": 2} + ) + assert response.status_code == 200, response.text + assert [task["kind"] for task in response.json()["tasks"]] == ["create"] + + +async def test_restarting_a_registration_replaces_the_unfinished_attempt(client, api, user): + """A new explicit attempt must not be blocked by an earlier pending row.""" + device_id = uuid4() + headers = await login_with_device(client, user, device_id) + async with AsyncClient( + base_url=str(client.base_url), headers=headers, timeout=10, trust_env=False + ) as device_api: + first = await device_api.post( + "/v1/agent-enrollments", + headers={"Idempotency-Key": "first"}, + json=registration(device_id, name="First"), + ) + assert first.status_code == 201, first.text + second = await device_api.post( + "/v1/agent-enrollments", + headers={"Idempotency-Key": "second"}, + json=registration(device_id, name="Second"), + ) + assert second.status_code == 201, second.text + assert second.json()["id"] != first.json()["id"] + response = await device_api.post( + f"/v1/agent-enrollments/{second.json()['id']}/finish", + headers={"Idempotency-Key": "finish-second"}, + json={}, + ) + assert response.status_code == 200, response.text + + +async def test_capabilities_advertise_client_device_identity_without_attestation(client): + """Clients can distinguish the simplified server before sending a registration.""" + response = await client.get("/v1/agent-capabilities") + assert response.status_code == 200 + body = response.json() + assert "powercell.device.v1" in body["extensions"] + assert "attestation_required" not in body diff --git a/tests/platform/api/e2e/powercell/test_enrollment.py b/tests/platform/api/e2e/powercell/test_enrollment.py deleted file mode 100644 index ddc2281d..00000000 --- a/tests/platform/api/e2e/powercell/test_enrollment.py +++ /dev/null @@ -1,436 +0,0 @@ -"""ACME enrollment interoperability and attacks against device-bound credentials.""" - -import asyncio -import json -from datetime import timedelta -from uuid import uuid4 - -import pytest -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec - -from .conftest import attestation, b64, jws, proof_headers - -pytestmark = pytest.mark.anyio - - -async def test_expired_unfinished_enrollment_reports_expired(api, enrollment, clock): - """A client recovering after a long outage sees expiry instead of a resumable enrollment.""" - from datetime import timedelta - - clock.now += timedelta(seconds=3601) - response = await api.get(f"/v1/agent-enrollments/{enrollment.row['id']}") - assert response.status_code == 200 and response.json()["status"] == "expired" - - -async def test_profile_capabilities_and_enrollment_ownership( - client, api, other_api, enrollment, clock -): - """The authorized profile contains only a nonextractable attested identity and cannot be read by another account.""" - response = await client.get("/v1/agent-capabilities") - assert set(response.json()["extensions"]) == { - "powercell.enrollment.v1", - "powercell.capacity.v1", - "powercell.eviction.v1", - "powercell.diagnostics.v1", - "powercell.isolation.v1", - "powercell.images.v1", - "powercell.recovery.v1", - } - assert response.json()["attestation_required"] - profile = enrollment.profile - assert profile["PayloadType"] == "Configuration" and len(profile["PayloadContent"]) == 1 - assert profile["PayloadScope"] == "User" - acme = profile["PayloadContent"][0] - assert ( - acme["PayloadType"] == "com.apple.security.acme" - and acme["Attest"] - and acme["HardwareBound"] - ) - assert not acme["KeyIsExtractable"] and not acme["AllowAllAppsAccess"] - assert acme["KeyType"] == "ECSECPrimeRandom" and acme["KeySize"] == 256 - for suffix in ["", "/profile"]: - response = await other_api.get(f"/v1/agent-enrollments/{enrollment.row['id']}" + suffix) - assert response.status_code == 404 - response = await api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": enrollment.key}, - json=enrollment.payload, - ) - assert response.status_code == 201 and response.json() == enrollment.row - response = await api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": enrollment.key}, - json={**enrollment.payload, "name": "different"}, - ) - assert response.status_code == 409 - clock.now += timedelta(hours=2) - assert (await api.get(f"/v1/agent-enrollments/{enrollment.row['id']}")).json()[ - "status" - ] == "expired" - assert ( - await api.get(f"/v1/agent-enrollments/{enrollment.row['id']}/profile") - ).status_code == 409 - assert (await client.get(enrollment.path + "/directory")).status_code == 401 - - -async def test_attested_finish_requires_key_and_retries_recover_same_credential( - api, other_api, user, bound_device, clock -): - """Even verified enrollment needs its private key, and exact signed retries recover only the original binding.""" - device = bound_device - identity = device.identity - response = await api.post(device.target, headers=device.headers, content=b"{}") - assert response.status_code == 401 - headers = proof_headers( - identity.key, identity.certificate, "POST", device.target, b"{}", device.headers, clock.now - ) - response = await api.post(device.target, headers=headers, content=b"{}") - assert response.status_code == 200 and response.json() == device.binding - response = await api.post(device.target, headers=headers, content=b"{}") - assert response.status_code == 401 - different = {**device.headers, "Idempotency-Key": str(uuid4())} - response = await api.post( - device.target, - headers=proof_headers( - identity.key, identity.certificate, "POST", device.target, b"{}", different, clock.now - ), - content=b"{}", - ) - assert response.status_code == 409 - response = await other_api.post( - device.target, headers={"Idempotency-Key": str(uuid4())}, content=b"{}" - ) - assert response.status_code == 404 - response = await api.get(device.target.removesuffix("/finish") + "/profile") - assert response.status_code == 409 - - -async def test_signed_session_capacity_and_revoked_unbind_retry(client, bound_device, clock): - """Copied credentials cannot start sessions; signed logout retries remain possible after revocation.""" - device = bound_device - identity = device.identity - headers = { - "Authorization": "Bearer " + device.binding["credential"], - "Content-Type": "application/json", - "Idempotency-Key": str(uuid4()), - } - target = "/agent/v1/session" - body = b'{"clean_start":true}' - response = await client.post(target, headers=headers, content=body) - assert response.status_code == 401 - signed = proof_headers( - identity.key, identity.certificate, "POST", target, body, headers, clock.now - ) - responses = await asyncio.gather( - *(client.post(target, headers=signed, content=body) for _ in range(2)) - ) - assert sorted(r.status_code for r in responses) == [200, 401], [r.text for r in responses] - session = next(r.json() for r in responses if r.status_code == 200) - headers["X-Agent-Session"] = session["session_id"] - target = "/agent/v1/capacity" - body = json.dumps( - { - "revision": 0, - "accepting_work": True, - "mode": "idle", - "cpu_millis": 2000, - "memory_bytes": 2048, - "disk_bytes": 8192, - "running_commands": 0, - "cpu_used_millis": 0, - "memory_used_bytes": 0, - } - ).encode() - response = await client.post( - target, - headers=proof_headers( - identity.key, identity.certificate, "POST", target, body, headers, clock.now - ), - content=body, - ) - assert response.status_code == 200, response.text - target = "/agent/v1/unbind" - body = b'{"cleanup_confirmed":true}' - for _ in range(2): - response = await client.post( - target, - headers=proof_headers( - identity.key, identity.certificate, "POST", target, body, headers, clock.now - ), - content=body, - ) - assert response.status_code == 200, response.text - response = await client.post(target, headers=headers, content=body) - assert response.status_code == 401 - response = await client.get( - "/agent/v1/session", - headers=proof_headers( - identity.key, identity.certificate, "GET", "/agent/v1/session", b"", headers, clock.now - ), - ) - assert response.status_code == 401 - - -@pytest.mark.parametrize( - "patch", - [ - {"version": True}, - {"version": 2}, - {"timestamp": 0}, - {"timestamp": True}, - {"nonce": "invalid"}, - {"certificate_sha256": "0" * 64}, - {"method": "POST"}, - {"target": "/agent/v1/heartbeat"}, - {"body_sha256": "0" * 64}, - {"authorization_sha256": "0" * 64}, - {"session": str(uuid4())}, - {"idempotency_key": "different"}, - {"extra": True}, - ], -) -async def test_request_proof_rejects_context_substitution(client, bound_device, clock, patch): - """Every signed context field and timestamp is validated against the actual HTTP request.""" - identity = bound_device.identity - target = "/agent/v1/session" - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - signed = proof_headers( - identity.key, identity.certificate, "GET", target, b"", headers, clock.now, patch=patch - ) - response = await client.get(target, headers=signed) - assert response.status_code == 401, response.text - - -@pytest.mark.parametrize( - "mutation", ["wrong_nonce", "untrusted_root", "wrong_key", "malformed", "missing_identity"] -) -async def test_attestation_and_csr_cannot_substitute_device( - client, api, acme_order, pki, clock, mutation -): - """Only a fresh trusted device chain followed by a matching CSR can become verified.""" - order = acme_order - e = order.enrollment - key = ec.generate_private_key(ec.SECP256R1()) - kwargs = {} - if mutation == "wrong_nonce": - kwargs["nonce"] = b"0" * 32 - if mutation == "missing_identity": - kwargs["extensions"] = [] - if mutation == "untrusted_root": - pki.intermediate_key = ec.generate_private_key(ec.SECP256R1()) - statement = attestation(pki, key, order.token, clock.now, **kwargs) - if mutation == "malformed": - statement = b64(b"not CBOR") - response = await client.post( - e.path + "/challenge", - json=jws( - order.key, e.base + "/challenge", order.nonce, {"attObj": statement}, kid=order.account - ), - ) - if mutation == "wrong_key": - assert response.status_code == 200 - other_key = ec.generate_private_key(ec.SECP256R1()) - csr = ( - x509.CertificateSigningRequestBuilder() - .subject_name(x509.Name([])) - .sign(other_key, hashes.SHA256()) - ) - response = await client.post( - e.path + "/finalize", - json=jws( - order.key, - e.base + "/finalize", - response.headers["Replay-Nonce"], - {"csr": b64(csr.public_bytes(serialization.Encoding.DER))}, - kid=order.account, - ), - ) - assert response.status_code == 400, response.text - response = await api.get(f"/v1/agent-enrollments/{e.row['id']}") - assert response.json()["status"] == "pending_attestation" - - -async def test_acme_nonces_signatures_and_identifiers_are_bound(client, acme_order): - """ACME rejects nonce replay, unsigned requests, altered targets and unrelated identifiers.""" - order = acme_order - e = order.enrollment - payload = jws(order.key, e.base + "/order", order.nonce, None, kid=order.account) - response = await client.post(e.path + "/order", json=payload) - assert response.status_code == 200 - response = await client.post(e.path + "/order", json=payload) - assert response.status_code == 400 and response.json()["type"].endswith(":badNonce") - nonce = response.headers["Replay-Nonce"] - payload = jws(order.key, e.base + "/order", nonce, None, kid=order.account) - response = await client.post(e.path + "/authorization", json=payload) - assert response.status_code == 401 - payload = jws(order.key, e.base + "/order", nonce, None, kid=order.account) - payload["signature"] = b64(b"0" * 64) - response = await client.post(e.path + "/order", json=payload) - assert response.status_code == 401 - response = await client.post( - e.path + "/new-order", - json=jws( - order.key, - e.base + "/new-order", - nonce, - {"identifiers": [{"type": "dns", "value": "example.org"}]}, - kid=order.account, - ), - ) - assert response.status_code == 400 - response = await client.post(e.path + "/order", json={}) - assert response.status_code == 401 - - -async def test_proof_query_and_signature_are_checked(client, bound_device, clock): - """Proofs cover the encoded query and reject a signature from another key.""" - identity = bound_device.identity - target = "/agent/v1/session?original=%2F" - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - signed = proof_headers( - identity.key, identity.certificate, "GET", target, b"", headers, clock.now - ) - assert (await client.get(target, headers=signed)).status_code == 200 - signed = proof_headers( - identity.key, identity.certificate, "GET", target, b"", headers, clock.now - ) - assert (await client.get("/agent/v1/session?original=/", headers=signed)).status_code == 401 - signed = proof_headers( - ec.generate_private_key(ec.SECP256R1()), - identity.certificate, - "GET", - target, - b"", - headers, - clock.now, - ) - assert (await client.get(target, headers=signed)).status_code == 401 - signed["X-PowerCell-Proof"] = "!" - assert (await client.get(target, headers=signed)).status_code == 401 - - -async def test_reinstallation_and_another_account_share_one_physical_identity( - client, other_api, other_user, bound_device, pki, clock -): - """Another installation/account receives independent credentials while the Apple-certified device ID remains stable.""" - response = await other_api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": str(uuid4())}, - json={**bound_device.identity.order.enrollment.payload, "installation_id": str(uuid4())}, - ) - assert response.status_code == 201 - enrollment = response.json() - response = await other_api.get(f"/v1/agent-enrollments/{enrollment['id']}/profile") - import plistlib - from urllib.parse import urlsplit - - base = plistlib.loads(response.content)["PayloadContent"][0]["DirectoryURL"].rsplit("/", 1)[0] - endpoint = urlsplit(base).path - account_key = ec.generate_private_key(ec.SECP256R1()) - device_key = ec.generate_private_key(ec.SECP256R1()) - response = await client.head(endpoint + "/nonce") - response = await client.post( - endpoint + "/new-account", - json=jws(account_key, base + "/new-account", response.headers["Replay-Nonce"], {}), - ) - assert response.status_code == 201 - account = response.headers["Location"] - response = await client.post( - endpoint + "/new-order", - json=jws( - account_key, - base + "/new-order", - response.headers["Replay-Nonce"], - {"identifiers": [{"type": "permanent-identifier", "value": enrollment["id"]}]}, - kid=account, - ), - ) - assert response.status_code == 201 - response = await client.post( - endpoint + "/authorization", - json=jws( - account_key, - base + "/authorization", - response.headers["Replay-Nonce"], - None, - kid=account, - ), - ) - token = response.json()["challenges"][0]["token"] - response = await client.post( - endpoint + "/challenge", - json=jws( - account_key, - base + "/challenge", - response.headers["Replay-Nonce"], - {"attObj": attestation(pki, device_key, token, clock.now)}, - kid=account, - ), - ) - assert response.status_code == 200 - csr = ( - x509.CertificateSigningRequestBuilder() - .subject_name(x509.Name([])) - .sign(device_key, hashes.SHA256()) - ) - response = await client.post( - endpoint + "/finalize", - json=jws( - account_key, - base + "/finalize", - response.headers["Replay-Nonce"], - {"csr": b64(csr.public_bytes(serialization.Encoding.DER))}, - kid=account, - ), - ) - assert response.status_code == 200 - response = await client.post( - endpoint + "/certificate", - json=jws( - account_key, base + "/certificate", response.headers["Replay-Nonce"], None, kid=account - ), - ) - certificate = x509.load_pem_x509_certificate(response.content) - target = f"/v1/agent-enrollments/{enrollment['id']}/finish" - headers = {**other_user["headers"], "Idempotency-Key": str(uuid4())} - response = await other_api.post( - target, - headers=proof_headers(device_key, certificate, "POST", target, b"{}", headers, clock.now), - content=b"{}", - ) - assert response.status_code == 200, response.text - assert response.json()["device_id"] == bound_device.binding["device_id"] - assert response.json()["computer_id"] != bound_device.binding["computer_id"] - assert response.json()["credential"] != bound_device.binding["credential"] - # Deleting either binding cannot delete the shared physical billing identity. - binding = response.json() - headers = { - "Authorization": "Bearer " + binding["credential"], - "Content-Type": "application/json", - "Idempotency-Key": str(uuid4()), - } - target = "/agent/v1/unbind" - body = b'{"cleanup_confirmed":true}' - response = await client.post( - target, - headers=proof_headers(device_key, certificate, "POST", target, body, headers, clock.now), - content=body, - ) - assert response.status_code == 200 - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - target = "/agent/v1/session" - response = await client.get( - target, - headers=proof_headers( - bound_device.identity.key, - bound_device.identity.certificate, - "GET", - target, - b"", - headers, - clock.now, - ), - ) - assert response.status_code == 200 diff --git a/tests/platform/api/e2e/powercell/test_owner_recovery.py b/tests/platform/api/e2e/powercell/test_owner_recovery.py index f7036919..d66bbc06 100644 --- a/tests/platform/api/e2e/powercell/test_owner_recovery.py +++ b/tests/platform/api/e2e/powercell/test_owner_recovery.py @@ -1,76 +1,118 @@ -"""Recovery revokes real attested device certificates without requiring the lost private key.""" +"""Account recovery detaches an agent while preserving the installation identity. + +The credential can be lost or revoked without invalidating the client-generated +device id. A later login from the same installation can register again and must +receive the same server device row. +""" -from datetime import timedelta from uuid import uuid4 import pytest -from .conftest import proof_headers - pytestmark = pytest.mark.anyio -@pytest.mark.parametrize("expired", [False, True]) -async def test_account_recovery_revokes_attested_binding(api, client, bound_device, clock, expired): - """A fresh account login can detach an expired or inaccessible identity while retaining device history.""" - device = bound_device - if expired: - clock.now += timedelta(days=366) - response = await client.post( - "/v1/auth/login", - json={"email": "alice@example.com", "password": " correct horse battery staple "}, - ) - assert response.status_code == 200 - api.headers["Authorization"] = "Bearer " + response.json()["access_token"] - target = f"/v1/computers/{device.binding['computer_id']}/unbind" +async def test_account_recovery_revokes_credential_and_reuses_device(api, client, bound_device, user): + """Unbinding is idempotent, revokes the agent, and a fresh registration keeps the device.""" + computer_id = bound_device.binding["computer_id"] + target = f"/v1/computers/{computer_id}/unbind" for _ in range(2): response = await api.post( target, headers={"Idempotency-Key": "owner-recovery"}, json={"cleanup_confirmed": True} ) assert response.status_code == 200, response.text - state = (await api.get(f"/v1/computers/{device.binding['computer_id']}")).json() - assert state["device_id"] == device.binding["device_id"] - assert state["certificate_sha256"] == device.binding["certificate_sha256"] + + state = (await api.get(f"/v1/computers/{computer_id}")).json() + assert state["device_id"] == bound_device.binding["device_id"] + assert "certificate_sha256" not in state assert state["session_id"] is None - # Even the original private key no longer authorizes this revoked binding. - target = "/agent/v1/session" - headers = { - "Authorization": "Bearer " + device.binding["credential"], - "Idempotency-Key": str(uuid4()), - "Content-Type": "application/json", - } - body = b'{"clean_start":true}' + response = await client.post( - target, - headers=proof_headers( - device.identity.key, - device.identity.certificate, - "POST", - target, - body, - headers, - clock.now, - ), - content=body, + "/agent/v1/session", + headers={ + "Authorization": "Bearer " + bound_device.binding["credential"], + "Idempotency-Key": str(uuid4()), + }, + json={"clean_start": True}, ) assert response.status_code == 401 - # The old certificate cannot recover the credential by replaying enrollment finish, either. - target = device.target - response = await api.post( - target, - headers=proof_headers( - device.identity.key, - device.identity.certificate, - "POST", - target, - b"{}", - { - "Authorization": api.headers["Authorization"], - "Idempotency-Key": device.headers["Idempotency-Key"], - "Content-Type": "application/json", - }, - clock.now, - ), - content=b"{}", + + login = await client.post( + "/v1/auth/login", + json={ + "login": user["email"], + "password": user["password"], + "device_id": bound_device.device_id, + }, ) - assert response.status_code in {401, 409} + assert login.status_code == 200, login.text + headers = {"Authorization": "Bearer " + login.json()["access_token"], "Idempotency-Key": str(uuid4())} + payload = { + "device_id": bound_device.device_id, + "name": "Recovered Mac", + "cpu_millis": 2000, + "memory_bytes": 2048, + "disk_bytes": 8192, + "isolation_modes": ["vm", "shared"], + } + response = await client.post("/v1/agent-enrollments", headers=headers, json=payload) + assert response.status_code == 201, response.text + enrollment = response.json() + response = await client.post( + f"/v1/agent-enrollments/{enrollment['id']}/finish", + headers={"Authorization": headers["Authorization"], "Idempotency-Key": "recover-finish"}, + json={}, + ) + assert response.status_code == 200, response.text + replacement = response.json() + assert replacement["computer_id"] != computer_id + assert replacement["device_id"] == bound_device.binding["device_id"] + assert replacement["credential"] != bound_device.binding["credential"] + + +async def test_same_installation_can_join_another_account(client, api, other_api, user, other_user): + """Switching accounts adds a device association instead of duplicating the device row.""" + device_id = uuid4() + first_login = await client.post( + "/v1/auth/login", + json={"login": user["email"], "password": user["password"], "device_id": str(device_id)}, + ) + assert first_login.status_code == 200, first_login.text + second_login = await client.post( + "/v1/auth/login", + json={ + "login": other_user["email"], + "password": "bob's sufficiently long password", + "device_id": str(device_id), + }, + ) + assert second_login.status_code == 200, second_login.text + + async def register(api_client, token, name): + headers = {"Authorization": "Bearer " + token, "Idempotency-Key": str(uuid4())} + payload = { + "device_id": str(device_id), + "name": name, + "cpu_millis": 2000, + "memory_bytes": 2048, + "disk_bytes": 8192, + "isolation_modes": ["vm", "shared"], + } + created = await api_client.post("/v1/agent-enrollments", headers=headers, json=payload) + assert created.status_code == 201, created.text + row = created.json() + finished = await api_client.post( + f"/v1/agent-enrollments/{row['id']}/finish", + headers={ + "Authorization": headers["Authorization"], + "Idempotency-Key": "finish-" + row["id"], + }, + json={}, + ) + assert finished.status_code == 200, finished.text + return finished.json() + + alice = await register(api, first_login.json()["access_token"], "Alice Mac") + bob = await register(other_api, second_login.json()["access_token"], "Bob Mac") + assert alice["computer_id"] != bob["computer_id"] + assert alice["device_id"] == bob["device_id"] diff --git a/tests/platform/api/e2e/powercell/test_relay.py b/tests/platform/api/e2e/powercell/test_relay.py deleted file mode 100644 index dcc45f31..00000000 --- a/tests/platform/api/e2e/powercell/test_relay.py +++ /dev/null @@ -1,866 +0,0 @@ -"""Real TLS/client-certificate and HTTP/2 CONNECT tests against the production relay.""" - -import asyncio -import hashlib -import socket -import ssl -from contextlib import asynccontextmanager -from datetime import timedelta -from urllib.parse import urlsplit -from uuid import uuid4 - -import h11 -import httpx -import pytest -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.x509.oid import NameOID -from h2.config import H2Configuration -from h2.connection import H2Connection -from h2.errors import ErrorCodes -from h2.events import DataReceived, ResponseReceived, StreamEnded, StreamReset, WindowUpdated -from h2.exceptions import H2Error -from h2.settings import SettingCodes - -from throng_api.app import create_app -from throng_api.models import DeviceCertificate, PhysicalDevice -from throng_api.relay import configuration - -from .conftest import certificate - -pytestmark = pytest.mark.anyio - - -class RelayWire: - """Exercise multiplexing and disconnection on one genuine TLS connection.""" - - def __init__(self, reader, writer, info): - self.reader, self.writer, self.info = reader, writer, info - self.h2 = H2Connection(H2Configuration(client_side=True, header_encoding="ascii")) - self.h2.initiate_connection() - self.flush() - - def flush(self): - """Send protocol frames without replacing the production transport.""" - self.writer.write(self.h2.data_to_send()) - - async def events_until(self, predicate, *, credit=True): - """Read bounded protocol progress, returning flow-control credit for received bytes.""" - events = [] - async with asyncio.timeout(3): - while not predicate(events): - data = await self.reader.read(65536) - assert data, "Relay disconnected unexpectedly" - batch = self.h2.receive_data(data) - for event in batch: - if isinstance(event, DataReceived) and credit: - self.h2.acknowledge_received_data( - event.flow_controlled_length, event.stream_id - ) - events.extend(batch) - self.flush() - return events - - async def connect(self, stream, headers=None): - """Open a TCP stream to the sole allowed API destination.""" - self.h2.send_headers( - stream, - headers - or [ - (":method", "CONNECT"), - (":authority", urlsplit(self.info["api_origin"]).hostname + ":80"), - ], - ) - self.flush() - events = await self.events_until( - lambda events: any( - isinstance(e, ResponseReceived) and e.stream_id == stream for e in events - ) - ) - return next( - int(dict(e.headers)[":status"]) - for e in events - if isinstance(e, ResponseReceived) and e.stream_id == stream - ) - - async def get(self, stream, target, authorization=None): - """Send one HTTP request over an authenticated CONNECT stream.""" - assert await self.connect(stream) == 200 - auth = f"Authorization: {authorization}\r\n" if authorization else "" - self.h2.send_data( - stream, - ( - f"GET {target} HTTP/1.1\r\nHost: api.test\r\n{auth}Connection: close\r\n\r\n" - ).encode(), - ) - self.flush() - events = await self.events_until( - lambda events: any(isinstance(e, StreamEnded) and e.stream_id == stream for e in events) - ) - data = b"".join( - e.data for e in events if isinstance(e, DataReceived) and e.stream_id == stream - ) - return int(data.split(b" ", 2)[1]), data - - -@pytest.fixture -def relay_wire(tls_context, app, verified_enrollment): - """Allocate a real reusable relay connection and always close its TLS transport.""" - - @asynccontextmanager - async def open_wire(): - reader, writer = await asyncio.open_connection( - "127.0.0.1", - urlsplit(app.state.powercell_relay["url"]).port, - ssl=tls_context, - server_hostname="localhost", - ) - try: - yield RelayWire(reader, writer, verified_enrollment.order.enrollment.row["relay"]) - finally: - writer.close() - await writer.wait_closed() - - return open_wire - - -@pytest.fixture -def relay_tls(tmp_path, pki, clock): - """Allocate isolated server TLS material and an unprivileged loopback port.""" - key = ec.generate_private_key(ec.SECP256R1()) - name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) - leaf = ( - x509.CertificateBuilder() - .subject_name(name) - .issuer_name(pki.root.subject) - .public_key(key.public_key()) - .serial_number(x509.random_serial_number()) - .not_valid_before(clock.now - timedelta(days=1)) - .not_valid_after(clock.now + timedelta(days=365)) - .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), False) - .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) - .add_extension( - x509.AuthorityKeyIdentifier.from_issuer_public_key(pki.root_key.public_key()), - critical=False, - ) - .sign(pki.root_key, hashes.SHA256()) - ) - cert_path, key_path = tmp_path / "relay.pem", tmp_path / "relay.key" - cert_path.write_bytes(leaf.public_bytes(serialization.Encoding.PEM)) - key_path.write_bytes( - key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - with socket.socket() as listener: - listener.bind(("127.0.0.1", 0)) - port = listener.getsockname()[1] - return { - "powercell_relay_url": f"https://localhost:{port}", - "powercell_relay_certificate": cert_path, - "powercell_relay_key": key_path, - } - - -@pytest.fixture -def app(app, relay_tls): - """Keep the parent fixture's real Apple-chain validation and add the actual TLS listener.""" - return create_app(app.state.settings.model_copy(update=relay_tls), clock=app.state.clock) - - -class RelayTransport(httpx.AsyncBaseTransport): - """Adapt raw CONNECT streams to HTTPX without bypassing TLS or the application.""" - - def __init__(self, context, info, *, destination=None): - self.context, self.info, self.destination = context, info, destination - - async def handle_async_request(self, request): - endpoint = urlsplit(self.info["url"]) - reader, writer = await asyncio.open_connection( - "127.0.0.1", endpoint.port, ssl=self.context, server_hostname="localhost" - ) - h2 = H2Connection(H2Configuration(client_side=True, header_encoding="ascii")) - h2.initiate_connection() - destination = self.destination or urlsplit(self.info["api_origin"]).hostname + ":80" - h2.send_headers(1, [(":method", "CONNECT"), (":authority", destination)]) - writer.write(h2.data_to_send()) - connected = asyncio.get_running_loop().create_future() - incoming, window = asyncio.Queue(), asyncio.Event() - - async def receive(): - try: - while chunk := await reader.read(65536): - for event in h2.receive_data(chunk): - if isinstance(event, ResponseReceived) and not connected.done(): - connected.set_result(int(dict(event.headers)[":status"])) - elif isinstance(event, DataReceived): - incoming.put_nowait(event.data) - h2.acknowledge_received_data(event.flow_controlled_length, 1) - elif isinstance(event, WindowUpdated): - window.set() - elif isinstance(event, StreamEnded): - incoming.put_nowait(None) - writer.write(h2.data_to_send()) - if not connected.done(): - connected.set_exception(httpx.ConnectError("TLS peer rejected")) - incoming.put_nowait(None) - except (H2Error, OSError, UnicodeError) as error: - if not connected.done(): - connected.set_exception(error) - incoming.put_nowait(error) - - receiver = asyncio.create_task(receive()) - try: - status = await asyncio.wait_for(connected, 3) - if status != 200: - raise httpx.ProxyError(f"CONNECT rejected: {status}") - body = await request.aread() - http = h11.Connection(h11.CLIENT) - data = http.send( - h11.Request( - method=request.method, - target=request.url.raw_path, - headers=request.headers.raw, - ) - ) - data += http.send(h11.Data(data=body)) + http.send(h11.EndOfMessage()) - while data: - while h2.local_flow_control_window(1) <= 0: - window.clear() - await asyncio.wait_for(window.wait(), 3) - size = min( - len(data), - h2.local_flow_control_window(1), - h2.max_outbound_frame_size, - ) - h2.send_data(1, data[:size]) - writer.write(h2.data_to_send()) - await writer.drain() - data = data[size:] - response, chunks = None, [] - while True: - event = http.next_event() - if event is h11.NEED_DATA: - chunk = await asyncio.wait_for(incoming.get(), 3) - if isinstance(chunk, Exception): - raise chunk - http.receive_data(chunk or b"") - elif isinstance(event, h11.Response): - response = event - elif isinstance(event, h11.Data): - chunks.append(event.data) - elif isinstance(event, h11.EndOfMessage): - return httpx.Response( - response.status_code, - headers=response.headers, - content=b"".join(chunks), - ) - elif isinstance(event, h11.ConnectionClosed): - raise httpx.RemoteProtocolError("Relay closed before HTTP response") - finally: - receiver.cancel() - await asyncio.gather(receiver, return_exceptions=True) - writer.close() - try: - await writer.wait_closed() - except OSError: - pass - - -@pytest.fixture -def tls_context(tmp_path, pki, verified_enrollment): - """Use the issued device certificate and its real matching test-only private key.""" - certificate_path, key_path = tmp_path / "device.pem", tmp_path / "device.key" - certificate_path.write_bytes( - verified_enrollment.certificate.public_bytes(serialization.Encoding.PEM) - ) - key_path.write_bytes( - verified_enrollment.key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - context = ssl.create_default_context(cafile=str(pki.root_file)) - # Exercise the same strict certificate checks on every supported Python version. - context.verify_flags |= ssl.VERIFY_X509_STRICT - context.set_alpn_protocols(["h2"]) - context.load_cert_chain(certificate_path, key_path) - return context - - -@pytest.fixture -async def relay_client(tls_context, app, verified_enrollment): - """Send native HTTP requests through a real authenticated CONNECT stream.""" - async with httpx.AsyncClient( - transport=RelayTransport(tls_context, verified_enrollment.order.enrollment.row["relay"]), - base_url="http://api.test", - timeout=5, - ) as client: - yield client - - -async def test_profile_scopes_relay_to_virtual_api_and_exact_attested_identity( - api, enrollment, app -): - """The downloaded profile grants only the intended API route, with the same ACME key.""" - profile = enrollment.profile - assert len(profile["PayloadContent"]) == 2 - acme, relay = profile["PayloadContent"] - assert profile["PayloadScope"] == "System" - assert relay["PayloadType"] == "com.apple.relay.managed" - assert relay["MatchDomains"] == [urlsplit(enrollment.row["relay"]["api_origin"]).hostname] - assert relay["Relays"] == [ - { - "HTTP2RelayURL": app.state.powercell_relay["url"], - "PayloadCertificateUUID": acme["PayloadUUID"], - } - ] - assert acme["HardwareBound"] and acme["Attest"] and not acme["AllowAllAppsAccess"] - reply = await api.get(f"/v1/agent-enrollments/{enrollment.row['id']}") - assert reply.json()["relay"] == enrollment.row["relay"] - reply = await api.get("/v1/agent-capabilities") - assert "powercell.relay.v1" in reply.json()["extensions"] - - -async def test_reused_connect_survives_six_second_delivery_gap(relay_wire): - """The measured retransmission gap must not close an otherwise reusable tunnel.""" - async with relay_wire() as wire: - assert await wire.connect(1) == 200 - - async def exchange(): - wire.h2.send_data(1, b"GET /health/live HTTP/1.1\r\nHost: api.test\r\n\r\n") - wire.flush() - - def complete(events): - data = b"".join( - e.data for e in events if isinstance(e, DataReceived) and e.stream_id == 1 - ) - if b"\r\n\r\n" not in data: - return False - header, body = data.split(b"\r\n\r\n", 1) - size = next( - int(line.split(b":", 1)[1]) - for line in header.split(b"\r\n") - if line.lower().startswith(b"content-length:") - ) - return len(body) >= size - - events = await wire.events_until(complete) - assert not any(isinstance(e, StreamEnded) for e in events) - data = b"".join( - e.data for e in events if isinstance(e, DataReceived) and e.stream_id == 1 - ) - assert data.startswith(b"HTTP/1.1 200") - - await exchange() - await asyncio.sleep(6) - await exchange() - - -async def test_relay_registers_real_attested_mac_and_authenticates_agent_requests( - relay_client, verified_enrollment, user, app, client -): - """The actual TLS key replaces request signatures without weakening account/credential checks.""" - enrollment = verified_enrollment.order.enrollment - target = f"/v1/agent-enrollments/{enrollment.row['id']}" - response = await relay_client.get(target + "/verification", headers=user["headers"]) - assert response.status_code == 200, response.text - assert ( - response.json()["certificate_sha256"] - == verified_enrollment.certificate.fingerprint(hashes.SHA256()).hex() - ) - headers = {**user["headers"], "Idempotency-Key": "relay-finish"} - response = await relay_client.post(target + "/finish", headers=headers, json={}) - assert response.status_code == 200, response.text - binding = response.json() - assert binding["relay"] == enrollment.row["relay"] - assert (await relay_client.post(target + "/finish", headers=headers, json={})).json() == binding - async with app.state.db.read() as session: - record = await session.get(DeviceCertificate, binding["certificate_sha256"]) - physical = await session.get(PhysicalDevice, record.device_id) - assert ( - physical.identity_hash - == hashlib.sha256(b"powercell.apple.udid.v1\x0000006000-0012345678901234").hexdigest() - ) - assert physical.id == binding["device_id"] - headers = {"Authorization": "Bearer " + binding["credential"]} - assert (await relay_client.get("/agent/v1/session", headers=headers)).status_code == 200 - assert (await relay_client.get("/agent/v1/session")).status_code == 401 - assert (await client.get("/agent/v1/session", headers=headers)).status_code == 401 - assert (await relay_client.get(target + "/verification")).status_code == 401 - - -async def test_plain_http_headers_cannot_forge_relay_authentication( - client, verified_enrollment, user -): - """Public listeners never trust forwarded certificates, fingerprints or proxy claims.""" - target = f"/v1/agent-enrollments/{verified_enrollment.order.enrollment.row['id']}/finish" - digest = verified_enrollment.certificate.fingerprint(hashes.SHA256()).hex() - for name in [ - "X-PowerCell-Certificate", - "X-Forwarded-Client-Cert", - "SSL-Client-Cert", - "powercell.relay_peer", - ]: - reply = await client.post( - target, - headers={**user["headers"], "Idempotency-Key": str(uuid4()), name: digest}, - json={}, - ) - assert reply.status_code == 401 - - -@pytest.mark.parametrize("destination", ["127.0.0.1:8000", "example.com:443", "169.254.169.254:80"]) -async def test_relay_is_not_an_open_proxy(tls_context, app, destination): - """Authenticated devices cannot use the listener to connect to arbitrary hosts or internal services.""" - async with httpx.AsyncClient( - transport=RelayTransport(tls_context, app.state.powercell_relay, destination=destination), - base_url="http://api.test", - ) as client: - with pytest.raises(httpx.ProxyError, match="403"): - await client.get("/health/ready") - - -async def test_relay_rejects_device_certificate_from_another_mac( - relay_client, api, verified_enrollment, tmp_path, app, pki, clock -): - """A different genuine client key cannot claim the first Mac's attested enrollment.""" - key = ec.generate_private_key(ec.SECP256R1()) - issuer_key = serialization.load_pem_private_key(pki.key_file.read_bytes(), None) - cert = certificate(key, issuer_key, x509.Name([]), pki.issuer.subject, clock.now) - cert_path, key_path = tmp_path / "other.pem", tmp_path / "other.key" - cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) - key_path.write_bytes( - key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - context = ssl.create_default_context(cafile=str(pki.root_file)) - context.set_alpn_protocols(["h2"]) - context.load_cert_chain(cert_path, key_path) - target = f"/v1/agent-enrollments/{verified_enrollment.order.enrollment.row['id']}/verification" - async with httpx.AsyncClient( - transport=RelayTransport(context, verified_enrollment.order.enrollment.row["relay"]), - base_url="http://api.test", - ) as wrong: - reply = await wrong.get(target, headers=api.headers) - assert reply.status_code == 401 - - -@pytest.mark.parametrize("change", ["expired", "revoked", "not_yet_valid", "missing"]) -async def test_each_relay_request_rechecks_device_validity( - relay_client, bound_device, app, clock, change -): - """A TLS-authenticated client loses access when its database certificate becomes unusable.""" - binding = bound_device.binding - headers = {"Authorization": "Bearer " + binding["credential"]} - assert (await relay_client.get("/agent/v1/session", headers=headers)).status_code == 200 - async with app.state.db.write() as session: - row = await session.get(DeviceCertificate, binding["certificate_sha256"]) - if change == "expired": - row.expires_at = clock.now - elif change == "revoked": - row.revoked_at = clock.now - elif change == "missing": - await session.delete(row) - else: - clock.now -= timedelta(days=2) - response = await relay_client.get("/agent/v1/session", headers=headers) - assert response.status_code == 401 and response.json()["detail"] == "Invalid device proof" - - -async def test_verified_connection_does_not_replace_account_ownership( - relay_client, verified_enrollment, other_user -): - """Knowing the enrollment and holding its physical key cannot replace its initiating account.""" - target = f"/v1/agent-enrollments/{verified_enrollment.order.enrollment.row['id']}" - response = await relay_client.get(target + "/verification", headers=other_user["headers"]) - assert response.status_code == 404 - response = await relay_client.post( - target + "/finish", - headers={**other_user["headers"], "Idempotency-Key": str(uuid4())}, - json={}, - ) - assert response.status_code == 404 - - -async def test_expired_and_pending_enrollments_cannot_be_verified( - relay_client, api, verified_enrollment, clock -): - """Transport authentication cannot finish a different unverified attempt or an expired enrollment.""" - response = await api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": str(uuid4())}, - json=verified_enrollment.order.enrollment.payload, - ) - target = f"/v1/agent-enrollments/{response.json()['id']}" - response = await relay_client.get(target + "/verification", headers=api.headers) - assert response.status_code == 409 - clock.now += timedelta(seconds=3601) - target = f"/v1/agent-enrollments/{verified_enrollment.order.enrollment.row['id']}" - assert ( - await relay_client.get(target + "/verification", headers=api.headers) - ).status_code == 409 - assert ( - await relay_client.post( - target + "/finish", - headers={**api.headers, "Idempotency-Key": str(uuid4())}, - json={}, - ) - ).status_code == 409 - - -async def test_relay_flow_control_preserves_large_upload_and_download(relay_client, user): - """Data larger than both HTTP/2 windows survives backpressure in each direction byte for byte.""" - data = bytes(range(256)) * 2048 - response = await relay_client.post( - "/v1/artifacts?filename=relay.bin", - headers={**user["headers"], "Content-Type": "application/octet-stream"}, - content=data, - ) - assert response.status_code == 201, response.text - assert response.json()["sha256"] == hashlib.sha256(data).hexdigest() - downloaded = await relay_client.get( - f"/v1/artifacts/{response.json()['id']}/content", headers=user["headers"] - ) - assert downloaded.status_code == 200 and downloaded.content == data - - -@pytest.mark.parametrize("failure", ["missing_certificate", "wrong_ca", "wrong_protocol"]) -async def test_tls_rejects_unauthenticated_or_incompatible_clients(app, tls_context, pki, failure): - """The listener requires a trusted client certificate and HTTP/2 before creating API scopes.""" - context = tls_context - if failure == "missing_certificate": - context = ssl.create_default_context(cafile=str(pki.root_file)) - context.set_alpn_protocols(["h2"]) - elif failure == "wrong_ca": - context = ssl.create_default_context(cafile=str(pki.root_file)) - context.set_alpn_protocols(["h2"]) - # The separate server root is deliberately not the accepted device CA. - key_path = pki.root_file.with_name("untrusted.key") - key_path.write_bytes( - pki.root_key.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - context.load_cert_chain(pki.root_file, key_path) - else: - context.set_alpn_protocols(["http/1.1"]) - port = urlsplit(app.state.powercell_relay["url"]).port - try: - reader, writer = await asyncio.open_connection( - "127.0.0.1", port, ssl=context, server_hostname="localhost" - ) - try: - assert await asyncio.wait_for(reader.read(1), 3) == b"" - finally: - writer.close() - try: - await writer.wait_closed() - except OSError: - pass - except (ssl.SSLError, ConnectionResetError): - pass - - -@pytest.mark.parametrize( - "url", - [ - "http://localhost:8444", - "https://user@localhost", - "https://localhost/path", - "https://localhost/?token=x", - "https://localhost/#fragment", - "https://", - "https://localhost:0", - ], -) -async def test_relay_configuration_rejects_unsafe_origins(app, url): - """A relay endpoint cannot carry credentials, insecure TLS, arbitrary paths or invalid ports.""" - with pytest.raises(ValueError): - configuration(app.state.settings.model_copy(update={"powercell_relay_url": url})) - - -async def test_partial_relay_configuration_cannot_silently_disable_verification(app): - """All relay TLS values and the attested-device trust anchor are mandatory together.""" - for field in [ - "powercell_relay_url", - "powercell_relay_certificate", - "powercell_relay_key", - "powercell_ca_certificate", - ]: - with pytest.raises(ValueError): - configuration(app.state.settings.model_copy(update={field: None})) - - -async def test_revocation_is_enforced_on_an_already_authenticated_tls_connection( - relay_wire, bound_device, app, clock -): - """An established TLS session cannot retain authorization after its certificate is revoked.""" - async with relay_wire() as wire: - credential = "Bearer " + bound_device.binding["credential"] - assert (await wire.get(1, "/agent/v1/session", credential))[0] == 200 - async with app.state.db.write() as session: - row = await session.get(DeviceCertificate, bound_device.binding["certificate_sha256"]) - row.revoked_at = clock.now - assert (await wire.get(3, "/agent/v1/session", credential))[0] == 401 - - -async def test_abandoned_upload_and_reset_do_not_block_other_streams(relay_wire): - """An incomplete command upload must not prevent a concurrent heartbeat or the next connection.""" - async with relay_wire() as wire: - assert await wire.connect(1) == 200 - # Leave HTTP incomplete, then cancel it while another stream remains usable. - wire.h2.send_data(1, b"POST /v1/artifacts HTTP/1.1\r\nHost: api.test\r\n") - wire.flush() - assert (await wire.get(3, "/health/ready"))[0] == 200 - wire.h2.reset_stream(1) - wire.flush() - assert (await wire.get(5, "/health/ready"))[0] == 200 - # A client half-close of an empty stream also leaves the connection usable. - assert await wire.connect(7) == 200 - wire.h2.send_data(7, b"", end_stream=True) - wire.flush() - assert (await wire.get(9, "/health/ready"))[0] == 200 - - -async def test_non_connect_requests_and_malformed_frames_cannot_enter_api(relay_wire): - """Reject unsupported proxy methods and corrupted HTTP/2 without exposing an API transport.""" - async with relay_wire() as wire: - assert ( - await wire.connect( - 1, - [ - (":method", "GET"), - (":scheme", "https"), - (":authority", "localhost"), - (":path", "/health/ready"), - ], - ) - == 405 - ) - assert (await wire.get(3, "/health/ready"))[0] == 200 - # A PING frame on a nonzero stream violates HTTP/2 and must terminate the connection. - wire.writer.write(b"\x00\x00\x08\x06\x00\x00\x00\x00\x01" + bytes(8)) - async with asyncio.timeout(3): - while await wire.reader.read(65536): - pass - async with relay_wire() as wire: - assert (await wire.get(1, "/health/ready"))[0] == 200 - - -async def test_client_goaway_disconnects_open_streams_cleanly(relay_wire): - """Client shutdown cancels an unfinished tunnel without breaking later connections.""" - async with relay_wire() as wire: - assert await wire.connect(1) == 200 - wire.h2.close_connection() - wire.flush() - async with asyncio.timeout(3): - while await wire.reader.read(65536): - pass - async with relay_wire() as wire: - assert (await wire.get(1, "/health/ready"))[0] == 200 - - -async def test_api_shutdown_closes_authenticated_connections_and_pending_streams( - relay_wire, http_server -): - """Stopping the API must stop its relay too, including unfinished uploads.""" - async with relay_wire() as wire: - assert await wire.connect(1) == 200 - wire.h2.send_data(1, b"POST /v1/artifacts HTTP/1.1\r\nHost: api.test\r\n") - wire.flush() - http_server.server.should_exit = True - _, pending = await asyncio.wait([http_server.task], timeout=3) - assert not pending, "API shutdown retained a relay connection" - async with asyncio.timeout(3): - while await wire.reader.read(65536): - pass - - -@pytest.mark.parametrize("stage", ["accept", "stream"]) -async def test_backend_socket_failure_closes_both_ends_without_breaking_listener( - relay_wire, monkeypatch, stage -): - """Failure while opening an in-process transport must not leak sockets or kill the TLS listener.""" - loop = asyncio.get_running_loop() - original_pair, pairs = socket.socketpair, [] - original_open = asyncio.open_connection - accepted = [] - original_accept = loop.connect_accepted_socket - - def capture_pair(): - pair = original_pair() - pairs.append(pair) - return pair - - async def unavailable(*args, **kwargs): - raise OSError("Simulated unavailable backend socket") - - async def failed_stream(*args, **kwargs): - if "sock" in kwargs: - raise OSError("Simulated unavailable backend stream") - return await original_open(*args, **kwargs) - - async def capture_accepted(*args, **kwargs): - transport, protocol = await original_accept(*args, **kwargs) - accepted.append(protocol) - return transport, protocol - - with monkeypatch.context() as patch: - patch.setattr(socket, "socketpair", capture_pair) - patch.setattr( - loop, "connect_accepted_socket", unavailable if stage == "accept" else capture_accepted - ) - if stage == "stream": - patch.setattr(asyncio, "open_connection", failed_stream) - async with relay_wire() as wire: - with pytest.raises(AssertionError, match="disconnected"): - await wire.connect(1) - assert pairs and all(s.fileno() == -1 for pair in pairs for s in pair) - assert all(not protocol.connections for protocol in accepted) - async with relay_wire() as wire: - assert (await wire.get(1, "/health/ready"))[0] == 200 - - -async def test_invalid_relay_tls_configuration_fails_startup(app, tmp_path): - """A broken server certificate fails startup instead of exposing a weaker relay.""" - invalid = tmp_path / "invalid.pem" - invalid.write_text("not a TLS certificate") - broken = create_app( - app.state.settings.model_copy(update={"powercell_relay_certificate": invalid}) - ) - with pytest.raises(ssl.SSLError): - async with broken.router.lifespan_context(broken): - pytest.fail("Invalid TLS material must not start a relay") - - -async def test_slow_download_backpressure_does_not_block_other_connects(relay_wire): - """A receiver that stops granting data capacity must not block independent CONNECT streams.""" - async with relay_wire() as wire: - wire.h2.update_settings({SettingCodes.INITIAL_WINDOW_SIZE: 16}) - wire.flush() - assert await wire.connect(1) == 200 - wire.h2.send_data( - 1, b"GET /health/ready HTTP/1.1\r\nHost: api.test\r\nConnection: close\r\n\r\n" - ) - wire.flush() - first = await wire.events_until( - lambda events: any(isinstance(e, DataReceived) for e in events), credit=False - ) - assert sum(len(e.data) for e in first if isinstance(e, DataReceived)) == 16 - assert await wire.connect(3) == 200 - wire.h2.increment_flow_control_window(4096, 1) - wire.flush() - rest = await wire.events_until( - lambda events: any(isinstance(e, StreamEnded) and e.stream_id == 1 for e in events) - ) - body = b"".join(e.data for e in first + rest if isinstance(e, DataReceived)) - assert body.startswith(b"HTTP/1.1 200") and b'"status":"ready"' in body - - -async def test_data_and_reset_after_refused_connect_do_not_open_a_backend(relay_wire): - """Late DATA, END_STREAM and RESET on rejected destinations do not affect valid API streams.""" - async with relay_wire() as wire: - headers = [(":method", "CONNECT"), (":authority", "forbidden.invalid:80")] - assert await wire.connect(1, headers) == 403 - wire.h2.send_data(1, b"late bytes", end_stream=True) - assert await wire.connect(3, headers) == 403 - wire.h2.reset_stream(3) - wire.flush() - assert (await wire.get(5, "/health/ready"))[0] == 200 - - -async def test_old_profile_routes_cannot_select_a_new_enrollments_identity(api, enrollment): - """Each enrollment has its own hostname; replay keeps that route stable and reinstall gets another.""" - first = enrollment.row["relay"] - response = await api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": str(uuid4())}, - json=enrollment.payload, - ) - second = response.json()["relay"] - assert second["url"] == first["url"] and second["api_origin"] != first["api_origin"] - response = await api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": enrollment.key}, - json=enrollment.payload, - ) - assert response.json()["relay"] == first - - -@pytest.mark.parametrize("boundary", ["read", "write", "drain"]) -async def test_live_backend_socket_error_resets_one_tunnel_and_preserves_its_peer( - relay_wire, monkeypatch, boundary, caplog -): - """Real TLS/HTTP2 CONNECT must expose a failed backend without a timeout. - - Only one in-process socket method fails. TLS, h2 frames, the sibling stream - and the live health endpoint retain the production path. RFC 9113 section - 8.5 requires CONNECT_ERROR rather than clean EOF for abnormal socket closure. - """ - caplog.set_level("INFO", logger="throng.transport") - original_open, injected = asyncio.open_connection, False - - async def fail_one_backend(*args, **kwargs): - nonlocal injected - reader, writer = await original_open(*args, **kwargs) - if "sock" in kwargs and not injected: - injected = True - - async def fail_async(*args, **kwargs): - raise ConnectionResetError("Disposable backend failure") - - def fail_write(*args, **kwargs): - raise BrokenPipeError("Disposable backend failure") - - if boundary == "read": - reader.read = fail_async - elif boundary == "write": - writer.write = fail_write - else: - writer.drain = fail_async - return reader, writer - - with monkeypatch.context() as patch: - patch.setattr(asyncio, "open_connection", fail_one_backend) - async with relay_wire() as wire: - wire.h2.send_headers( - 1, - [ - (":method", "CONNECT"), - (":authority", urlsplit(wire.info["api_origin"]).hostname + ":80"), - ], - ) - wire.flush() - events = await wire.events_until( - lambda rows: any(isinstance(e, ResponseReceived) and e.stream_id == 1 for e in rows) - ) - if boundary != "read": - wire.h2.send_data(1, b"GET /health/ready HTTP/1.1\r\nHost: api.test\r\n\r\n") - wire.flush() - if not any(isinstance(e, StreamReset) and e.stream_id == 1 for e in events): - try: - events += await wire.events_until( - lambda rows: any( - isinstance(e, StreamReset) and e.stream_id == 1 for e in rows - ) - ) - except TimeoutError: - pass # A missing reset is an assertion, not an infrastructure error. - assert injected - assert [(e.stream_id, e.error_code) for e in events if isinstance(e, StreamReset)] == [ - (1, ErrorCodes.CONNECT_ERROR) - ] - assert not any(isinstance(e, StreamEnded) and e.stream_id == 1 for e in events) - assert (await wire.get(3, "/health/ready"))[0] == 200 - reason = "backend_download_error" if boundary == "read" else "backend_upload_error" - assert any(f'"reason":"{reason}"' in row.message for row in caplog.records) diff --git a/tests/platform/api/e2e/test_powercell_execution.py b/tests/platform/api/e2e/test_powercell_execution.py index 80f8e866..7a7c9c3e 100644 --- a/tests/platform/api/e2e/test_powercell_execution.py +++ b/tests/platform/api/e2e/test_powercell_execution.py @@ -30,24 +30,25 @@ def capacity_report(): } -async def test_capabilities_fail_closed_without_issuer(client, api): - """An unconfigured server never advertises enrollment or creates an unverifiable device.""" +async def test_capabilities_need_no_operator_pki_but_require_device_login(client, api): + """Registration is always advertised, while an unknown device still cannot enroll.""" response = await client.get("/v1/agent-capabilities") assert response.status_code == 200 - assert response.json()["attestation_required"] is True - assert "powercell.enrollment.v1" not in response.json()["extensions"] + body = response.json() + assert "attestation_required" not in body + assert {"powercell.enrollment.v1", "powercell.device.v1"} <= set(body["extensions"]) response = await api.post( "/v1/agent-enrollments", headers={"Idempotency-Key": str(uuid4())}, json={ - "installation_id": str(uuid4()), + "device_id": str(uuid4()), "isolation_modes": ["vm", "shared"], "cpu_millis": 2000, "memory_bytes": 2048, "disk_bytes": 8192, }, ) - assert response.status_code == 503 + assert response.status_code == 409 async def test_targets_below_reservations_and_revisions_are_atomic( @@ -433,8 +434,8 @@ async def test_cleanup_idempotency_headers_are_bounded(agent_api, header): assert response.status_code == 422 -async def test_powercell_runtime_cannot_bypass_attestation(api): - """The legacy computer registration path cannot create a Power Cell execution worker.""" +async def test_powercell_runtime_requires_the_agent_registration_path(api): + """The legacy computer endpoint cannot create a Power Cell execution worker.""" response = await api.post( "/v1/computers", json={ diff --git a/tests/platform/api/integration/powercell_security/conftest.py b/tests/platform/api/integration/powercell_security/conftest.py deleted file mode 100644 index 267f1ce1..00000000 --- a/tests/platform/api/integration/powercell_security/conftest.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Reuse the real PKI and HTTP setup for fault injection and persistence assertions.""" - -from tests.platform.api.e2e.powercell.conftest import acme_order as acme_order -from tests.platform.api.e2e.powercell.conftest import app as app -from tests.platform.api.e2e.powercell.conftest import bound_device as bound_device -from tests.platform.api.e2e.powercell.conftest import enrollment as enrollment -from tests.platform.api.e2e.powercell.conftest import pki as pki -from tests.platform.api.e2e.powercell.conftest import verified_enrollment as verified_enrollment diff --git a/tests/platform/api/integration/powercell_security/test_security_guards.py b/tests/platform/api/integration/powercell_security/test_security_guards.py deleted file mode 100644 index 7be3b58e..00000000 --- a/tests/platform/api/integration/powercell_security/test_security_guards.py +++ /dev/null @@ -1,391 +0,0 @@ -"""Real cryptography and database fault states complement the HTTP enrollment scenarios.""" - -import base64 -import hashlib -import json -from datetime import timedelta -from uuid import uuid4 - -import cbor2 -import pytest -from cryptography import x509 -from cryptography.hazmat.primitives import hashes, serialization -from cryptography.hazmat.primitives.asymmetric import ec -from sqlalchemy import delete - -from tests.platform.api.e2e.powercell.conftest import attestation, certificate, proof_headers -from throng_api import device_security -from throng_api.device_security import NONCE_OID, SEP_OID, SERIAL_OID, SIP_OID, UDID_OID -from throng_api.enrollment import configure_authority -from throng_api.models import ( - AgentEnrollment, - ComputerOwnership, - DeviceCertificate, - ProtocolNonce, -) - -pytestmark = pytest.mark.anyio - - -@pytest.mark.parametrize( - "changes", - [ - {"powercell_acme_url": "https://example.org/acme/powercell", "powercell_ca_key": None}, - {"powercell_acme_url": "http://example.org/acme/powercell"}, - {"powercell_acme_url": "https://user@example.org/acme/powercell"}, - {"powercell_acme_url": "https://example.org/acme/powercell?bad=1"}, - {"powercell_ca_key": "wrong-key"}, - ], -) -async def test_issuer_configuration_fails_closed(app, pki, tmp_path, changes): - """Partial, insecure and mismatched issuer configuration cannot create an operational authority.""" - if changes.get("powercell_ca_key") == "wrong-key": - file = tmp_path / "wrong.key" - file.write_bytes( - ec.generate_private_key(ec.SECP256R1()).private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - ) - changes = {**changes, "powercell_ca_key": file} - with pytest.raises(ValueError): - configure_authority(app.state.settings.model_copy(update=changes)) - - -@pytest.mark.parametrize( - "case", ["format", "chain", "anchor", "curve", "blank_identity", "blank_sep"] -) -async def test_attestation_structure_and_certified_properties(app, pki, clock, monkeypatch, case): - """Untrusted structure, trust-anchor changes, unsupported keys and blank certified properties are rejected.""" - token = "fresh challenge" - key = ec.generate_private_key(ec.SECP384R1() if case == "curve" else ec.SECP256R1()) - fields = [ - (UDID_OID, b"" if case == "blank_identity" else b"MAC"), - (SERIAL_OID, b"SERIAL"), - (SEP_OID, b"" if case == "blank_sep" else b"1"), - (SIP_OID, b"\x01"), - (NONCE_OID, hashlib.sha256(token.encode()).digest()), - ] - encoded = base64.urlsafe_b64decode( - attestation(pki, key, token, clock.now, extensions=fields) + "==" - ) - if case == "format": - encoded = cbor2.dumps({"fmt": "not-apple"}) - if case == "chain": - encoded = cbor2.dumps({"fmt": "apple", "attStmt": {"x5c": []}}) - if case == "anchor": - monkeypatch.setattr(device_security, "APPLE_ROOT_SHA256", "0" * 64) - with pytest.raises(ValueError): - device_security.validate_attestation(encoded, token, clock.now) - - -@pytest.mark.parametrize("content", [b'{"x":1,"x":2}', b'{"x":NaN}', b'{"x":Infinity}']) -async def test_security_json_rejects_ambiguous_and_nonfinite_inputs(content): - """Signed JSON cannot rely on parser disagreements about duplicate members or nonfinite numbers.""" - with pytest.raises(ValueError): - device_security.strict_json(content) - - -@pytest.mark.parametrize("state", ["expired", "revoked", "future", "missing"]) -async def test_certificate_lifetime_and_revocation_are_enforced( - client, bound_device, app, clock, state -): - """Possession alone cannot authorize an expired, revoked, absent or not-yet-valid stored identity.""" - identity = bound_device.identity - sha = bound_device.binding["certificate_sha256"] - async with app.state.db.write() as session: - row = await session.get(DeviceCertificate, sha) - if state == "expired": - row.expires_at = clock.now - if state == "revoked": - row.revoked_at = clock.now - if state == "missing": - await session.delete(row) - if state == "future": - cert = certificate( - identity.key, - identity.key, - identity.certificate.subject, - identity.certificate.subject, - clock.now + timedelta(days=3), - ) - row.pem = cert.public_bytes(serialization.Encoding.PEM) - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - response = await client.get( - "/agent/v1/session", - headers=proof_headers( - identity.key, identity.certificate, "GET", "/agent/v1/session", b"", headers, clock.now - ), - ) - assert response.status_code == 401 - - -@pytest.mark.parametrize("settings", [{"controller_enabled": False}], indirect=True) -async def test_expired_nonce_can_be_reused_only_with_a_fresh_signature( - client, bound_device, app, clock -): - """An expired persisted replay marker is replaced under the same transaction as fresh verification.""" - identity = bound_device.identity - nonce = str(uuid4()) - async with app.state.db.write() as session: - session.add( - ProtocolNonce( - namespace=bound_device.binding["certificate_sha256"], - value=nonce, - expires_at=clock.now - timedelta(seconds=1), - ) - ) - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - response = await client.get( - "/agent/v1/session", - headers=proof_headers( - identity.key, - identity.certificate, - "GET", - "/agent/v1/session", - b"", - headers, - clock.now, - patch={"nonce": nonce}, - ), - ) - assert response.status_code == 200 - - -async def test_revocation_between_proof_and_handler_is_rechecked( - client, bound_device, app, clock, monkeypatch -): - """Credential use is checked again after the separately committed proof transaction.""" - original = device_security.verify_proof - - async def revoke_after_proof(session, request, certificate_hash, **kwargs): - await original(session, request, certificate_hash, **kwargs) - row = await session.get(DeviceCertificate, certificate_hash) - row.revoked_at = clock.now - - monkeypatch.setattr(device_security, "verify_proof", revoke_after_proof) - identity = bound_device.identity - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - response = await client.get( - "/agent/v1/session", - headers=proof_headers( - identity.key, identity.certificate, "GET", "/agent/v1/session", b"", headers, clock.now - ), - ) - assert response.status_code == 401 - - -async def test_signed_diagnostics_are_bounded_without_a_session(client, bound_device, app, clock): - """Device verification also covers deferred uploads and enforces their smaller body limit.""" - identity = bound_device.identity - identifier = str(uuid4()) - target = "/agent/v1/diagnostics/" + identifier - headers = {"Authorization": "Bearer " + bound_device.binding["credential"]} - content = json.dumps( - {"id": identifier, "created": clock.now.isoformat(), "message": "late error"} - ).encode() - response = await client.put( - target, - headers=proof_headers( - identity.key, identity.certificate, "PUT", target, content, headers, clock.now - ), - content=content, - ) - assert response.status_code == 200, response.text - app.state.settings.max_diagnostic_bytes = 10 - response = await client.put( - target, - headers=proof_headers( - identity.key, identity.certificate, "PUT", target, content, headers, clock.now - ), - content=content, - ) - assert response.status_code == 413 - - -async def test_persisted_credentials_are_encrypted_and_revoked_finish_is_not_recoverable( - api, bound_device, app, clock -): - """Enrollment stores encrypted retry material and refuses recovery after normal credential rotation.""" - identity = bound_device.identity - async with app.state.db.read() as session: - row = await session.get(AgentEnrollment, identity.order.enrollment.row["id"]) - assert bound_device.binding["credential"].encode() not in row.credential_encrypted - response = await api.post(f"/v1/computers/{bound_device.binding['computer_id']}/credentials") - assert response.status_code == 201 - response = await api.post( - bound_device.target, - headers=proof_headers( - identity.key, - identity.certificate, - "POST", - bound_device.target, - b"{}", - bound_device.headers, - clock.now, - ), - content=b"{}", - ) - assert response.status_code == 409 - - -async def test_enrollment_finish_rejects_unverified_and_invalid_retry_input( - api, user, verified_enrollment, enrollment, clock -): - """Finalization requires a verified enrollment, an empty body and a bounded idempotency key.""" - identity = verified_enrollment - target = f"/v1/agent-enrollments/{enrollment.row['id']}/finish" - headers = {**user["headers"], "Idempotency-Key": "x" * 129} - response = await api.post( - target, - headers=proof_headers( - identity.key, identity.certificate, "POST", target, b"{}", headers, clock.now - ), - content=b"{}", - ) - assert response.status_code == 422 - response = await api.post( - target, headers={"Idempotency-Key": str(uuid4())}, content=b'{"extra":true}' - ) - assert response.status_code == 422 - clock.now += timedelta(hours=2) - response = await api.post(target, headers={"Idempotency-Key": str(uuid4())}, content=b"{}") - assert response.status_code == 409 - - -async def test_enrollment_quota_bounds_pending_records(api, enrollment): - """An authenticated user cannot accumulate an unbounded number of live ACME challenges.""" - for i in range(20): - response = await api.post( - "/v1/agent-enrollments", - headers={"Idempotency-Key": str(uuid4())}, - json={**enrollment.payload, "installation_id": str(uuid4())}, - ) - assert response.status_code == (201 if i < 19 else 429) - - -@pytest.mark.parametrize("membership", ["admin"], indirect=True) -async def test_diagnostics_do_not_follow_transferred_ownership( - api, other_api, client, agent, computer, company, membership, clock -): - """A new computer owner cannot read failure logs captured for the previous owner.""" - identifier = str(uuid4()) - response = await client.put( - "/agent/v1/diagnostics/" + identifier, - headers=agent["headers"], - json={"id": identifier, "created": clock.now.isoformat(), "message": "private old log"}, - ) - assert response.status_code == 200 - response = await api.patch( - f"/v1/computer-ownerships/{computer['ownership']['id']}", - json={"company_id": company["id"]}, - ) - assert response.status_code == 200 - response = await other_api.get(f"/v1/computers/{computer['id']}/diagnostics/{identifier}") - assert response.status_code == 404 - - -async def test_ownerless_cleanup_and_diagnostic_failure(client, agent, app, computer, clock): - """A partially detached computer can clean up, but cannot create ownerless diagnostic content.""" - async with app.state.db.write() as session: - await session.execute( - delete(ComputerOwnership).where(ComputerOwnership.computer_id == computer["id"]) - ) - identifier = str(uuid4()) - response = await client.put( - "/agent/v1/diagnostics/" + identifier, - headers=agent["headers"], - json={"id": identifier, "created": clock.now.isoformat(), "message": "no owner"}, - ) - assert response.status_code == 409 - response = await client.post( - "/agent/v1/unbind", - headers={**agent["headers"], "Idempotency-Key": str(uuid4())}, - json={"cleanup_confirmed": True}, - ) - assert response.status_code == 200 - - -async def test_expired_issuer_cannot_sign_even_a_verified_key(app, clock): - """A configured CA ceases issuance at its own expiry, regardless of requested certificate duration.""" - from types import SimpleNamespace - - key = ec.generate_private_key(ec.SECP256R1()) - csr = ( - x509.CertificateSigningRequestBuilder() - .subject_name(x509.Name([])) - .sign(key, hashes.SHA256()) - ) - with pytest.raises(ValueError, match="not currently valid"): - app.state.powercell_authority.issue( - SimpleNamespace(id=str(uuid4())), csr, clock.now + timedelta(days=3651) - ) - - -async def test_capacity_requires_advertised_isolation_and_complete_inventory( - api, client, agent, computer, computer_resources, app -): - """Invalid local defaults or deleted inventory cannot be accepted as a new scheduler policy.""" - from throng_api.models import Computer - - async with app.state.db.write() as session: - row = await session.get(Computer, computer["id"]) - row.isolation_modes = ["vm"] - payload = { - "revision": 0, - "accepting_work": True, - "mode": "idle", - "cpu_millis": 2000, - "memory_bytes": 2048, - "disk_bytes": 8192, - "running_commands": 0, - "cpu_used_millis": 0, - "memory_used_bytes": 0, - "default_isolation": "shared", - } - response = await client.post( - "/agent/v1/capacity", - headers={**agent["headers"], "Idempotency-Key": str(uuid4())}, - json=payload, - ) - assert response.status_code == 422 - response = await api.delete(f"/v1/computer-resources/{computer_resources['cpu']['id']}") - assert response.status_code == 204 - response = await client.post( - "/agent/v1/capacity", - headers={**agent["headers"], "Idempotency-Key": str(uuid4())}, - json={**payload, "default_isolation": "vm"}, - ) - assert response.status_code == 409 - - -async def test_scheduler_skips_an_unadvertised_isolation_mode( - api, client, agent, app, computer, isolate_payload -): - """An unsupported plugin mode stays unassigned without blocking a compatible isolate behind it.""" - from throng_api.models import Computer - - async with app.state.db.write() as session: - row = await session.get(Computer, computer["id"]) - row.isolation_modes = ["vm"] - response = await api.post( - "/v1/isolates", - headers={"Idempotency-Key": str(uuid4())}, - json={**isolate_payload, "isolation_mode": "shared"}, - ) - assert response.status_code == 202 - waiting = response.json()["id"] - response = await api.post( - "/v1/isolates", - headers={"Idempotency-Key": str(uuid4())}, - json={**isolate_payload, "isolation_mode": "vm"}, - ) - assert response.status_code == 202 - compatible = response.json()["id"] - response = await client.post( - "/agent/v1/tasks/claim", headers=agent["headers"], json={"wait_seconds": 2} - ) - assert response.status_code == 200 - assert [t["isolate_id"] for t in response.json()["tasks"]] == [compatible] - assert (await api.get("/v1/isolates/" + waiting)).json()["computer_id"] is None diff --git a/tests/platform/api/integration/test_device_migration.py b/tests/platform/api/integration/test_device_migration.py new file mode 100644 index 00000000..2d00f3c5 --- /dev/null +++ b/tests/platform/api/integration/test_device_migration.py @@ -0,0 +1,68 @@ +"""Migration 0028 keeps pending installations usable without attestation.""" + +import json +from datetime import UTC, datetime +from uuid import uuid4 + +import anyio +import pytest +from alembic import command +from sqlalchemy import create_engine, text + +pytestmark = pytest.mark.anyio + + +async def test_pending_installation_becomes_a_device_key(alembic_config, settings): + """An offline enrollment survives the upgrade and is linked to its account.""" + await anyio.to_thread.run_sync(command.downgrade, alembic_config, "0027") + user_id, enrollment_id, installation_id = uuid4(), uuid4(), uuid4() + now = datetime(2026, 11, 25, 12, tzinfo=UTC) + engine = create_engine(settings.database_url.replace("+aiosqlite", "")) + try: + with engine.begin() as connection: + connection.execute( + text( + "INSERT INTO agent_enrollments " + "(id, actor_id, installation_id, request, expires_at, acme_secret, " + " order_created, challenge_token, created_at) " + "VALUES (:id, :actor, :installation, :request, :expires, :acme, 0, :challenge, :created)" + ), + { + "id": str(enrollment_id), + "actor": str(user_id), + "installation": str(installation_id), + "request": json.dumps({"installation_id": str(installation_id)}), + "expires": now, + "acme": "legacy-secret", + "challenge": "legacy-challenge", + "created": now, + }, + ) + finally: + engine.dispose() + + await anyio.to_thread.run_sync(command.upgrade, alembic_config, "head") + + engine = create_engine(settings.database_url.replace("+aiosqlite", "")) + try: + with engine.connect() as connection: + device = connection.execute( + text("SELECT id, client_key FROM devices WHERE client_key = :key"), + {"key": str(installation_id)}, + ).one() + enrollment = connection.execute( + text("SELECT device_id FROM agent_enrollments WHERE id = :id"), + {"id": str(enrollment_id)}, + ).one() + account = connection.execute( + text( + "SELECT 1 FROM device_accounts " + "WHERE device_id = :device AND user_id = :user" + ), + {"device": device.id, "user": str(user_id)}, + ).one() + finally: + engine.dispose() + + assert enrollment.device_id == device.id + assert account[0] == 1 diff --git a/tests/platform/api/integration/test_powercell_upgrade.py b/tests/platform/api/integration/test_powercell_upgrade.py index 66f0719e..fbe9073b 100644 --- a/tests/platform/api/integration/test_powercell_upgrade.py +++ b/tests/platform/api/integration/test_powercell_upgrade.py @@ -11,16 +11,16 @@ pytestmark = pytest.mark.anyio -async def test_old_powercell_rows_cannot_keep_legacy_bearer_authentication( +async def test_old_powercell_rows_keep_credential_authentication_after_migration( app, agent_api, computer ): - """A Power Cell runtime registered before migration must enroll instead of retaining unsigned access.""" + """A pre-upgrade row becomes a normal credential-authenticated worker.""" async with app.state.db.write() as session: row = await session.get(Computer, computer["id"]) row.runtime = "powercell-ubuntu-arm64-v1" response = await agent_api.get("/agent/v1/session") - assert response.status_code == 401 - assert response.json()["detail"] == "Mutating Compute requires attested enrollment" + assert response.status_code == 200 + assert response.json()["computer_id"] == computer["id"] async def test_optional_isolation_fields_preserve_preupgrade_idempotency(api, app, isolate_payload): diff --git a/tests/platform/api/integration/test_relay_accept_ownership.py b/tests/platform/api/integration/test_relay_accept_ownership.py deleted file mode 100644 index 6c25c796..00000000 --- a/tests/platform/api/integration/test_relay_accept_ownership.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Relay shutdown owns accepted TCP peers even across callback scheduling races. - -The loopback socket is real. Only TLS metadata is supplied at the boundary: these -cases exercise connection ownership, independently of TLS certificate validation, -which remains covered by the relay's existing full TLS/HTTP2 E2E tests. -""" - -import asyncio -import inspect -import unittest -from types import SimpleNamespace -from unittest.mock import Mock - -from throng_api.relay import RelayServer - - -class RelayAcceptOwnershipTests(unittest.IsolatedAsyncioTestCase): - async def exercise_socket(self, mode): - server = RelayServer(None, None, None) - peer_ready, listener_closed = asyncio.Event(), asyncio.Event() - peers, tasks, held = [], [], [] - tls = SimpleNamespace( - selected_alpn_protocol=lambda: "h2", getpeercert=lambda **kw: b"test-only" - ) - - def invoke(reader, writer): - result = server.connected(reader, writer) - if inspect.iscoroutine(result): - result = asyncio.create_task(result) - if isinstance(result, asyncio.Task): - tasks.append(result) - else: - tasks.extend(server.connections) - if mode == "cancel_before_start": - for task in tasks: - task.cancel() - - def accepted(reader, writer): - peers.append(writer) - extra = writer.get_extra_info - writer.get_extra_info = lambda name, default=None: ( - tls if name == "ssl_object" else extra(name, default) - ) - if mode == "late": - held.append((reader, writer)) - else: - invoke(reader, writer) - peer_ready.set() - - server.listener = await asyncio.start_server(accepted, "127.0.0.1", 0) - close_listener = server.listener.close - - def close(): - close_listener() - listener_closed.set() - - server.listener.close = close - reader, writer = await asyncio.open_connection( - "127.0.0.1", server.listener.sockets[0].getsockname()[1] - ) - await asyncio.wait_for(peer_ready.wait(), 1) - result = {} - closing = None - try: - if mode == "late": - closing = asyncio.create_task(server.close()) - await asyncio.wait_for(listener_closed.wait(), 1) - before = set(asyncio.all_tasks()) - invoke(*held[0]) - result["spawned"] = len(set(asyncio.all_tasks()) - before) - try: - await asyncio.wait_for(asyncio.shield(closing), 0.3) - result["closed"] = True - except TimeoutError: - result["closed"] = False - else: - try: - result["eof"] = await asyncio.wait_for(reader.read(1), 0.3) == b"" - except TimeoutError: - result["eof"] = False - result["pending"] = [task for task in tasks if not task.done()] - result["tracked"] = list(server.connections) - finally: - # RED must release all of its own sockets and tasks before asserting. - writer.transport.abort() - for peer in peers: - peer.transport.abort() - for task in tasks: - task.cancel() - await asyncio.gather(*tasks, return_exceptions=True) - if closing: - closing.cancel() - await asyncio.gather(closing, return_exceptions=True) - server.listener.close() - await server.listener.wait_closed() - return result - - async def test_late_accepted_callback_creates_no_work_after_relay_close(self): - """An accepted event queued before close may arrive after the shutdown - snapshot. It must abort immediately, without adding an unowned handler. - """ - result = await self.exercise_socket("late") - self.assertEqual(result["spawned"], 0) - self.assertTrue(result["closed"]) - self.assertFalse(result["pending"]) - self.assertFalse(result["tracked"]) - - async def test_cancel_before_handler_first_step_releases_tcp_peer(self): - """Cancellation before the first coroutine step cannot execute finally; - the synchronous accept owner must still close the accepted TCP peer. - """ - result = await self.exercise_socket("cancel_before_start") - self.assertTrue(result["eof"], "A cancelled-before-start relay task leaked its peer") - self.assertFalse(result["tracked"]) - - async def test_cancellation_during_tls_close_drops_tracking(self): - """Shutdown may cancel a handler already awaiting TLS close_notify. - Tracking must be removed even when cancellation interrupts its finally. - """ - entered = asyncio.Event() - - async def wait_closed(): - entered.set() - await asyncio.Event().wait() - - writer = SimpleNamespace( - get_extra_info=Mock(return_value=SimpleNamespace(selected_alpn_protocol=lambda: None)), - close=Mock(), - wait_closed=wait_closed, - transport=SimpleNamespace(abort=Mock()), - ) - server = RelayServer(None, None, None) - result = server.connected(None, writer) - task = asyncio.create_task(result) if inspect.iscoroutine(result) else result - await asyncio.wait_for(entered.wait(), 1) - task.cancel() - await asyncio.gather(task, return_exceptions=True) - retained = list(server.connections) - server.connections.clear() - self.assertFalse(retained, "Cancelled TLS closure retained the completed connection") - writer.transport.abort.assert_called() diff --git a/tests/platform/api/integration/test_relay_backend_signal.py b/tests/platform/api/integration/test_relay_backend_signal.py deleted file mode 100644 index 5c391f4b..00000000 --- a/tests/platform/api/integration/test_relay_backend_signal.py +++ /dev/null @@ -1,135 +0,0 @@ -"""CONNECT errors reach the peer, independently of backend socket cleanup. - -Both HTTP/2 peers use the real h2 state machine. Only backend read/write/drain -failures are injected; there are no network settings, external hosts or processes. -RFC 9113 section 8.5 requires CONNECT_ERROR for an abnormal backend TCP close. -""" - -import asyncio -import json -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock - -import pytest -from h2.config import H2Configuration -from h2.connection import H2Connection -from h2.errors import ErrorCodes -from h2.events import StreamEnded, StreamReset - -from throng_api.relay import _Stream - - -def connected_stream(): - """Keep a second real stream available to detect connection-wide damage.""" - client = H2Connection(H2Configuration(client_side=True, header_encoding="ascii")) - server = H2Connection(H2Configuration(client_side=False, header_encoding="ascii")) - client.initiate_connection() - server.initiate_connection() - server.receive_data(client.data_to_send()) - client.receive_data(server.data_to_send()) - for stream_id in (1, 3): - client.send_headers(stream_id, [(":method", "CONNECT"), (":authority", "local.invalid:80")]) - server.receive_data(client.data_to_send()) - for stream_id in (1, 3): - server.send_headers(stream_id, [(":status", "200")]) - client.receive_data(server.data_to_send()) - received = [] - - def flush(): - received.extend(client.receive_data(server.data_to_send())) - - connection = SimpleNamespace(h2=server, streams={}, flush=flush) - writer = SimpleNamespace(write=Mock(), drain=AsyncMock(), write_eof=Mock(), close=Mock()) - reader = SimpleNamespace(read=AsyncMock(return_value=b"")) - stream = _Stream(connection, 1, reader, writer) - connection.streams[1] = stream - return client, server, connection, stream, received - - -async def download_without_leak(stream): - """The assertion must follow cleanup even when the candidate regresses.""" - upload = asyncio.create_task(asyncio.Event().wait()) - stream.tasks = [upload] - try: - await stream.download() - finally: - upload.cancel() - await asyncio.gather(upload, return_exceptions=True) - - -@pytest.mark.anyio -@pytest.mark.parametrize("boundary", ["read", "write", "drain"]) -async def test_backend_socket_failure_resets_only_the_failed_connect(boundary, caplog): - """Read and write failures must become immediate remote errors, not timeouts. - - RST_STREAM CONNECT_ERROR preserves interrupted-content semantics. Sending - successful EOF could falsely certify a response without a Content-Length; - closing the whole connection would break an unrelated heartbeat tunnel. - """ - caplog.set_level("INFO", logger="throng.transport") - client, server, connection, stream, received = connected_stream() - if boundary == "read": - stream.reader.read.side_effect = ConnectionResetError - await download_without_leak(stream) - else: - getattr(stream.writer, boundary).side_effect = BrokenPipeError - stream.incoming.put_nowait((b"request", 7)) - await stream.upload() - resets = [event for event in received if isinstance(event, StreamReset)] - assert [(event.stream_id, event.error_code) for event in resets] == [ - (1, ErrorCodes.CONNECT_ERROR) - ] - assert not any(isinstance(event, StreamEnded) for event in received) - stream.writer.close.assert_called_once() - reason = "backend_download_error" if boundary == "read" else "backend_upload_error" - # Operational queries require this event/reason pair; additional useful - # metadata may be added without changing the close event's meaning. - rows = [json.loads(row.message) for row in caplog.records if row.name == "throng.transport"] - assert any(row.get("event") == "relay_close" and row.get("reason") == reason for row in rows) - client.send_data(3, b"unrelated heartbeat") - assert any( - getattr(event, "data", None) == b"unrelated heartbeat" - for event in server.receive_data(client.data_to_send()) - ) - - -@pytest.mark.anyio -async def test_backend_eof_remains_a_clean_stream_end(): - """An ordinary FIN is END_STREAM, not a retry-worthy CONNECT_ERROR.""" - _, _, connection, stream, received = connected_stream() - await download_without_leak(stream) - assert [event.stream_id for event in received if isinstance(event, StreamEnded)] == [1] - assert not any(isinstance(event, StreamReset) for event in received) - assert not connection.streams - stream.writer.close.assert_called_once() - - -@pytest.mark.anyio -@pytest.mark.parametrize("boundary", ["read", "write"]) -@pytest.mark.parametrize("race", ["peer_reset", "transport_write_failure"]) -async def test_backend_failure_cleanup_survives_a_simultaneously_closed_peer(boundary, race): - """Reporting an error is best effort after the peer has already gone away. - - A second reset of a closed h2 stream raises StreamClosedError. A failed outer - socket write can also raise while flushing the reset. Neither may interrupt - backend cleanup or become an unhandled stream-task exception. - """ - client, server, connection, stream, _ = connected_stream() - if race == "peer_reset": - client.reset_stream(1) - server.receive_data(client.data_to_send()) - else: - connection.flush = Mock(side_effect=BrokenPipeError) - error = None - try: - if boundary == "read": - stream.reader.read.side_effect = ConnectionResetError - await download_without_leak(stream) - else: - stream.writer.write.side_effect = BrokenPipeError - stream.incoming.put_nowait((b"request", 7)) - await stream.upload() - except Exception as failure: - error = failure - assert error is None, f"Error signaling interrupted cleanup: {type(error).__name__}" - stream.writer.close.assert_called_once() diff --git a/tests/platform/api/integration/test_relay_failures.py b/tests/platform/api/integration/test_relay_failures.py deleted file mode 100644 index 6c2dfd4e..00000000 --- a/tests/platform/api/integration/test_relay_failures.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Fault injection for OS socket failures that cannot reliably be triggered over TLS.""" - -import asyncio -import json -import os -import subprocess -import sys -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock - -import pytest - -from throng_api.relay import RelayHTTPProtocol, RelayServer, _Stream - -pytestmark = pytest.mark.anyio - - -async def test_real_http_idle_timeout_closes_and_records_reason(caplog): - """The embedded HTTP parser records the actual idle close, including its reason.""" - import uvicorn - from uvicorn.server import ServerState - - config = uvicorn.Config(lambda scope, receive, send: None, lifespan="off", log_config=None) - config.load() - protocol = RelayHTTPProtocol(config, ServerState(), {}) - transport = Mock() - transport.is_closing.return_value = False - protocol.transport = transport - caplog.set_level("INFO", logger="throng.transport") - protocol.timeout_keep_alive_handler() - transport.close.assert_called_once() - assert json.loads(caplog.records[-1].message) == { - "event": "relay_close", - "reason": "idle_timeout", - } - - -async def test_broken_backend_upload_closes_the_socket(caplog): - """An OS write failure must release the tunnel instead of retaining a blocked upload.""" - caplog.set_level("INFO", logger="throng.transport") - writer = SimpleNamespace(write=Mock(side_effect=BrokenPipeError), close=Mock()) - connection = SimpleNamespace(h2=Mock(), flush=Mock()) - stream = _Stream(connection, 1, None, writer) - stream.incoming.put_nowait((b"request", 7)) - await stream.upload() - writer.close.assert_called_once() - rows = [json.loads(row.message) for row in caplog.records if row.name == "throng.transport"] - assert any( - row.get("event") == "relay_close" and row.get("reason") == "backend_upload_error" - for row in rows - ) - - -async def test_broken_backend_download_cancels_upload_and_removes_stream(caplog): - """An OS read failure must remove the tunnel and cancel its otherwise waiting upload.""" - caplog.set_level("INFO", logger="throng.transport") - connection = SimpleNamespace(streams={}, h2=Mock(), flush=Mock()) - writer = SimpleNamespace(close=Mock()) - reader = SimpleNamespace(read=AsyncMock(side_effect=ConnectionResetError)) - stream = _Stream(connection, 1, reader, writer) - connection.streams[1] = stream - upload = asyncio.create_task(asyncio.Event().wait()) - stream.tasks = [upload] - await stream.download() - await asyncio.gather(upload, return_exceptions=True) - assert upload.cancelled() and not connection.streams - writer.close.assert_called_once() - rows = [json.loads(row.message) for row in caplog.records if row.name == "throng.transport"] - assert any( - row.get("event") == "relay_close" and row.get("reason") == "backend_download_error" - for row in rows - ) - - -async def test_tls_disconnect_error_does_not_retain_connection(): - """A peer disconnect during TLS closure must still remove the connection from shutdown tracking.""" - server = RelayServer(None, None, None) - writer = SimpleNamespace( - get_extra_info=Mock(return_value=SimpleNamespace(selected_alpn_protocol=lambda: None)), - close=Mock(), - wait_closed=AsyncMock(side_effect=ConnectionResetError), - transport=SimpleNamespace(abort=Mock()), - ) - await server.connected(None, writer) - assert not server.connections - writer.close.assert_called_once() - - -def test_selected_env_file_does_not_inherit_the_developers_relay_settings(tmp_path): - """An explicitly selected deployment config must not borrow relay keys/ports from the local .env.""" - (tmp_path / ".env").write_text("THRONG_POWERCELL_RELAY_URL=https://unrelated.invalid:8444\n") - selected = tmp_path / "isolated.env" - selected.write_text("THRONG_CONTROLLER_ENABLED=false\n") - environment = {key: value for key, value in os.environ.items() if not key.startswith("THRONG_")} - environment["THRONG_ENV_FILE"] = str(selected) - subprocess.run( - [ - sys.executable, - "-c", - "from throng_api.config import Settings; s=Settings(); " - "assert s.powercell_relay_url is None; assert not s.controller_enabled", - ], - cwd=tmp_path, - env=environment, - check=True, - capture_output=True, - ) diff --git a/tests/platform/api/integration/test_transport_observability.py b/tests/platform/api/integration/test_transport_observability.py index 1cf365a0..6f3f3bd7 100644 --- a/tests/platform/api/integration/test_transport_observability.py +++ b/tests/platform/api/integration/test_transport_observability.py @@ -8,7 +8,6 @@ import pytest from throng_api import transport -from throng_api.config import Settings from throng_api.transport import RequestLog pytestmark = pytest.mark.anyio @@ -82,11 +81,3 @@ async def app(scope, receive, send): row = json.loads(caplog.records[-1].message) assert row["status"] == 500 and row["duration_ms"] >= 0 assert "secret" not in caplog.records[-1].message - - -def test_relay_keepalive_is_explicit_and_bounded(): - """The relay idle timeout accommodates measured outages without an unbounded lifetime.""" - assert Settings(_env_file=None).powercell_relay_keep_alive_seconds == 30 - for invalid in [0, 301]: - with pytest.raises(ValueError): - Settings(powercell_relay_keep_alive_seconds=invalid, _env_file=None)