purple-ssh 2.40.0

Open-source terminal SSH manager and SSH config editor. Search hundreds of hosts, sync from 16 clouds, transfer files, manage Docker and Podman over SSH, sign short-lived Vault SSH certs and expose an MCP server for AI agents. Rust TUI, MIT licensed.
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};

use serde::Deserialize;

use super::{Provider, ProviderError, ProviderHost, map_ureq_error};

pub struct Azure {
    pub subscriptions: Vec<String>,
}

// --- VM response models ---

#[derive(Deserialize)]
#[cfg_attr(not(test), allow(dead_code))]
struct VmListResponse {
    #[serde(default)]
    value: Vec<VirtualMachine>,
    #[serde(rename = "nextLink")]
    next_link: Option<String>,
}

#[derive(Deserialize)]
struct VirtualMachine {
    name: String,
    #[serde(default)]
    location: String,
    #[serde(default)]
    tags: Option<HashMap<String, String>>,
    #[serde(default)]
    properties: VmProperties,
}

#[derive(Deserialize, Default)]
struct VmProperties {
    #[serde(rename = "vmId", default)]
    vm_id: String,
    #[serde(rename = "hardwareProfile")]
    hardware_profile: Option<HardwareProfile>,
    #[serde(rename = "storageProfile")]
    storage_profile: Option<StorageProfile>,
    #[serde(rename = "networkProfile")]
    network_profile: Option<NetworkProfile>,
    #[serde(rename = "instanceView")]
    instance_view: Option<InstanceView>,
}

#[derive(Deserialize)]
struct HardwareProfile {
    #[serde(rename = "vmSize")]
    vm_size: String,
}

#[derive(Deserialize)]
struct StorageProfile {
    #[serde(rename = "imageReference")]
    image_reference: Option<ImageReference>,
}

#[derive(Deserialize)]
struct ImageReference {
    offer: Option<String>,
    sku: Option<String>,
    #[allow(dead_code)]
    id: Option<String>,
}

#[derive(Deserialize)]
struct NetworkProfile {
    #[serde(rename = "networkInterfaces", default)]
    network_interfaces: Vec<NetworkInterfaceRef>,
}

#[derive(Deserialize)]
struct NetworkInterfaceRef {
    id: String,
    properties: Option<NicRefProperties>,
}

#[derive(Deserialize)]
struct NicRefProperties {
    primary: Option<bool>,
}

#[derive(Deserialize)]
struct InstanceView {
    #[serde(default)]
    statuses: Vec<InstanceViewStatus>,
}

#[derive(Deserialize)]
struct InstanceViewStatus {
    code: String,
}

// --- NIC response models ---

#[derive(Deserialize)]
#[cfg_attr(not(test), allow(dead_code))]
struct NicListResponse {
    #[serde(default)]
    value: Vec<Nic>,
    #[serde(rename = "nextLink")]
    #[allow(dead_code)]
    next_link: Option<String>,
}

#[derive(Deserialize)]
struct Nic {
    id: String,
    #[serde(default)]
    properties: NicProperties,
}

#[derive(Deserialize, Default)]
struct NicProperties {
    #[serde(rename = "ipConfigurations", default)]
    ip_configurations: Vec<IpConfiguration>,
}

#[derive(Deserialize)]
struct IpConfiguration {
    #[serde(default)]
    properties: IpConfigProperties,
}

#[derive(Deserialize, Default)]
struct IpConfigProperties {
    #[serde(rename = "privateIPAddress")]
    private_ip_address: Option<String>,
    #[serde(rename = "publicIPAddress")]
    public_ip_address: Option<PublicIpRef>,
    primary: Option<bool>,
}

#[derive(Deserialize)]
struct PublicIpRef {
    id: String,
}

// --- Public IP response models ---

#[derive(Deserialize)]
#[cfg_attr(not(test), allow(dead_code))]
struct PublicIpListResponse {
    #[serde(default)]
    value: Vec<PublicIp>,
    #[serde(rename = "nextLink")]
    #[allow(dead_code)]
    next_link: Option<String>,
}

#[derive(Deserialize)]
struct PublicIp {
    id: String,
    #[serde(default)]
    properties: PublicIpProperties,
}

#[derive(Deserialize, Default)]
struct PublicIpProperties {
    #[serde(rename = "ipAddress")]
    ip_address: Option<String>,
}

// --- Auth models ---

/// Service principal credentials. Supports two JSON formats:
/// - Azure CLI output (`az ad sp create-for-rbac`): `appId`, `password`, `tenant`
/// - Manual/portal format: `clientId`, `clientSecret`, `tenantId`
#[derive(Deserialize)]
struct ServicePrincipal {
    #[serde(alias = "tenantId", alias = "tenant")]
    tenant_id: String,
    #[serde(alias = "clientId", alias = "appId")]
    client_id: String,
    #[serde(alias = "clientSecret", alias = "password")]
    client_secret: String,
}

#[derive(Deserialize)]
struct TokenResponse {
    access_token: String,
}

/// Validate that a subscription ID is a valid UUID (8-4-4-4-12 hex chars).
pub fn is_valid_subscription_id(id: &str) -> bool {
    let parts: Vec<&str> = id.split('-').collect();
    if parts.len() != 5 {
        return false;
    }
    let expected_lens = [8, 4, 4, 4, 12];
    parts
        .iter()
        .zip(expected_lens.iter())
        .all(|(part, &len)| part.len() == len && part.chars().all(|c| c.is_ascii_hexdigit()))
}

/// Detect whether a token string is a path to a service principal JSON file.
fn is_sp_file(token: &str) -> bool {
    token.to_ascii_lowercase().ends_with(".json")
}

/// Exchange service principal credentials for an access token.
fn resolve_sp_token(path: &str) -> Result<String, ProviderError> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| ProviderError::Http(format!("Failed to read SP file {}: {}", path, e)))?;
    let sp: ServicePrincipal = serde_json::from_str(&content)
        .map_err(|e| ProviderError::Http(format!(
            "Failed to parse SP file: {}. Expected JSON with appId/password/tenant (az CLI) or clientId/clientSecret/tenantId.", e
        )))?;

    let agent = super::http_agent();
    let url = format!(
        "https://login.microsoftonline.com/{}/oauth2/v2.0/token",
        sp.tenant_id
    );
    let mut resp = agent
        .post(&url)
        .send_form([
            ("grant_type", "client_credentials"),
            ("client_id", sp.client_id.as_str()),
            ("client_secret", sp.client_secret.as_str()),
            ("scope", "https://management.azure.com/.default"),
        ])
        .map_err(map_ureq_error)?;

    let token_resp: TokenResponse = resp
        .body_mut()
        .read_json()
        .map_err(|e| ProviderError::Parse(format!("Token response: {}", e)))?;

    Ok(token_resp.access_token)
}

/// Resolve token: if it's a path to a SP JSON file, exchange it for an access token.
/// Otherwise, use it as a raw access token. Strips "Bearer " prefix if present.
fn resolve_token(token: &str) -> Result<String, ProviderError> {
    if is_sp_file(token) {
        resolve_sp_token(token)
    } else {
        let t = token.strip_prefix("Bearer ").unwrap_or(token);
        if t.is_empty() {
            return Err(ProviderError::AuthFailed);
        }
        Ok(t.to_string())
    }
}

/// Select the best IP for a VM by looking up its primary NIC and IP configuration.
/// Priority: public IP > private IP > None.
fn select_ip(
    vm: &VirtualMachine,
    nic_map: &HashMap<String, &Nic>,
    public_ip_map: &HashMap<String, String>,
) -> Option<String> {
    let net_profile = vm.properties.network_profile.as_ref()?;
    if net_profile.network_interfaces.is_empty() {
        return None;
    }

    // Find primary NIC, fallback to first
    let nic_ref = net_profile
        .network_interfaces
        .iter()
        .find(|n| {
            n.properties
                .as_ref()
                .and_then(|p| p.primary)
                .unwrap_or(false)
        })
        .or_else(|| net_profile.network_interfaces.first())?;

    let nic_id_lower = nic_ref.id.to_ascii_lowercase();
    let nic = nic_map.get(&nic_id_lower)?;

    // Find primary IP config, fallback to first
    let ip_config = nic
        .properties
        .ip_configurations
        .iter()
        .find(|c| c.properties.primary.unwrap_or(false))
        .or_else(|| nic.properties.ip_configurations.first())?;

    // Try public IP first
    if let Some(ref pub_ref) = ip_config.properties.public_ip_address {
        let pub_id_lower = pub_ref.id.to_ascii_lowercase();
        if let Some(addr) = public_ip_map.get(&pub_id_lower) {
            if !addr.is_empty() {
                return Some(addr.clone());
            }
        }
    }

    // Fallback to private IP
    if let Some(ref private) = ip_config.properties.private_ip_address {
        if !private.is_empty() {
            return Some(private.clone());
        }
    }

    None
}

/// Extract power state from instanceView statuses.
fn extract_power_state(instance_view: &Option<InstanceView>) -> Option<String> {
    let iv = instance_view.as_ref()?;
    for status in &iv.statuses {
        if let Some(suffix) = status.code.strip_prefix("PowerState/") {
            return Some(suffix.to_string());
        }
    }
    None
}

/// Build OS string from image reference: "{offer}-{sku}".
fn build_os_string(image_ref: &Option<ImageReference>) -> Option<String> {
    let img = image_ref.as_ref()?;
    let offer = img.offer.as_deref()?;
    let sku = img.sku.as_deref()?;
    if offer.is_empty() || sku.is_empty() {
        return None;
    }
    Some(format!("{}-{}", offer, sku))
}

/// Build metadata key-value pairs for a VM.
fn build_metadata(vm: &VirtualMachine) -> Vec<(String, String)> {
    let mut metadata = Vec::new();
    if !vm.location.is_empty() {
        metadata.push(("region".to_string(), vm.location.to_ascii_lowercase()));
    }
    if let Some(ref hw) = vm.properties.hardware_profile {
        if !hw.vm_size.is_empty() {
            metadata.push(("vm_size".to_string(), hw.vm_size.clone()));
        }
    }
    if let Some(ref sp) = vm.properties.storage_profile {
        if let Some(os) = build_os_string(&sp.image_reference) {
            metadata.push(("image".to_string(), os));
        }
    }
    if let Some(state) = extract_power_state(&vm.properties.instance_view) {
        metadata.push(("status".to_string(), state));
    }
    metadata
}

/// Build tags from Azure VM tags (key:value map).
fn build_tags(vm: &VirtualMachine) -> Vec<String> {
    let mut tags = Vec::new();
    if let Some(ref vm_tags) = vm.tags {
        for (k, v) in vm_tags {
            if v.is_empty() {
                tags.push(k.clone());
            } else {
                tags.push(format!("{}:{}", k, v));
            }
        }
    }
    tags
}

/// Fetch a paginated Azure API list endpoint. Returns the deserialized items.
fn fetch_paginated<T: serde::de::DeserializeOwned>(
    agent: &ureq::Agent,
    initial_url: &str,
    access_token: &str,
    cancel: &AtomicBool,
    resource_name: &str,
    progress: &dyn Fn(&str),
) -> Result<Vec<T>, ProviderError> {
    // We need to deserialize a response that has `value: Vec<T>` and `nextLink: Option<String>`.
    // Since we can't use generics with serde easily, we'll use serde_json::Value.
    let mut all_items = Vec::new();
    let mut next_url: Option<String> = Some(initial_url.to_string());

    for page in 0u32.. {
        if cancel.load(Ordering::Relaxed) {
            return Err(ProviderError::Cancelled);
        }
        if page > 500 {
            break;
        }

        let url = match next_url.take() {
            Some(u) => u,
            None => break,
        };

        progress(&format!(
            "Fetching {} ({} so far)...",
            resource_name,
            all_items.len()
        ));

        let mut response = match agent
            .get(&url)
            .header("Authorization", &format!("Bearer {}", access_token))
            .call()
        {
            Ok(r) => r,
            Err(e) => {
                let err = map_ureq_error(e);
                // AuthFailed and RateLimited always propagate immediately
                if matches!(err, ProviderError::AuthFailed | ProviderError::RateLimited) {
                    return Err(err);
                }
                // On later pages, return what we have so far instead of losing it
                if !all_items.is_empty() {
                    break;
                }
                return Err(err);
            }
        };

        let body: serde_json::Value = match response.body_mut().read_json() {
            Ok(v) => v,
            Err(e) => {
                if !all_items.is_empty() {
                    break;
                }
                return Err(ProviderError::Parse(format!(
                    "{} response: {}",
                    resource_name, e
                )));
            }
        };

        if let Some(value_array) = body.get("value").and_then(|v| v.as_array()) {
            for item in value_array {
                match serde_json::from_value(item.clone()) {
                    Ok(parsed) => all_items.push(parsed),
                    Err(_) => continue, // skip malformed items
                }
            }
        }

        next_url = body
            .get("nextLink")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .filter(|s| s.starts_with("https://management.azure.com/"))
            .map(|s| s.to_string());
    }

    Ok(all_items)
}

impl Provider for Azure {
    fn name(&self) -> &str {
        "azure"
    }

    fn short_label(&self) -> &str {
        "az"
    }

    fn fetch_hosts_cancellable(
        &self,
        token: &str,
        cancel: &AtomicBool,
    ) -> Result<Vec<ProviderHost>, ProviderError> {
        self.fetch_hosts_with_progress(token, cancel, &|_| {})
    }

    fn fetch_hosts_with_progress(
        &self,
        token: &str,
        cancel: &AtomicBool,
        progress: &dyn Fn(&str),
    ) -> Result<Vec<ProviderHost>, ProviderError> {
        if self.subscriptions.is_empty() {
            return Err(ProviderError::Http(
                "No Azure subscriptions configured. Set at least one subscription ID.".to_string(),
            ));
        }

        // Validate subscription ID format (UUID: 8-4-4-4-12 hex chars)
        for sub in &self.subscriptions {
            if !is_valid_subscription_id(sub) {
                return Err(ProviderError::Http(format!(
                    "Invalid subscription ID '{}'. Expected UUID format (e.g. 12345678-1234-1234-1234-123456789012).",
                    sub
                )));
            }
        }

        progress("Authenticating...");
        let access_token = resolve_token(token)?;

        if cancel.load(Ordering::Relaxed) {
            return Err(ProviderError::Cancelled);
        }

        let agent = super::http_agent();
        let mut all_hosts = Vec::new();
        let mut failures = 0usize;
        let total = self.subscriptions.len();

        for (i, sub) in self.subscriptions.iter().enumerate() {
            if cancel.load(Ordering::Relaxed) {
                return Err(ProviderError::Cancelled);
            }

            progress(&format!("Subscription {}/{} ({})...", i + 1, total, sub));

            match self.fetch_subscription(&agent, &access_token, sub, cancel, progress) {
                Ok(hosts) => all_hosts.extend(hosts),
                Err(ProviderError::Cancelled) => return Err(ProviderError::Cancelled),
                Err(ProviderError::AuthFailed) => return Err(ProviderError::AuthFailed),
                Err(ProviderError::RateLimited) => return Err(ProviderError::RateLimited),
                Err(_) => {
                    failures += 1;
                }
            }
        }

        if failures > 0 && !all_hosts.is_empty() {
            return Err(ProviderError::PartialResult {
                hosts: all_hosts,
                failures,
                total,
            });
        }
        if failures > 0 && all_hosts.is_empty() {
            return Err(ProviderError::Http(format!(
                "All {} subscription(s) failed.",
                total
            )));
        }

        progress(&format!("{} VMs", all_hosts.len()));
        Ok(all_hosts)
    }
}

impl Azure {
    fn fetch_subscription(
        &self,
        agent: &ureq::Agent,
        access_token: &str,
        subscription_id: &str,
        cancel: &AtomicBool,
        progress: &dyn Fn(&str),
    ) -> Result<Vec<ProviderHost>, ProviderError> {
        // 1. Fetch all VMs (with instanceView expanded for power state)
        let vm_url = format!(
            "https://management.azure.com/subscriptions/{}/providers/Microsoft.Compute/virtualMachines?api-version=2024-07-01&$expand=instanceView",
            subscription_id
        );
        let vms: Vec<VirtualMachine> =
            fetch_paginated(agent, &vm_url, access_token, cancel, "VMs", progress)?;

        if cancel.load(Ordering::Relaxed) {
            return Err(ProviderError::Cancelled);
        }

        // 2. Fetch all NICs
        let nic_url = format!(
            "https://management.azure.com/subscriptions/{}/providers/Microsoft.Network/networkInterfaces?api-version=2024-05-01",
            subscription_id
        );
        let nics: Vec<Nic> =
            fetch_paginated(agent, &nic_url, access_token, cancel, "NICs", progress)?;

        if cancel.load(Ordering::Relaxed) {
            return Err(ProviderError::Cancelled);
        }

        // 3. Fetch all public IPs
        let pip_url = format!(
            "https://management.azure.com/subscriptions/{}/providers/Microsoft.Network/publicIPAddresses?api-version=2024-05-01",
            subscription_id
        );
        let public_ips: Vec<PublicIp> = fetch_paginated(
            agent,
            &pip_url,
            access_token,
            cancel,
            "public IPs",
            progress,
        )?;

        // Build lookup maps (case-insensitive Azure resource IDs)
        let nic_map: HashMap<String, &Nic> = nics
            .iter()
            .map(|n| (n.id.to_ascii_lowercase(), n))
            .collect();

        let public_ip_map: HashMap<String, String> = public_ips
            .iter()
            .filter_map(|p| {
                p.properties
                    .ip_address
                    .as_ref()
                    .map(|addr| (p.id.to_ascii_lowercase(), addr.clone()))
            })
            .collect();

        // 4. Join: VM -> NIC -> public IP
        let mut hosts = Vec::new();
        for vm in &vms {
            // Skip VMs with empty vm_id (would collide in sync engine)
            if vm.properties.vm_id.is_empty() {
                continue;
            }
            if let Some(ip) = select_ip(vm, &nic_map, &public_ip_map) {
                hosts.push(ProviderHost {
                    server_id: vm.properties.vm_id.clone(),
                    name: vm.name.clone(),
                    ip,
                    tags: build_tags(vm),
                    metadata: build_metadata(vm),
                });
            }
        }

        Ok(hosts)
    }
}

#[cfg(test)]
#[path = "azure_tests.rs"]
mod tests;