volli-manager 0.1.12

Manager for volli
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
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
use super::crypto::secret_dir;
use super::peer_db::{load_peers, save_peers};
use super::save_csk;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD_NO_PAD;
use ed25519_dalek::SigningKey;
use eyre::{Report, eyre};
use std::fs;
use std::path::PathBuf;
use toml;
use volli_core::{ManagerPeerEntry, profile as core_profile};

type CertData = (Vec<u8>, Vec<u8>, bool, Option<PathBuf>, Option<PathBuf>);

#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
struct ManagerProfile {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    host: Option<String>,
    #[serde(default)]
    bind_host: Option<String>,
    #[serde(default)]
    tcp_port: Option<u16>,
    #[serde(default)]
    quic_port: Option<u16>,
    #[serde(default)]
    max_workers: Option<u32>,
    #[serde(default)]
    worker_whitelist: Option<Vec<String>>,
    #[serde(default)]
    manager_whitelist: Option<Vec<String>>,
}

fn load_profile(profile: &str) -> Result<ManagerProfile, Report> {
    Ok(core_profile::load_profile("manager", profile)?.unwrap_or_default())
}

fn save_profile(profile: &str, data: &ManagerProfile) -> Result<(), Report> {
    core_profile::save_profile("manager", profile, data)
}

pub fn save_profile_host(profile: &str, host: &str) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.host = Some(host.to_string());
    save_profile(profile, &cfg)
}

pub fn load_profile_host(profile: &str) -> Result<Option<String>, Report> {
    Ok(load_profile(profile)?.host)
}

pub fn save_bind_host(profile: &str, host: &str) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.bind_host = Some(host.to_string());
    save_profile(profile, &cfg)
}

pub fn load_bind_host(profile: &str) -> Result<Option<String>, Report> {
    Ok(load_profile(profile)?.bind_host)
}

pub fn save_tcp_port(profile: &str, port: u16) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.tcp_port = Some(port);
    save_profile(profile, &cfg)
}

pub fn load_tcp_port(profile: &str) -> Result<Option<u16>, Report> {
    Ok(load_profile(profile)?.tcp_port)
}

pub fn save_quic_port(profile: &str, port: u16) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.quic_port = Some(port);
    save_profile(profile, &cfg)
}

pub fn load_quic_port(profile: &str) -> Result<Option<u16>, Report> {
    Ok(load_profile(profile)?.quic_port)
}

pub fn save_worker_whitelist(profile: &str, addrs: &[String]) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.worker_whitelist = Some(addrs.to_vec());
    save_profile(profile, &cfg)
}

pub fn load_worker_whitelist(profile: &str) -> Result<Option<Vec<String>>, Report> {
    Ok(load_profile(profile)?.worker_whitelist)
}

pub fn save_max_workers(profile: &str, max_workers: u32) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.max_workers = Some(max_workers);
    save_profile(profile, &cfg)
}

pub fn load_max_workers(profile: &str) -> Result<Option<u32>, Report> {
    Ok(load_profile(profile)?.max_workers)
}

pub fn save_manager_whitelist(profile: &str, list: &[String]) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.manager_whitelist = Some(list.to_vec());
    save_profile(profile, &cfg)
}

pub fn load_manager_whitelist(profile: &str) -> Result<Option<Vec<String>>, Report> {
    Ok(load_profile(profile)?.manager_whitelist)
}

pub fn load_manager_name(profile: &str) -> Result<Option<String>, Report> {
    let cfg = load_profile(profile)?;
    Ok(cfg.name)
}

pub fn save_manager_name(profile: &str, name: &str) -> Result<(), Report> {
    let mut cfg = load_profile(profile)?;
    cfg.name = Some(name.to_string());
    save_profile(profile, &cfg)
}

/// Builder pattern for batching profile updates to reduce disk I/O
///
/// This builder allows you to update multiple profile fields and cryptographic
/// material in batched operations, rather than making separate saves for each field.
/// It unifies both profile metadata and cryptographic material persistence.
///
/// # Examples
///
/// Create a new profile with multiple fields:
/// ```rust,no_run
/// use volli_manager::update_profile;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let result = update_profile("my_profile")?
///         .name("My Manager")
///         .host("manager.example.com")
///         .tcp_port(4434)
///         .quic_port(4433)
///         .worker_whitelist(&["worker1".to_string(), "worker2".to_string()])
///         .save();
///     Ok(())
/// }
/// ```
///
/// Update configuration and persist cryptographic material:
/// ```rust,no_run
/// use volli_manager::update_profile;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     # let mut rng = rand_core::OsRng;
///     # let signing_key = ed25519_dalek::SigningKey::generate(&mut rng);
///     # let cert_der = vec![0u8; 32];
///     # let key_der = vec![0u8; 32];
///     # let csk = [0u8; 32];
///     # let version = 1u32;
///     let result = update_profile("my_profile")?
///         .host("new-host.com")
///         .signing_key(&signing_key, true, None, None)  // persist keys
///         .certificate(&cert_der, &key_der, true, None, None)  // persist cert
///         .cluster_key(&csk, version, true)  // persist CSK
///         .save_all(); // Save everything atomically
///     Ok(())
/// }
/// ```
pub struct ManagerProfileBuilder {
    profile_name: String,
    config: ManagerProfile,
    // Cryptographic material to persist
    signing_key_data: Option<(SigningKey, bool, Option<PathBuf>, Option<PathBuf>)>,
    cert_data: Option<CertData>,
    csk_data: Option<([u8; 32], u32, bool)>,
    secret_dir_override: Option<PathBuf>,
}

impl ManagerProfileBuilder {
    /// Create a new builder for the given profile
    ///
    /// Loads the existing profile if it exists, or creates a new empty one.
    /// All subsequent method calls will modify this loaded state.
    pub fn new(profile: &str) -> Result<Self, Report> {
        let config = load_profile(profile)?;
        Ok(Self {
            profile_name: profile.to_string(),
            config,
            signing_key_data: None,
            cert_data: None,
            csk_data: None,
            secret_dir_override: None,
        })
    }

    /// Set the profile name (used for display purposes)
    ///
    /// # Arguments
    /// * `name` - Human-readable name for this manager profile
    pub fn name(mut self, name: &str) -> Self {
        self.config.name = Some(name.to_string());
        self
    }

    /// Set the advertised host address
    ///
    /// This is the hostname or IP address that other managers and workers
    /// will use to connect to this manager.
    ///
    /// # Arguments
    /// * `host` - Hostname or IP address (e.g., "manager.example.com" or "192.168.1.100")
    pub fn host(mut self, host: &str) -> Self {
        self.config.host = Some(host.to_string());
        self
    }

    /// Set the bind host address
    ///
    /// This is the address the manager will bind to for incoming connections.
    /// Use "0.0.0.0" to bind to all interfaces.
    ///
    /// # Arguments
    /// * `bind_host` - Address to bind to (e.g., "0.0.0.0", "127.0.0.1")
    pub fn bind_host(mut self, bind_host: &str) -> Self {
        self.config.bind_host = Some(bind_host.to_string());
        self
    }

    /// Set the TCP port for fallback connections
    ///
    /// # Arguments
    /// * `port` - TCP port number (typically 4434)
    pub fn tcp_port(mut self, port: u16) -> Self {
        self.config.tcp_port = Some(port);
        self
    }

    /// Set the QUIC port for primary connections
    ///
    /// # Arguments
    /// * `port` - QUIC port number (typically 4433)
    pub fn quic_port(mut self, port: u16) -> Self {
        self.config.quic_port = Some(port);
        self
    }

    /// Set the soft cap for workers on this manager
    ///
    /// # Arguments
    /// * `max` - Maximum number of workers this manager should aim to host
    pub fn max_workers(mut self, max: u32) -> Self {
        self.config.max_workers = Some(max);
        self
    }

    /// Set the worker whitelist
    ///
    /// Only workers from these addresses will be allowed to connect.
    /// Pass an empty slice to allow all workers.
    ///
    /// # Arguments
    /// * `addrs` - List of allowed worker addresses (CIDR notation supported)
    pub fn worker_whitelist(mut self, addrs: &[String]) -> Self {
        self.config.worker_whitelist = Some(addrs.to_vec());
        self
    }

    /// Set the manager whitelist
    ///
    /// Only managers from these addresses will be allowed to connect.
    /// Pass an empty slice to allow all managers.
    ///
    /// # Arguments
    /// * `list` - List of allowed manager addresses (CIDR notation supported)
    pub fn manager_whitelist(mut self, list: &[String]) -> Self {
        self.config.manager_whitelist = Some(list.to_vec());
        self
    }

    /// Set the signing key for persistence
    ///
    /// # Arguments
    /// * `signing_key` - The signing key to persist
    /// * `persist` - Whether to actually write the keys to disk
    /// * `sk_path` - Optional custom path for the secret key
    /// * `pk_path` - Optional custom path for the public key
    pub fn signing_key(
        mut self,
        signing_key: &SigningKey,
        persist: bool,
        sk_path: Option<PathBuf>,
        pk_path: Option<PathBuf>,
    ) -> Self {
        self.signing_key_data = Some((signing_key.clone(), persist, sk_path, pk_path));
        self
    }

    /// Set the TLS certificate and key for persistence
    ///
    /// # Arguments
    /// * `cert_der` - Certificate in DER format
    /// * `key_der` - Private key in DER format
    /// * `persist` - Whether to actually write the certificate to disk
    /// * `cert_path` - Optional custom path for the certificate
    /// * `key_path` - Optional custom path for the private key
    pub fn certificate(
        mut self,
        cert_der: &[u8],
        key_der: &[u8],
        persist: bool,
        cert_path: Option<PathBuf>,
        key_path: Option<PathBuf>,
    ) -> Self {
        self.cert_data = Some((
            cert_der.to_vec(),
            key_der.to_vec(),
            persist,
            cert_path,
            key_path,
        ));
        self
    }

    /// Set the cluster shared key for persistence
    ///
    /// # Arguments
    /// * `csk` - The cluster shared key
    /// * `version` - CSK version number
    /// * `persist` - Whether to actually write the CSK to disk
    pub fn cluster_key(mut self, csk: &[u8; 32], version: u32, persist: bool) -> Self {
        self.csk_data = Some((*csk, version, persist));
        self
    }

    /// Override the default secret directory
    pub fn secret_dir(mut self, dir: PathBuf) -> Self {
        self.secret_dir_override = Some(dir);
        self
    }

    /// Save only the profile configuration to disk
    ///
    /// This performs only one disk write for the profile metadata,
    /// making it much more efficient than calling individual save functions.
    /// Use `save_all()` if you also need to persist cryptographic material.
    ///
    /// # Returns
    /// * `Ok(())` if the profile was saved successfully
    /// * `Err(Report)` if there was an I/O error or serialization failed
    pub fn save(self) -> Result<(), Report> {
        save_profile(&self.profile_name, &self.config)
    }

    /// Save all changes including cryptographic material to disk
    ///
    /// This replaces the functionality of both `persist_profile` and profile config saves,
    /// providing a unified interface for all profile-related persistence.
    ///
    /// # Returns
    /// * `Ok(())` if everything was saved successfully
    /// * `Err(Report)` if there was an I/O error or serialization failed
    pub fn save_all(self) -> Result<(), Report> {
        tracing::debug!(
            "ProfileBuilder::save_all starting for profile '{}'",
            self.profile_name
        );

        let secret_dir = self
            .secret_dir_override
            .unwrap_or_else(|| secret_dir(Some(&self.profile_name)));

        tracing::debug!("Using secret_dir: {}", secret_dir.display());

        // Save cryptographic material first
        if let Some((csk, version, persist)) = self.csk_data
            && persist
        {
            tracing::debug!(
                "Saving CSK for profile '{}' version {}",
                self.profile_name,
                version
            );
            save_csk(&self.profile_name, &csk, version)?;
            tracing::debug!("CSK saved successfully");
        }

        if let Some((signing_key, persist, sk_path, pk_path)) = self.signing_key_data
            && persist
        {
            tracing::debug!("Saving signing key for profile '{}'", self.profile_name);
            let sk_path = sk_path.unwrap_or_else(|| secret_dir.join("manager_sk"));
            let pk_path = pk_path.unwrap_or_else(|| secret_dir.join("manager_pk"));

            fs::create_dir_all(&secret_dir)?;
            fs::write(&sk_path, hex::encode(signing_key.to_bytes()))?;
            let ver_bytes = signing_key.verifying_key().to_bytes();
            fs::write(&pk_path, hex::encode(ver_bytes))?;
            tracing::debug!("Generated manager keypair at {}", secret_dir.display());
        }

        if let Some((cert_der, key_der, persist, cert_path, key_path)) = self.cert_data
            && persist
        {
            tracing::debug!("Saving certificate for profile '{}'", self.profile_name);
            let cert_path = cert_path.unwrap_or_else(|| secret_dir.join("tls_cert.der"));
            let key_path = key_path.unwrap_or_else(|| secret_dir.join("tls_key.der"));

            if let Some(parent) = cert_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&cert_path, &cert_der)?;
            fs::write(&key_path, &key_der)?;
            tracing::debug!("Certificate saved successfully");
        }

        // Finally save the profile configuration
        tracing::debug!("Saving profile configuration for '{}'", self.profile_name);
        save_profile(&self.profile_name, &self.config)?;
        tracing::debug!(
            "ProfileBuilder::save_all completed successfully for profile '{}'",
            self.profile_name
        );
        Ok(())
    }
}

/// Get a builder for updating a profile with batched changes
///
/// This is the recommended way to update multiple profile fields efficiently.
/// Instead of calling individual `save_*` functions which each write to disk,
/// use this builder to batch all updates into a single disk write.
///
/// # Examples
///
/// ```rust,no_run
/// use volli_manager::update_profile;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Update multiple fields efficiently
///     update_profile("my_profile")?
///         .host("new-host.com")
///         .tcp_port(8080)
///         .quic_port(8443)
///         .worker_whitelist(&["192.168.1.0/24".to_string()])
///         .save()?;
///
///     // Update just one field
///     update_profile("my_profile")?
///         .name("Updated Manager Name")
///         .save()?;
///
///     Ok(())
/// }
/// ```
///
/// # Arguments
/// * `profile` - Name of the profile to update
///
/// # Returns
/// * `Ok(ManagerProfileBuilder)` - A builder ready for method chaining
/// * `Err(Report)` - If the profile cannot be loaded
pub fn update_profile(profile: &str) -> Result<ManagerProfileBuilder, Report> {
    ManagerProfileBuilder::new(profile)
}

pub fn list_profiles() -> Result<Vec<String>, Report> {
    core_profile::list_profiles("manager")
}

pub fn delete_profile(profile: &str) -> Result<(), Report> {
    core_profile::delete_profile("manager", profile)
}

pub fn profile_exists(profile: &str) -> bool {
    core_profile::profile_exists("manager", profile)
}

pub fn rename_profile(old: &str, new: &str) -> Result<(), Report> {
    core_profile::rename_profile("manager", old, new)
}

pub fn save_bootstrap(profile: &str) -> Result<(), Report> {
    let dir = secret_dir(Some(profile));
    fs::create_dir_all(&dir)?;
    fs::write(dir.join("bootstrap"), b"1")?;
    Ok(())
}

pub fn load_bootstrap(profile: &str) -> bool {
    secret_dir(Some(profile)).join("bootstrap").exists()
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ManagerProfileExport {
    pub name: String,
    pub host: Option<String>,
    pub bind_host: Option<String>,
    pub peers: Vec<ManagerPeerEntry>,
    pub worker_whitelist: Option<Vec<String>>,
    pub manager_whitelist: Option<Vec<String>>,
    pub max_workers: Option<u32>,
    pub manager_sk: Option<String>,
    pub manager_pk: Option<String>,
    pub tls_cert: Option<String>,
    pub tls_key: Option<String>,
    pub tls_fp: Option<String>,
}

pub fn export_profile(profile: &str) -> Result<String, Report> {
    let dir = secret_dir(Some(profile));
    if !dir.exists() {
        return Err(eyre!("profile not found"));
    }
    let host = load_profile_host(profile).ok().flatten();
    let bind_host = load_bind_host(profile).ok().flatten();
    let peers = load_peers(profile).unwrap_or_default();
    let worker_whitelist = load_worker_whitelist(profile).ok().flatten();
    let manager_whitelist = load_manager_whitelist(profile).ok().flatten();
    let max_workers = load_max_workers(profile).ok().flatten();
    let manager_sk = std::fs::read_to_string(dir.join("manager_sk")).ok();
    let manager_pk = std::fs::read_to_string(dir.join("manager_pk")).ok();
    let tls_cert = std::fs::read(dir.join("tls_cert.der"))
        .ok()
        .map(|b| STANDARD_NO_PAD.encode(b));
    let tls_key = std::fs::read(dir.join("tls_key.der"))
        .ok()
        .map(|b| STANDARD_NO_PAD.encode(b));
    let manager_name = load_manager_name(profile)
        .ok()
        .flatten()
        .unwrap_or_else(|| profile.to_string());
    let exp = ManagerProfileExport {
        name: manager_name,
        host,
        bind_host,
        peers,
        worker_whitelist,
        manager_whitelist,
        max_workers,
        manager_sk,
        manager_pk,
        tls_cert,
        tls_key,
        tls_fp: None,
    };
    Ok(toml::to_string(&exp)?)
}

pub fn import_profile(data: &str, name: Option<&str>, force: bool) -> Result<String, Report> {
    let mut exp: ManagerProfileExport = toml::from_str(data)?;
    if let Some(n) = name {
        exp.name = n.to_string();
    }
    let dir = secret_dir(Some(&exp.name));
    if dir.exists() && !force {
        return Err(eyre!("profile exists"));
    }
    std::fs::create_dir_all(&dir)?;
    // Use builder pattern to batch profile updates into a single disk write
    let mut builder = ManagerProfileBuilder::new(&exp.name)?;

    if let Some(ref v) = exp.host {
        builder = builder.host(v);
    }
    if let Some(ref v) = exp.bind_host {
        builder = builder.bind_host(v);
    }
    if let Some(ref v) = exp.worker_whitelist {
        builder = builder.worker_whitelist(v);
    }
    if let Some(ref v) = exp.manager_whitelist {
        builder = builder.manager_whitelist(v);
    }
    if let Some(v) = exp.max_workers {
        builder = builder.max_workers(v);
    }
    builder = builder.name(&exp.name);
    builder.save()?;

    // Save peers separately as they have their own storage mechanism
    if !exp.peers.is_empty() {
        save_peers(&exp.name, &exp.peers)?;
    }
    if let Some(ref v) = exp.manager_sk {
        std::fs::write(dir.join("manager_sk"), v)?;
    }
    if let Some(ref v) = exp.manager_pk {
        std::fs::write(dir.join("manager_pk"), v)?;
    }
    if let Some(ref v) = exp.tls_cert {
        std::fs::write(
            dir.join("tls_cert.der"),
            STANDARD_NO_PAD.decode(v.as_bytes())?,
        )?;
    }
    if let Some(ref v) = exp.tls_key {
        std::fs::write(
            dir.join("tls_key.der"),
            STANDARD_NO_PAD.decode(v.as_bytes())?,
        )?;
    }
    // Manager name is now saved via the builder pattern above
    Ok(exp.name)
}