leeca_proxmox 0.2.0

A modern, safe, and async-first SDK for interacting with Proxmox Virtual Environment servers
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
#![feature(error_generic_member_access)]

//! A safe and ergonomic Rust client for the Proxmox VE API.
//!
//! This crate provides a strongly-typed interface for interacting with Proxmox Virtual Environment.
//! Validation rules (like password strength, DNS resolution) are **opt-in** via a [`ValidationConfig`].
//! By default, only basic format checks are performed to ensure the values can be used in HTTP requests.
//!
//! # Example
//! ```no_run
//! use leeca_proxmox::{ProxmoxClient, ProxmoxResult};
//!
//! #[tokio::main]
//! async fn main() -> ProxmoxResult<()> {
//!     let mut client = ProxmoxClient::builder()
//!         .host("192.168.1.182")
//!         .port(8006)
//!         .credentials("user", "password", "pam")
//!         .secure(false)          // disable HTTPS for local development
//!         .build()
//!         .await?;
//!
//!     client.login().await?;
//!     println!("Authenticated!");
//!     Ok(())
//! }
//! ```

mod auth;
mod core;

pub use crate::core::domain::error::{ProxmoxError, ProxmoxResult, ValidationError};

use crate::{
    auth::application::service::login_service::LoginService,
    core::domain::{
        model::{proxmox_auth::ProxmoxAuth, proxmox_connection::ProxmoxConnection},
        value_object::{
            ProxmoxCSRFToken, ProxmoxHost, ProxmoxPassword, ProxmoxPort, ProxmoxRealm,
            ProxmoxTicket, ProxmoxUrl, ProxmoxUsername, validate_host, validate_password,
            validate_port, validate_realm, validate_url, validate_username,
        },
    },
};
use std::backtrace::Backtrace;
use std::time::Duration;

/// Configuration for validating client inputs.
///
/// By default, all extra checks are disabled, meaning only basic format validation is performed.
/// You can enable specific checks by calling the corresponding builder methods.
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Minimum password strength (zxcvbn score 0-4). If `None`, password strength is not checked.
    pub password_min_score: Option<zxcvbn::Score>,
    /// If true, DNS resolution is performed for hostnames.
    pub resolve_dns: bool,
    /// If true, reserved usernames (root, admin, etc.) are rejected.
    pub block_reserved_usernames: bool,
    /// Ticket lifetime for expiration checks (default 2 hours).
    pub ticket_lifetime: Duration,
    /// CSRF token lifetime (default 5 minutes).
    pub csrf_lifetime: Duration,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            password_min_score: None,
            resolve_dns: false,
            block_reserved_usernames: false,
            ticket_lifetime: Duration::from_secs(7200),
            csrf_lifetime: Duration::from_secs(300),
        }
    }
}

/// A strongly-typed client for the Proxmox VE API.
///
/// Use the builder to configure connection settings and validation rules.
#[derive(Debug)]
pub struct ProxmoxClient {
    connection: ProxmoxConnection,
    auth: Option<ProxmoxAuth>,
    config: ValidationConfig,
}

/// Builder for [`ProxmoxClient`].
#[derive(Debug)]
pub struct ProxmoxClientBuilder {
    host: Option<String>,
    port: Option<u16>,
    username: Option<String>,
    password: Option<String>,
    realm: Option<String>,
    secure: bool,
    accept_invalid_certs: bool,
    config: ValidationConfig,
}

impl Default for ProxmoxClientBuilder {
    fn default() -> Self {
        Self {
            host: None,
            port: None,
            username: None,
            password: None,
            realm: None,
            secure: true, // Default to HTTPS
            accept_invalid_certs: false,
            config: ValidationConfig::default(),
        }
    }
}

impl ProxmoxClientBuilder {
    /// Sets the Proxmox VE host address.
    #[must_use]
    pub fn host(mut self, host: impl Into<String>) -> Self {
        self.host = Some(host.into());
        self
    }

    /// Sets the Proxmox VE API port (default 8006).
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Sets the authentication credentials.
    #[must_use]
    pub fn credentials(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
        realm: impl Into<String>,
    ) -> Self {
        self.username = Some(username.into());
        self.password = Some(password.into());
        self.realm = Some(realm.into());
        self
    }

    /// Configures TLS security: `true` for HTTPS, `false` for HTTP.
    ///
    /// When `false`, certificate validation is also disabled for convenience.
    #[must_use]
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        if !secure {
            self.accept_invalid_certs = true;
        }
        self
    }

    /// Configures certificate validation: `true` accepts invalid/self-signed certificates.
    #[must_use]
    pub fn accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }

    /// Replaces the validation configuration with a custom one.
    #[must_use]
    pub fn with_validation_config(mut self, config: ValidationConfig) -> Self {
        self.config = config;
        self
    }

    /// Enables password strength checking with a minimum score (0-4).
    #[must_use]
    pub fn enable_password_strength(mut self, min_score: u8) -> Self {
        self.config.password_min_score = Some(match min_score {
            0 => zxcvbn::Score::Zero,
            1 => zxcvbn::Score::One,
            2 => zxcvbn::Score::Two,
            3 => zxcvbn::Score::Three,
            4 => zxcvbn::Score::Four,
            _ => zxcvbn::Score::Three,
        });
        self
    }

    /// Enables DNS resolution for hostnames (may block during build).
    #[must_use]
    pub fn enable_dns_resolution(mut self) -> Self {
        self.config.resolve_dns = true;
        self
    }

    /// Blocks reserved usernames (root, admin, etc.).
    #[must_use]
    pub fn block_reserved_usernames(mut self) -> Self {
        self.config.block_reserved_usernames = true;
        self
    }

    /// Constructs a [`ProxmoxClient`] after validating all inputs according to the configuration.
    pub async fn build(self) -> ProxmoxResult<ProxmoxClient> {
        // Extract required fields
        let host_str = self.host.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "host".to_string(),
                message: "Host is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;
        let port_num = self.port.unwrap_or(8006);
        let username_str = self.username.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "username".to_string(),
                message: "Username is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;
        let password_str = self.password.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "password".to_string(),
                message: "Password is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;
        let realm_str = self.realm.ok_or_else(|| ProxmoxError::Validation {
            source: ValidationError::Field {
                field: "realm".to_string(),
                message: "Realm is required".to_string(),
            },
            backtrace: Backtrace::capture(),
        })?;

        // Perform validation
        validate_host(&host_str, self.config.resolve_dns).map_err(|e| {
            ProxmoxError::Validation {
                source: e,
                backtrace: Backtrace::capture(),
            }
        })?;
        validate_port(port_num).map_err(|e| ProxmoxError::Validation {
            source: e,
            backtrace: Backtrace::capture(),
        })?;
        validate_username(&username_str, self.config.block_reserved_usernames).map_err(|e| {
            ProxmoxError::Validation {
                source: e,
                backtrace: Backtrace::capture(),
            }
        })?;
        validate_password(&password_str, self.config.password_min_score).map_err(|e| {
            ProxmoxError::Validation {
                source: e,
                backtrace: Backtrace::capture(),
            }
        })?;
        validate_realm(&realm_str).map_err(|e| ProxmoxError::Validation {
            source: e,
            backtrace: Backtrace::capture(),
        })?;

        // Construct URL
        let scheme = if self.secure { "https" } else { "http" };
        let url_str = format!("{}://{}:{}/", scheme, host_str, port_num);
        validate_url(&url_str).map_err(|e| ProxmoxError::Validation {
            source: e,
            backtrace: Backtrace::capture(),
        })?;

        // Create value objects (unchecked, already validated)
        let host = ProxmoxHost::new_unchecked(host_str);
        let port = ProxmoxPort::new_unchecked(port_num);
        let username = ProxmoxUsername::new_unchecked(username_str);
        let password = ProxmoxPassword::new_unchecked(password_str);
        let realm = ProxmoxRealm::new_unchecked(realm_str);
        let url = ProxmoxUrl::new_unchecked(url_str);

        let connection = ProxmoxConnection::new(
            host,
            port,
            username,
            password,
            realm,
            self.secure,
            self.accept_invalid_certs,
            url,
        );

        Ok(ProxmoxClient {
            connection,
            auth: None,
            config: self.config,
        })
    }
}

impl ProxmoxClient {
    /// Creates a new builder with default settings.
    #[must_use]
    pub fn builder() -> ProxmoxClientBuilder {
        ProxmoxClientBuilder::default()
    }

    /// Authenticates with the Proxmox VE server.
    pub async fn login(&mut self) -> ProxmoxResult<()> {
        let service = LoginService::new();
        self.auth = Some(service.execute(&self.connection).await?);
        Ok(())
    }

    /// Returns `true` if authenticated.
    #[must_use]
    pub fn is_authenticated(&self) -> bool {
        self.auth.is_some()
    }

    /// Returns the authentication ticket, if authenticated.
    #[must_use]
    pub fn auth_token(&self) -> Option<&ProxmoxTicket> {
        self.auth.as_ref().map(|a| a.ticket())
    }

    /// Returns the CSRF token, if authenticated.
    #[must_use]
    pub fn csrf_token(&self) -> Option<&ProxmoxCSRFToken> {
        self.auth.as_ref().and_then(|a| a.csrf_token())
    }

    /// Checks if the ticket is expired based on configured lifetime.
    #[must_use]
    pub fn is_ticket_expired(&self) -> bool {
        self.auth_token()
            .map(|t| t.is_expired(self.config.ticket_lifetime))
            .unwrap_or(true)
    }

    /// Checks if the CSRF token is expired.
    #[must_use]
    pub fn is_csrf_expired(&self) -> bool {
        self.csrf_token()
            .map(|c| c.is_expired(self.config.csrf_lifetime))
            .unwrap_or(true)
    }
}

#[cfg(test)]
mod tests {
    mod integration;
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_builder_default_secure() {
        let builder = ProxmoxClientBuilder::default();
        assert!(builder.secure);
        assert!(!builder.accept_invalid_certs);
    }

    #[tokio::test]
    async fn test_builder_missing_host() {
        let builder = ProxmoxClientBuilder::default()
            .port(8006)
            .credentials("user", "pass", "pam");
        let err = builder.build().await.unwrap_err();
        assert!(
            matches!(err, ProxmoxError::Validation { source: ValidationError::Field { field, .. }, .. } if field == "host")
        );
    }

    #[tokio::test]
    async fn test_builder_missing_username() {
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006);
        let err = builder.build().await.unwrap_err();
        assert!(
            matches!(err, ProxmoxError::Validation { source: ValidationError::Field { field, .. }, .. } if field == "username")
        );
    }

    #[tokio::test]
    async fn test_builder_valid_minimal() {
        let client = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "password123", "pam")
            .build()
            .await
            .unwrap();
        assert!(!client.is_authenticated());
        assert!(client.auth_token().is_none());
        assert!(client.csrf_token().is_none());
        // No ticket/CSRF => they are considered expired
        assert!(client.is_ticket_expired());
        assert!(client.is_csrf_expired());
    }

    #[tokio::test]
    async fn test_builder_with_validation_config() {
        let config = ValidationConfig {
            password_min_score: Some(zxcvbn::Score::Three),
            resolve_dns: true,
            block_reserved_usernames: true,
            ..Default::default()
        };
        // Use a password that meets length but is weak
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "password", "pam") // length 8, weak
            .with_validation_config(config.clone());
        let err = builder.build().await.unwrap_err();
        assert!(matches!(
            err,
            ProxmoxError::Validation {
                source: ValidationError::ConstraintViolation(_),
                ..
            }
        ));

        // Now with strong password
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "Str0ng!P@ss", "pam")
            .with_validation_config(config);
        assert!(builder.build().await.is_ok());
    }

    #[tokio::test]
    async fn test_client_login_no_auth() {
        let client = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("user", "password123", "pam")
            .build()
            .await
            .unwrap();
        assert!(!client.is_authenticated());
    }

    #[tokio::test]
    async fn test_builder_enable_methods() {
        let builder = ProxmoxClientBuilder::default()
            .host("example.com")
            .port(8006)
            .credentials("root", "password", "pam") // length 8, weak password
            .enable_password_strength(3)
            .enable_dns_resolution()
            .block_reserved_usernames();
        // Should fail because password weak and username reserved
        let err = builder.build().await.unwrap_err();
        assert!(matches!(err, ProxmoxError::Validation { .. }));
    }

    #[test]
    fn test_validation_config_default() {
        let config = ValidationConfig::default();
        assert_eq!(config.password_min_score, None);
        assert!(!config.resolve_dns);
        assert!(!config.block_reserved_usernames);
        assert_eq!(config.ticket_lifetime, Duration::from_secs(7200));
        assert_eq!(config.csrf_lifetime, Duration::from_secs(300));
    }

    // We'll test expiration methods with mocked tokens
    #[test]
    fn test_expiration_checks() {
        let ticket = ProxmoxTicket::new_unchecked("PVE:ticket".to_string());
        let csrf = ProxmoxCSRFToken::new_unchecked("id:val".to_string());
        let auth = ProxmoxAuth::new(ticket, Some(csrf));
        let client = ProxmoxClient {
            connection: ProxmoxConnection::new(
                ProxmoxHost::new_unchecked("host".to_string()),
                ProxmoxPort::new_unchecked(8006),
                ProxmoxUsername::new_unchecked("user".to_string()),
                ProxmoxPassword::new_unchecked("pass".to_string()),
                ProxmoxRealm::new_unchecked("pam".to_string()),
                true,
                false,
                ProxmoxUrl::new_unchecked("https://host:8006/".to_string()),
            ),
            auth: Some(auth),
            config: ValidationConfig::default(),
        };
        assert!(!client.is_ticket_expired());
        assert!(!client.is_csrf_expired());
    }
}