"""Chaves nomeadas, escopos e /v1/status (ADR 0027 §9 e §10).""" import hashlib import json import sys from dataclasses import replace import pytest from app import keys from app.keys import KEY_RE, issue_key, keys_path, revoke_key from tests.conftest import HEADERS, KEY, body pytestmark = pytest.mark.anyio def _issue(settings, scopes, name="backend-test"): record, plaintext = issue_key(keys_path(settings.data_dir), name, tuple(scopes)) return record, {"X-Service-Key": plaintext} def test_issued_key_has_the_contract_format_and_only_its_hash_is_stored(settings): record, plaintext = issue_key(keys_path(settings.data_dir), "backend-test", ("tts", "status")) match = KEY_RE.fullmatch(plaintext) assert match and match.group(1) == record.key_id stored = keys_path(settings.data_dir).read_text(encoding="utf-8") secret = match.group(2) assert secret not in stored and plaintext not in stored entry = json.loads(stored)["keys"][0] assert set(entry) == {"keyId", "name", "scopes", "secretSha256", "createdAt", "revokedAt"} assert entry["scopes"] == ["status", "tts"] and entry["revokedAt"] is None if sys.platform != "win32": # permissão POSIX; no Windows o arquivo herda a ACL da pasta do usuário assert (keys_path(settings.data_dir).stat().st_mode & 0o077) == 0 # 0600 async def test_env_key_keeps_working_with_every_scope(make_client): async with make_client() as client: status = await client.get("/v1/status", headers=HEADERS) synth = await client.post("/v1/synthesize", headers=HEADERS, json=body()) health = await client.get("/health", headers=HEADERS) assert status.status_code == 200 and synth.status_code == 200 and health.status_code == 200 assert status.json()["key"] == {"keyId": "env", "name": "env", "scopes": ["admin", "convert", "status", "transcribe", "tts"]} async def test_key_issued_while_running_works_without_restart(make_client, settings): async with make_client() as client: _, headers = _issue(settings, ["tts"]) response = await client.post("/v1/synthesize", headers=headers, json=body()) assert response.status_code == 200 async def test_revoked_key_stops_working_without_restart(make_client, settings): async with make_client() as client: record, headers = _issue(settings, ["tts", "status"]) assert (await client.get("/v1/voices", headers=headers)).status_code == 200 revoke_key(keys_path(settings.data_dir), record.key_id) response = await client.get("/v1/voices", headers=headers) env = await client.get("/v1/voices", headers=HEADERS) assert response.status_code == 401 and response.json()["error"]["code"] == "unauthorized" assert env.status_code == 200 @pytest.mark.parametrize( ("method", "path", "scope"), [ ("GET", "/v1/status", "status"), ("POST", "/v1/transcribe", "transcribe"), ("GET", "/v1/transcribe/jobs/abcdefgh12", "transcribe"), ], ) async def test_key_without_route_scope_is_403(make_client, settings, method, path, scope): async with make_client() as client: _, headers = _issue(settings, ["tts"]) response = await client.request(method, path, headers=headers) assert response.status_code == 403 assert response.json() == { "error": {"code": "insufficient_scope", "message": "A chave não tem o escopo desta operação.", "requiredScope": scope} } async def test_transcribe_only_key_cannot_synthesize_nor_list_voices(make_client, settings): async with make_client() as client: _, headers = _issue(settings, ["transcribe"]) synth = await client.post("/v1/synthesize", headers=headers, json=body()) voices = await client.get("/v1/voices/pt-br-test", headers=headers) assert synth.status_code == 403 and voices.status_code == 403 async def test_unknown_route_is_404_with_valid_key_and_401_without(make_client, settings): async with make_client() as client: _, headers = _issue(settings, ["tts"]) known_key = await client.get("/rota-que-nao-existe", headers=headers) no_key = await client.get("/rota-que-nao-existe") assert known_key.status_code == 404 and no_key.status_code == 401 async def test_wrong_secret_for_existing_key_id_is_401(make_client, settings): async with make_client() as client: record, _ = _issue(settings, ["tts"]) forged = {"X-Service-Key": f"dvk_{record.key_id}_{'A' * 43}"} response = await client.get("/v1/voices", headers=forged) assert response.status_code == 401 async def test_corrupted_key_file_fails_closed_but_env_key_recovers(make_client, settings): async with make_client() as client: _, headers = _issue(settings, ["tts"]) assert (await client.get("/v1/voices", headers=headers)).status_code == 200 keys_path(settings.data_dir).write_text("{nao-e-json", encoding="utf-8") named = await client.get("/v1/voices", headers=headers) env = await client.get("/v1/voices", headers=HEADERS) assert named.status_code == 401 and env.status_code == 200 async def test_status_exposes_operations_queues_voices_and_key(make_client, settings): async with make_client() as client: record, headers = _issue(settings, ["status", "tts"], name="srv-1") response = await client.get("/v1/status", headers=headers) assert response.status_code == 200 and response.headers["cache-control"] == "no-store" data = response.json() assert set(data) == {"status", "version", "device", "rvc", "azure", "engines", "operations", "queues", "voices", "key"} assert data["operations"] == ["tts", "transcribe"] assert data["engines"] == {"tts": "fake", "transcribe": "fake-stt"} assert data["queues"]["synthesis"] == {"running": 0, "waiting": 0, "maxConcurrency": 1, "maxQueue": 4} assert data["queues"]["transcription"]["maxQueue"] == 4 # padrão do CenaForge (episódios longos) assert data["voices"]["count"] == 1 and len(data["voices"]["catalogHash"]) == 64 assert data["voices"]["items"] == [{"id": "pt-br-test", "revision": data["voices"]["items"][0]["revision"], "operations": ["tts"]}] assert data["key"] == {"keyId": record.key_id, "name": "srv-1", "scopes": ["status", "tts"]} text = response.text for leak in (str(settings.data_dir), str(settings.models_dir), KEY, headers["X-Service-Key"], record.secret_sha256): assert leak not in text async def test_status_catalog_hash_is_stable_and_follows_revision(make_client, settings): async with make_client() as client: first = (await client.get("/v1/status", headers=HEADERS)).json()["voices"]["catalogHash"] again = (await client.get("/v1/status", headers=HEADERS)).json()["voices"]["catalogHash"] assert first == again lock = json.loads(settings.lock_path.read_text()) (settings.models_dir / "piper" / "fake.onnx").write_bytes(b"outro-modelo") lock["files"][0]["sha256"] = hashlib.sha256(b"outro-modelo").hexdigest() settings.lock_path.write_text(json.dumps(lock)) async with make_client() as client: changed = (await client.get("/v1/status", headers=HEADERS)).json()["voices"]["catalogHash"] assert changed != first async def test_status_without_stt_omits_transcribe(make_client): async with make_client(stt=None) as client: data = (await client.get("/v1/status", headers=HEADERS)).json() assert data["operations"] == ["tts"] assert data["engines"]["transcribe"] is None and data["queues"]["transcription"] is None @pytest.fixture def rvc_settings(settings, tmp_path): # No CenaForge o RVC vive nas vozes de personagem do usuário (voz base + .pth), não no catálogo base. (settings.models_dir / "rvc").mkdir(parents=True, exist_ok=True) (settings.models_dir / "rvc" / "fake.pth").write_bytes(b"pth") path = tmp_path / "user-voices.json" path.write_text(json.dumps({"voices": [{ "id": "heroi", "name": "Herói", "baseVoice": "pt-br-test", "rvc": {"model": "rvc/fake.pth", "modelSha256": hashlib.sha256(b"pth").hexdigest()}, }]})) return replace(settings, user_catalog_path=path, enable_rvc=True) async def test_rvc_voice_requires_convert_scope(make_client, rvc_settings): async with make_client(user_catalog_path=rvc_settings.user_catalog_path, enable_rvc=True) as client: _, headers = _issue(rvc_settings, ["tts", "status"]) synth = await client.post("/v1/synthesize", headers=headers, json=body(voiceId="heroi")) status = (await client.get("/v1/status", headers=headers)).json() assert synth.status_code == 403 assert synth.json()["error"] == { "code": "insufficient_scope", "message": "A chave não tem o escopo desta operação.", "requiredScope": "convert" } assert status["operations"] == ["tts", "transcribe", "convert"] assert status["voices"]["items"][0]["operations"] == ["tts", "convert"] # ---------- CLI ---------- def test_cli_create_prints_key_once_and_list_never_shows_secret(settings, monkeypatch, capsys): monkeypatch.setenv("VOICE_DATA_DIR", str(settings.data_dir)) assert keys.main(["create", "--name", "backend-prod", "--scopes", "tts,transcribe,status"]) == 0 created = capsys.readouterr().out plaintext = next(line for line in created.splitlines() if line.startswith("dvk_")) assert KEY_RE.fullmatch(plaintext) assert keys.main(["list"]) == 0 listed = json.loads(capsys.readouterr().out) assert listed[0]["name"] == "backend-prod" and listed[0]["scopes"] == ["status", "transcribe", "tts"] assert "secretSha256" not in listed[0] and plaintext not in json.dumps(listed) key_id = listed[0]["keyId"] assert keys.main(["revoke", key_id]) == 0 assert key_id in capsys.readouterr().out assert keys.main(["list"]) == 0 assert json.loads(capsys.readouterr().out)[0]["revokedAt"] is not None @pytest.mark.parametrize( "argv", [ ["create", "--name", "x", "--scopes", "root"], ["create", "--name", "x", "--scopes", ""], ["create", "--name", "nome com espaço", "--scopes", "tts"], ["revoke", "nao-e-um-id"], ], ) def test_cli_rejects_bad_input(settings, monkeypatch, argv): monkeypatch.setenv("VOICE_DATA_DIR", str(settings.data_dir)) assert keys.main(argv) == 2 assert not keys_path(settings.data_dir).exists() def test_cli_revoke_unknown_key_id_is_1(settings, monkeypatch): monkeypatch.setenv("VOICE_DATA_DIR", str(settings.data_dir)) assert keys.main(["revoke", "abcdefghijkl"]) == 1