Repository navigation
Expand file tree
/
Copy pathconfig_runtime.rs
More file actions
4204 lines (3961 loc) · 172 KB
/
Copy pathconfig_runtime.rs
File metadata and controls
4204 lines (3961 loc) · 172 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
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Runtime gateway configuration: applies polled and streamed sandbox
//! configuration and provider environments after startup, and reports apply
//! results back to the gateway.
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use miette::Result;
use openshell_core::PolicyValidationFailureMode;
use openshell_core::proposals::AgentProposals;
use openshell_core::proto::{
ConfigApplyFailure, ConfigApplyOutcome, ConfigUpdateResult, PolicyLoadResult,
ProviderReadinessReason, SandboxConfigurationAdmission,
};
use openshell_ocsf::{ConfigStateChangeBuilder, SeverityId, StateId, StatusId, ocsf_emit};
use openshell_supervisor_network::opa::PolicyGenerationGuard;
use openshell_supervisor_process::skills;
use openshell_supervisor_process::supervisor_session::{
ConfigApplyRequest, config_admission, config_apply_failure, sandbox_config_revision,
};
use tracing::{debug, info, warn};
use crate::provider_readiness::EnvironmentIdentity;
use crate::{
CapturedProviderEnvironment, FailedRuntimeRevision, GatewayRuntimeFailureDisposition,
InitialPollDisposition, LoadedPolicyOrigin, MiddlewareAuthentication,
MiddlewareRegistryReconciliation, MiddlewareRegistryStatus, MiddlewareReloadContext,
PolicyGatewayClient, PolicyPollLoopContext, PolicyStatusUpdate, RejectedPolicyGeneration,
apply_gateway_runtime_reload_failure, apply_policy_validation_failure,
emit_policy_validation_failure, endpoint_status, enqueue_policy_status,
gateway_policy_runtime_needs_reconciliation, initial_poll_disposition,
middleware_registry_needs_rebuild, next_poll_delay, ocsf_ctx,
provider_environment_is_installable, reconcile_middleware_registry,
reload_gateway_configuration_runtime, retain_extension_credentials, run_policy_status_reporter,
unchanged_policy_revision_candidate, unchanged_policy_revision_ready_to_ack,
};
async fn receive_config_apply(
receiver: &mut Option<tokio::sync::mpsc::Receiver<ConfigApplyRequest>>,
) -> Option<ConfigApplyRequest> {
match receiver {
Some(receiver) => receiver.recv().await,
None => std::future::pending().await,
}
}
/// What applying one delivered update produced, before its update ID is
/// attached.
#[derive(Clone, Debug)]
struct DeliveredResult {
outcome: ConfigApplyOutcome,
failure: Option<ConfigApplyFailure>,
admission: SandboxConfigurationAdmission,
policy_load: Option<PolicyLoadResult>,
}
impl DeliveredResult {
fn into_update_result(self, update_id: String) -> ConfigUpdateResult {
ConfigUpdateResult {
update_id,
outcome: self.outcome.into(),
failure: self.failure,
admission: Some(self.admission),
policy_load: self.policy_load,
}
}
}
fn policy_load_result(status: PolicyStatusUpdate) -> PolicyLoadResult {
PolicyLoadResult {
version: status.version,
loaded: status.loaded,
error: status.error,
}
}
#[derive(Debug)]
struct RejectedStreamSandbox {
configuration_instance_id: String,
requested_revision: openshell_core::proto::ConfigSnapshotRevision,
environment: EnvironmentIdentity,
error: String,
failure_mode: PolicyValidationFailureMode,
result: DeliveredResult,
}
impl RejectedStreamSandbox {
fn matches(
&self,
snapshot: &openshell_core::grpc_client::SettingsPollResult,
requested_revision: &openshell_core::proto::ConfigSnapshotRevision,
environment: &EnvironmentIdentity,
) -> bool {
self.configuration_instance_id == snapshot.configuration_instance_id
&& self.requested_revision == *requested_revision
&& self.environment == *environment
&& self.error == snapshot.configuration_error
&& self.failure_mode == snapshot.policy_validation_failure_mode
}
}
/// Configuration delivered over the supervisor session. Each update carries
/// the sandbox configuration and the provider environment it names.
#[derive(Default)]
struct StreamConfigurationState {
/// Last rejected configuration, so a redelivery does not quarantine the
/// runtime again.
rejected_sandbox: Option<Box<RejectedStreamSandbox>>,
}
/// Where a reconciled sandbox configuration's provider environment comes from.
enum ProviderSource {
/// Policy polling fetches the environment when the requested one changed
/// or the last installation needs a retry.
Fetch,
/// Session delivery prepared the environment its update carried, or
/// `None` when the installed environment matches.
Delivered(Option<CapturedProviderEnvironment>),
}
/// Why a sandbox configuration snapshot was not activated.
struct ConfigRejection {
/// Stable failure code reported on the supervisor session.
code: &'static str,
/// Diagnostic reported on the supervisor session.
detail: String,
/// Error reported with the rejected configuration admission.
admission_error: String,
}
enum ReconcileOutcome {
/// The runtime already enforces the snapshot.
Unchanged,
/// The runtime now enforces the snapshot.
Applied,
Rejected(ConfigRejection),
}
struct Reconciled {
outcome: ReconcileOutcome,
/// Policy load status for `ReportPolicyStatus`. Session delivery reports
/// the same status through its acknowledgement instead.
policy_status: Option<PolicyStatusUpdate>,
}
impl Reconciled {
fn rejected(code: &'static str, detail: String, admission_error: String) -> Self {
Self {
outcome: ReconcileOutcome::Rejected(ConfigRejection {
code,
detail,
admission_error,
}),
policy_status: None,
}
}
}
/// Configuration the supervisor runtime has applied.
///
/// Policy polling and session delivery share this state and one reconcile
/// path. They differ only in where snapshots and provider environments come
/// from and in how results reach the gateway.
struct ConfigRuntime {
reloads_gateway_policy: bool,
config_revision: u64,
/// Last applied sandbox revision. A failed delivery reports it as the
/// retained revision while its policy remains enforced.
applied_revision: Option<openshell_core::proto::ConfigSnapshotRevision>,
provider_env_revision: u64,
policy_version: u32,
policy_hash: String,
policy_generation: Option<PolicyGenerationGuard>,
endpoint_policy: Option<openshell_core::proto::SandboxPolicy>,
middleware_services: Vec<openshell_core::proto::SupervisorMiddlewareService>,
extension_authentication_enabled: bool,
middleware_registry_status: MiddlewareRegistryStatus,
settings: std::collections::HashMap<String, openshell_core::proto::EffectiveSetting>,
last_failed_runtime_revision: Option<FailedRuntimeRevision>,
rejected_policy_generation: Option<RejectedPolicyGeneration>,
has_last_valid_policy: bool,
stream: StreamConfigurationState,
}
impl ConfigRuntime {
/// Seed the trackers from startup; the first poll records what startup
/// loaded.
fn new(ctx: &PolicyPollLoopContext) -> Self {
Self {
reloads_gateway_policy: ctx.loaded_policy_origin.allows_gateway_policy_reload(),
config_revision: 0,
applied_revision: None,
provider_env_revision: ctx.provider_credentials.snapshot().revision,
policy_version: 0,
policy_hash: String::new(),
policy_generation: None,
endpoint_policy: ctx.endpoint_policy.clone(),
middleware_services: Vec::new(),
extension_authentication_enabled: ctx.extension_authentication_enabled,
middleware_registry_status: ctx.middleware_registry_status,
settings: std::collections::HashMap::new(),
last_failed_runtime_revision: None,
rejected_policy_generation: None,
has_last_valid_policy: ctx.loaded_policy_origin.has_last_valid_policy(),
stream: StreamConfigurationState::default(),
}
}
/// Bring the runtime to one sandbox configuration snapshot.
///
/// The caller reports the outcome, then records an applied snapshot with
/// [`Self::commit`]. A failed report leaves it to be reconciled again.
async fn reconcile<C: PolicyGatewayClient>(
&mut self,
ctx: &PolicyPollLoopContext,
client: &C,
result: &openshell_core::grpc_client::SettingsPollResult,
provider: ProviderSource,
) -> Result<Reconciled> {
use openshell_core::proto::PolicySource;
use std::sync::atomic::Ordering;
let reloads_gateway_policy = self.reloads_gateway_policy;
let mut policy_status = None;
// Reuse installed per-service credentials, rotating only when one is
// missing or due. Rotation happens on the existing gateway channel and
// updates slots in place, so it is independent of config revision and
// registry equality.
let middleware_credentials = if result.extension_authentication_enabled {
match client
.extension_credentials_for(&result.supervisor_middleware_services)
.await
{
Ok(credentials) => credentials,
Err(error) => {
warn!(error = %error, "Settings poll: extension credential refresh failed");
std::collections::HashMap::new()
}
}
} else {
std::collections::HashMap::new()
};
if reloads_gateway_policy && !result.configuration_admitted {
let disposition = apply_policy_validation_failure(
&ctx.opa_engine,
result.policy_validation_failure_mode,
self.has_last_valid_policy,
result.version,
&result.configuration_error,
)?;
emit_policy_validation_failure(
&disposition,
result.version,
&result.policy_hash,
&result.configuration_error,
);
self.rejected_policy_generation = Some(RejectedPolicyGeneration {
version: result.version,
policy_hash: result.policy_hash.clone(),
validation_error: result.configuration_error.clone(),
configured_mode: result.policy_validation_failure_mode,
});
return Ok(Reconciled::rejected(
"configuration_rejected",
result.configuration_error.clone(),
result.configuration_error.clone(),
));
}
let config_changed = result.config_revision != self.config_revision;
let desired_identity = EnvironmentIdentity::from_settings(result);
let provider_env_changed = match &provider {
ProviderSource::Fetch => {
result.provider_env_revision != self.provider_env_revision
|| ctx.provider_readiness.needs_environment(&desired_identity)
}
ProviderSource::Delivered(provider) => provider.is_some(),
};
let policy_changed = result.policy_hash != self.policy_hash;
let extension_authentication_changed =
self.extension_authentication_enabled != result.extension_authentication_enabled;
let middleware_registry_changed = extension_authentication_changed
|| middleware_registry_needs_rebuild(
self.middleware_registry_status,
&self.middleware_services,
&result.supervisor_middleware_services,
);
// A valid candidate may intentionally restore byte-for-byte policy
// content that was active before a rejected update. Its hash then
// equals `policy_hash`, but the runtime is still quarantined and must
// reload (or it would remain deny-all indefinitely).
let recovering_rejected_policy = reloads_gateway_policy
&& self.rejected_policy_generation.is_some()
&& result.configuration_admitted;
let policy_runtime_changed = (reloads_gateway_policy
&& (provider_env_changed
|| self
.policy_generation
.as_ref()
.is_some_and(PolicyGenerationGuard::is_stale)))
|| recovering_rejected_policy
|| extension_authentication_changed
|| gateway_policy_runtime_needs_reconciliation(
reloads_gateway_policy,
&self.policy_hash,
&result.policy_hash,
&self.middleware_services,
&result.supervisor_middleware_services,
self.middleware_registry_status,
);
// Recovery already has its own acknowledgement path below. Giving it
// precedence here prevents a restored last-known-good policy from
// also being acknowledged as an ordinary same-hash revision.
let unchanged_policy_revision = unchanged_policy_revision_candidate(
reloads_gateway_policy,
recovering_rejected_policy,
self.policy_version,
&self.policy_hash,
result,
);
let mut policy_runtime_reconciled = false;
// A local policy override is not coupled to the gateway policy
// snapshot, so its service registry can still be reconciled alone.
// Gateway policy snapshots, however, must install policy and registry
// as one generation below.
if !reloads_gateway_policy {
reconcile_middleware_registry(
&ctx.opa_engine,
&ctx.middleware_connector,
MiddlewareRegistryReconciliation {
desired_services: &result.supervisor_middleware_services,
authentication: MiddlewareAuthentication {
credentials: middleware_credentials.clone(),
enabled: result.extension_authentication_enabled,
},
registry_changed: middleware_registry_changed,
extension_credentials: &ctx.extension_credentials,
current_services: &mut self.middleware_services,
status: &mut self.middleware_registry_status,
},
)
.await;
if self.middleware_registry_status == MiddlewareRegistryStatus::Synchronized {
self.extension_authentication_enabled = result.extension_authentication_enabled;
}
}
if !config_changed
&& !provider_env_changed
&& !policy_runtime_changed
&& unchanged_policy_revision.is_none()
{
return Ok(Reconciled {
outcome: ReconcileOutcome::Unchanged,
policy_status: None,
});
}
if config_changed || provider_env_changed {
// Log which settings changed.
log_setting_changes(&self.settings, &result.settings);
// A posture change after a rejected update takes effect immediately.
// The compiled last-known-good engine remains available beneath a
// fail-closed quarantine, so an explicit retain_last_valid selection
// can reactivate it without accepting any part of the invalid policy.
if !policy_changed && let Some(rejected) = self.rejected_policy_generation.as_mut() {
let mode = result.policy_validation_failure_mode;
if mode != rejected.configured_mode {
let disposition = apply_policy_validation_failure(
&ctx.opa_engine,
mode,
self.has_last_valid_policy,
rejected.version,
&rejected.validation_error,
)?;
emit_policy_validation_failure(
&disposition,
rejected.version,
&rejected.policy_hash,
&rejected.validation_error,
);
rejected.configured_mode = mode;
}
}
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Other, "detected")
.unmapped("old_config_revision", serde_json::json!(self.config_revision))
.unmapped("new_config_revision", serde_json::json!(result.config_revision))
.unmapped("policy_changed", serde_json::json!(policy_changed))
.unmapped("provider_env_changed", serde_json::json!(provider_env_changed))
.message(format!(
"Settings poll: config change detected [old_revision:{} new_revision:{} policy_changed:{policy_changed} provider_env_changed:{provider_env_changed}]",
self.config_revision,
result.config_revision
))
.build());
}
// Prepare the matching environment before activation. Failed refreshes
// revoke static credentials while preserving independently bound dynamic grants.
let prepared_provider = match provider {
_ if !provider_env_changed => None,
ProviderSource::Fetch => {
match self
.fetch_provider_environment(ctx, client, result, &desired_identity)
.await
{
Ok(prepared) => Some(prepared),
Err(rejection) => {
return Ok(Reconciled {
outcome: ReconcileOutcome::Rejected(rejection),
policy_status: None,
});
}
}
}
ProviderSource::Delivered(provider) => provider,
};
let mut runtime_error = String::new();
if policy_runtime_changed {
let pid = ctx.entrypoint_pid.load(Ordering::Acquire);
let runtime_result = reload_gateway_configuration_runtime(
&ctx.opa_engine,
result.policy.as_ref(),
pid,
MiddlewareReloadContext {
desired_services: &result.supervisor_middleware_services,
authentication: &MiddlewareAuthentication {
credentials: middleware_credentials.clone(),
enabled: result.extension_authentication_enabled,
},
registry_changed: middleware_registry_changed,
connector: &ctx.middleware_connector,
},
ctx.vm_identity,
|| {
if let Some(prepared) = prepared_provider.as_ref() {
ctx.provider_credentials
.install_prepared(&prepared.credentials);
}
},
)
.await;
match runtime_result {
Ok(generation) => {
policy_runtime_reconciled = true;
if let Some(prepared) = prepared_provider.as_ref() {
ctx.provider_readiness.credentials_installed(
prepared.identity.clone(),
&ctx.provider_credentials,
prepared.expires_at_ms,
);
}
ctx.provider_readiness.policy_activated(
&desired_identity,
result.config_revision,
generation.clone(),
);
self.policy_generation = Some(generation);
let policy = result
.policy
.as_ref()
.expect("successful runtime reload requires a policy payload");
self.has_last_valid_policy = true;
self.rejected_policy_generation = None;
if policy_changed {
if let Some(policy_local_ctx) = ctx.policy_local_ctx.as_ref() {
policy_local_ctx.set_current_policy(policy.clone()).await;
}
if result.global_policy_version > 0 {
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.unmapped("policy_hash", serde_json::json!(&result.policy_hash))
.unmapped("global_version", serde_json::json!(result.global_policy_version))
.message(format!(
"Policy reloaded successfully (global) [policy_hash:{} global_version:{}]",
result.policy_hash,
result.global_policy_version
))
.build());
} else {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.unmapped("policy_hash", serde_json::json!(&result.policy_hash))
.message(format!(
"Policy reloaded successfully [policy_hash:{}]",
result.policy_hash
))
.build()
);
}
if result.version > 0 && result.policy_source == PolicySource::Sandbox {
policy_status = Some(PolicyStatusUpdate::loaded(result.version));
self.policy_version = result.version;
}
} else if recovering_rejected_policy
&& result.version > 0
&& result.policy_source == PolicySource::Sandbox
{
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.unmapped("policy_hash", serde_json::json!(&result.policy_hash))
.message(format!(
"Policy reloaded successfully and fail-closed quarantine cleared [policy_hash:{}]",
result.policy_hash
))
.build()
);
policy_status = Some(PolicyStatusUpdate::loaded(result.version));
self.policy_version = result.version;
}
if middleware_registry_changed {
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.unmapped(
"supervisor_middleware_service_count",
serde_json::json!(result.supervisor_middleware_services.len())
)
.message(format!(
"Supervisor policy runtime reloaded atomically [service_count:{}]",
result.supervisor_middleware_services.len()
))
.build());
}
self.policy_hash.clone_from(&result.policy_hash);
self.endpoint_policy.clone_from(&result.policy);
self.middleware_services
.clone_from(&result.supervisor_middleware_services);
self.extension_authentication_enabled = result.extension_authentication_enabled;
retain_extension_credentials(
&ctx.extension_credentials,
&result.supervisor_middleware_services,
result.extension_authentication_enabled,
);
self.middleware_registry_status = MiddlewareRegistryStatus::Synchronized;
self.last_failed_runtime_revision = None;
}
Err(failure) => {
runtime_error = failure.to_string();
ctx.provider_readiness
.policy_install_failed(desired_identity.clone(), result.config_revision);
let failed_revision = FailedRuntimeRevision::new(
result.config_revision,
&result.policy_hash,
&failure,
);
if self.last_failed_runtime_revision.as_ref() != Some(&failed_revision) {
let failure_mode = result.policy_validation_failure_mode;
match apply_gateway_runtime_reload_failure(
&ctx.opa_engine,
failure,
failure_mode,
self.has_last_valid_policy,
result.version,
)? {
GatewayRuntimeFailureDisposition::PolicyRejected {
error,
disposition,
} => {
emit_policy_validation_failure(
&disposition,
result.version,
&result.policy_hash,
&error,
);
self.rejected_policy_generation = Some(RejectedPolicyGeneration {
version: result.version,
policy_hash: result.policy_hash.clone(),
validation_error: error.clone(),
configured_mode: failure_mode,
});
if policy_changed
&& result.version > 0
&& result.policy_source == PolicySource::Sandbox
{
policy_status =
Some(PolicyStatusUpdate::failed(result.version, error));
}
}
GatewayRuntimeFailureDisposition::MiddlewareUnavailable { error } => {
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.state(StateId::Other, "failed")
.unmapped("version", serde_json::json!(result.version))
.unmapped("error", serde_json::json!(&error))
.unmapped("previous_policy_active", serde_json::json!(true))
.message(format!(
"Supervisor middleware registry unavailable, keeping last-known-good policy runtime active [version:{} error:{error}]",
result.version
))
.build());
}
}
}
self.last_failed_runtime_revision = Some(failed_revision);
// Nothing was installed, so the registry status still
// describes the live registry. The retry is driven by the
// persisting hash/service-set mismatch (or an existing
// NeedsReconciliation), not by degrading the status here.
}
}
}
if policy_runtime_changed && !policy_runtime_reconciled {
return Ok(Reconciled {
outcome: ReconcileOutcome::Rejected(ConfigRejection {
code: "runtime_apply_failed",
detail: runtime_error,
admission_error: "Effective configuration failed runtime preparation; prior credentials remain installed".to_string(),
}),
policy_status,
});
}
if !reloads_gateway_policy && let Some(prepared) = prepared_provider.as_ref() {
ctx.provider_credentials
.install_prepared(&prepared.credentials);
ctx.provider_readiness.credentials_installed(
prepared.identity.clone(),
&ctx.provider_credentials,
prepared.expires_at_ms,
);
}
if provider_env_changed || policy_runtime_reconciled {
self.provider_env_revision = result.provider_env_revision;
}
if let Some(version) = unchanged_policy_revision_ready_to_ack(
unchanged_policy_revision,
policy_runtime_changed,
policy_runtime_reconciled,
) {
policy_status = Some(PolicyStatusUpdate::unchanged_loaded(
version,
result.policy_hash.clone(),
));
self.policy_version = version;
}
if reloads_gateway_policy
&& !policy_runtime_changed
&& let Some(generation) = self
.policy_generation
.as_ref()
.filter(|generation| !generation.is_stale())
{
// The same installed policy may serve a new attachment/configuration
// identity. Its generation is retained, never inferred from a cursor.
ctx.provider_readiness.policy_activated(
&desired_identity,
result.config_revision,
generation.clone(),
);
}
if policy_runtime_reconciled || provider_env_changed {
endpoint_status::reset(
ctx.endpoint_observation_tx.as_ref(),
self.endpoint_policy.as_ref(),
&self.policy_hash,
ctx.provider_credentials.snapshot().revision,
)
.await;
}
// Apply OCSF JSON toggle from the `ocsf_json_enabled` setting.
apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings);
report_deprecated_ocsf_schema_version(&ctx.ocsf_schema_version, &result.settings);
// Apply the agent-proposals feature toggle. On a false→true transition
// we lazily install the skill so a sandbox that started with the flag
// off picks up the surface without a recreate. We never uninstall on
// a true→false transition: stale skill content on disk is harmless
// because route_request and agent_next_steps both gate on the live
// shared flag, so the agent that reads the skill will see 404s and an
// empty `next_steps` array regardless.
apply_agent_proposals_enabled(
&ctx.agent_proposals,
agent_proposals_enabled_from_settings(&result.settings),
"settings poll",
Some(result.config_revision),
skills::install_static_skills,
);
Ok(Reconciled {
outcome: ReconcileOutcome::Applied,
policy_status,
})
}
/// Record a reconciled snapshot as applied.
fn commit(&mut self, result: openshell_core::grpc_client::SettingsPollResult) {
if self.reloads_gateway_policy {
self.applied_revision = Some(sandbox_config_revision(&result));
}
self.config_revision = result.config_revision;
if !self.reloads_gateway_policy {
self.policy_hash = result.policy_hash;
}
self.settings = result.settings;
}
/// Fetch and prepare the provider environment a polled snapshot requests.
async fn fetch_provider_environment<C: PolicyGatewayClient>(
&self,
ctx: &PolicyPollLoopContext,
client: &C,
result: &openshell_core::grpc_client::SettingsPollResult,
desired_identity: &EnvironmentIdentity,
) -> std::result::Result<CapturedProviderEnvironment, ConfigRejection> {
ctx.provider_readiness.credentials_failed(
desired_identity.clone(),
ProviderReadinessReason::WaitingForCredentials,
);
let provider = match client
.fetch_provider_environment(
&ctx.gateway,
&ctx.sandbox_id,
ctx.provider_credentials.requires_stable_placeholders(),
)
.await
{
Ok(provider)
if EnvironmentIdentity::from_environment(&provider) == *desired_identity
&& provider_environment_is_installable(provider.readiness_reason) =>
{
provider
}
failed => {
let reason = match failed {
Ok(provider)
if provider.readiness_reason != ProviderReadinessReason::Unspecified =>
{
provider.readiness_reason
}
Ok(_) => ProviderReadinessReason::SnapshotMismatch,
Err(_) => ProviderReadinessReason::CredentialInstallFailed,
};
self.revoke_provider_environment(
ctx,
desired_identity.clone(),
reason,
result.provider_env_revision,
)
.await;
let error = "Provider environment is unavailable or changed during preparation";
return Err(ConfigRejection {
code: "provider_environment_unavailable",
detail: error.to_string(),
admission_error: error.to_string(),
});
}
};
if let Ok(prepared) = CapturedProviderEnvironment::prepare(&provider) {
return Ok(prepared);
}
self.reject_provider_bindings(ctx, desired_identity.clone(), provider)
.await;
let error = "Provider environment bindings failed validation";
Err(ConfigRejection {
code: "invalid_provider_environment",
detail: error.to_string(),
admission_error: error.to_string(),
})
}
/// Revoke static provider credentials after the requested environment
/// could not be obtained. Previous dynamic grants remain active.
async fn revoke_provider_environment(
&self,
ctx: &PolicyPollLoopContext,
identity: EnvironmentIdentity,
reason: ProviderReadinessReason,
revision: u64,
) {
ctx.provider_readiness.credentials_failed(identity, reason);
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::High)
.status(StatusId::Failure)
.state(StateId::Disabled, "fail_closed")
.message("Provider environment refresh failed; static credentials were revoked and previous dynamic grants remain active")
.build());
ctx.provider_credentials
.revoke_static_provider_environment(revision);
endpoint_status::reset(
ctx.endpoint_observation_tx.as_ref(),
self.endpoint_policy.as_ref(),
&self.policy_hash,
revision,
)
.await;
}
/// Revoke static credentials whose bindings failed validation while
/// keeping the environment's dynamic grants.
async fn reject_provider_bindings(
&self,
ctx: &PolicyPollLoopContext,
identity: EnvironmentIdentity,
provider: openshell_core::grpc_client::ProviderEnvironmentResult,
) {
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::High)
.status(StatusId::Failure)
.state(StateId::Disabled, "fail_closed")
.message("Provider environment bindings failed validation; static credentials were revoked and fetched dynamic grants remain active")
.build());
ctx.provider_readiness
.credentials_failed(identity, ProviderReadinessReason::CredentialInstallFailed);
let revision = provider.provider_env_revision;
// Repeat the rejected binding validation on the live state to
// revoke static material and retain the fetched dynamic grants.
let _ = ctx
.provider_credentials
.install_bound_environment_with_stable_placeholders(
provider.provider_env_revision,
provider.environment,
provider.credential_expires_at_ms,
provider.dynamic_credentials,
provider.static_credential_bindings,
provider.non_secret_environment_keys,
provider.stable_placeholder_environment_keys,
);
endpoint_status::reset(
ctx.endpoint_observation_tx.as_ref(),
self.endpoint_policy.as_ref(),
&self.policy_hash,
revision,
)
.await;
}
/// Apply one payload delivered over the supervisor session and answer it.
async fn apply_delivered<C: PolicyGatewayClient>(
&mut self,
ctx: &PolicyPollLoopContext,
client: &C,
request: ConfigApplyRequest,
) {
let ConfigApplyRequest { update, response } = request;
let openshell_core::proto::ConfigUpdate {
update_id,
sandbox_config,
provider_environment,
} = update;
let (Some(sandbox_config), Some(provider_environment)) =
(sandbox_config, provider_environment)
else {
// The session validates updates before they reach the runtime.
let _ = response.send(ConfigUpdateResult {
update_id,
outcome: ConfigApplyOutcome::Unsupported.into(),
failure: Some(config_apply_failure(
"invalid_update",
"configuration update is missing a configuration part",
false,
)),
admission: None,
policy_load: None,
});
return;
};
let result = self
.apply_delivered_sandbox(ctx, client, sandbox_config.into(), provider_environment)
.await;
let _ = response.send(result.into_update_result(update_id));
}
/// Apply a delivered sandbox configuration with the provider environment
/// it names. The environment is installed only when the runtime does not
/// already hold it; one that cannot be installed rejects the update, as a
/// failed fetch does when polling.
async fn apply_delivered_sandbox<C: PolicyGatewayClient>(
&mut self,
ctx: &PolicyPollLoopContext,
client: &C,
snapshot: openshell_core::grpc_client::SettingsPollResult,
provider_environment: openshell_core::proto::ProviderEnvironmentSnapshot,
) -> DeliveredResult {
let requested_revision = sandbox_config_revision(&snapshot);
let desired_environment = EnvironmentIdentity::from_settings(&snapshot);
let provider = if !snapshot.configuration_admitted {
if let Some(routes) = &ctx.app_routes {
routes.suspend();
}
if !self.reloads_gateway_policy {
return DeliveredResult {
outcome: ConfigApplyOutcome::FailedRetainedLastKnownGood,
failure: Some(config_apply_failure(
"configuration_rejected",
&snapshot.configuration_error,
true,
)),
admission: config_admission(&snapshot, false),
policy_load: None,
};
}
if self.reloads_gateway_policy
&& let Some(rejected) = self.stream.rejected_sandbox.as_ref()
&& rejected.matches(&snapshot, &requested_revision, &desired_environment)
{
return DeliveredResult {
admission: config_admission(&snapshot, false),
..rejected.result.clone()
};
}
None
} else if !ctx
.provider_readiness
.needs_environment(&desired_environment)
{
None
} else {
match self
.prepare_delivered_provider(ctx, provider_environment, &desired_environment)
.await
{
Ok(prepared) => Some(prepared),
Err(failure) => {
if let Some(routes) = &ctx.app_routes {
routes.suspend();
}
// Static credentials were revoked, so this configuration
// is not applied until its environment installs.
let outcome = if self.applied_revision.is_some() {
ConfigApplyOutcome::FailedRetainedLastKnownGood
} else {
ConfigApplyOutcome::FailedClosed
};
return DeliveredResult {
outcome,
failure: Some(failure),
admission: config_admission(&snapshot, false),
policy_load: None,
};
}
}
};
let consumes_provider = provider.is_some();
let (rejection, policy_status) = match self
.reconcile(ctx, client, &snapshot, ProviderSource::Delivered(provider))
.await
{
Ok(Reconciled {
outcome: ReconcileOutcome::Rejected(rejection),
policy_status,
}) => (rejection, policy_status),
Ok(Reconciled {
outcome,
policy_status,
}) => {
if let Some(routes) = &ctx.app_routes {
routes.install(&snapshot);
}
self.stream.rejected_sandbox = None;
let _ = ctx.workspace_tx.send(snapshot.workspace.clone());
let outcome = if !self.reloads_gateway_policy {
ConfigApplyOutcome::RetainedLocalOverride
} else if matches!(outcome, ReconcileOutcome::Unchanged) {
ConfigApplyOutcome::IgnoredDuplicate
} else {
ConfigApplyOutcome::Applied
};
let admission = config_admission(&snapshot, true);
self.commit(snapshot);
return DeliveredResult {
outcome,
failure: None,
admission,
policy_load: policy_status.map(policy_load_result),
};
}
Err(error) => {
if let Some(routes) = &ctx.app_routes {
routes.suspend();