-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathtest_client.py
More file actions
647 lines (508 loc) · 20.9 KB
/
test_client.py
File metadata and controls
647 lines (508 loc) · 20.9 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# SPDX-FileCopyrightText: © 2025 Phala Network <[email protected]>
#
# SPDX-License-Identifier: Apache-2.0
import hashlib
import os
import warnings
from evidence_api.tdx.quote import TdxQuote
import httpx
import pytest
from dstack_sdk import AsyncDstackClient
from dstack_sdk import AsyncTappdClient
from dstack_sdk import AttestResponse
from dstack_sdk import DstackClient
from dstack_sdk import GetKeyResponse
from dstack_sdk import GetQuoteResponse
from dstack_sdk import GetTlsKeyResponse
from dstack_sdk import SignResponse
from dstack_sdk import TappdClient
from dstack_sdk import VerifyResponse
from dstack_sdk import VersionResponse
from dstack_sdk.dstack_client import InfoResponse
from dstack_sdk.dstack_client import TcbInfo
def test_sync_client_get_key():
client = DstackClient()
result = client.get_key() # Test default algorithm (secp256k1)
assert isinstance(result, GetKeyResponse)
assert isinstance(result.decode_key(), bytes)
assert len(result.decode_key()) == 32
# Test specifying algorithm
result_ed = client.get_key(algorithm="ed25519")
assert isinstance(result_ed, GetKeyResponse)
assert len(result_ed.decode_key()) == 32
with pytest.raises(Exception): # Assuming unsupported algo raises error
client.get_key(algorithm="rsa")
def test_sync_client_get_quote():
client = DstackClient()
result = client.get_quote("test")
assert isinstance(result, GetQuoteResponse)
def test_sync_client_attest():
client = DstackClient()
result = client.attest("test")
assert isinstance(result, AttestResponse)
assert len(result.attestation) > 0
def test_sync_client_get_tls_key():
client = DstackClient()
result = client.get_tls_key()
assert isinstance(result, GetTlsKeyResponse)
assert isinstance(result.key, str)
assert len(result.key) > 0
assert len(result.certificate_chain) > 0
def test_sync_client_get_info():
client = DstackClient()
result = client.info()
check_info_response(result)
def check_info_response(result: InfoResponse):
assert isinstance(result, InfoResponse)
assert isinstance(result.app_id, str)
assert isinstance(result.instance_id, str)
assert isinstance(result.tcb_info, TcbInfo)
assert len(result.tcb_info.mrtd) == 96
assert len(result.tcb_info.rtmr0) == 96
assert len(result.tcb_info.rtmr1) == 96
assert len(result.tcb_info.rtmr2) == 96
assert len(result.tcb_info.rtmr3) == 96
assert len(result.tcb_info.compose_hash) == 64
assert len(result.tcb_info.device_id) == 64
assert len(result.tcb_info.app_compose) > 0
assert len(result.tcb_info.event_log) > 0
@pytest.mark.asyncio
async def test_async_client_get_key():
client = AsyncDstackClient()
result = await client.get_key() # Test default algorithm (secp256k1)
assert isinstance(result, GetKeyResponse)
assert isinstance(result.decode_key(), bytes)
assert len(result.decode_key()) == 32
# Test specifying algorithm
result_ed = await client.get_key(algorithm="ed25519")
assert isinstance(result_ed, GetKeyResponse)
assert len(result_ed.decode_key()) == 32
with pytest.raises(Exception): # Assuming unsupported algo raises error
await client.get_key(algorithm="rsa")
@pytest.mark.asyncio
async def test_async_client_get_quote():
client = AsyncDstackClient()
result = await client.get_quote("test")
assert isinstance(result, GetQuoteResponse)
@pytest.mark.asyncio
async def test_async_client_attest():
client = AsyncDstackClient()
result = await client.attest("test")
assert isinstance(result, AttestResponse)
assert len(result.attestation) > 0
@pytest.mark.asyncio
async def test_async_client_get_tls_key():
client = AsyncDstackClient()
result = await client.get_tls_key()
assert isinstance(result, GetTlsKeyResponse)
assert isinstance(result.key, str)
assert result.key.startswith("-----BEGIN PRIVATE KEY-----")
assert len(result.certificate_chain) > 0
@pytest.mark.asyncio
async def test_async_client_get_info():
client = AsyncDstackClient()
result = await client.info()
check_info_response(result)
@pytest.mark.asyncio
async def test_tls_key_uniqueness():
"""Test that TLS keys are unique across multiple calls."""
client = AsyncDstackClient()
result1 = await client.get_tls_key()
result2 = await client.get_tls_key()
# TLS keys should be unique for each call
assert result1.key != result2.key
@pytest.mark.asyncio
async def test_replay_rtmr():
client = AsyncDstackClient()
result = await client.get_quote("test")
# TODO evidence_api is a bit out-of-date, we need an up-to-date implementation.
tdxQuote = TdxQuote(bytearray(bytes.fromhex(result.quote)))
rtmrs = result.replay_rtmrs()
assert rtmrs[0] == tdxQuote.body.rtmr0.hex()
assert rtmrs[1] == tdxQuote.body.rtmr1.hex()
assert rtmrs[2] == tdxQuote.body.rtmr2.hex()
assert rtmrs[3] == tdxQuote.body.rtmr3.hex()
@pytest.mark.asyncio
async def test_get_quote_raw_hash_error():
with pytest.raises(ValueError) as excinfo:
client = AsyncDstackClient()
await client.get_quote("0" * 65)
assert "64 bytes" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
client = AsyncDstackClient()
await client.get_quote(b"0" * 129)
assert "64 bytes" in str(excinfo.value)
@pytest.mark.asyncio
async def test_report_data():
reportdata = "test"
client = AsyncDstackClient()
result = await client.get_quote(reportdata)
tdxQuote = TdxQuote(bytearray(result.decode_quote()))
reportdata = reportdata.encode("utf-8") + b"\x00" * (64 - len(reportdata))
assert reportdata == tdxQuote.body.reportdata
def test_sync_client_is_reachable():
"""Test that sync client can check if service is reachable."""
client = DstackClient()
is_reachable = client.is_reachable()
assert isinstance(is_reachable, bool)
assert is_reachable
@pytest.mark.asyncio
async def test_async_client_is_reachable():
"""Test that async client can check if service is reachable."""
client = AsyncDstackClient()
is_reachable = await client.is_reachable()
assert isinstance(is_reachable, bool)
assert is_reachable
def test_tls_key_as_uint8array():
"""Test that TLS key can be converted to bytes with as_uint8array method."""
client = DstackClient()
result = client.get_tls_key()
# Test full length
full_bytes = result.as_uint8array()
assert isinstance(full_bytes, bytes)
assert len(full_bytes) > 0
# Test with max_length
key_32 = result.as_uint8array(32)
assert isinstance(key_32, bytes)
assert len(key_32) == 32
assert len(key_32) != len(full_bytes)
def test_tls_key_with_alt_names():
"""Test TLS key generation with alt names."""
client = DstackClient()
alt_names = ["localhost", "127.0.0.1"]
result = client.get_tls_key(
subject="test-subject",
alt_names=alt_names,
usage_ra_tls=True,
usage_server_auth=True,
usage_client_auth=True,
)
assert isinstance(result, GetTlsKeyResponse)
assert result.key is not None
assert len(result.certificate_chain) > 0
def test_unix_socket_file_not_exist():
"""Test that client raises error when Unix socket file doesn't exist."""
# Temporarily remove environment variable to test file check
import os
saved_env = os.environ.get("DSTACK_SIMULATOR_ENDPOINT")
if "DSTACK_SIMULATOR_ENDPOINT" in os.environ:
del os.environ["DSTACK_SIMULATOR_ENDPOINT"]
try:
with pytest.raises(FileNotFoundError) as exc_info:
DstackClient("/non/existent/socket")
assert "Unix socket file /non/existent/socket does not exist" in str(
exc_info.value
)
finally:
# Restore environment variable
if saved_env:
os.environ["DSTACK_SIMULATOR_ENDPOINT"] = saved_env
def assert_emit_event_behavior(error: Exception | None) -> None:
if "DSTACK_SIMULATOR_ENDPOINT" in os.environ:
assert isinstance(error, httpx.HTTPStatusError)
assert error.response.status_code == 400
else:
assert error is None, f"emit_event unexpectedly failed: {error}"
def test_non_unix_socket_endpoints():
"""Test that client doesn't throw error for non-unix socket paths."""
import os
saved_env = os.environ.get("DSTACK_SIMULATOR_ENDPOINT")
if "DSTACK_SIMULATOR_ENDPOINT" in os.environ:
del os.environ["DSTACK_SIMULATOR_ENDPOINT"]
try:
# These should not raise errors
client1 = DstackClient("http://localhost:8080")
client2 = DstackClient("https://example.com")
assert client1 is not None
assert client2 is not None
finally:
# Restore environment variable
if saved_env:
os.environ["DSTACK_SIMULATOR_ENDPOINT"] = saved_env
@pytest.mark.asyncio
async def test_emit_event():
"""Test emit event functionality."""
client = AsyncDstackClient()
error = None
try:
await client.emit_event("test-event", "test payload")
await client.emit_event("test-event-bytes", b"test payload bytes")
except Exception as exc: # pragma: no cover - behavior depends on runtime mode
error = exc
assert_emit_event_behavior(error)
def test_sync_emit_event():
"""Test sync emit event functionality."""
client = DstackClient()
error = None
try:
client.emit_event("test-event", "test payload")
client.emit_event("test-event-bytes", b"test payload bytes")
except Exception as exc: # pragma: no cover - behavior depends on runtime mode
error = exc
assert_emit_event_behavior(error)
def test_emit_event_validation():
"""Test emit event input validation."""
client = DstackClient()
# Empty event name should raise error
with pytest.raises(ValueError) as exc_info:
client.emit_event("", "payload")
assert "event name cannot be empty" in str(exc_info.value)
SIGN_TEST_DATA = b"Test message for signing"
SIGN_BAD_DATA = b"This is not the original message"
def test_sync_sign_verify_ed25519():
client = DstackClient()
algo = "ed25519"
sign_resp = client.sign(algo, SIGN_TEST_DATA)
assert isinstance(sign_resp, SignResponse)
assert len(sign_resp.decode_signature()) > 0
assert len(sign_resp.decode_public_key()) > 0
assert len(sign_resp.signature_chain) > 0
verify_resp = client.verify(
algo,
SIGN_TEST_DATA,
sign_resp.decode_signature(),
sign_resp.decode_public_key(),
)
assert isinstance(verify_resp, VerifyResponse)
assert verify_resp.valid is True
verify_bad = client.verify(
algo, SIGN_BAD_DATA, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_bad.valid is False
def test_sync_sign_verify_secp256k1():
client = DstackClient()
algo = "secp256k1"
sign_resp = client.sign(algo, SIGN_TEST_DATA)
assert isinstance(sign_resp, SignResponse)
verify_resp = client.verify(
algo,
SIGN_TEST_DATA,
sign_resp.decode_signature(),
sign_resp.decode_public_key(),
)
assert verify_resp.valid is True
verify_bad = client.verify(
algo, SIGN_BAD_DATA, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_bad.valid is False
def test_sync_sign_verify_secp256k1_prehashed():
client = DstackClient()
algo = "secp256k1_prehashed"
digest = hashlib.sha256(SIGN_TEST_DATA).digest()
assert len(digest) == 32
sign_resp = client.sign(algo, digest)
assert isinstance(sign_resp, SignResponse)
verify_resp = client.verify(
algo, digest, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_resp.valid is True
bad_digest = hashlib.sha256(SIGN_BAD_DATA).digest()
verify_bad = client.verify(
algo, bad_digest, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_bad.valid is False
def test_sync_sign_prehashed_length_error():
client = DstackClient()
algo = "secp256k1_prehashed"
with pytest.raises(ValueError) as excinfo:
client.sign(algo, b"too short")
assert "32-byte digest" in str(excinfo.value)
@pytest.mark.asyncio
async def test_async_sign_verify_ed25519():
client = AsyncDstackClient()
algo = "ed25519"
sign_resp = await client.sign(algo, SIGN_TEST_DATA)
assert isinstance(sign_resp, SignResponse)
assert len(sign_resp.decode_signature()) > 0
assert len(sign_resp.decode_public_key()) > 0
verify_resp = await client.verify(
algo,
SIGN_TEST_DATA,
sign_resp.decode_signature(),
sign_resp.decode_public_key(),
)
assert verify_resp.valid is True
verify_bad = await client.verify(
algo, SIGN_BAD_DATA, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_bad.valid is False
@pytest.mark.asyncio
async def test_async_sign_verify_secp256k1():
client = AsyncDstackClient()
algo = "secp256k1"
sign_resp = await client.sign(algo, SIGN_TEST_DATA)
assert isinstance(sign_resp, SignResponse)
verify_resp = await client.verify(
algo,
SIGN_TEST_DATA,
sign_resp.decode_signature(),
sign_resp.decode_public_key(),
)
assert verify_resp.valid is True
verify_bad = await client.verify(
algo, SIGN_BAD_DATA, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_bad.valid is False
@pytest.mark.asyncio
async def test_async_sign_verify_secp256k1_prehashed():
client = AsyncDstackClient()
algo = "secp256k1_prehashed"
digest = hashlib.sha256(SIGN_TEST_DATA).digest()
sign_resp = await client.sign(algo, digest)
assert isinstance(sign_resp, SignResponse)
verify_resp = await client.verify(
algo, digest, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_resp.valid is True
bad_digest = hashlib.sha256(SIGN_BAD_DATA).digest()
verify_bad = await client.verify(
algo, bad_digest, sign_resp.decode_signature(), sign_resp.decode_public_key()
)
assert verify_bad.valid is False
@pytest.mark.asyncio
async def test_async_sign_prehashed_length_error():
client = AsyncDstackClient()
algo = "secp256k1_prehashed"
with pytest.raises(ValueError) as excinfo:
await client.sign(algo, b"too short")
assert "32-byte digest" in str(excinfo.value)
# Test deprecated TappdClient
def test_tappd_client_deprecated():
"""Test that TappdClient shows deprecation warning."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
TappdClient()
# Filter for TappdClient deprecation warnings specifically
tappd_warnings = [
warning
for warning in w
if issubclass(warning.category, DeprecationWarning)
and "TappdClient is deprecated" in str(warning.message)
]
assert len(tappd_warnings) == 1
assert "TappdClient is deprecated" in str(tappd_warnings[0].message)
def test_tappd_client_derive_key_deprecated():
"""Test that TappdClient.derive_key shows deprecation warning."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
client = TappdClient()
client.derive_key("/", "test")
# Should have warnings for both constructor and derive_key
warning_messages = [str(warning.message) for warning in w]
assert any("TappdClient is deprecated" in msg for msg in warning_messages)
assert any("derive_key is deprecated" in msg for msg in warning_messages)
def test_tappd_client_tdx_quote_deprecated():
"""Test that TappdClient.tdx_quote shows deprecation warning."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
client = TappdClient()
client.tdx_quote("test data", "raw")
# Should have warnings for both constructor and tdx_quote
warning_messages = [str(warning.message) for warning in w]
assert any("TappdClient is deprecated" in msg for msg in warning_messages)
assert any("tdx_quote is deprecated" in msg for msg in warning_messages)
# Test AsyncTappdClient
def test_async_tappd_client_deprecated():
"""Test that AsyncTappdClient shows deprecation warning."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
AsyncTappdClient()
# Filter for AsyncTappdClient deprecation warnings specifically
tappd_warnings = [
warning
for warning in w
if issubclass(warning.category, DeprecationWarning)
and "AsyncTappdClient is deprecated" in str(warning.message)
]
assert len(tappd_warnings) == 1
assert "AsyncTappdClient is deprecated" in str(tappd_warnings[0].message)
@pytest.mark.asyncio
async def test_async_tappd_client_derive_key_deprecated():
"""Test that AsyncTappdClient.derive_key shows deprecation warning."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
client = AsyncTappdClient()
await client.derive_key("/", "test")
# Should have warnings for both constructor and derive_key
warning_messages = [str(warning.message) for warning in w]
assert any("AsyncTappdClient is deprecated" in msg for msg in warning_messages)
assert any("derive_key is deprecated" in msg for msg in warning_messages)
@pytest.mark.asyncio
async def test_async_tappd_client_tdx_quote_deprecated():
"""Test that AsyncTappdClient.tdx_quote shows deprecation warning."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
client = AsyncTappdClient()
await client.tdx_quote("test data", "raw")
# Should have warnings for both constructor and tdx_quote
warning_messages = [str(warning.message) for warning in w]
assert any("AsyncTappdClient is deprecated" in msg for msg in warning_messages)
assert any("tdx_quote is deprecated" in msg for msg in warning_messages)
def test_sync_client_version():
client = DstackClient()
result = client.version()
assert isinstance(result, VersionResponse)
assert result.version != ""
@pytest.mark.asyncio
async def test_async_client_version():
client = AsyncDstackClient()
result = await client.version()
assert isinstance(result, VersionResponse)
assert result.version != ""
def test_sync_client_get_key_k256_alias():
client = DstackClient()
result_k256 = client.get_key(path="/test", purpose="p", algorithm="k256")
result_secp = client.get_key(path="/test", purpose="p", algorithm="secp256k1")
# k256 is an alias for secp256k1, should produce the same key
assert result_k256.decode_key() == result_secp.decode_key()
@pytest.mark.asyncio
async def test_async_client_get_key_k256_alias():
client = AsyncDstackClient()
result_k256 = await client.get_key(path="/test", purpose="p", algorithm="k256")
result_secp = await client.get_key(path="/test", purpose="p", algorithm="secp256k1")
assert result_k256.decode_key() == result_secp.decode_key()
def test_sync_client_get_key_secp256k1_prehashed_rejected():
client = DstackClient()
with pytest.raises(Exception):
client.get_key(algorithm="secp256k1_prehashed")
@pytest.mark.asyncio
async def test_async_client_get_key_secp256k1_prehashed_rejected():
client = AsyncDstackClient()
with pytest.raises(Exception):
await client.get_key(algorithm="secp256k1_prehashed")
@pytest.mark.asyncio
async def test_async_tappd_client_is_reachable():
"""Test that AsyncTappdClient can check if service is reachable."""
client = AsyncTappdClient()
is_reachable = await client.is_reachable()
assert isinstance(is_reachable, bool)
assert is_reachable
# Test sync client called from async context
@pytest.mark.asyncio
async def test_sync_client_in_async_context_get_key():
"""Test that sync client works when called from async context."""
client = DstackClient()
result = client.get_key()
assert isinstance(result, GetKeyResponse)
assert isinstance(result.decode_key(), bytes)
assert len(result.decode_key()) == 32
@pytest.mark.asyncio
async def test_sync_client_in_async_context_get_info():
"""Test that sync client info works when called from async context."""
client = DstackClient()
result = client.info()
check_info_response(result)
@pytest.mark.asyncio
async def test_mixed_sync_async_calls():
"""Test mixing sync and async client calls in the same async context."""
sync_client = DstackClient()
async_client = AsyncDstackClient()
# Call sync client from async context
sync_result = sync_client.get_key()
assert isinstance(sync_result, GetKeyResponse)
# Call async client normally
async_result = await async_client.get_key()
assert isinstance(async_result, GetKeyResponse)
# Both should work and return valid results
assert len(sync_result.decode_key()) == 32
assert len(async_result.decode_key()) == 32