-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadapter.rs
More file actions
2073 lines (1919 loc) · 78.9 KB
/
Copy pathadapter.rs
File metadata and controls
2073 lines (1919 loc) · 78.9 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
use anyhow::{Context, Result, bail};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Weak;
use tokio::sync::mpsc;
use crate::approval_flow::notification::WindowNotifier;
use crate::approval_flow::protocol::HostFrame;
use crate::approval_flow::protocol::PolicyMessage;
use crate::approval_flow::session::ApprovalSession;
use crate::approval_flow::watcher::PolicyWatcher;
use crate::approval_flow::window::{
self, CredentialDecisionDelivery, DecisionDelivery, RequestAction,
};
use crate::credential_flow::integrations::{
applied_integration_routes, resolve_applied_integrations, resolve_connectable_integrations,
};
use crate::credential_flow::notification::WindowCredentialNotifier;
use crate::credential_flow::providers::{DefProvider, Provider};
use crate::credential_flow::registry::expand_credentials_for_wire_with_custom;
use crate::credential_flow::session::CredentialSession;
use crate::credential_flow::store::{
CredentialStateFile, CredentialStore, JsonFileCredentialStore, default_credentials_path,
};
use crate::credential_flow::watcher::CredentialWatcher;
use crate::log;
use crate::relay;
use lns_policy::{FilePolicyStore, Policy, RouteRule};
use super::real::RealFs;
use super::traits::{Fs, WritableFile};
use super::{APPROVAL_TICK, APPROVAL_TIMEOUT, SupervisorAssets, SupervisorSession};
pub(super) async fn ensure() -> Result<PathBuf> {
ensure_with(
|k| std::env::var_os(k),
super::resolve_embedded_supervisor(),
)
.await
}
pub(super) async fn ensure_with(
env_get: impl Fn(&str) -> Option<std::ffi::OsString>,
embedded: Option<&[u8]>,
) -> Result<PathBuf> {
if let Some(override_path) = env_get("LNS_SUPERVISOR_BIN") {
let p = PathBuf::from(override_path);
if !p.is_file() {
bail!(
"LNS_SUPERVISOR_BIN={} is not a regular file. Set the env var to a \
host-readable static-musl supervisor ELF, or unset it to use the \
supervisor embedded into lns-service at build time.",
p.display()
);
}
let path_str = p.display();
log::debug!("using supervisor from LNS_SUPERVISOR_BIN override: {path_str}");
return Ok(p);
}
let cache = crate::cache::root()?.join("supervisor");
let Some(bytes) = embedded else {
bail!(
"no embedded supervisor (lns-service was built with LNS_SUPERVISOR_BIN=skip) and no \
LNS_SUPERVISOR_BIN override set. Rebuild without LNS_SUPERVISOR_BIN=skip to embed the \
supervisor, or set LNS_SUPERVISOR_BIN=/path/to/static-musl/lns-supervisor."
);
};
install_embedded_supervisor(&RealFs, &cache, bytes).await
}
/// Install the embedded supervisor ELF into `cache` at a content-addressed path, idempotently.
async fn install_embedded_supervisor(fs: &impl Fs, cache: &Path, bytes: &[u8]) -> Result<PathBuf> {
let sha = format!("{:x}", Sha256::digest(bytes));
let bin_path = cache.join(format!("supervisor-embedded-{}", &sha[..16]));
if fs.exists(&bin_path).await {
return Ok(bin_path);
}
fs.create_dir_all(cache)
.await
.with_context(|| format!("create_dir_all {}", cache.display()))?;
atomic_write_executable(fs, &bin_path, bytes)
.await
.with_context(|| format!("installing embedded supervisor at {}", bin_path.display()))?;
Ok(bin_path)
}
async fn atomic_write_with_mode(fs: &impl Fs, path: &Path, bytes: &[u8], mode: u32) -> Result<()> {
let tmp = path.with_extension("tmp");
let _ = fs.remove_file(&tmp).await;
{
let mut f = fs
.create_new(&tmp)
.await
.with_context(|| format!("creating {}", tmp.display()))?;
f.write_all(bytes)
.await
.with_context(|| format!("writing {}", tmp.display()))?;
f.sync_all()
.await
.with_context(|| format!("fsync {}", tmp.display()))?;
}
fs.set_permissions(&tmp, mode)
.await
.with_context(|| format!("chmod {}", tmp.display()))?;
fs.rename(&tmp, path)
.await
.with_context(|| format!("rename {} -> {}", tmp.display(), path.display()))?;
Ok(())
}
async fn atomic_write_executable(fs: &impl Fs, path: &Path, bytes: &[u8]) -> Result<()> {
atomic_write_with_mode(fs, path, bytes, 0o755).await
}
async fn decision_delivery_loop(
session: Weak<ApprovalSession>,
mut decision_rx: mpsc::UnboundedReceiver<DecisionDelivery>,
) {
while let Some(delivery) = decision_rx.recv().await {
let Some(session) = session.upgrade() else {
break;
};
match delivery.action {
RequestAction::Decide(decision) => {
session.record_decision(&delivery.id, decision);
}
// Accepting an integration offer drives a connect (async) rather than a per-request verdict.
RequestAction::ConnectIntegration => {
session.connect_offer(&delivery.id).await;
}
// A pasted token connects the integration without the interactive sign-in.
RequestAction::UseToken { value } => {
session.connect_offer_with_token(&delivery.id, value).await;
}
}
}
}
/// Mirror of [`decision_delivery_loop`]; `Weak` so the loop never keeps the session alive past its run.
async fn credential_delivery_loop(
session: Weak<CredentialSession>,
mut decision_rx: mpsc::UnboundedReceiver<CredentialDecisionDelivery>,
) {
while let Some(delivery) = decision_rx.recv().await {
let Some(session) = session.upgrade() else {
break;
};
// A pasted token is an Allow(Stored) — it arms the slot directly via record_decision; only the browser-consent Allow drives the device sign-in.
let pasted_token = matches!(
delivery.request,
crate::credential_flow::session::CredentialDecisionRequest::Allow(
crate::credential_flow::store::CredentialEntry::Stored { .. }
)
);
// Accepting an oauth prompt via the browser consent drives a device sign-in (async) instead of arming a static value.
if session.is_oauth_prompt(&delivery.id)
&& matches!(
delivery.request,
crate::credential_flow::session::CredentialDecisionRequest::Allow(_)
)
&& !pasted_token
{
session.connect_oauth(&delivery.id).await;
} else {
session.record_decision(&delivery.id, delivery.request);
}
}
}
async fn tick_timeouts_loop(weak: Weak<ApprovalSession>) {
let mut interval = tokio::time::interval(APPROVAL_TICK);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
interval.tick().await;
if !sweep_once(&weak) {
break;
}
}
}
async fn credential_tick_timeouts_loop(weak: Weak<CredentialSession>) {
let mut interval = tokio::time::interval(APPROVAL_TICK);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
interval.tick().await;
if !credential_sweep_once(&weak) {
break;
}
}
}
fn credential_sweep_once(weak: &Weak<CredentialSession>) -> bool {
let Some(session) = weak.upgrade() else {
return false;
};
session.tick_timeouts(std::time::Instant::now());
true
}
fn sweep_once(weak: &Weak<ApprovalSession>) -> bool {
let Some(session) = weak.upgrade() else {
return false;
};
session.tick_timeouts(std::time::Instant::now());
true
}
/// Defaults to empty and warns on store error, so a malformed `~/.lns-credentials.json` doesn't silently wipe the developer's rules at startup.
fn load_credentials_or_warn(store: &dyn CredentialStore, path: &Path) -> CredentialStateFile {
match store.load() {
Ok(state) => state,
Err(e) => {
let path_str = path.display();
log::warn!("could not load {path_str} ({e}); starting with empty credential state");
CredentialStateFile::new()
}
}
}
/// Defaults to an empty user catalog and warns on load error, so a malformed `~/.lns-integrations.yaml` doesn't break a run — the bundled catalog still applies.
fn load_user_catalog_or_warn(path: &Path) -> lns_policy::integrations::Catalog {
match lns_policy::integrations::Catalog::load_or_default(path) {
Ok(catalog) => catalog,
Err(e) => {
let path_str = path.display();
log::warn!(
"could not load {path_str} ({e}); using the bundled integration catalog only"
);
lns_policy::integrations::Catalog::default()
}
}
}
/// The env vars seeded as placeholders for this run's connected and connectable integrations; stripped from `-e` so a real secret can't bypass the placeholder.
fn collect_managed_env_vars(providers: &[DefProvider]) -> Vec<String> {
providers.iter().map(|p| p.env_var().to_string()).collect()
}
/// `Weak` so the closure doesn't keep the credential session alive past the run; a dropped session yields an empty list.
fn make_credentials_provider(
credential_session: &Arc<CredentialSession>,
) -> crate::approval_flow::session::CredentialsProvider {
let weak = Arc::downgrade(credential_session);
Box::new(move || {
weak.upgrade()
.map(|cs| {
expand_credentials_for_wire_with_custom(&cs.current_state(), cs.custom_providers())
})
.unwrap_or_default()
})
}
fn build_credential_notifier(
decision_tx: tokio::sync::mpsc::UnboundedSender<CredentialDecisionDelivery>,
custom_providers: Arc<Vec<DefProvider>>,
) -> WindowCredentialNotifier {
let window_state = window::get().expect("window state installed by caller");
WindowCredentialNotifier::with_registry_detection(
window_state,
decision_tx,
window::ctx(),
custom_providers,
)
}
/// The follow-up `Policy` frame after a credential decision must carry both the current network policy and the registry-expanded credentials.
fn make_policy_emitter(
session: Arc<ApprovalSession>,
sink: tokio::sync::mpsc::UnboundedSender<HostFrame>,
custom_providers: Arc<Vec<DefProvider>>,
) -> crate::credential_flow::session::PolicyEmitter {
Box::new(move |state| {
let network = session.current_policy().network;
let credentials = expand_credentials_for_wire_with_custom(state, &custom_providers);
let _ = sink.send(HostFrame::Policy(PolicyMessage {
network: Some(network),
credentials: Some(credentials),
}));
})
}
/// A watcher reload replaces the live policy from disk, where connected integrations are recorded id-only; this deriver re-applies their catalog routes so the reload doesn't drop them.
fn make_integration_route_deriver(
catalog: Vec<lns_policy::integrations::Integration>,
) -> crate::approval_flow::session::IntegrationRouteDeriver {
Box::new(move |ids| applied_integration_routes(ids, &catalog))
}
/// Connecting an un-connected catalog integration allows its routes on the approval session's live policy (and persists `integrations:`), so the held request proceeds without a relaunch.
fn make_connect_emitter(
session: Arc<ApprovalSession>,
routes: Arc<HashMap<String, Vec<RouteRule>>>,
) -> crate::credential_flow::session::ConnectEmitter {
Box::new(move |id| {
let rules = routes.get(id).cloned().unwrap_or_default();
session.connect_integration(id, rules);
})
}
/// Pairs each connectable integration's id with its catalog display name and route patterns, so a held request to one of those domains can offer to connect it instead of asking about the bare host.
fn build_offerable(
connectable: &crate::credential_flow::integrations::ConnectableIntegrations,
catalog: &[lns_policy::integrations::Integration],
) -> Vec<crate::approval_flow::session::OfferableIntegration> {
connectable
.routes
.iter()
.map(|(id, routes)| {
let display_name = catalog
.iter()
.find(|i| &i.id == id)
.map(|i| i.display_name().to_string())
.unwrap_or_else(|| id.clone());
let token_fallback = catalog
.iter()
.find(|i| &i.id == id)
.and_then(|i| i.token_fallback.clone());
crate::approval_flow::session::OfferableIntegration {
id: id.clone(),
display_name,
patterns: routes.iter().map(|r| r.match_pattern.clone()).collect(),
token_fallback,
}
})
.collect()
}
/// Bridges an accepted network offer to the credential subsystem's connect; `Weak` so it never keeps the credential session alive past the run.
struct CredentialConnector {
credential_session: Weak<CredentialSession>,
}
impl crate::approval_flow::session::IntegrationConnector for CredentialConnector {
fn connect<'a>(&'a self, id: &'a str) -> futures_util::future::BoxFuture<'a, bool> {
Box::pin(async move {
match self.credential_session.upgrade() {
Some(cs) => cs.connect_integration_now(id).await,
None => false,
}
})
}
fn connect_with_token<'a>(
&'a self,
id: &'a str,
value: String,
) -> futures_util::future::BoxFuture<'a, bool> {
Box::pin(async move {
match self.credential_session.upgrade() {
Some(cs) => cs.connect_integration_with_token(id, value),
None => false,
}
})
}
}
type CredentialSubsystem = (
Arc<CredentialSession>,
crate::credential_flow::watcher::CredentialWatcher,
);
/// A device-flow access token within this many seconds of expiry is refreshed at run start rather than served stale.
const OAUTH_REFRESH_SKEW_SECS: u64 = 60;
/// The per-integration oauth wiring a run hands to its credential subsystem: device-flow configs, display names, and token fallbacks, all keyed by integration id.
struct OauthWiring {
configs: HashMap<String, crate::oauth::OauthConfig>,
pkce_configs: HashMap<String, crate::oauth::PkceConfig>,
display_names: HashMap<String, String>,
token_fallbacks: HashMap<String, lns_policy::integrations::TokenFallback>,
}
async fn start_credential_subsystem(
session: Arc<ApprovalSession>,
credential_frame_tx: tokio::sync::mpsc::UnboundedSender<HostFrame>,
custom_providers: Arc<Vec<DefProvider>>,
connectable_ids: HashSet<String>,
connectable_routes: Arc<HashMap<String, Vec<RouteRule>>>,
oauth: OauthWiring,
) -> Result<CredentialSubsystem> {
// The credentials file is per-machine $HOME state, so its path is independent of `--policy`.
let credentials_path = default_credentials_path();
let credential_store: Arc<dyn CredentialStore> =
Arc::new(JsonFileCredentialStore::new(credentials_path.clone()));
let mut initial_credential_state =
load_credentials_or_warn(credential_store.as_ref(), &credentials_path);
// Renew any oauth grant that expired since last use before the session arms it (the dominant case; a mid-run expiry falls back to the held-request re-prompt).
crate::oauth::refresh_due_entries(
&mut initial_credential_state,
&oauth.configs,
&crate::oauth::RealDeviceFlow,
&crate::oauth::RealClock,
credential_store.as_ref(),
OAUTH_REFRESH_SKEW_SECS,
)
.await;
let (credential_decision_tx, credential_decision_rx) = tokio::sync::mpsc::unbounded_channel();
let credential_notifier = Arc::new(build_credential_notifier(
credential_decision_tx,
custom_providers.clone(),
));
let policy_emitter = make_policy_emitter(
session.clone(),
credential_frame_tx.clone(),
custom_providers.clone(),
);
let connect_emitter = make_connect_emitter(session.clone(), connectable_routes);
let credential_session = Arc::new(
CredentialSession::with_policy_emitter(
initial_credential_state,
credential_notifier,
credential_store,
credential_frame_tx,
APPROVAL_TIMEOUT,
policy_emitter,
)
.with_custom_providers(custom_providers)
.with_bundled_ids(
lns_policy::integrations::bundled_integrations()
.iter()
.map(|i| i.id.clone())
.collect(),
)
.with_connect_emitter(connectable_ids, connect_emitter)
.with_oauth(
oauth.configs,
Arc::new(crate::oauth::RealDeviceFlow),
Arc::new(crate::oauth::RealClock),
)
.with_pkce(
oauth.pkce_configs,
Arc::new(crate::oauth::RealAuthCodeFlow),
Arc::new(crate::oauth::RealCallbackListener),
Box::new(crate::browser::open),
Box::new(crate::oauth::PkceChallenge::generate),
crate::credential_flow::session::PKCE_SIGN_IN_TIMEOUT,
)
.with_oauth_display_names(oauth.display_names)
.with_token_fallbacks(oauth.token_fallbacks),
);
tokio::spawn(credential_delivery_loop(
Arc::downgrade(&credential_session),
credential_decision_rx,
));
tokio::spawn(credential_tick_timeouts_loop(Arc::downgrade(
&credential_session,
)));
// Back-reference so the approval session's Policy emits carry the credential registry instead of `credentials: null`.
session.set_credentials_provider(make_credentials_provider(&credential_session));
let credential_watcher = CredentialWatcher::spawn(credentials_path, credential_session.clone())
.context("watching credentials file")?;
Ok((credential_session, credential_watcher))
}
pub(super) async fn start(
run_id: u32,
policy_path: &Path,
guest_tools_root: PathBuf,
user_env: Vec<String>,
) -> Result<SupervisorSession> {
let mut policy = Policy::load_or_default(policy_path)
.with_context(|| format!("loading policy {}", policy_path.display()))?;
// Applied integrations resolve against the effective catalog (bundled ∪ user) into both wire credentials and allow-routes, captured once at boot so a later edit can't reach an already-forked workload.
let user_catalog =
load_user_catalog_or_warn(&lns_policy::integrations::default_integrations_path());
let catalog = lns_policy::integrations::effective_integrations(&user_catalog);
let applied = resolve_applied_integrations(&policy, &catalog);
// Un-connected catalog integrations are seeded unarmed so their use offers a live connect.
let connectable = resolve_connectable_integrations(&policy, &catalog);
policy.network.allowed_routes.extend(applied.routes);
let connectable_ids: HashSet<String> = connectable
.providers
.iter()
.map(|p| p.id().to_string())
.collect();
let offerable = build_offerable(&connectable, &catalog);
let connectable_routes = Arc::new(connectable.routes);
let mut custom = applied.providers;
custom.extend(connectable.providers);
let custom_providers = Arc::new(custom);
let managed_env_vars = collect_managed_env_vars(&custom_providers);
let window_state = window::get().context(
"approval window state was not installed at boot; \
tray::run_tray must run before any policy-bearing run starts",
)?;
let (decision_tx, decision_rx) = tokio::sync::mpsc::unbounded_channel::<DecisionDelivery>();
let notifier = Arc::new(WindowNotifier::new(
window_state,
decision_tx,
window::ctx(),
));
log::info!("Approvals", "window ready");
let store = Arc::new(FilePolicyStore::new(policy_path.to_path_buf()));
let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel::<HostFrame>();
let credential_frame_tx = frame_tx.clone();
let session = Arc::new(
ApprovalSession::new(policy, notifier, store, frame_tx, APPROVAL_TIMEOUT)
.with_offers(offerable),
);
session.set_integration_route_deriver(make_integration_route_deriver(catalog.clone()));
tokio::spawn(decision_delivery_loop(
Arc::downgrade(&session),
decision_rx,
));
tokio::spawn(tick_timeouts_loop(Arc::downgrade(&session)));
let watcher = PolicyWatcher::spawn(policy_path.to_path_buf(), session.clone())
.with_context(|| format!("watching policy {}", policy_path.display()))?;
let oauth_configs: HashMap<String, crate::oauth::OauthConfig> = applied
.oauth_configs
.iter()
.chain(connectable.oauth_configs.iter())
.map(|(id, auth)| (id.clone(), crate::oauth::OauthConfig::from(auth)))
.collect();
let pkce_configs: HashMap<String, crate::oauth::PkceConfig> = applied
.pkce_configs
.iter()
.chain(connectable.pkce_configs.iter())
.map(|(id, auth)| (id.clone(), crate::oauth::PkceConfig::from(auth)))
.collect();
let oauth_display_names: HashMap<String, String> = catalog
.iter()
.filter(|i| i.oauth.is_some())
.map(|i| (i.id.clone(), i.display_name().to_string()))
.collect();
let token_fallbacks: HashMap<String, lns_policy::integrations::TokenFallback> = catalog
.iter()
.filter_map(|i| i.token_fallback.clone().map(|tf| (i.id.clone(), tf)))
.collect();
let (credential_session, credential_watcher) = start_credential_subsystem(
session.clone(),
credential_frame_tx,
custom_providers,
connectable_ids,
connectable_routes,
OauthWiring {
configs: oauth_configs,
pkce_configs,
display_names: oauth_display_names,
token_fallbacks,
},
)
.await?;
// Back-reference (Weak so it never outlives the run) so accepting a network offer drives the credential subsystem's connect.
session.set_connector(Arc::new(CredentialConnector {
credential_session: Arc::downgrade(&credential_session),
}));
let supervisor_bin = ensure().await?;
let relay = relay::spawn(run_id, session, credential_session, frame_rx, user_env)?;
log::debug!(url = %relay.url, "relay listening");
log::info!("Auditing", "to {}", relay.audit_path.display());
Ok(SupervisorSession {
assets: SupervisorAssets {
supervisor_bin,
guest_tools_root,
},
relay,
watcher: Some(watcher),
credential_watcher: Some(credential_watcher),
managed_env_vars,
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
fn fixture_session() -> (Arc<ApprovalSession>, mpsc::UnboundedReceiver<HostFrame>) {
use crate::approval_flow::session::tests::{CapturingStore, RecordingNotifier};
use lns_policy::Policy;
let notifier = Arc::new(RecordingNotifier::default());
let store = Arc::new(CapturingStore::default());
let (frame_tx, frame_rx) = mpsc::unbounded_channel::<HostFrame>();
let session = Arc::new(ApprovalSession::new(
Policy::default(),
notifier,
store,
frame_tx,
std::time::Duration::from_secs(30),
));
(session, frame_rx)
}
#[derive(Default)]
struct RecordingConnector {
connects: std::sync::Mutex<Vec<String>>,
token_connects: std::sync::Mutex<Vec<(String, String)>>,
}
impl crate::approval_flow::session::IntegrationConnector for RecordingConnector {
fn connect<'a>(&'a self, id: &'a str) -> futures_util::future::BoxFuture<'a, bool> {
Box::pin(async move {
self.connects.lock().unwrap().push(id.to_string());
true
})
}
fn connect_with_token<'a>(
&'a self,
id: &'a str,
value: String,
) -> futures_util::future::BoxFuture<'a, bool> {
Box::pin(async move {
self.token_connects
.lock()
.unwrap()
.push((id.to_string(), value));
true
})
}
}
#[tokio::test]
async fn decision_delivery_loop_applies_each_delivery_and_exits_on_tx_drop() {
use crate::approval_flow::protocol::{Decision, HostFrame, RequestPending};
let (session, mut frame_rx) = fixture_session();
let (tx, rx) = mpsc::unbounded_channel::<DecisionDelivery>();
session.submit_pending(
RequestPending {
id: "r1".into(),
host: "api.linear.app".into(),
action: "CONNECT api.linear.app:443".into(),
reason: "policy-ambiguous".into(),
},
std::time::Instant::now(),
);
tx.send(DecisionDelivery {
id: "r1".into(),
action: RequestAction::Decide(Decision::AllowOnce),
})
.unwrap();
drop(tx);
decision_delivery_loop(Arc::downgrade(&session), rx).await;
let frame = frame_rx.try_recv().expect("decision frame");
match frame {
HostFrame::RequestDecision(d) => {
assert_eq!(d.id, "r1");
assert_eq!(d.decision, Decision::AllowOnce);
}
other => panic!("expected RequestDecision, got {other:?}"),
}
}
#[tokio::test]
async fn decision_delivery_loop_routes_a_connect_action_to_connect_offer() {
use crate::approval_flow::protocol::{Decision, HostFrame, RequestPending};
use crate::approval_flow::session::OfferableIntegration;
use crate::approval_flow::session::tests::{CapturingStore, RecordingNotifier};
let notifier = Arc::new(RecordingNotifier::default());
let store = Arc::new(CapturingStore::default());
let (frame_tx, mut frame_rx) = mpsc::unbounded_channel::<HostFrame>();
let session = Arc::new(
ApprovalSession::new(
Policy::default(),
notifier,
store,
frame_tx,
std::time::Duration::from_secs(30),
)
.with_offers(vec![OfferableIntegration {
id: "some-oauth".into(),
display_name: "GitHub".into(),
patterns: vec!["api.some-oauth.example".into()],
token_fallback: None,
}]),
);
let connector = Arc::new(RecordingConnector::default());
session.set_connector(connector.clone());
session.submit_pending(
RequestPending {
id: "r1".into(),
host: "api.some-oauth.example".into(),
action: "CONNECT api.some-oauth.example:443".into(),
reason: "policy-ambiguous".into(),
},
std::time::Instant::now(),
);
let (tx, rx) = mpsc::unbounded_channel::<DecisionDelivery>();
tx.send(DecisionDelivery {
id: "r1".into(),
action: RequestAction::ConnectIntegration,
})
.unwrap();
drop(tx);
decision_delivery_loop(Arc::downgrade(&session), rx).await;
assert_eq!(
connector.connects.lock().unwrap().as_slice(),
&["some-oauth".to_string()],
"accepting the offer drives the interactive connect"
);
match frame_rx.try_recv().expect("decision frame") {
HostFrame::RequestDecision(d) => {
assert_eq!(d.id, "r1");
assert_eq!(
d.decision,
Decision::AllowOnce,
"a connected offer releases the held request"
);
}
other => panic!("expected RequestDecision, got {other:?}"),
}
}
#[tokio::test]
async fn decision_delivery_loop_routes_a_use_token_action_to_connect_offer_with_token() {
use crate::approval_flow::protocol::{Decision, HostFrame, RequestPending};
use crate::approval_flow::session::OfferableIntegration;
use crate::approval_flow::session::tests::{CapturingStore, RecordingNotifier};
let notifier = Arc::new(RecordingNotifier::default());
let store = Arc::new(CapturingStore::default());
let (frame_tx, mut frame_rx) = mpsc::unbounded_channel::<HostFrame>();
let session = Arc::new(
ApprovalSession::new(
Policy::default(),
notifier,
store,
frame_tx,
std::time::Duration::from_secs(30),
)
.with_offers(vec![OfferableIntegration {
id: "some-oauth".into(),
display_name: "GitHub".into(),
patterns: vec!["api.some-oauth.example".into()],
token_fallback: None,
}]),
);
let connector = Arc::new(RecordingConnector::default());
session.set_connector(connector.clone());
session.submit_pending(
RequestPending {
id: "r1".into(),
host: "api.some-oauth.example".into(),
action: "CONNECT api.some-oauth.example:443".into(),
reason: "policy-ambiguous".into(),
},
std::time::Instant::now(),
);
let (tx, rx) = mpsc::unbounded_channel::<DecisionDelivery>();
tx.send(DecisionDelivery {
id: "r1".into(),
action: RequestAction::UseToken {
value: "some-pasted-token".into(),
},
})
.unwrap();
drop(tx);
decision_delivery_loop(Arc::downgrade(&session), rx).await;
assert_eq!(
connector.token_connects.lock().unwrap().as_slice(),
&[("some-oauth".to_string(), "some-pasted-token".to_string())],
"a UseToken action drives the token connect with the pasted value"
);
assert!(
connector.connects.lock().unwrap().is_empty(),
"the interactive connect must not run for a token paste"
);
match frame_rx.try_recv().expect("decision frame") {
HostFrame::RequestDecision(d) => {
assert_eq!(d.id, "r1");
assert_eq!(d.decision, Decision::AllowOnce);
}
other => panic!("expected RequestDecision, got {other:?}"),
}
}
#[tokio::test]
async fn decision_delivery_loop_breaks_when_upgrade_fails_with_buffered_delivery() {
use crate::approval_flow::protocol::Decision;
let (session, _frame_rx) = fixture_session();
let weak = Arc::downgrade(&session);
let (tx, rx) = mpsc::unbounded_channel::<DecisionDelivery>();
let stale_clone = tx.clone();
stale_clone
.send(DecisionDelivery {
id: "r1".into(),
action: RequestAction::Decide(Decision::AllowOnce),
})
.unwrap();
drop(session);
drop(tx);
drop(stale_clone);
tokio::time::timeout(
std::time::Duration::from_secs(2),
decision_delivery_loop(weak, rx),
)
.await
.expect("loop must exit promptly when upgrade fails");
}
#[tokio::test]
async fn decision_delivery_loop_exits_when_session_strong_refs_drop() {
use crate::approval_flow::notification::WindowNotifier;
use crate::approval_flow::session::ApprovalSession;
use crate::approval_flow::window::WindowState;
use lns_policy::Policy;
use std::sync::Arc;
let window_state = WindowState::new();
let (decision_tx, decision_rx) = mpsc::unbounded_channel::<DecisionDelivery>();
let notifier = Arc::new(WindowNotifier::new(window_state, decision_tx, None));
use crate::approval_flow::session::tests::CapturingStore;
let store = Arc::new(CapturingStore::default());
let (frame_tx, _frame_rx) = mpsc::unbounded_channel::<HostFrame>();
let session = Arc::new(ApprovalSession::new(
Policy::default(),
notifier,
store,
frame_tx,
std::time::Duration::from_secs(30),
));
let weak = Arc::downgrade(&session);
let handle = tokio::spawn(decision_delivery_loop(weak, decision_rx));
tokio::task::yield_now().await;
drop(session);
tokio::time::timeout(std::time::Duration::from_secs(2), handle)
.await
.expect("decision_delivery_loop must exit once strong refs drop")
.expect("decision_delivery_loop task panicked");
}
#[tokio::test]
async fn tick_timeouts_loop_exits_when_strong_refs_drop() {
let (session, _frame_rx) = fixture_session();
let weak = Arc::downgrade(&session);
drop(session);
tokio::time::timeout(std::time::Duration::from_secs(2), tick_timeouts_loop(weak))
.await
.expect("ticker exits promptly once session drops");
}
#[tokio::test]
async fn tick_timeouts_loop_invokes_sweep_while_session_alive() {
let (session, _frame_rx) = fixture_session();
let weak = Arc::downgrade(&session);
let handle = tokio::spawn(tick_timeouts_loop(weak));
tokio::task::yield_now().await;
drop(session);
tokio::time::timeout(std::time::Duration::from_secs(2), handle)
.await
.expect("ticker exits after session drop")
.expect("ticker task panicked");
}
#[test]
fn sweep_once_returns_false_when_session_dropped() {
let (session, _frame_rx) = fixture_session();
let weak = Arc::downgrade(&session);
drop(session);
assert!(!sweep_once(&weak), "no strong refs → loop should exit");
}
fn fixture_credential_session() -> (Arc<CredentialSession>, mpsc::UnboundedReceiver<HostFrame>)
{
fixture_credential_session_seeding(Arc::new(Vec::new()))
}
fn fixture_credential_session_seeding(
custom: Arc<Vec<DefProvider>>,
) -> (Arc<CredentialSession>, mpsc::UnboundedReceiver<HostFrame>) {
use crate::credential_flow::notification::NoopCredentialNotifier;
let (store, _dir) = tempfile_credential_store();
// Leak the tempdir guard for the life of the session (test-only).
Box::leak(Box::new(_dir));
let (frame_tx, frame_rx) = mpsc::unbounded_channel::<HostFrame>();
let session = Arc::new(
CredentialSession::new(
CredentialStateFile::new(),
Arc::new(NoopCredentialNotifier),
store,
frame_tx,
std::time::Duration::from_secs(30),
)
.with_custom_providers(custom),
);
(session, frame_rx)
}
/// Real store (not an inline fake) keeps its `CredentialStore` impl out of the coverage gap.
fn tempfile_credential_store() -> (
Arc<crate::credential_flow::store::JsonFileCredentialStore>,
tempfile::TempDir,
) {
let dir = tempfile::TempDir::new().expect("tempdir");
let path = dir.path().join("creds.json");
(
Arc::new(crate::credential_flow::store::JsonFileCredentialStore::new(
path,
)),
dir,
)
}
#[test]
fn load_credentials_or_warn_returns_stored_state_on_ok() {
use crate::credential_flow::store::CredentialEntry;
let (store, _dir) = tempfile_credential_store();
let mut seeded = CredentialStateFile::new();
seeded.insert("some-provider".into(), CredentialEntry::HostDetect);
store.save(&seeded).unwrap();
let state = load_credentials_or_warn(store.as_ref(), Path::new("/tmp/x"));
assert!(state.contains_key("some-provider"));
}
#[test]
fn load_credentials_or_warn_defaults_to_empty_and_warns_on_store_error() {
init_tracing_capture();
let dir = tempfile::TempDir::new().expect("tempdir");
let path = dir.path().join("creds.json");
std::fs::write(&path, "{ this is not valid json").unwrap();
let store = crate::credential_flow::store::JsonFileCredentialStore::new(path.clone());
let state = load_credentials_or_warn(&store, &path);
assert!(
state.is_empty(),
"malformed credentials file must surface as empty in-memory state, got {state:?}"
);
}
#[test]
fn load_user_catalog_or_warn_reads_an_existing_user_catalog() {
use lns_policy::integrations::{AuthKind, Catalog, CredentialAuth, Integration};
let dir = tempfile::TempDir::new().expect("tempdir");
let path = dir.path().join(".lns-integrations.yaml");
Catalog {
integrations: vec![Integration {
id: "acme".into(),
name: None,
auth_kind: AuthKind::Credential,
routes: Vec::new(),
credential: Some(CredentialAuth {
env_var: "ACME_API_KEY".into(),
placeholder: "acme_LNSPLACEHOLDER".into(),
injections: Vec::new(),
}),
oauth: None,
token_fallback: None,
}],
}
.save_atomic(&path)
.unwrap();
let catalog = load_user_catalog_or_warn(&path);
assert_eq!(catalog.integrations.len(), 1);
assert_eq!(catalog.integrations[0].id, "acme");
}
#[test]
fn load_user_catalog_or_warn_defaults_to_empty_and_warns_on_load_error() {
init_tracing_capture();
let dir = tempfile::TempDir::new().expect("tempdir");
let path = dir.path().join(".lns-integrations.yaml");
std::fs::write(&path, "integrations: not-a-list\n").unwrap();
let catalog = load_user_catalog_or_warn(&path);
assert!(
catalog.integrations.is_empty(),
"a malformed user catalog must surface as empty so the run still gets the bundled set"
);
}
#[test]
fn make_credentials_provider_returns_registry_expansion_while_session_alive() {
let (session, _frame_rx) = fixture_credential_session_seeding(acme_custom());
let provider = make_credentials_provider(&session);
let creds = provider();
let ids: Vec<&str> = creds.iter().map(|c| c.id.as_str()).collect();
assert!(ids.contains(&"acme"), "got {ids:?}");
}
#[test]
fn make_policy_emitter_sends_policy_with_network_and_credentials() {
use crate::credential_flow::store::{CredentialEntry, CredentialStateFile};
use lns_policy::RouteRule;
let (session, mut session_rx) = fixture_session();
let mut updated = Policy::default();
updated.add_rule(RouteRule::allow_host("api.linear.app"));
session.apply_external_policy(updated);