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
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Docker registry authentication configuration.
///
/// Used to access private Docker registries when deploying containers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DockerConfig {
    /// Docker registry username
    pub username: String,

    /// Docker registry password
    pub password: String,

    /// Optional custom registry URL
    pub registry: Option<String>,
}

/// Advanced features configuration for TEE deployments.
///
/// Controls security and visibility settings for deployed applications.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedFeatures {
    /// Enable transparent proxy support
    pub tproxy: bool,

    /// Enable Key Management System integration
    pub kms: bool,

    /// Make system information publicly accessible
    pub public_sys_info: bool,

    /// Make application logs publicly accessible
    pub public_logs: bool,

    /// Docker registry authentication settings
    pub docker_config: DockerConfig,

    /// List this deployment in public directories
    pub listed: bool,
}

/// Docker Compose manifest configuration.
///
/// Defines the application structure using Docker Compose format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComposeManifest {
    /// Name of the application
    pub name: String,

    /// Enabled features for this deployment
    pub features: Vec<String>,

    /// Docker Compose file content
    pub docker_compose_file: String,
}

/// Virtual Machine configuration for a TEE deployment.
///
/// Defines the resources and settings for the VM that will run the containerized application.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VmConfig {
    /// Name of the deployment
    pub name: String,

    /// Docker Compose manifest configuration
    pub compose_manifest: ComposeManifest,

    /// Number of virtual CPU cores
    pub vcpu: u32,

    /// Memory allocation in MB
    pub memory: u32,

    /// Disk size allocation in GB
    pub disk_size: u32,

    /// ID of the TEEPod to deploy to
    pub teepod_id: u64,

    /// Container image to use
    pub image: String,

    /// Advanced features configuration
    pub advanced_features: AdvancedFeatures,
}

/// Encrypted environment variable entry.
///
/// Used for secure transmission of sensitive environment variables.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedEnv {
    /// Environment variable name
    pub key: String,

    /// Encrypted environment variable value
    pub value: String,
}

/// Response from a deployment operation.
///
/// Contains information about the created deployment including its ID and status.
/// This struct uses custom deserialization to handle variations in API responses.
#[derive(Debug, Clone, Serialize)]
pub struct DeploymentResponse {
    /// Unique identifier for the deployment
    pub id: u64,

    /// Current status of the deployment (e.g., "pending", "running")
    pub status: String,

    /// Additional deployment details as key-value pairs
    pub details: Option<HashMap<String, serde_json::Value>>,
}

// Implement custom deserialization to handle different API response formats
impl<'de> Deserialize<'de> for DeploymentResponse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;

        // First, try to deserialize as a generic Value
        let value = serde_json::Value::deserialize(deserializer)?;

        // If it's not an object, return an error
        let obj = match value.as_object() {
            Some(obj) => obj,
            None => return Err(D::Error::custom("Expected object for DeploymentResponse")),
        };

        // Try to extract the ID field from various possible formats
        let id = if let Some(id_value) = obj.get("id") {
            if let Some(id_num) = id_value.as_u64() {
                id_num
            } else if let Some(id_str) = id_value.as_str() {
                id_str.parse::<u64>().unwrap_or(0)
            } else {
                0 // Default ID if can't parse
            }
        } else if let Some(id_value) = obj.get("uuid") {
            if let Some(id_num) = id_value.as_u64() {
                id_num
            } else if let Some(id_str) = id_value.as_str() {
                id_str.parse::<u64>().unwrap_or(0)
            } else {
                0 // Default ID if can't parse
            }
        } else if let Some(id_value) = obj.get("app_id") {
            if let Some(id_str) = id_value.as_str() {
                // Extract numeric part from "app_123" format
                if id_str.starts_with("app_") {
                    id_str[4..].parse::<u64>().unwrap_or(0)
                } else {
                    id_str.parse::<u64>().unwrap_or(0)
                }
            } else {
                0 // Default ID if can't parse
            }
        } else {
            // If no ID field is found, generate a random one
            use rand::Rng;
            rand::thread_rng().gen()
        };

        // Extract status field
        let status = obj
            .get("status")
            .and_then(|v| v.as_str())
            .unwrap_or("pending")
            .to_string();

        // Create details map with all fields from the response
        let mut details = HashMap::new();
        for (k, v) in obj {
            details.insert(k.clone(), v.clone());
        }

        Ok(DeploymentResponse {
            id,
            status,
            details: Some(details),
        })
    }
}

/// Response when retrieving a compose configuration.
///
/// Contains both the compose configuration and the public key needed for
/// encrypting environment variables for updates.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComposeResponse {
    /// The compose file configuration
    pub compose_file: serde_json::Value,

    /// Public key for encrypting environment variables
    pub env_pubkey: String,
}

/// Response from a pubkey request.
///
/// Contains the public key and other configuration details needed for deployment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PubkeyResponse {
    /// Public key for encrypting environment variables
    pub app_env_encrypt_pubkey: String,

    /// Generated application ID
    pub app_id: String,

    /// Salt used in app ID generation
    pub app_id_salt: String,

    /// Compose manifest configuration
    pub compose_manifest: ComposeManifest,

    /// Disk size in GB
    pub disk_size: u64,

    /// Encrypted environment variables
    pub encrypted_env: String,

    /// Container image to use
    pub image: String,

    /// Whether the deployment should be listed publicly
    pub listed: bool,

    /// Memory allocation in MB
    pub memory: u64,

    /// Name of the deployment
    pub name: String,

    /// Port mappings
    pub ports: Option<Vec<String>>,

    /// ID of the TEEPod to deploy to
    pub teepod_id: u64,

    /// User ID associated with deployment
    pub user_id: Option<String>,

    /// Number of virtual CPUs
    pub vcpu: u64,
}

/// Compose manifest configuration.
///
/// Contains Docker Compose and related deployment settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComposeManifestResponse {
    /// Optional bash script
    pub bash_script: Option<String>,

    /// Docker Compose file contents
    pub docker_compose_file: String,

    /// Docker registry configuration
    pub docker_config: DockerConfig,

    /// Enabled features for the deployment
    pub features: Vec<String>,

    /// Whether KMS is enabled
    pub kms_enabled: bool,

    /// Manifest version number
    pub manifest_version: u64,

    /// Name of the deployment
    pub name: String,

    /// Pre-launch script contents
    pub pre_launch_script: String,

    /// Whether logs should be public
    pub public_logs: bool,

    /// Whether system info should be public
    pub public_sysinfo: bool,

    /// Runner type (e.g. "docker-compose")
    pub runner: String,

    /// Salt for configuration
    pub salt: String,

    /// Whether transparent proxy is enabled
    pub tproxy_enabled: bool,

    /// Version of the manifest
    pub version: String,
}

/// Response from the TEEPod discovery API endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeePodDiscoveryResponse {
    /// Capacity limits for the TEEPod cluster
    pub capacity: TeePodCapacity,

    /// List of available TEEPod nodes
    pub nodes: Vec<TeePodNode>,

    /// Service tier (e.g. "pro")
    pub tier: String,
}

/// Capacity configuration for a TEEPod cluster.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeePodCapacity {
    /// Maximum disk space in GB
    pub max_disk: u64,

    /// Maximum number of instances
    pub max_instances: u64,

    /// Maximum memory in MB
    pub max_memory: u64,

    /// Maximum number of virtual CPUs
    pub max_vcpu: u64,
}

/// Information about a TEEPod node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeePodNode {
    /// Available VM images
    pub images: Vec<TeePodImage>,

    /// Whether the node is publicly listed
    pub listed: bool,

    /// Node name
    pub name: String,

    /// Number of remaining CVM slots
    pub remaining_cvm_slots: u64,

    /// Remaining memory in MB
    pub remaining_memory: f64,

    /// Remaining virtual CPU capacity
    pub remaining_vcpu: f64,

    /// Resource availability score (0.0-1.0)
    pub resource_score: f64,

    /// Unique identifier for the TEEPod
    pub teepod_id: u64,
}

/// VM image configuration for a TEEPod.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeePodImage {
    /// BIOS file name
    pub bios: String,

    /// Kernel command line parameters
    pub cmdline: String,

    /// Image configuration description
    pub description: String,

    /// Hard disk image path (if any)
    pub hda: Option<String>,

    /// Initial ramdisk file name
    pub initrd: String,

    /// Whether this is a development image
    pub is_dev: bool,

    /// Kernel image file name
    pub kernel: String,

    /// Image name
    pub name: String,

    /// Root filesystem image name
    pub rootfs: String,

    /// Root filesystem hash
    pub rootfs_hash: String,

    /// Whether root filesystem is shared read-only
    pub shared_ro: bool,

    /// Image version numbers [major, minor, patch]
    pub version: Vec<u64>,
}

/// Response containing network information for a deployment.
///
/// Provides details about connectivity, IP addresses, and public URLs
/// for accessing the deployed application.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInfoResponse {
    /// Whether the deployment is online and responding
    pub is_online: bool,

    /// Whether the deployment is publicly accessible
    pub is_public: bool,

    /// Error message if there's a connectivity issue (null if no error)
    pub error: Option<String>,

    /// Internal IP address of the deployment
    pub internal_ip: String,

    /// Timestamp of the latest connectivity handshake
    pub latest_handshake: String,

    /// Public URLs for accessing the deployment
    pub public_urls: PublicUrls,
}

/// Public URLs for accessing a deployment.
///
/// Contains URLs for different parts of the deployment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicUrls {
    /// URL for the main application
    pub app: String,

    /// URL for the instance/container
    pub instance: String,
}

/// System information for a disk in a virtual machine.
///
/// Contains details about a disk's name, mount point, and size information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskInfo {
    /// Name of the disk (e.g., "sda1")
    pub name: String,

    /// Mount point of the disk (e.g., "/", "/home")
    pub mount_point: Option<String>,

    /// Total size of the disk in bytes
    pub total_size: u64,

    /// Free space available on the disk in bytes
    pub free_size: u64,
}

/// Detailed system information for a virtual machine.
///
/// Contains comprehensive details about the operating system, hardware,
/// and resource utilization of a deployed container VM.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
    /// Operating system name (e.g., "Linux")
    pub os_name: String,

    /// Operating system version
    pub os_version: String,

    /// Linux kernel version
    pub kernel_version: String,

    /// CPU model name
    pub cpu_model: String,

    /// Number of CPU cores
    pub num_cpus: u32,

    /// Total physical memory in bytes
    pub total_memory: u64,

    /// Available memory in bytes
    pub available_memory: u64,

    /// Used memory in bytes
    pub used_memory: u64,

    /// Free memory in bytes
    pub free_memory: u64,

    /// Total swap space in bytes
    pub total_swap: u64,

    /// Used swap space in bytes
    pub used_swap: u64,

    /// Free swap space in bytes
    pub free_swap: u64,

    /// System uptime in seconds
    pub uptime: u64,

    /// 1-minute load average
    pub loadavg_one: f32,

    /// 5-minute load average
    pub loadavg_five: f32,

    /// 15-minute load average
    pub loadavg_fifteen: f32,

    /// Information about mounted disks
    pub disks: Vec<DiskInfo>,
}

/// Response containing system statistics for a container VM.
///
/// Provides details about the operational status and system resource usage
/// of a deployed application in the Phala TEE Cloud.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStatsResponse {
    /// Whether the VM is online and responding
    pub is_online: bool,

    /// Whether the VM is publicly accessible
    pub is_public: bool,

    /// Error message if there's an issue (null if no error)
    pub error: Option<String>,

    /// Detailed system information
    pub sysinfo: SystemInfo,
}

// ─────────────────────────────────────────────────────────────────────────────
// CVM lifecycle types
// ─────────────────────────────────────────────────────────────────────────────

/// Full CVM info from `GET /api/v1/cvms/{cvm_id}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CvmInfo {
    pub id: u64,
    pub status: String,
    pub name: String,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// CVM state from `GET /api/v1/cvms/{cvm_id}/state`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CvmStateResponse {
    pub status: String,
    pub is_running: bool,
}

/// TEE attestation from `GET /api/v1/cvms/{cvm_id}/attestation`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationResponse {
    #[serde(default)]
    pub tcb_info: serde_json::Value,
    #[serde(default)]
    pub app_certificates: serde_json::Value,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}