Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
6099 lines (5689 loc) · 232 KB
/
Copy pathlib.rs
File metadata and controls
6099 lines (5689 loc) · 232 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
//! Supervisor middleware registration and chain execution.
pub mod headers;
mod remote;
mod response;
mod websocket;
pub use response::{
HttpResponseDiagnostics, HttpResponseFinish, HttpResponseInvocation,
HttpResponseInvocationOutcome, HttpResponseMiddlewareFailure, HttpResponsePreflightInput,
HttpResponsePreflightOutcome, HttpResponseSession, MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES,
MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES,
};
pub use websocket::{
WebSocketCoverage, WebSocketCoverageState, WebSocketInvocation, WebSocketInvocationOutcome,
WebSocketMessageAdmission, WebSocketMessageOutcome, WebSocketMessageType,
WebSocketPreflightInput, WebSocketPreflightResult, WebSocketSession,
WebSocketSessionStartOutcome,
};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use miette::{Result, miette};
use prost::Message;
use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware;
use openshell_core::proto::{
Decision, Finding, HeaderMutation, HttpHeader, HttpRequestEvaluation, HttpRequestTarget,
MiddlewareBinding, MiddlewareManifest, NetworkMiddlewareConfig, RequestContext, SandboxPolicy,
SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, SupervisorMiddlewareService,
ValidateConfigRequest, ValidateConfigResponse,
};
use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore};
use tonic::{Request, Response as TonicResponse, Status as TonicStatus};
pub use openshell_core::middleware::{
HttpRequestView, HttpResponseResultStream, InProcessMiddleware, SupervisorMiddlewareEndpoint,
WebSocketResponseStream,
};
pub type MiddlewareService =
dyn SupervisorMiddleware<EvaluateWebSocketSessionStream = WebSocketResponseStream>;
struct GeneratedMiddlewareEndpoint {
service: Arc<MiddlewareService>,
}
#[tonic::async_trait]
impl SupervisorMiddlewareEndpoint for GeneratedMiddlewareEndpoint {
async fn describe(
&self,
request: Request<()>,
) -> std::result::Result<TonicResponse<MiddlewareManifest>, TonicStatus> {
self.service.describe(request).await
}
async fn validate_config(
&self,
request: Request<ValidateConfigRequest>,
) -> std::result::Result<TonicResponse<ValidateConfigResponse>, TonicStatus> {
self.service.validate_config(request).await
}
async fn evaluate_http_request(
&self,
request: Request<HttpRequestEvaluation>,
) -> std::result::Result<TonicResponse<openshell_core::proto::HttpRequestResult>, TonicStatus>
{
self.service.evaluate_http_request(request).await
}
async fn open_websocket_session(
&self,
_receiver: tokio::sync::mpsc::Receiver<openshell_core::proto::WebSocketSessionEvent>,
) -> std::result::Result<WebSocketResponseStream, TonicStatus> {
Err(TonicStatus::unimplemented(
"middleware service does not expose an in-process WebSocket stream",
))
}
}
#[tonic::async_trait]
impl InProcessMiddleware for GeneratedMiddlewareEndpoint {
async fn describe(&self) -> MiddlewareManifest {
self.service
.describe(Request::new(()))
.await
.expect("generated in-process Describe failed")
.into_inner()
}
async fn validate_config(
&self,
middleware_name: &str,
config: &prost_types::Struct,
) -> Result<()> {
let response = self
.service
.validate_config(Request::new(ValidateConfigRequest {
config: Some(config.clone()),
middleware_name: middleware_name.to_string(),
}))
.await
.map_err(|error| miette!("{error}"))?
.into_inner();
if response.valid {
Ok(())
} else {
Err(miette!("{}", response.reason))
}
}
async fn evaluate_http_request(
&self,
request: HttpRequestView<'_>,
) -> Result<openshell_core::proto::HttpRequestResult> {
self.service
.evaluate_http_request(Request::new(request_view_to_evaluation(request)))
.await
.map(tonic::Response::into_inner)
.map_err(|error| miette!("{error}"))
}
}
/// Adapt a generated HTTP-only service to the borrowed in-process contract.
///
/// This compatibility adapter is intended for tests and downstream HTTP-only
/// implementations. First-party built-ins implement [`InProcessMiddleware`]
/// directly so their HTTP path remains allocation-free.
pub fn http_only_endpoint(service: Arc<MiddlewareService>) -> Arc<dyn InProcessMiddleware> {
Arc::new(GeneratedMiddlewareEndpoint { service })
}
struct EndpointInProcessAdapter {
endpoint: Arc<dyn SupervisorMiddlewareEndpoint>,
}
#[tonic::async_trait]
impl InProcessMiddleware for EndpointInProcessAdapter {
async fn describe(&self) -> MiddlewareManifest {
self.endpoint
.describe(Request::new(()))
.await
.expect("in-process endpoint Describe failed")
.into_inner()
}
async fn validate_config(
&self,
middleware_name: &str,
config: &prost_types::Struct,
) -> Result<()> {
let response = self
.endpoint
.validate_config(Request::new(ValidateConfigRequest {
config: Some(config.clone()),
middleware_name: middleware_name.to_string(),
}))
.await
.map_err(|error| miette!("{error}"))?
.into_inner();
if response.valid {
Ok(())
} else {
Err(miette!("{}", response.reason))
}
}
async fn evaluate_http_request(
&self,
request: HttpRequestView<'_>,
) -> Result<openshell_core::proto::HttpRequestResult> {
self.endpoint
.evaluate_http_request(Request::new(request_view_to_evaluation(request)))
.await
.map(tonic::Response::into_inner)
.map_err(|error| miette!("{error}"))
}
async fn open_websocket_session(
&self,
requests: tokio::sync::mpsc::Receiver<openshell_core::proto::WebSocketSessionEvent>,
) -> std::result::Result<WebSocketResponseStream, tonic::Status> {
self.endpoint.open_websocket_session(requests).await
}
async fn open_http_response_pre_return(
&self,
requests: tokio::sync::mpsc::Receiver<openshell_core::proto::HttpResponseEvent>,
) -> std::result::Result<HttpResponseResultStream, tonic::Status> {
self.endpoint.open_http_response_pre_return(requests).await
}
}
/// Adapt a transport-neutral endpoint to the in-process registry contract.
///
/// Prefer implementing [`InProcessMiddleware`] directly. This compatibility
/// path materializes an owned HTTP request, but preserves direct WebSocket
/// streams for endpoint implementations that predate the borrowed contract.
pub fn in_process_endpoint(
endpoint: Arc<dyn SupervisorMiddlewareEndpoint>,
) -> Arc<dyn InProcessMiddleware> {
Arc::new(EndpointInProcessAdapter { endpoint })
}
/// Maximum short-lived middleware work items allowed to wait for active
/// capacity.
///
/// Waiters do not buffer request or message bodies, so the queue can absorb a
/// larger burst without increasing the active payload-memory bound.
pub const MAX_QUEUED_MIDDLEWARE_WORK: usize = MAX_CONCURRENT_MIDDLEWARE_WORK * 2;
/// One slot in the shared middleware work budget.
///
/// Callers that buffer request or message bodies acquire this guard first and
/// retain it through evaluation, bounding aggregate buffered middleware input.
#[derive(Debug)]
pub struct MiddlewareWorkAdmission {
_work: OwnedSemaphorePermit,
saturated: bool,
}
impl MiddlewareWorkAdmission {
pub fn saturated(&self) -> bool {
self.saturated
}
}
/// Result of attempting to enter the bounded middleware work queue.
///
/// Active-capacity saturation is ordinary backpressure: callers that obtain a
/// waiter slot eventually receive [`Self::Admitted`]. [`Self::QueueExhausted`]
/// is immediate load shedding after both active capacity and the waiter queue
/// are full.
#[derive(Debug)]
pub enum MiddlewareWorkAdmissionOutcome {
Admitted(MiddlewareWorkAdmission),
QueueExhausted,
}
impl MiddlewareWorkAdmissionOutcome {
/// Preserve the existing failure behavior for protocols whose outer layer
/// already translates middleware admission errors into a stable response
/// or typed termination.
pub fn into_admission(self) -> Result<MiddlewareWorkAdmission> {
match self {
Self::Admitted(admission) => Ok(admission),
Self::QueueExhausted => Err(miette!(
"middleware admission queue is full; refusing additional buffered work"
)),
}
}
}
/// One slot in the shared persistent middleware session budget.
///
/// Protocol-specific session runners retain this guard while at least one
/// streaming stage remains active. Registry replacement preserves the shared
/// admission state so future streaming HTTP middleware can use the same
/// process-wide bound.
#[derive(Debug)]
struct MiddlewareSessionPermit {
_session: OwnedSemaphorePermit,
}
enum MiddlewareSessionAdmission {
Admitted(MiddlewareSessionPermit),
AtCapacity,
}
pub use openshell_core::middleware::{
DEFAULT_MIDDLEWARE_TIMEOUT, MAX_CONCURRENT_MIDDLEWARE_SESSIONS, MAX_CONCURRENT_MIDDLEWARE_WORK,
MAX_MIDDLEWARE_CHAIN_FINDINGS, MAX_MIDDLEWARE_CHAIN_STAGES, MAX_MIDDLEWARE_CHAIN_TIMEOUT,
MAX_MIDDLEWARE_CONFIGS, MAX_MIDDLEWARE_FINDINGS_PER_STAGE, MAX_MIDDLEWARE_PREFLIGHT_TIMEOUT,
MAX_MIDDLEWARE_SELECTOR_PATTERNS, MAX_MIDDLEWARE_TIMEOUT, MIN_MIDDLEWARE_TIMEOUT,
middleware_timeout_or_default, parse_middleware_timeout,
};
/// Largest logical payload or replacement accepted by the middleware platform.
pub const MAX_MIDDLEWARE_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
/// Largest encoded service-specific configuration attached to one evaluation.
pub const MAX_MIDDLEWARE_CONFIG_BYTES: usize = 64 * 1024;
/// Largest encoded request identity context attached to one evaluation.
pub const MAX_MIDDLEWARE_CONTEXT_BYTES: usize = 4 * 1024;
/// Largest encoded destination and request target attached to one evaluation.
pub const MAX_MIDDLEWARE_TARGET_BYTES: usize = 32 * 1024;
/// Largest number of request header lines exposed to one middleware.
pub const MAX_MIDDLEWARE_HEADERS: usize = 128;
/// Largest encoded request header collection exposed to one middleware.
pub const MAX_MIDDLEWARE_HEADER_BYTES: usize = 64 * 1024;
/// Largest operator-provided reason accepted in one middleware result.
pub const MAX_MIDDLEWARE_REASON_BYTES: usize = 4 * 1024;
/// Largest stable reason code accepted in one middleware result.
pub const MAX_MIDDLEWARE_REASON_CODE_BYTES: usize = 64;
/// Largest encoded individual finding accepted from one middleware stage.
pub const MAX_MIDDLEWARE_FINDING_BYTES: usize = 4 * 1024;
/// Largest number of metadata entries accepted from one middleware stage.
pub const MAX_MIDDLEWARE_METADATA_ENTRIES: usize = 64;
/// Largest combined metadata key/value payload accepted from one middleware stage.
pub const MAX_MIDDLEWARE_METADATA_BYTES: usize = 32 * 1024;
const MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES: usize = 64 * 1024;
const MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES: usize = 64 * 1024;
const MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES: usize = MAX_MIDDLEWARE_CONFIG_BYTES
+ MAX_MIDDLEWARE_CONTEXT_BYTES
+ MAX_MIDDLEWARE_TARGET_BYTES
+ MAX_MIDDLEWARE_HEADER_BYTES
+ MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES;
const MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES: usize = MAX_MIDDLEWARE_REASON_BYTES
+ MAX_MIDDLEWARE_REASON_CODE_BYTES
+ MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES
+ MAX_MIDDLEWARE_FINDINGS_PER_STAGE * MAX_MIDDLEWARE_FINDING_BYTES
+ MAX_MIDDLEWARE_METADATA_BYTES
+ MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES;
/// gRPC envelope headroom derived from every bounded non-payload component.
pub const MIDDLEWARE_GRPC_ENVELOPE_BYTES: usize =
if MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES > MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES {
MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES
} else {
MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES
};
/// gRPC message limit derived from the payload and bounded protobuf components.
pub const MIDDLEWARE_GRPC_MESSAGE_BYTES: usize =
MAX_MIDDLEWARE_PAYLOAD_BYTES + MIDDLEWARE_GRPC_ENVELOPE_BYTES;
const MAX_STABLE_IDENTIFIER_BYTES: usize = 128;
const EXTERNAL_FINDING_LABEL: &str = "External middleware finding";
#[cfg(test)]
const HTTP_REQUEST_OPERATION: SupervisorMiddlewareOperation =
SupervisorMiddlewareOperation::HttpRequest;
const PRE_CREDENTIALS_PHASE: SupervisorMiddlewarePhase = SupervisorMiddlewarePhase::PreCredentials;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OnError {
FailClosed,
FailOpen,
}
impl OnError {
pub fn parse(value: &str) -> Result<Self> {
match value {
"" | "fail_closed" => Ok(Self::FailClosed),
"fail_open" => Ok(Self::FailOpen),
other => Err(miette!(
"invalid middleware on_error '{other}', expected fail_closed or fail_open"
)),
}
}
}
#[derive(Debug, Clone)]
pub struct ChainEntry {
pub name: String,
pub implementation: String,
pub order: i32,
pub config: prost_types::Struct,
pub on_error: OnError,
}
impl TryFrom<(&str, &NetworkMiddlewareConfig)> for ChainEntry {
type Error = miette::Report;
fn try_from((name, value): (&str, &NetworkMiddlewareConfig)) -> Result<Self> {
if name.is_empty() {
return Err(miette!("middleware config name cannot be empty"));
}
if value.middleware.is_empty() {
return Err(miette!(
"middleware config '{}' must reference a middleware",
name
));
}
Ok(Self {
name: name.to_string(),
implementation: value.middleware.clone(),
order: value.order,
config: value.config.clone().unwrap_or_default(),
on_error: OnError::parse(&value.on_error)?,
})
}
}
/// A policy-selected middleware config joined with metadata reported by its
/// service's `Describe` call.
///
/// An unregistered implementation is retained so `on_error` can decide whether
/// the request fails open or closed. A registered implementation without the
/// requested binding is not part of this chain.
#[derive(Clone)]
pub struct DescribedChainEntry {
entry: ChainEntry,
service: Option<Arc<MiddlewareServiceState>>,
binding: Option<MiddlewareBinding>,
max_payload_bytes: usize,
timeout: Duration,
}
struct DescribedChain {
entries: Vec<DescribedChainEntry>,
unbound: Vec<ChainEntry>,
}
impl DescribedChainEntry {
pub fn max_payload_bytes(&self) -> usize {
self.max_payload_bytes
}
pub fn on_error(&self) -> OnError {
self.entry.on_error
}
pub fn timeout(&self) -> Duration {
self.timeout
}
/// True when this entry resolved to a registered binding and will be
/// evaluated. When false, the binding is absent from the current registry
/// and the entry is handled entirely by its `on_error` policy, so it
/// imposes no payload-buffering limit on the chain.
pub fn is_resolved(&self) -> bool {
self.binding.is_some()
}
}
/// Re-checks a middleware-transformed request body against sandbox policy.
///
/// Returns `Some(reason)` to deny the chain, `None` to proceed. Invoked after
/// each stage that replaces the body so neither a later stage nor the upstream
/// sees a payload the policy would reject. Protocols with no body-aware policy
/// select [`TransformedBodyPolicy::NotPolicyRelevant`] instead.
pub type TransformedBodyValidator<'a> = dyn Fn(&[u8]) -> Result<Option<String>> + Send + Sync + 'a;
/// Whether middleware body replacements affect the selected request policy.
///
/// The network pipeline must choose a mode explicitly. This avoids representing
/// a security-relevant re-evaluation requirement as an optional callback where
/// an omitted value is indistinguishable from an intentionally body-independent
/// protocol.
#[derive(Clone, Copy)]
pub enum TransformedBodyPolicy<'a> {
/// The selected policy does not inspect the request body.
NotPolicyRelevant,
/// Re-evaluate every body replacement before the next stage runs.
Reevaluate(&'a TransformedBodyValidator<'a>),
}
#[derive(Debug, Clone)]
pub struct HttpRequestInput {
pub request_id: String,
pub sandbox_id: String,
pub sandbox_name: String,
pub workspace: String,
pub scheme: String,
pub host: String,
pub port: u16,
pub method: String,
pub path: String,
pub query: String,
/// Lowercased request headers in wire order. Repeated header names are
/// preserved as separate entries so middleware inspects every value the
/// upstream will receive.
pub headers: Vec<(String, String)>,
/// Lowercased names nominated by the original request's `Connection`
/// headers. Their values are not exposed to middleware, but mutations must
/// still treat these dynamically hop-by-hop fields as protected.
pub connection_nominated_headers: Vec<String>,
pub body: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct ChainOutcome {
pub allowed: bool,
pub reason: String,
pub body: Vec<u8>,
/// Ordered, validated mutations to replay against the original raw request.
pub header_mutations: Vec<HeaderMutation>,
pub findings: Vec<NamespacedFinding>,
pub metadata: BTreeMap<String, BTreeMap<String, String>>,
pub applied: Vec<MiddlewareInvocation>,
/// Present only when a middleware completed successfully and explicitly
/// denied the request. Fail-closed service errors and transformed-body
/// policy denials are not represented as middleware decisions.
pub denial: Option<MiddlewareDenial>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MiddlewareDenial {
/// Stable policy-local middleware config identity.
pub config_name: String,
/// Validated service-defined code. Free-form service reason text is never
/// carried into client responses or security logs.
pub reason_code: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamespacedFinding {
pub middleware: String,
pub finding: Finding,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MiddlewareInvocation {
pub name: String,
pub implementation: String,
pub decision: Decision,
pub transformed: bool,
/// True when the middleware could not be evaluated and `on_error` was applied
/// (service error, malformed/unsafe response, etc.). The `decision` reflects
/// the `on_error` outcome, not a decision the middleware actually returned.
pub failed: bool,
}
enum OnErrorAction {
/// `fail_open`: skip this middleware, leaving the request unchanged.
FailOpen,
/// `fail_closed`: short-circuit the chain and deny with the given reason.
FailClosed(String),
}
/// Apply a middleware entry's `on_error` policy after a failure (service error or
/// malformed response). Records a `failed` invocation for telemetry in both cases.
fn apply_on_error(
entry: &DescribedChainEntry,
reason: &str,
applied: &mut Vec<MiddlewareInvocation>,
) -> OnErrorAction {
match entry.entry.on_error {
OnError::FailOpen => {
applied.push(MiddlewareInvocation {
name: entry.entry.name.clone(),
implementation: entry.entry.implementation.clone(),
decision: Decision::Allow,
transformed: false,
failed: true,
});
OnErrorAction::FailOpen
}
OnError::FailClosed => {
applied.push(MiddlewareInvocation {
name: entry.entry.name.clone(),
implementation: entry.entry.implementation.clone(),
decision: Decision::Deny,
transformed: false,
failed: true,
});
OnErrorAction::FailClosed(format!("middleware_failed: {reason}"))
}
}
}
fn request_view_to_evaluation(request: HttpRequestView<'_>) -> HttpRequestEvaluation {
HttpRequestEvaluation {
phase: request.phase() as i32,
context: Some(request.context().clone()),
config: Some(request.config().clone()),
target: Some(request.target().clone()),
headers: request.headers().to_vec(),
body: request.body().to_vec(),
middleware_name: request.middleware_name().to_string(),
}
}
#[derive(Clone)]
pub struct ChainRunner {
registry: Arc<MiddlewareRegistry>,
}
#[derive(Clone)]
enum MiddlewareDispatch {
/// Built-ins borrow the current request state and never construct protobuf.
InProcess(Arc<dyn InProcessMiddleware>),
/// Operator services receive an owned protobuf through the gRPC adapter.
Grpc(remote::GrpcMiddlewareService),
}
impl MiddlewareDispatch {
async fn describe(
&self,
) -> std::result::Result<tonic::Response<MiddlewareManifest>, tonic::Status> {
match self {
Self::InProcess(service) => Ok(tonic::Response::new(service.describe().await)),
Self::Grpc(service) => service.describe().await,
}
}
async fn validate_config(
&self,
middleware_name: &str,
config: &prost_types::Struct,
) -> std::result::Result<tonic::Response<ValidateConfigResponse>, tonic::Status> {
match self {
Self::InProcess(service) => Ok(tonic::Response::new(
match service.validate_config(middleware_name, config).await {
Ok(()) => ValidateConfigResponse {
valid: true,
reason: String::new(),
},
Err(error) => ValidateConfigResponse {
valid: false,
reason: error.to_string(),
},
},
)),
Self::Grpc(service) => service.validate_config(middleware_name, config).await,
}
}
async fn evaluate_http_request(
&self,
request: HttpRequestView<'_>,
) -> std::result::Result<tonic::Response<openshell_core::proto::HttpRequestResult>, tonic::Status>
{
match self {
Self::InProcess(service) => service
.evaluate_http_request(request)
.await
.map(tonic::Response::new)
.map_err(|error| tonic::Status::invalid_argument(error.to_string())),
Self::Grpc(service) => service.evaluate_http_request(request).await,
}
}
async fn open_websocket_session(
&self,
receiver: tokio::sync::mpsc::Receiver<openshell_core::proto::WebSocketSessionEvent>,
) -> std::result::Result<WebSocketResponseStream, tonic::Status> {
match self {
Self::InProcess(service) => service.open_websocket_session(receiver).await,
Self::Grpc(service) => service.open_websocket_session(receiver).await,
}
}
async fn open_http_response_pre_return(
&self,
receiver: tokio::sync::mpsc::Receiver<openshell_core::proto::HttpResponseEvent>,
) -> std::result::Result<HttpResponseResultStream, tonic::Status> {
match self {
Self::InProcess(service) => service.open_http_response_pre_return(receiver).await,
Self::Grpc(service) => service.open_http_response_pre_return(receiver).await,
}
}
}
struct MiddlewareServiceState {
/// Policy-facing built-in name or operator-owned registration name. The
/// single-service test constructor leaves this empty and uses the manifest
/// name after Describe.
attachment_name: Option<String>,
service: MiddlewareDispatch,
manifest: OnceCell<MiddlewareManifest>,
diagnostic_policy: MiddlewareDiagnosticPolicy,
operator_max_payload_bytes: Option<usize>,
operator_timeout: Duration,
}
impl MiddlewareServiceState {
fn timeout_for_binding(&self, binding: &MiddlewareBinding) -> Result<Duration> {
if binding.timeout.trim().is_empty() {
Ok(self.operator_timeout)
} else {
parse_middleware_timeout(&binding.timeout)
.map(|binding_timeout| binding_timeout.min(self.operator_timeout))
.map_err(|reason| miette!("middleware binding has invalid timeout: {reason}"))
}
}
}
async fn call_with_timeout<T>(
timeout: Duration,
operation: &'static str,
future: impl Future<Output = std::result::Result<tonic::Response<T>, tonic::Status>>,
) -> std::result::Result<tonic::Response<T>, tonic::Status> {
tokio::time::timeout(timeout, future).await.map_err(|_| {
tonic::Status::deadline_exceeded(format!("middleware {operation} timed out"))
})?
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MiddlewareDiagnosticPolicy {
Preserve,
Normalize,
}
impl MiddlewareDiagnosticPolicy {
fn error_reason(self, error: &tonic::Status) -> String {
match self {
Self::Preserve => safe_reason(&error.to_string()),
Self::Normalize => "external_service_error".to_string(),
}
}
fn process_result(
self,
middleware_name: &str,
result: &mut openshell_core::proto::HttpRequestResult,
) {
if self == Self::Normalize {
normalize_untrusted_diagnostics(middleware_name, result);
}
}
fn header_mutation_error_reason(self, error: &headers::HeaderMutationError) -> String {
match self {
Self::Preserve => safe_reason(&error.to_string()),
Self::Normalize => error.code().to_string(),
}
}
}
/// Validated middleware services available to a gateway or one supervisor.
///
/// In-process services are supplied by the composition root; the generic
/// registry does not select concrete built-ins. All in-process and remote
/// services are described before construction succeeds, so callers never
/// observe a partially registered service set.
#[derive(Clone)]
pub struct MiddlewareRegistry {
services: Arc<Vec<Arc<MiddlewareServiceState>>>,
registered_services: Arc<Vec<RegisteredMiddlewareService>>,
middleware_names: Arc<HashSet<String>>,
work_admission: Arc<Semaphore>,
work_admission_waiters: Arc<Semaphore>,
session_admission: Arc<Semaphore>,
}
impl std::fmt::Debug for MiddlewareRegistry {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("MiddlewareRegistry")
.field("service_count", &self.services.len())
.field("registered_service_count", &self.registered_services.len())
.field("middleware_count", &self.middleware_names.len())
.field(
"available_work_permits",
&self.work_admission.available_permits(),
)
.field(
"available_session_permits",
&self.session_admission.available_permits(),
)
.finish()
}
}
#[derive(Clone)]
struct RegisteredMiddlewareService {
registration: SupervisorMiddlewareService,
}
impl Default for MiddlewareRegistry {
fn default() -> Self {
Self {
services: Arc::new(Vec::new()),
registered_services: Arc::new(Vec::new()),
middleware_names: Arc::new(HashSet::new()),
work_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_WORK)),
work_admission_waiters: Arc::new(Semaphore::new(MAX_QUEUED_MIDDLEWARE_WORK)),
session_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_SESSIONS)),
}
}
}
fn validate_registration(registration: &SupervisorMiddlewareService) -> Result<Duration> {
if !is_stable_identifier(®istration.name) {
return Err(miette!(
"supervisor middleware registration names must be 1-{MAX_STABLE_IDENTIFIER_BYTES} bytes and contain only ASCII letters, digits, '.', '_', '-', or '/'"
));
}
if registration.name.starts_with("openshell/") {
return Err(miette!(
"middleware registration '{}' cannot claim the reserved openshell/ namespace",
registration.name
));
}
if !registration.grpc_endpoint.starts_with("http://")
&& !registration.grpc_endpoint.starts_with("https://")
{
return Err(miette!(
"middleware registration '{}' grpc_endpoint must use http:// or https://",
registration.name
));
}
if registration.max_payload_bytes > MAX_MIDDLEWARE_PAYLOAD_BYTES as u64 {
return Err(miette!(
"middleware registration '{}' max_payload_bytes exceeds the platform maximum of {MAX_MIDDLEWARE_PAYLOAD_BYTES}",
registration.name
));
}
middleware_timeout_or_default(®istration.timeout).map_err(|reason| {
miette!(
"middleware registration '{}' has invalid timeout: {reason}",
registration.name
)
})
}
fn is_stable_identifier(value: &str) -> bool {
!value.is_empty()
&& value.len() <= MAX_STABLE_IDENTIFIER_BYTES
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'/'))
}
fn is_stable_reason_code(value: &str) -> bool {
value.len() <= MAX_MIDDLEWARE_REASON_CODE_BYTES
&& value.as_bytes().first().is_some_and(u8::is_ascii_lowercase)
&& value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}
fn middleware_denial_reason(config_name: &str, reason_code: Option<&str>) -> String {
let config_id: String = config_name
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '_' | '-') {
character
} else {
'_'
}
})
.take(MAX_STABLE_IDENTIFIER_BYTES)
.collect();
reason_code.map_or_else(
|| format!("middleware_denied:{config_id}"),
|code| format!("middleware_denied:{config_id}:{code}"),
)
}
fn validate_payload_limit(source: &str, binding: &MiddlewareBinding) -> Result<usize> {
if binding.max_payload_bytes == 0 {
return Err(miette!("{source} must advertise a non-zero payload limit"));
}
if binding.max_payload_bytes > MAX_MIDDLEWARE_PAYLOAD_BYTES as u64 {
return Err(miette!(
"{source} payload limit exceeds the platform maximum of {MAX_MIDDLEWARE_PAYLOAD_BYTES}"
));
}
usize::try_from(binding.max_payload_bytes)
.map_err(|_| miette!("{source} reports a payload limit too large for this platform"))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SupportedBinding {
HttpPreCredentials,
HttpResponsePreReturn,
WebSocketPreCredentials,
}
fn supported_binding(source: &str, binding: &MiddlewareBinding) -> Result<SupportedBinding> {
match (
SupervisorMiddlewareOperation::try_from(binding.operation).ok(),
SupervisorMiddlewarePhase::try_from(binding.phase).ok(),
) {
(
Some(SupervisorMiddlewareOperation::HttpRequest),
Some(SupervisorMiddlewarePhase::PreCredentials),
) => Ok(SupportedBinding::HttpPreCredentials),
(
Some(SupervisorMiddlewareOperation::HttpResponse),
Some(SupervisorMiddlewarePhase::PreReturn),
) => Ok(SupportedBinding::HttpResponsePreReturn),
(
Some(SupervisorMiddlewareOperation::WebsocketMessage),
Some(SupervisorMiddlewarePhase::PreCredentials),
) => Ok(SupportedBinding::WebSocketPreCredentials),
(
Some(SupervisorMiddlewareOperation::WebsocketMessage),
Some(SupervisorMiddlewarePhase::PreReturn),
) => Err(miette!(
"{source} advertises WEBSOCKET_MESSAGE/PRE_RETURN, which is not yet supported"
)),
_ => Err(miette!(
"{source} advertises an unsupported middleware operation/phase pair"
)),
}
}
fn validate_manifest_bindings(
source: &str,
manifest: &MiddlewareManifest,
operator_max_payload_bytes: Option<usize>,
) -> Result<()> {
if manifest.bindings.is_empty() {
return Err(miette!("{source} describes no bindings"));
}
let mut described_pairs = HashSet::with_capacity(manifest.bindings.len());
for binding in &manifest.bindings {
supported_binding(source, binding)?;
if !described_pairs.insert((binding.operation, binding.phase)) {
return Err(miette!(
"{source} describes a duplicate middleware operation/phase pair"
));
}
let advertised = validate_payload_limit(source, binding)?;
if !binding.timeout.trim().is_empty() {
parse_middleware_timeout(&binding.timeout)
.map_err(|reason| miette!("{source} has invalid timeout for binding: {reason}"))?;
}
if operator_max_payload_bytes.is_some_and(|limit| limit > advertised) {
return Err(miette!(
"{source} max_payload_bytes ({}) exceeds the binding capability ({advertised})",
operator_max_payload_bytes.expect("operator limit checked above")
));
}
if operator_max_payload_bytes == Some(0) {
return Err(miette!(
"{source} must configure max_payload_bytes for every payload-bearing binding"
));
}
}
Ok(())
}
fn validate_external_manifest(
registration: &SupervisorMiddlewareService,
manifest: &MiddlewareManifest,
operator_max_payload_bytes: usize,
authenticated: bool,
) -> Result<()> {
validate_manifest_bindings(
&format!("external middleware registration '{}'", registration.name),
manifest,
Some(operator_max_payload_bytes),
)?;
validate_expected_audience(
®istration.name,
®istration.audience,
&manifest.expected_audience,
authenticated && !registration.allow_insecure_transport,
)
}
/// After authenticated Describe succeeds, reject a registration whose
/// configured audience differs from the one the service says it verifies.
///
/// This is a post-authentication consistency assertion, not audience discovery:
/// a strict verifier may reject an incorrect audience before returning its
/// manifest. A service that does not advertise an audience is accepted unchanged.
fn validate_expected_audience(
registration_name: &str,
configured: &str,
advertised: &str,
authenticated: bool,
) -> Result<()> {
if !authenticated || advertised.is_empty() {
return Ok(());
}
if advertised != configured {
return Err(miette!(
"middleware registration '{registration_name}' expects audience \
'{advertised}' but OpenShell is configured to mint '{configured}'"
));
}
Ok(())
}
/// External diagnostic text is untrusted and may contain request data. Keep
/// only values derived from the validated, operator-owned registration name
/// and numeric finding counts; do not carry per-request free-form text into
/// logs.
fn normalize_untrusted_diagnostics(
middleware_name: &str,
result: &mut openshell_core::proto::HttpRequestResult,
) {
let reason_id: String = middleware_name
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '_' | '-') {
character
} else {
'_'
}
})
.collect();
result.reason = format!("middleware_denied:{reason_id}");
result.metadata.clear();
for finding in &mut result.findings {
finding.r#type = format!("{middleware_name}.finding");
finding.label = EXTERNAL_FINDING_LABEL.to_string();
finding.confidence.clear();
finding.severity = match finding.severity.as_str() {
"low" => "low",
"high" => "high",
_ => "medium",
}
.to_string();
}
}
fn validate_request_view(request: HttpRequestView<'_>) -> std::result::Result<(), &'static str> {
if request.body().len() > MAX_MIDDLEWARE_PAYLOAD_BYTES {
return Err("request_body_over_capacity");