-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathmain.rs
More file actions
203 lines (173 loc) · 6.17 KB
/
Copy pathmain.rs
File metadata and controls
203 lines (173 loc) · 6.17 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
// SPDX-FileCopyrightText: © 2024-2025 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0
use std::sync::Arc;
use anyhow::{Context, Result};
use clap::Parser;
use dstack_verifier::{
CvmVerifier, VerificationDetails, VerificationRequest, VerificationResponse,
};
use figment::{
providers::{Env, Format, Toml},
Figment,
};
use rocket::{fairing::AdHoc, get, post, serde::json::Json, State};
use serde::{Deserialize, Serialize};
use tracing::{error, info};
#[derive(Parser)]
#[command(name = "dstack-verifier")]
#[command(about = "HTTP server providing CVM verification services")]
struct Cli {
#[arg(short, long, default_value = "dstack-verifier.toml")]
config: String,
/// Oneshot mode: verify a single report JSON file and exit
#[arg(long, value_name = "FILE")]
verify: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config {
pub address: String,
pub port: u16,
pub image_cache_dir: String,
pub pccs_url: Option<String>,
pub image_download_url: String,
pub image_download_timeout_secs: u64,
}
#[post("/verify", data = "<request>")]
async fn verify_cvm(
verifier: &State<Arc<CvmVerifier>>,
request: Json<VerificationRequest>,
) -> Json<VerificationResponse> {
match verifier.verify(request.into_inner()).await {
Ok(response) => Json(response),
Err(e) => {
error!("Verification failed: {:?}", e);
Json(VerificationResponse {
is_valid: false,
details: VerificationDetails {
quote_verified: false,
event_log_verified: false,
os_image_hash_verified: false,
report_data: None,
tcb_status: None,
advisory_ids: vec![],
app_info: None,
acpi_tables: None,
rtmr_debug: None,
},
reason: Some(format!("Internal error: {}", e)),
})
}
}
}
#[get("/health")]
fn health() -> Json<serde_json::Value> {
Json(serde_json::json!({
"status": "ok",
"service": "dstack-verifier"
}))
}
async fn run_oneshot(file_path: &str, config: &Config) -> anyhow::Result<()> {
use std::fs;
info!("Running in oneshot mode for file: {}", file_path);
// Read the JSON file
let content = fs::read_to_string(file_path)
.map_err(|e| anyhow::anyhow!("Failed to read file {}: {}", file_path, e))?;
// Parse as VerificationRequest
let request: VerificationRequest = serde_json::from_str(&content)
.map_err(|e| anyhow::anyhow!("Failed to parse JSON: {}", e))?;
// Create verifier
let verifier = CvmVerifier::new(
config.image_cache_dir.clone(),
config.image_download_url.clone(),
std::time::Duration::from_secs(config.image_download_timeout_secs),
config.pccs_url.clone(),
);
// Run verification
info!("Starting verification...");
let response = verifier.verify(request).await?;
// Persist response next to the input file for convenience
let output_path = format!("{file_path}.verification.json");
let serialized = serde_json::to_string_pretty(&response)
.map_err(|e| anyhow::anyhow!("Failed to encode verification result: {}", e))?;
fs::write(&output_path, serialized).map_err(|e| {
anyhow::anyhow!(
"Failed to write verification result to {}: {}",
output_path,
e
)
})?;
info!("Stored verification result at {}", output_path);
// Output results
println!("\n=== Verification Results ===");
println!("Valid: {}", response.is_valid);
println!("Quote verified: {}", response.details.quote_verified);
println!(
"Event log verified: {}",
response.details.event_log_verified
);
println!(
"OS image hash verified: {}",
response.details.os_image_hash_verified
);
if let Some(tcb_status) = &response.details.tcb_status {
println!("TCB status: {}", tcb_status);
}
if !response.details.advisory_ids.is_empty() {
println!("Advisory IDs: {:?}", response.details.advisory_ids);
}
if let Some(reason) = &response.reason {
println!("Reason: {}", reason);
}
if let Some(report_data) = &response.details.report_data {
println!("Report data: {}", report_data);
}
if let Some(app_info) = &response.details.app_info {
println!("\n=== App Info ===");
println!("App ID: {}", hex::encode(&app_info.app_id));
println!("Instance ID: {}", hex::encode(&app_info.instance_id));
println!("Compose hash: {}", hex::encode(&app_info.compose_hash));
}
// Exit with appropriate code
if !response.is_valid {
std::process::exit(1);
}
Ok(())
}
#[rocket::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::try_init().ok();
let cli = Cli::parse();
let default_config_str = include_str!("../dstack-verifier.toml");
let figment = Figment::from(rocket::Config::default())
.merge(Toml::string(default_config_str))
.merge(Toml::file(&cli.config))
.merge(Env::prefixed("DSTACK_VERIFIER_"));
let config: Config = figment.extract().context("Failed to load configuration")?;
// Check for oneshot mode
if let Some(file_path) = cli.verify {
if let Err(e) = run_oneshot(&file_path, &config).await {
error!("Oneshot verification failed: {:#}", e);
std::process::exit(1);
}
std::process::exit(0);
}
let verifier = Arc::new(CvmVerifier::new(
config.image_cache_dir.clone(),
config.image_download_url.clone(),
std::time::Duration::from_secs(config.image_download_timeout_secs),
config.pccs_url.clone(),
));
rocket::custom(figment)
.mount("/", rocket::routes![verify_cvm, health])
.manage(verifier)
.attach(AdHoc::on_liftoff("Startup", |_| {
Box::pin(async {
info!("dstack-verifier started successfully");
})
}))
.launch()
.await
.map_err(|err| anyhow::anyhow!("launch rocket failed: {err:?}"))?;
Ok(())
}