phala-tee-deploy-rs 0.2.0

Rust client for deploying and managing Docker containers on Phala TEE Cloud (dstack)
Documentation
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
use super::*;
use serde_json::json;
use std::collections::HashMap;
use std::time::Duration;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// Helper function to create a test configuration
fn create_test_config(api_url: String) -> DeploymentConfig {
    let mut env_vars = HashMap::new();
    env_vars.insert("TEST_KEY".to_string(), "test_value".to_string());
    env_vars.insert("ANOTHER_KEY".to_string(), "another_value".to_string());

    DeploymentConfig::new(
        "test_api_key".to_string(),
        "version: '3'".to_string(),
        env_vars,
        1,
        "test-image:latest".to_string(),
    )
    .with_api_url(api_url)
}

#[tokio::test]
async fn test_successful_deployment_flow() {
    let mock_server = MockServer::start().await;

    // Mock the pubkey endpoint with a full PubkeyResponse body
    Mock::given(method("POST"))
        .and(path("/cvms/pubkey/from_cvm_configuration"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "app_env_encrypt_pubkey": format!("0x{}", hex::encode([1u8; 32])),
            "app_id": "app_1",
            "app_id_salt": "test_salt",
            "compose_manifest": { "name": "test", "features": [], "docker_compose_file": "" },
            "disk_size": 10,
            "encrypted_env": "",
            "image": "test:latest",
            "listed": false,
            "memory": 1024,
            "name": "test",
            "teepod_id": 1,
            "vcpu": 1
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Mock the deployment endpoint with validation
    Mock::given(method("POST"))
        .and(path("/cvms/from_cvm_configuration"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": 123,
            "status": "pending",
            "details": {
                "deployment_time": "2024-03-14T12:00:00Z"
            }
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();
    let result = client.deploy().await.unwrap();

    assert_eq!(result.id, 123);
    assert_eq!(result.status, "pending");
}

#[tokio::test]
async fn test_api_error_handling() {
    let mock_server = MockServer::start().await;

    // Mock API error response
    Mock::given(method("POST"))
        .and(path("/cvms/pubkey/from_cvm_configuration"))
        .respond_with(ResponseTemplate::new(422).set_body_json(json!({
            "error": "Invalid configuration"
        })))
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();
    let result = client.deploy().await;

    assert!(matches!(
        result,
        Err(Error::Api {
            status_code: 422,
            ..
        })
    ));
}

#[tokio::test]
async fn test_timeout_handling() {
    let mock_server = MockServer::start().await;

    // Mock delayed response beyond timeout
    Mock::given(method("POST"))
        .and(path("/cvms/pubkey/from_cvm_configuration"))
        .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(6)))
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();
    let result = client.deploy().await;

    assert!(matches!(result, Err(Error::HttpClient(_))));
}

#[tokio::test]
async fn test_get_available_teepods() {
    let mock_server = MockServer::start().await;

    // Mock the teepods available endpoint
    Mock::given(method("GET"))
        .and(path("/teepods/available"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "capacity": { "max_disk": 100, "max_instances": 10, "max_memory": 65536, "max_vcpu": 16 },
            "tier": "pro",
            "nodes": [
                {
                    "teepod_id": 123,
                    "listed": true,
                    "name": "test-node",
                    "remaining_cvm_slots": 5,
                    "remaining_memory": 32768.0,
                    "remaining_vcpu": 8.0,
                    "resource_score": 0.8,
                    "images": [
                        {
                            "name": "test-image:latest",
                            "bios": "bios.bin",
                            "cmdline": "",
                            "description": "test image",
                            "hda": null,
                            "initrd": "initrd.img",
                            "is_dev": false,
                            "kernel": "vmlinuz",
                            "rootfs": "rootfs.img",
                            "rootfs_hash": "abc123",
                            "shared_ro": false,
                            "version": [1, 0, 0]
                        }
                    ]
                }
            ]
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();
    let result = client.get_available_teepods().await.unwrap();

    assert_eq!(result.nodes[0].teepod_id, 123);
    assert_eq!(result.nodes[0].images[0].name, "test-image:latest");
}

#[tokio::test]
async fn test_get_available_teepods_error() {
    let mock_server = MockServer::start().await;

    // Mock error response
    Mock::given(method("GET"))
        .and(path("/teepods/available"))
        .respond_with(ResponseTemplate::new(403).set_body_json(json!({
            "error": "Unauthorized access"
        })))
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();
    let result = client.get_available_teepods().await;

    assert!(matches!(
        result,
        Err(Error::Api {
            status_code: 403,
            ..
        })
    ));
}

#[tokio::test]
async fn test_get_pubkey_for_config() {
    let mock_server = MockServer::start().await;

    // Mock the pubkey endpoint with a full PubkeyResponse body
    Mock::given(method("POST"))
        .and(path("/cvms/pubkey/from_cvm_configuration"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "app_env_encrypt_pubkey": format!("0x{}", hex::encode([1u8; 32])),
            "app_id": "app_1",
            "app_id_salt": "test_salt",
            "compose_manifest": { "name": "test", "features": [], "docker_compose_file": "" },
            "disk_size": 10,
            "encrypted_env": "",
            "image": "test:latest",
            "listed": false,
            "memory": 1024,
            "name": "test",
            "teepod_id": 1,
            "vcpu": 1
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();

    let vm_config = json!({
        "name": "test-vm",
        "compose_manifest": {
            "docker_compose_file": "version: '3'",
            "name": "test"
        },
        "teepod_id": 123,
        "image": "test-image:latest"
    });

    let result = client.get_pubkey_for_config(&vm_config).await.unwrap();

    assert_eq!(result.app_id_salt, "test_salt");
    assert!(result.app_env_encrypt_pubkey.starts_with("0x"));
}

#[tokio::test]
async fn test_deploy_with_config() {
    let mock_server = MockServer::start().await;

    // Mock the deployment endpoint
    Mock::given(method("POST"))
        .and(path("/cvms/from_cvm_configuration"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": 123,
            "status": "creating",
            "details": {
                "creation_time": "2024-03-14T12:00:00Z"
            }
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();

    let vm_config = json!({
        "name": "test-vm",
        "compose_manifest": {
            "docker_compose_file": "version: '3'",
            "name": "test"
        },
        "teepod_id": 123,
        "image": "test-image:latest"
    });

    let env_vars = vec![
        ("TEST_KEY".to_string(), "test_value".to_string()),
        ("DEBUG".to_string(), "true".to_string()),
    ];

    // Public key that would normally come from the API
    let pubkey = format!("0x{}", hex::encode([1u8; 32]));

    let result = client
        .deploy_with_config_do_encrypt(vm_config, &env_vars, &pubkey, "test_salt")
        .await
        .unwrap();

    assert_eq!(result.id, 123);
    assert_eq!(result.status, "creating");
    assert!(result.details.is_some());
}

#[tokio::test]
async fn test_deploy_with_config_error() {
    let mock_server = MockServer::start().await;

    // Mock deployment error
    Mock::given(method("POST"))
        .and(path("/cvms/from_cvm_configuration"))
        .respond_with(ResponseTemplate::new(400).set_body_json(json!({
            "error": "Invalid configuration"
        })))
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();

    let vm_config = json!({
        "name": "test-vm",
        "compose_manifest": {
            "docker_compose_file": "version: '3'",
            "name": "test"
        },
        "teepod_id": 123,
        "image": "test-image:latest"
    });

    let env_vars = vec![("TEST_KEY".to_string(), "test_value".to_string())];

    // Public key that would normally come from the API
    let pubkey = format!("0x{}", hex::encode([1u8; 32]));

    let result = client
        .deploy_with_config_do_encrypt(vm_config, &env_vars, &pubkey, "test_salt")
        .await;

    assert!(matches!(
        result,
        Err(Error::Api {
            status_code: 400,
            ..
        })
    ));
}

#[tokio::test]
async fn test_get_compose() {
    let mock_server = MockServer::start().await;

    // Mock the compose endpoint
    Mock::given(method("GET"))
        .and(path("/cvms/test-app-123/compose"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "compose_file": {
                "name": "test-app",
                "docker_compose_file": "version: '3'",
                "pre_launch_script": "#!/bin/bash\necho 'Hello'"
            },
            "env_pubkey": format!("0x{}", hex::encode([1u8; 32]))
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();
    let result = client.get_compose("test-app-123").await.unwrap();

    assert_eq!(result.compose_file["name"], "test-app");
    assert!(result.env_pubkey.starts_with("0x"));
}

#[tokio::test]
async fn test_update_compose() {
    let mock_server = MockServer::start().await;

    // Mock the update endpoint
    Mock::given(method("PUT"))
        .and(path("/cvms/test-app-123/compose"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "message": "Compose configuration updated"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();

    let compose_file = json!({
        "name": "updated-app",
        "docker_compose_file": "version: '3'",
        "pre_launch_script": "#!/bin/bash\necho 'Hello Updated'"
    });

    let env_vars = HashMap::from([("NEW_VAR".to_string(), "new_value".to_string())]);

    // Public key that would normally come from the API
    let pubkey = format!("0x{}", hex::encode([1u8; 32]));

    let result = client
        .update_compose("test-app-123", compose_file, Some(env_vars), pubkey)
        .await
        .unwrap();

    assert_eq!(result["status"], "success");
}

#[tokio::test]
async fn test_update_compose_without_env_vars() {
    let mock_server = MockServer::start().await;

    // Mock the update endpoint
    Mock::given(method("PUT"))
        .and(path("/cvms/test-app-123/compose"))
        .and(header("Content-Type", "application/json"))
        .and(header("x-api-key", "test_api_key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "success",
            "message": "Compose configuration updated"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = create_test_config(mock_server.uri());
    let client = TeeClient::new(config).unwrap();

    let compose_file = json!({
        "name": "updated-app",
        "docker_compose_file": "version: '3'",
        "pre_launch_script": "#!/bin/bash\necho 'Hello Updated'"
    });

    // Public key that would normally come from the API
    let pubkey = format!("0x{}", hex::encode([1u8; 32]));

    // Test without env vars
    let result = client
        .update_compose("test-app-123", compose_file, None, pubkey)
        .await
        .unwrap();

    assert_eq!(result["status"], "success");
}