-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxmux.rs
More file actions
2534 lines (2334 loc) · 83.3 KB
/
Copy pathproxmux.rs
File metadata and controls
2534 lines (2334 loc) · 83.3 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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! PROXMUX: Proxmox VE cluster inventory using the Proxmox API (ticket session auth).
//! Storage lives next to other NoSuckShell SSH-dir files; API secrets use the app master key when set, else plain text in a user-only file.
use super::{HostEnrichContext, NssPlugin, PluginCapability, PluginManifest};
use crate::app_prefs;
use crate::secure_store::{decrypt_with_app_master, try_encrypt_with_app_master};
use crate::ssh_config::HostConfig;
use crate::ssh_home::effective_ssh_dir;
use crate::sensitive::SecretString;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet};
use std::fs;
use reqwest::Proxy;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, TcpStream, ToSocketAddrs};
use std::str::FromStr;
use std::sync::{Condvar, Mutex, OnceLock};
pub const PROXMUX_PLUGIN_ID: &str = "dev.nosuckshell.plugin.proxmux";
/// Stored in `proxy_id` to force a direct HTTPS connection (no proxy).
const PROXY_DIRECT_ID: &str = "direct";
pub struct ProxmuxPlugin;
impl NssPlugin for ProxmuxPlugin {
fn manifest(&self) -> PluginManifest {
PluginManifest {
id: PROXMUX_PLUGIN_ID.to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
display_name: "PROXMUX".to_string(),
capabilities: vec![PluginCapability::SettingsUi, PluginCapability::HostMetadataEnricher],
}
}
fn required_entitlement(&self) -> Option<&'static str> {
Some("dev.nosuckshell.addon.proxmox")
}
fn enrich_host_config(&self, _host: &mut HostConfig, _ctx: &HostEnrichContext) -> Result<()> {
Ok(())
}
fn invoke(&self, method: &str, arg: &Value) -> Result<Value> {
match method {
"listState" => Ok(list_state()?),
"saveCluster" => Ok(save_cluster(arg)?),
"removeCluster" => Ok(remove_cluster(arg)?),
"setActiveCluster" => Ok(set_active_cluster(arg)?),
"testConnection" => Ok(test_connection(arg)?),
"testConnectionDraft" => Ok(test_connection_draft(arg)?),
"fetchResources" => Ok(fetch_resources(arg)?),
"guestStatus" => Ok(guest_status(arg)?),
"guestPower" => Ok(guest_power(arg)?),
"toggleProxmuxFavorite" => Ok(toggle_proxmux_favorite(arg)?),
"fetchSpiceProxy" => Ok(fetch_spice_proxy(arg)?),
"fetchQemuVncProxy" => Ok(fetch_qemu_vnc_proxy(arg)?),
"fetchLxcTermProxy" => Ok(fetch_lxc_term_proxy(arg)?),
"fetchNodeTermProxy" => Ok(fetch_node_term_proxy(arg)?),
"qemuSpiceCapable" => Ok(qemu_spice_capable(arg)?),
"saveProxySettings" => Ok(save_proxy_settings(arg)?),
"saveProxyProfiles" => Ok(save_proxy_profiles(arg)?),
"fetchTlsCertificate" => Ok(fetch_tls_certificate(arg)?),
_ => anyhow::bail!("unknown method: {method}"),
}
}
}
fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct ApiSecretEncrypted {
ciphertext: String,
salt: String,
nonce: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct StoredCluster {
id: String,
name: String,
proxmox_url: String,
api_user: String,
#[serde(default)]
totp_code: String,
#[serde(default)]
api_token_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
api_secret_plain: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
api_secret_encrypted: Option<ApiSecretEncrypted>,
#[serde(default)]
failover_urls: Vec<String>,
#[serde(default = "default_true")]
is_enabled: bool,
#[serde(default)]
allow_insecure_tls: bool,
/// PEM-encoded leaf (or chain) associated with this cluster.
/// NOTE: the current HTTP client logic still disables standard TLS verification
/// (e.g. via `danger_accept_invalid_certs(true)`) when this field is set; the PEM is
/// not used as a replacement trust store.
#[serde(default)]
tls_trusted_cert_pem: Option<SecretString>,
/// Hex SHA-256 of the leaf DER (fingerprint) recorded when `tls_trusted_cert_pem` is set.
/// This is currently informational and is not enforced by the HTTP client.
#[serde(default)]
tls_trusted_leaf_sha256: Option<String>,
/// `None`/empty = use global default proxy (`ProxmuxState.http_proxy_url`); `Some("direct")` = no proxy; `Some(profile id)` = named profile.
#[serde(default)]
proxy_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProxyProfile {
id: String,
#[serde(default)]
name: String,
#[serde(default)]
url: String,
/// Extra comma-separated bypass hosts for this profile (merged with global + cluster hosts).
#[serde(default)]
no_proxy_extra: String,
#[serde(default = "default_true")]
is_enabled: bool,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProxmuxState {
#[serde(default)]
active_cluster_id: Option<String>,
#[serde(default)]
clusters: HashMap<String, StoredCluster>,
/// Per cluster: stable resource keys (`node:{name}` or `qemu|lxc:{node}:{vmid}`).
#[serde(default)]
favorites: HashMap<String, Vec<String>>,
/// Corporate HTTP(S) proxy for Proxmox API traffic, e.g. `http://proxy.example:8080` (optional).
#[serde(default)]
http_proxy_url: String,
/// Comma-separated bypass list (same idea as `NO_PROXY`), e.g. `localhost,127.0.0.1,.lan,*.internal`.
#[serde(default)]
no_proxy: String,
#[serde(default)]
proxy_profiles: Vec<ProxyProfile>,
}
fn state_path() -> Result<std::path::PathBuf> {
Ok(effective_ssh_dir()?.join("nosuckshell.proxmux.v1.json"))
}
fn load_state() -> Result<ProxmuxState> {
let path = state_path()?;
if !path.exists() {
return Ok(ProxmuxState::default());
}
let raw = fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
let mut state: ProxmuxState = serde_json::from_str(&raw).context("parse proxmux state")?;
if migrate_legacy_token_clusters(&mut state) > 0 {
save_state(&state)?;
}
Ok(state)
}
fn save_state(state: &ProxmuxState) -> Result<()> {
let path = state_path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let raw = serde_json::to_string_pretty(state)?;
fs::write(&path, &raw)?;
#[cfg(unix)]
{
let mut perms = fs::metadata(&path)?.permissions();
perms.set_mode(0o600);
fs::set_permissions(&path, perms)?;
}
Ok(())
}
fn normalize_base_url(url: &str) -> String {
url.trim().trim_end_matches('/').to_string()
}
#[derive(Debug, Clone)]
struct ProxmoxSessionAuth {
cookie_header: String,
csrf_prevention_token: String,
}
#[derive(Debug, Clone)]
struct CachedSession {
auth: ProxmoxSessionAuth,
created_at_unix_secs: u64,
}
const SESSION_CACHE_TTL_SECS: u64 = 60 * 60;
fn session_cache() -> &'static std::sync::Mutex<HashMap<String, CachedSession>> {
static CACHE: std::sync::OnceLock<std::sync::Mutex<HashMap<String, CachedSession>>> = std::sync::OnceLock::new();
CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProxmuxCacheBucket {
FetchResources,
GuestStatus,
}
#[derive(Debug, Clone)]
struct ProxmuxCacheEntry {
value: Value,
cached_at_ms: u64,
expires_at_ms: u64,
}
impl ProxmuxCacheEntry {
fn is_fresh_at(&self, now_ms: u64) -> bool {
now_ms < self.expires_at_ms
}
}
#[derive(Debug, Default, Clone)]
struct ProxmuxCacheStats {
hits: u64,
misses: u64,
stores: u64,
deduped_waits: u64,
invalidations: u64,
}
#[derive(Debug, Default)]
struct ProxmuxCacheState {
entries: HashMap<String, ProxmuxCacheEntry>,
in_flight: HashSet<String>,
stats: ProxmuxCacheStats,
}
impl ProxmuxCacheState {
fn invalidate_prefix(&mut self, prefix: &str) -> usize {
let before = self.entries.len();
self.entries.retain(|k, _| !k.starts_with(prefix));
let removed = before.saturating_sub(self.entries.len());
if removed > 0 {
self.stats.invalidations = self.stats.invalidations.saturating_add(removed as u64);
}
removed
}
fn purge_expired(&mut self, now_ms: u64) {
self.entries.retain(|_, entry| entry.is_fresh_at(now_ms));
}
fn evict_if_needed(&mut self) {
if self.entries.len() <= PROXMUX_CACHE_MAX_ENTRIES {
return;
}
let mut by_age: Vec<(String, u64)> = self
.entries
.iter()
.map(|(k, v)| (k.clone(), v.cached_at_ms))
.collect();
by_age.sort_by_key(|(_, ts)| *ts);
let drop_count = self.entries.len().saturating_sub(PROXMUX_CACHE_MAX_ENTRIES);
for (key, _) in by_age.into_iter().take(drop_count) {
self.entries.remove(&key);
}
}
}
const PROXMUX_CACHE_TTL_FETCH_RESOURCES_MS: u64 = 9_000;
const PROXMUX_CACHE_TTL_GUEST_STATUS_MS: u64 = 5_000;
const PROXMUX_CACHE_MAX_ENTRIES: usize = 96;
fn proxmux_cache_ttl_ms(bucket: ProxmuxCacheBucket) -> u64 {
match bucket {
ProxmuxCacheBucket::FetchResources => PROXMUX_CACHE_TTL_FETCH_RESOURCES_MS,
ProxmuxCacheBucket::GuestStatus => PROXMUX_CACHE_TTL_GUEST_STATUS_MS,
}
}
fn proxmux_cache_key_for_fetch_resources(cluster_id: &str) -> String {
format!("fetchResources:{cluster_id}")
}
fn proxmux_cache_key_for_guest_status(
cluster_id: &str,
node: &str,
guest_type: &str,
vmid: &str,
) -> String {
format!("guestStatus:{cluster_id}:{node}:{guest_type}:{vmid}")
}
fn proxmux_cache_sync() -> &'static (Mutex<ProxmuxCacheState>, Condvar) {
static CACHE: OnceLock<(Mutex<ProxmuxCacheState>, Condvar)> = OnceLock::new();
CACHE.get_or_init(|| (Mutex::new(ProxmuxCacheState::default()), Condvar::new()))
}
fn now_unix_millis() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
fn proxmux_cache_debug_enabled() -> bool {
matches!(std::env::var("NSS_PROXMUX_CACHE_DEBUG").ok().as_deref(), Some("1"))
}
fn proxmux_cache_debug_log(message: &str) {
if proxmux_cache_debug_enabled() {
eprintln!("[proxmux-cache] {message}");
}
}
fn proxmux_cache_invalidate_prefix(prefix: &str) {
let (lock, cv) = proxmux_cache_sync();
if let Ok(mut state) = lock.lock() {
let removed = state.invalidate_prefix(prefix);
if removed > 0 {
proxmux_cache_debug_log(&format!("invalidate prefix={prefix} removed={removed}"));
}
}
cv.notify_all();
}
fn proxmux_cache_invalidate_cluster(cluster_id: &str) {
proxmux_cache_invalidate_prefix(&format!("fetchResources:{cluster_id}"));
proxmux_cache_invalidate_prefix(&format!("guestStatus:{cluster_id}:"));
}
fn proxmux_cache_invalidate_exact(key: &str) {
let (lock, cv) = proxmux_cache_sync();
if let Ok(mut state) = lock.lock() {
if state.entries.remove(key).is_some() {
state.stats.invalidations = state.stats.invalidations.saturating_add(1);
proxmux_cache_debug_log(&format!("invalidate exact key={key}"));
}
}
cv.notify_all();
}
fn proxmux_cache_invalidate_after_guest_power(
cluster_id: &str,
node: &str,
guest_type: &str,
vmid: &str,
) {
proxmux_cache_invalidate_exact(&proxmux_cache_key_for_guest_status(
cluster_id,
node,
guest_type,
vmid,
));
proxmux_cache_invalidate_exact(&proxmux_cache_key_for_fetch_resources(cluster_id));
}
fn proxmux_cache_invalidate_after_toggle_favorite(cluster_id: &str) {
proxmux_cache_invalidate_exact(&proxmux_cache_key_for_fetch_resources(cluster_id));
}
fn proxmux_cached_json<F>(cache_key: String, bucket: ProxmuxCacheBucket, fetcher: F) -> Result<Value>
where
F: FnOnce() -> Result<Value>,
{
let ttl_ms = proxmux_cache_ttl_ms(bucket);
let (lock, cv) = proxmux_cache_sync();
loop {
let now_ms = now_unix_millis();
let mut state = lock
.lock()
.map_err(|_| anyhow::anyhow!("proxmux cache lock poisoned"))?;
state.purge_expired(now_ms);
if let Some(value) = state
.entries
.get(&cache_key)
.filter(|entry| entry.is_fresh_at(now_ms))
.map(|entry| entry.value.clone())
{
state.stats.hits = state.stats.hits.saturating_add(1);
proxmux_cache_debug_log(&format!("hit key={cache_key}"));
return Ok(value);
}
if !state.in_flight.contains(&cache_key) {
state.in_flight.insert(cache_key.clone());
state.stats.misses = state.stats.misses.saturating_add(1);
drop(state);
let fetched = fetcher();
let mut state = lock
.lock()
.map_err(|_| anyhow::anyhow!("proxmux cache lock poisoned"))?;
state.in_flight.remove(&cache_key);
if let Ok(value) = &fetched {
let cached_at_ms = now_unix_millis();
state.entries.insert(
cache_key.clone(),
ProxmuxCacheEntry {
value: value.clone(),
cached_at_ms,
expires_at_ms: cached_at_ms.saturating_add(ttl_ms),
},
);
state.evict_if_needed();
state.stats.stores = state.stats.stores.saturating_add(1);
proxmux_cache_debug_log(&format!("store key={cache_key} ttl_ms={ttl_ms}"));
} else {
proxmux_cache_debug_log(&format!("fetch error key={cache_key}"));
}
cv.notify_all();
return fetched;
}
state.stats.deduped_waits = state.stats.deduped_waits.saturating_add(1);
let _guard = cv
.wait(state)
.map_err(|_| anyhow::anyhow!("proxmux cache wait poisoned"))?;
}
}
#[allow(dead_code)]
fn pve_api_token_header(user: &str, token_id: &str, secret: &str) -> String {
format!("PVEAPIToken={user}!{token_id}={secret}")
}
fn now_unix_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn session_cache_key(cluster_id: &str, base_url: &str) -> String {
format!("{cluster_id}|{}", normalize_base_url(base_url))
}
fn read_cluster_password(c: &StoredCluster) -> Result<String> {
if let Some(enc) = &c.api_secret_encrypted {
return decrypt_with_app_master(&enc.ciphertext, &enc.salt, &enc.nonce);
}
if let Some(p) = &c.api_secret_plain {
if !p.is_empty() {
return Ok(p.clone());
}
}
anyhow::bail!("Missing password for this cluster")
}
fn invalidate_cached_session(cluster_id: &str, base_url: &str) {
let key = session_cache_key(cluster_id, base_url);
if let Ok(mut cache) = session_cache().lock() {
cache.remove(&key);
}
}
fn parse_json_data_field(body: Value, context: &str) -> Result<Value> {
body.get("data")
.cloned()
.ok_or_else(|| anyhow::anyhow!("missing data in {context} response"))
}
fn parse_ticket_session_auth(body: &Value) -> Result<ProxmoxSessionAuth> {
let data = body
.get("data")
.and_then(|v| v.as_object())
.ok_or_else(|| anyhow::anyhow!("missing data in access/ticket response"))?;
let ticket = data
.get("ticket")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|v| !v.is_empty())
.ok_or_else(|| anyhow::anyhow!("missing ticket in access/ticket response"))?;
let csrf = data
.get("CSRFPreventionToken")
.and_then(|v| v.as_str())
.map(str::trim)
.unwrap_or_default()
.to_string();
Ok(ProxmoxSessionAuth {
cookie_header: format!("PVEAuthCookie={ticket}"),
csrf_prevention_token: csrf,
})
}
fn login_ticket_session(client: &reqwest::blocking::Client, base_url: &str, c: &StoredCluster) -> Result<ProxmoxSessionAuth> {
let password = read_cluster_password(c)?;
if c.api_user.trim().is_empty() {
anyhow::bail!("apiUser is required");
}
let url = format!("{}/api2/json/access/ticket", normalize_base_url(base_url));
let mut form: Vec<(&str, String)> = vec![
("username", c.api_user.trim().to_string()),
("password", password),
];
if !c.totp_code.trim().is_empty() {
form.push(("otp", c.totp_code.trim().to_string()));
}
let response = client
.post(&url)
.header("Accept", "application/json")
.form(&form)
.send()
.with_context(|| format!("POST {url}"))?;
let status = response.status();
if !status.is_success() {
let text = response.text().unwrap_or_default();
anyhow::bail!("{}", pve_error_hint(status.as_u16(), &text));
}
let body: Value = response.json().context("parse access/ticket JSON")?;
parse_ticket_session_auth(&body)
}
fn session_auth_for_base(client: &reqwest::blocking::Client, c: &StoredCluster, base_url: &str, force_refresh: bool) -> Result<ProxmoxSessionAuth> {
let normalized = normalize_base_url(base_url);
if normalized.is_empty() {
anyhow::bail!("empty base URL");
}
let key = session_cache_key(&c.id, &normalized);
if !force_refresh {
if let Ok(cache) = session_cache().lock() {
if let Some(entry) = cache.get(&key) {
let age = now_unix_secs().saturating_sub(entry.created_at_unix_secs);
if age < SESSION_CACHE_TTL_SECS {
return Ok(entry.auth.clone());
}
}
}
}
let auth = login_ticket_session(client, &normalized, c)?;
if let Ok(mut cache) = session_cache().lock() {
cache.insert(
key,
CachedSession {
auth: auth.clone(),
created_at_unix_secs: now_unix_secs(),
},
);
}
Ok(auth)
}
fn pve_get_json_data(client: &reqwest::blocking::Client, c: &StoredCluster, base_url: &str, path_tail: &str) -> Result<Value> {
let normalized = normalize_base_url(base_url);
let url = format!("{normalized}{path_tail}");
for attempt in 0..2 {
let auth = session_auth_for_base(client, c, &normalized, attempt > 0)?;
let response = client
.get(&url)
.header("Cookie", &auth.cookie_header)
.header("Accept", "application/json")
.send()
.with_context(|| format!("GET {url}"))?;
let status = response.status();
if status.as_u16() == 401 && attempt == 0 {
invalidate_cached_session(&c.id, &normalized);
continue;
}
if !status.is_success() {
let text = response.text().unwrap_or_default();
anyhow::bail!("{}", pve_error_hint(status.as_u16(), &text));
}
let body: Value = response.json().context("parse Proxmox JSON")?;
return parse_json_data_field(body, "Proxmox GET");
}
anyhow::bail!("Proxmox GET failed after retry")
}
fn pve_post_json_data(
client: &reqwest::blocking::Client,
c: &StoredCluster,
base_url: &str,
path_tail: &str,
form_fields: &[(&str, String)],
) -> Result<Value> {
let normalized = normalize_base_url(base_url);
let url = format!("{normalized}{path_tail}");
for attempt in 0..2 {
let auth = session_auth_for_base(client, c, &normalized, attempt > 0)?;
let mut req = client
.post(&url)
.header("Cookie", &auth.cookie_header)
.header("Accept", "application/json");
if !auth.csrf_prevention_token.is_empty() {
req = req.header("CSRFPreventionToken", &auth.csrf_prevention_token);
}
if !form_fields.is_empty() {
req = req.form(form_fields);
}
let response = req.send().with_context(|| format!("POST {url}"))?;
let status = response.status();
if status.as_u16() == 401 && attempt == 0 {
invalidate_cached_session(&c.id, &normalized);
continue;
}
if !status.is_success() {
let text = response.text().unwrap_or_default();
anyhow::bail!("{}", pve_error_hint(status.as_u16(), &text));
}
let body: Value = response.json().context("parse Proxmox JSON")?;
return parse_json_data_field(body, "Proxmox POST");
}
anyhow::bail!("Proxmox POST failed after retry")
}
fn write_api_secret_fields(secret: &str) -> Result<(Option<String>, Option<ApiSecretEncrypted>)> {
if secret.is_empty() {
anyhow::bail!("empty API secret");
}
match try_encrypt_with_app_master(secret) {
Some(Ok((ciphertext, salt, nonce))) => Ok((
None,
Some(ApiSecretEncrypted {
ciphertext,
salt,
nonce,
}),
)),
Some(Err(e)) => Err(e),
None => Ok((Some(secret.to_string()), None)),
}
}
fn merge_stored_secret(new_secret: &str, existing: &StoredCluster) -> Result<(Option<String>, Option<ApiSecretEncrypted>)> {
if new_secret.is_empty() {
Ok((existing.api_secret_plain.clone(), existing.api_secret_encrypted.clone()))
} else {
write_api_secret_fields(new_secret)
}
}
fn build_cluster_slug(name: &str, used: &HashSet<String>) -> String {
let base: String = name
.to_lowercase()
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() {
ch
} else {
'-'
}
})
.collect::<String>()
.trim_matches('-')
.chars()
.fold(String::new(), |mut acc, ch| {
if ch == '-' && acc.ends_with('-') {
return acc;
}
acc.push(ch);
acc
});
let base = if base.is_empty() { "cluster".to_string() } else { base };
if !used.contains(&base) {
return base;
}
let mut n = 2u32;
loop {
let id = format!("{base}-{n}");
if !used.contains(&id) {
return id;
}
n += 1;
}
}
/// Host part of a Proxmox base URL (`https://px01.lan:8006` → `px01.lan`).
fn host_from_proxmox_base(raw: &str) -> Option<String> {
let t = raw.trim();
if t.is_empty() {
return None;
}
let with_scheme = if t.contains("://") {
t.to_string()
} else {
format!("https://{t}")
};
let u = url::Url::parse(&with_scheme).ok()?;
u.host_str().map(|h| h.to_string())
}
/// User-configured `no_proxy` plus every Proxmox cluster host (and optional `cluster` for draft tests).
/// When a corporate HTTP proxy is set, internal hostnames like `px01.lan` must bypass the proxy or
/// connections time out.
fn effective_no_proxy(
state: &ProxmuxState,
cluster: Option<&StoredCluster>,
profile_no_proxy_extra: Option<&str>,
) -> String {
let mut seen = HashSet::<String>::new();
let mut out: Vec<String> = Vec::new();
let mut push_host = |h: String| {
let key = h.to_lowercase();
if seen.insert(key) {
out.push(h);
}
};
for part in state.no_proxy.split(',') {
let p = part.trim();
if !p.is_empty() {
push_host(p.to_string());
}
}
if let Some(extra) = profile_no_proxy_extra {
for part in extra.split(',') {
let p = part.trim();
if !p.is_empty() {
push_host(p.to_string());
}
}
}
for c in state.clusters.values() {
for url in std::iter::once(c.proxmox_url.as_str()).chain(c.failover_urls.iter().map(|s| s.as_str())) {
if let Some(h) = host_from_proxmox_base(url) {
push_host(h);
}
}
}
if let Some(c) = cluster {
for url in std::iter::once(c.proxmox_url.as_str()).chain(c.failover_urls.iter().map(|s| s.as_str())) {
if let Some(h) = host_from_proxmox_base(url) {
push_host(h);
}
}
}
out.join(",")
}
fn resolve_proxy_http_url(state: &ProxmuxState, cluster: &StoredCluster) -> Option<String> {
let raw = cluster.proxy_id.as_deref().map(str::trim).unwrap_or("");
if raw.is_empty() {
let u = state.http_proxy_url.trim();
return if u.is_empty() {
None
} else {
Some(u.to_string())
};
}
if raw.eq_ignore_ascii_case(PROXY_DIRECT_ID) {
return None;
}
state
.proxy_profiles
.iter()
.find(|p| p.id == raw && p.is_enabled)
.and_then(|p| {
let u = p.url.trim();
if u.is_empty() {
None
} else {
Some(u.to_string())
}
})
}
fn profile_no_proxy_extra_line(state: &ProxmuxState, cluster: &StoredCluster) -> Option<String> {
let raw = cluster.proxy_id.as_deref().map(str::trim).unwrap_or("");
if raw.is_empty() || raw.eq_ignore_ascii_case(PROXY_DIRECT_ID) {
return None;
}
state
.proxy_profiles
.iter()
.find(|p| p.id == raw && p.is_enabled)
.map(|p| p.no_proxy_extra.trim().to_string())
.filter(|s| !s.is_empty())
}
fn leaf_sha256_from_pem(pem: &str) -> Result<String> {
let cert = native_tls::Certificate::from_pem(pem.trim().as_bytes()).context("parse PEM certificate")?;
let der = cert.to_der().context("certificate DER")?;
Ok(hex::encode(Sha256::digest(&der)))
}
/// Fetch the peer certificate **chain** (leaf + intermediates) as PEM and the leaf SHA-256.
/// Proxmox often presents a leaf signed by a local CA; trusting only the leaf PEM is not enough
/// for OpenSSL verification (`unable to get local issuer certificate`).
fn fetch_peer_chain_pem_and_leaf_sha256(base_url: &str) -> Result<(String, String)> {
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
let with_scheme = if base_url.contains("://") {
base_url.to_string()
} else {
format!("https://{}", base_url.trim())
};
let u = url::Url::parse(&with_scheme).context("parse Proxmox URL")?;
let host = u.host_str().ok_or_else(|| anyhow::anyhow!("URL missing host"))?;
let port = u.port().unwrap_or(8006);
let addr_label = format!("{host}:{port}");
let mut addrs = addr_label
.to_socket_addrs()
.with_context(|| format!("resolve {addr_label}"))?;
let addr = addrs
.next()
.ok_or_else(|| anyhow::anyhow!("Could not resolve {addr_label}"))?;
let tcp = TcpStream::connect_timeout(&addr, app_prefs::connect_timeout_duration()).context("TCP connect")?;
let mut builder = SslConnector::builder(SslMethod::tls()).context("openssl SslConnector")?;
builder.set_verify(SslVerifyMode::NONE);
let connector = builder.build();
let stream = connector.connect(host, tcp).context("TLS handshake")?;
let ssl = stream.ssl();
let mut pem_acc = String::new();
let mut leaf_der: Option<Vec<u8>> = None;
if let Some(chain) = ssl.peer_cert_chain() {
for (i, cert) in chain.iter().enumerate() {
if i == 0 {
leaf_der = Some(cert.to_der().context("leaf to_der")?);
}
let pem = cert.to_pem().context("to_pem")?;
pem_acc.push_str(&String::from_utf8_lossy(&pem));
}
}
if leaf_der.is_none() {
if let Some(leaf) = ssl.peer_certificate() {
leaf_der = Some(leaf.to_der().context("peer_certificate to_der")?);
let pem = leaf.to_pem().context("peer_certificate to_pem")?;
pem_acc.push_str(&String::from_utf8_lossy(&pem));
}
}
let leaf_der = leaf_der.ok_or_else(|| anyhow::anyhow!("server did not present a certificate"))?;
if pem_acc.trim().is_empty() {
anyhow::bail!("empty PEM chain from server");
}
let sha256 = hex::encode(Sha256::digest(&leaf_der));
Ok((pem_acc, sha256))
}
fn fetch_tls_certificate(arg: &Value) -> Result<Value> {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FetchTlsCertificateArg {
#[serde(default)]
cluster_id: Option<String>,
#[serde(default)]
proxmox_url: Option<String>,
}
let p: FetchTlsCertificateArg = serde_json::from_value(arg.clone()).context("parse fetchTlsCertificate")?;
let base_url = if let Some(id) = p.cluster_id.filter(|s| !s.trim().is_empty()) {
let state = load_state()?;
let c = state
.clusters
.get(&id)
.ok_or_else(|| anyhow::anyhow!("unknown cluster"))?;
normalize_base_url(&c.proxmox_url)
} else if let Some(u) = p.proxmox_url {
normalize_base_url(&u)
} else {
anyhow::bail!("clusterId or proxmoxUrl is required");
};
if base_url.is_empty() {
anyhow::bail!("Proxmox URL is required.");
}
let (pem, sha256) = fetch_peer_chain_pem_and_leaf_sha256(&base_url)?;
Ok(json!({
"ok": true,
"pem": pem,
"leafSha256": sha256,
}))
}
fn http_client(state: &ProxmuxState, cluster: Option<&StoredCluster>) -> Result<reqwest::blocking::Client> {
let allow_insecure = cluster.map(|c| c.allow_insecure_tls).unwrap_or(false);
let has_trusted_pem = cluster
.and_then(|c| c.tls_trusted_cert_pem.as_ref())
.map(|s| s.expose_secret().trim())
.filter(|s| !s.is_empty())
.is_some();
// PVE often omits chain links or uses CAs that do not verify as OpenSSL trust anchors even when
// the PEM bundle is complete. When the user stored a PEM (from fetch or paste), treat that as
// explicit trust for this cluster and skip built-in verification — same effective posture as
// "Allow insecure TLS", while the PEM + leaf fingerprint remain for identity / rotation UX.
let mut b = reqwest::blocking::Client::builder()
.connect_timeout(app_prefs::connect_timeout_duration())
.timeout(app_prefs::http_request_timeout_duration())
.danger_accept_invalid_certs(allow_insecure || has_trusted_pem)
.user_agent(concat!("NoSuckShell-PROXMUX/", env!("CARGO_PKG_VERSION")));
let proxy_url = cluster
.and_then(|c| resolve_proxy_http_url(state, c))
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
if let Some(ref url) = proxy_url {
let prof_extra_owned = cluster.and_then(|c| profile_no_proxy_extra_line(state, c));
let no_proxy_eff = effective_no_proxy(state, cluster, prof_extra_owned.as_deref());
let mut p = Proxy::all(url).context("parse HTTP proxy URL")?;
if !no_proxy_eff.is_empty() {
p = p.no_proxy(reqwest::NoProxy::from_string(&no_proxy_eff));
}
b = b.proxy(p);
}
b.build().context("build HTTP client")
}
fn try_fetch_version(
client: &reqwest::blocking::Client,
base_url: &str,
cluster: &StoredCluster,
) -> Result<serde_json::Value> {
pve_get_json_data(client, cluster, base_url, "/api2/json/version")
}
fn with_failover<T, F>(primary: &str, failover: &[String], mut f: F) -> Result<T>
where
F: FnMut(&str) -> Result<T>,
{
let mut last_err = None;
for base in std::iter::once(primary.to_string()).chain(failover.iter().cloned()) {
let base = normalize_base_url(&base);
if base.is_empty() {
continue;
}
match f(&base) {
Ok(v) => return Ok(v),
Err(e) => last_err = Some(e),
}
}
Err(last_err.unwrap_or_else(|| anyhow::anyhow!("no base URL to try")))
}
/// Best-effort GET returning the Proxmox `data` JSON value; used for inventory IP enrichment only.
fn try_pve_get_json_data_optional(
client: &reqwest::blocking::Client,
cluster: &StoredCluster,
primary: &str,
failover: &[String],
path_tail: &str,
) -> Option<Value> {
for base in std::iter::once(primary.to_string()).chain(failover.iter().cloned()) {
let base = normalize_base_url(&base);
if base.is_empty() {
continue;
}
if let Ok(data) = pve_get_json_data(client, cluster, &base, path_tail) {
return Some(data);
}
}
None
}
fn normalize_ip_candidate(raw: &str) -> Option<String> {
let t = raw.trim();
if t.is_empty() {
return None;
}
let base = t.split('/').next()?.trim();
if base.is_empty() {
return None;
}
let ip: IpAddr = base.parse().ok()?;
Some(match ip {
IpAddr::V4(a) => a.to_string(),
IpAddr::V6(a) => a.to_string(),
})
}
fn append_ips_from_text(s: &str, v4: &mut Vec<String>, v6: &mut Vec<String>) {
for token in s.split(|c| c == ' ' || c == ',' || c == ';') {
let t = token.trim();
if t.is_empty() {
continue;
}
let Some(canonical) = normalize_ip_candidate(t) else {
continue;
};
match IpAddr::from_str(&canonical) {
Ok(IpAddr::V4(a)) => v4.push(a.to_string()),
Ok(IpAddr::V6(a)) => v6.push(a.to_string()),
Err(_) => {}
}
}
}
fn collect_ips_from_node_network(data: &Value) -> (Vec<String>, Vec<String>) {
let mut v4 = Vec::new();
let mut v6 = Vec::new();
let Some(arr) = data.as_array() else {
return (v4, v6);
};
for item in arr {
if let Some(s) = item.get("address").and_then(|x| x.as_str()) {
append_ips_from_text(s, &mut v4, &mut v6);
}
if let Some(s) = item.get("address6").and_then(|x| x.as_str()) {
append_ips_from_text(s, &mut v4, &mut v6);
}
}
(v4, v6)
}