File size: 12,763 Bytes
9410704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""Tests for Speech Engine JWT verification."""

import asyncio
import base64
import hashlib
import hmac
import json
import time
import typing
import warnings

import pytest
from websockets.asyncio.client import connect as ws_connect
from websockets.exceptions import InvalidStatus

from elevenlabs.speech_engine import SpeechEngineServer
from elevenlabs.speech_engine.resource import (
    SpeechEngineResource,
    verify_speech_engine_jwt,
)

TEST_API_KEY = "test-key"
JWT_ISSUER = "https://api.elevenlabs.io/convai/speech-engine"
JWT_SUBJECT = "convai_speech_engine_upstream"


# ---------------------------------------------------------------------------
# JWT test helpers
# ---------------------------------------------------------------------------


def _base64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def _create_test_jwt(
    payload: typing.Dict[str, typing.Any],
    api_key: str = TEST_API_KEY,
) -> str:
    header = {"alg": "HS256", "typ": "JWT"}
    header_b64 = _base64url_encode(json.dumps(header).encode())
    payload_b64 = _base64url_encode(json.dumps(payload).encode())
    secret = hashlib.sha256(api_key.encode("utf-8")).digest()
    signature = hmac.new(
        secret, f"{header_b64}.{payload_b64}".encode(), hashlib.sha256
    ).digest()
    return f"{header_b64}.{payload_b64}.{_base64url_encode(signature)}"


def _valid_payload(**overrides: typing.Any) -> typing.Dict[str, typing.Any]:
    now = int(time.time())
    return {
        "iss": JWT_ISSUER,
        "sub": JWT_SUBJECT,
        "iat": now,
        "exp": now + 300,
        **overrides,
    }


# ---------------------------------------------------------------------------
# verify_speech_engine_jwt
# ---------------------------------------------------------------------------


class TestVerifySpeechEngineJwt:
    def test_valid_token(self) -> None:
        token = _create_test_jwt(_valid_payload())
        payload = verify_speech_engine_jwt(token, TEST_API_KEY)
        assert payload["iss"] == JWT_ISSUER
        assert payload["sub"] == JWT_SUBJECT

    def test_accepts_bearer_prefix(self) -> None:
        token = _create_test_jwt(_valid_payload())
        payload = verify_speech_engine_jwt(f"Bearer {token}", TEST_API_KEY)
        assert payload["iss"] == JWT_ISSUER

    def test_rejects_wrong_key(self) -> None:
        token = _create_test_jwt(_valid_payload(), api_key="other-key")
        with pytest.raises(ValueError, match="signature mismatch"):
            verify_speech_engine_jwt(token, TEST_API_KEY)

    def test_strips_residency_suffix_before_hashing(self) -> None:
        # The API signs with the base key; the server may hold the full residency key.
        token = _create_test_jwt(_valid_payload(), api_key="sk_abc123")
        payload = verify_speech_engine_jwt(token, "sk_abc123_residency_in")
        assert payload["iss"] == JWT_ISSUER

    def test_rejects_residency_key_with_wrong_base(self) -> None:
        token = _create_test_jwt(_valid_payload(), api_key="sk_other")
        with pytest.raises(ValueError, match="signature mismatch"):
            verify_speech_engine_jwt(token, "sk_abc123_residency_eu")

    def test_rejects_wrong_issuer(self) -> None:
        token = _create_test_jwt(_valid_payload(iss="https://evil.com"))
        with pytest.raises(ValueError, match="expected issuer"):
            verify_speech_engine_jwt(token, TEST_API_KEY)

    def test_rejects_wrong_subject(self) -> None:
        token = _create_test_jwt(_valid_payload(sub="wrong_subject"))
        with pytest.raises(ValueError, match="expected subject"):
            verify_speech_engine_jwt(token, TEST_API_KEY)

    def test_rejects_expired_token_beyond_leeway(self) -> None:
        now = int(time.time())
        token = _create_test_jwt(
            _valid_payload(exp=now - 120, iat=now - 420)
        )
        with pytest.raises(ValueError, match="expired"):
            verify_speech_engine_jwt(token, TEST_API_KEY)

    def test_accepts_expired_within_leeway(self) -> None:
        now = int(time.time())
        token = _create_test_jwt(
            _valid_payload(exp=now - 30, iat=now - 330)
        )
        payload = verify_speech_engine_jwt(token, TEST_API_KEY)
        assert payload["iss"] == JWT_ISSUER

    def test_rejects_future_iat_beyond_leeway(self) -> None:
        now = int(time.time())
        token = _create_test_jwt(
            _valid_payload(iat=now + 120, exp=now + 420)
        )
        with pytest.raises(ValueError, match="iat is in the future"):
            verify_speech_engine_jwt(token, TEST_API_KEY)

    def test_accepts_future_iat_within_leeway(self) -> None:
        now = int(time.time())
        token = _create_test_jwt(
            _valid_payload(iat=now + 30, exp=now + 330)
        )
        payload = verify_speech_engine_jwt(token, TEST_API_KEY)
        assert payload["iss"] == JWT_ISSUER

    def test_rejects_malformed_token(self) -> None:
        with pytest.raises(ValueError, match="expected 3 parts"):
            verify_speech_engine_jwt("not.a.valid.jwt.token", TEST_API_KEY)

    def test_rejects_missing_exp(self) -> None:
        payload = _valid_payload()
        del payload["exp"]
        token = _create_test_jwt(payload)
        with pytest.raises(ValueError, match="missing exp"):
            verify_speech_engine_jwt(token, TEST_API_KEY)

    def test_rejects_missing_iat(self) -> None:
        payload = _valid_payload()
        del payload["iat"]
        token = _create_test_jwt(payload)
        with pytest.raises(ValueError, match="missing iat"):
            verify_speech_engine_jwt(token, TEST_API_KEY)


# ---------------------------------------------------------------------------
# SpeechEngineResource.verify_request
# ---------------------------------------------------------------------------


class _FakeClientWrapper:
    def __init__(self, api_key: str) -> None:
        self._api_key = api_key

    def get_headers(self) -> dict:
        return {"xi-api-key": self._api_key}


class TestVerifyRequest:
    def test_valid_header(self) -> None:
        resource = SpeechEngineResource(
            "seng_test", client_wrapper=_FakeClientWrapper(TEST_API_KEY)
        )
        token = _create_test_jwt(_valid_payload())
        assert resource.verify_request(
            {"x-elevenlabs-speech-engine-authorization": token}
        )

    def test_missing_header(self) -> None:
        resource = SpeechEngineResource(
            "seng_test", client_wrapper=_FakeClientWrapper(TEST_API_KEY)
        )
        assert not resource.verify_request({})

    def test_no_api_key(self) -> None:
        resource = SpeechEngineResource("seng_test")
        token = _create_test_jwt(_valid_payload())
        assert not resource.verify_request(
            {"x-elevenlabs-speech-engine-authorization": token}
        )

    def test_invalid_token(self) -> None:
        resource = SpeechEngineResource(
            "seng_test", client_wrapper=_FakeClientWrapper(TEST_API_KEY)
        )
        assert not resource.verify_request(
            {"x-elevenlabs-speech-engine-authorization": "bad-token"}
        )


# ---------------------------------------------------------------------------
# SpeechEngineServer — api_key requirement
# ---------------------------------------------------------------------------


class TestServerApiKeyRequirement:
    @pytest.mark.asyncio
    async def test_raises_without_api_key(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.delenv("ELEVENLABS_API_KEY", raising=False)
        from elevenlabs.speech_engine import SpeechEngineServer

        server = SpeechEngineServer(port=0)
        with pytest.raises(RuntimeError, match="API key"):
            await server.serve()


# ---------------------------------------------------------------------------
# SpeechEngineServer — disable_auth
# ---------------------------------------------------------------------------


async def _run_server_briefly(server: SpeechEngineServer) -> asyncio.Task:
    """Start ``server`` in a background task and wait until it's listening."""
    task = asyncio.create_task(server.serve())
    # Give the server loop a moment to reach `await self._stop_event.wait()`.
    for _ in range(50):
        await asyncio.sleep(0.02)
        if server._server is not None:
            break
    return task


def _server_port(server: SpeechEngineServer) -> int:
    import socket as _socket

    # websockets.serve(host="") binds both IPv4 and IPv6; on macOS the first
    # socket is often IPv6. Prefer an IPv4 socket so the client can connect
    # via 127.0.0.1 reliably.
    ipv4 = [
        s for s in server._server.sockets if s.family == _socket.AF_INET
    ]
    chosen = ipv4[0] if ipv4 else next(iter(server._server.sockets), None)
    if chosen is None:
        raise RuntimeError("server has no sockets")
    return int(chosen.getsockname()[1])


class TestServerDisableAuth:
    @pytest.mark.asyncio
    async def test_serves_without_api_key_when_disable_auth(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.delenv("ELEVENLABS_API_KEY", raising=False)
        server = SpeechEngineServer(port=0, disable_auth=True)
        task = None
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                task = await _run_server_briefly(server)
                assert server._server is not None
        finally:
            await server.stop()
            if task is not None:
                await task

    @pytest.mark.asyncio
    async def test_emits_warning_when_disable_auth(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.delenv("ELEVENLABS_API_KEY", raising=False)
        server = SpeechEngineServer(port=0, disable_auth=True)
        task = None
        try:
            with warnings.catch_warnings(record=True) as caught:
                warnings.simplefilter("always")
                task = await _run_server_briefly(server)
                messages = [str(w.message) for w in caught]
                assert any("authentication is disabled" in m for m in messages)
        finally:
            await server.stop()
            if task is not None:
                await task

    @pytest.mark.asyncio
    async def test_accepts_unauthenticated_connection(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.delenv("ELEVENLABS_API_KEY", raising=False)

        init_ids: typing.List[str] = []

        async def on_init(conversation_id: str, session: typing.Any) -> None:
            init_ids.append(conversation_id)

        server = SpeechEngineServer(port=0, disable_auth=True, on_init=on_init)
        task = None
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                task = await _run_server_briefly(server)
            port = _server_port(server)
            async with ws_connect(f"ws://127.0.0.1:{port}") as ws:
                await ws.send(
                    json.dumps({"type": "init", "conversation_id": "conv_1"})
                )
                await asyncio.sleep(0.1)
            assert init_ids == ["conv_1"]
        finally:
            await server.stop()
            if task is not None:
                await task

    @pytest.mark.asyncio
    async def test_rejects_missing_header_when_auth_enabled(self) -> None:
        server = SpeechEngineServer(port=0, api_key=TEST_API_KEY)
        task = None
        try:
            task = await _run_server_briefly(server)
            port = _server_port(server)
            with pytest.raises(InvalidStatus) as exc:
                async with ws_connect(f"ws://127.0.0.1:{port}"):
                    pass
            assert exc.value.response.status_code == 401
        finally:
            await server.stop()
            if task is not None:
                await task

    @pytest.mark.asyncio
    async def test_rejects_invalid_jwt_when_auth_enabled(self) -> None:
        server = SpeechEngineServer(port=0, api_key=TEST_API_KEY)
        task = None
        try:
            task = await _run_server_briefly(server)
            port = _server_port(server)
            with pytest.raises(InvalidStatus) as exc:
                async with ws_connect(
                    f"ws://127.0.0.1:{port}",
                    additional_headers={
                        "X-Elevenlabs-Speech-Engine-Authorization": "not.a.jwt"
                    },
                ):
                    pass
            assert exc.value.response.status_code == 401
        finally:
            await server.stop()
            if task is not None:
                await task