Repository navigation
Expand file tree
/
Copy pathprofiles.rs
More file actions
5486 lines (5131 loc) · 183 KB
/
Copy pathprofiles.rs
File metadata and controls
5486 lines (5131 loc) · 183 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
//! Declarative provider type profiles.
#![allow(deprecated)] // NetworkBinary::harness remains in the public proto for compatibility.
use openshell_core::proto::{
GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkBinary,
NetworkEndpoint, NetworkPolicyRule, ProviderCredentialRefresh,
ProviderCredentialRefreshMaterial, ProviderCredentialRefreshOutput,
ProviderCredentialRefreshStrategy, ProviderProfile, ProviderProfileCategory,
ProviderProfileCredential, ProviderProfileDiscovery,
};
use openshell_core::secrets::uses_reserved_revision_namespace;
use openshell_policy::{L7EndpointFields, validate_l7_endpoint_semantics};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use std::sync::OnceLock;
const PATH_TEMPLATE_CREDENTIAL_PLACEHOLDER: &str = "{credential}";
const BUILT_IN_PROFILE_YAMLS: &[&str] = &[
include_str!("../../../providers/aws.yaml"),
include_str!("../../../providers/aws-bedrock.yaml"),
include_str!("../../../providers/aws-s3.yaml"),
include_str!("../../../providers/claude-code.yaml"),
include_str!("../../../providers/codex.yaml"),
include_str!("../../../providers/copilot.yaml"),
include_str!("../../../providers/cursor.yaml"),
include_str!("../../../providers/deepinfra.yaml"),
include_str!("../../../providers/github.yaml"),
include_str!("../../../providers/google-cloud.yaml"),
include_str!("../../../providers/google-vertex-ai.yaml"),
include_str!("../../../providers/nvidia.yaml"),
include_str!("../../../providers/pypi.yaml"),
include_str!("../../../providers/tars.yaml"),
];
#[derive(Debug, thiserror::Error)]
pub enum ProfileError {
#[error("failed to parse provider profile YAML: {0}")]
Parse(#[from] serde_yml::Error),
#[error("failed to parse provider profile JSON: {0}")]
JsonParse(#[from] serde_json::Error),
#[error("provider profile id is required")]
MissingId,
#[error("duplicate provider profile id: {0}")]
DuplicateId(String),
#[error("provider profile '{id}' has invalid endpoint '{host}:{port}'")]
InvalidEndpoint { id: String, host: String, port: u32 },
#[error("provider profile '{id}' has duplicate credential env var '{env_var}'")]
DuplicateCredentialEnvVar { id: String, env_var: String },
#[error("provider profile '{id}' validation error: {field}: {message}")]
ValidationError {
id: String,
field: String,
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileValidationDiagnostic {
pub source: String,
pub profile_id: String,
pub field: String,
pub message: String,
pub severity: String,
}
impl ProfileValidationDiagnostic {
fn error(
source: impl Into<String>,
profile_id: impl Into<String>,
field: impl Into<String>,
message: impl Into<String>,
) -> Self {
Self {
source: source.into(),
profile_id: profile_id.into(),
field: field.into(),
message: message.into(),
severity: "error".to_string(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CredentialProfile {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub env_vars: Vec<String>,
#[serde(default)]
pub required: bool,
#[serde(default)]
pub auth_style: String,
#[serde(default)]
pub header_name: String,
#[serde(default)]
pub query_param: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh: Option<CredentialRefreshProfile>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub path_template: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_grant: Option<TokenGrantProfile>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct TokenGrantProfile {
pub token_endpoint: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub audience: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub jwt_svid_audience: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub client_assertion_type: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub scopes: Vec<String>,
#[serde(default, skip_serializing_if = "is_zero_i64")]
pub cache_ttl_seconds: i64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub audience_overrides: Vec<TokenGrantAudienceOverrideProfile>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct TokenGrantAudienceOverrideProfile {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub host: String,
#[serde(default, skip_serializing_if = "is_zero")]
pub port: u32,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub path: String,
pub audience: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub scopes: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CredentialRefreshProfile {
#[serde(
default = "default_refresh_strategy",
deserialize_with = "deserialize_refresh_strategy",
serialize_with = "serialize_refresh_strategy"
)]
pub strategy: ProviderCredentialRefreshStrategy,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub token_url: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub scopes: Vec<String>,
#[serde(default, skip_serializing_if = "is_zero_i64")]
pub refresh_before_seconds: i64,
#[serde(default, skip_serializing_if = "is_zero_i64")]
pub max_lifetime_seconds: i64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub material: Vec<CredentialRefreshMaterialProfile>,
/// Additional credentials this refresh mints beyond its primary credential.
/// Each entry maps a strategy-defined semantic output id to a sibling
/// credential whose `env_vars` receive the minted value.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub additional_outputs: Vec<CredentialRefreshOutputProfile>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CredentialRefreshMaterialProfile {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub description: String,
#[serde(default)]
pub required: bool,
#[serde(default)]
pub secret: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CredentialRefreshOutputProfile {
/// Strategy-defined semantic output id (e.g. `session_token`).
pub output: String,
/// Sibling credential name whose `env_vars` receive this output.
pub credential: String,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct DiscoveryProfile {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub credentials: Vec<String>,
}
// These YAML/JSON DTOs mirror the network policy protos intentionally. Keep
// every lossless conversion below in sync with proto/sandbox.proto. If a field
// is added to NetworkEndpoint, L7Rule, L7Allow, L7DenyRule, L7QueryMatcher,
// GraphqlOperation, or NetworkBinary, add it here and in both conversion
// directions unless the import/lint path explicitly rejects it.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct EndpointProfile {
pub host: String,
#[serde(default, skip_serializing_if = "is_zero")]
pub port: u32,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub protocol: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub tls: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub access: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub enforcement: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rules: Option<Vec<L7RuleProfile>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed_ips: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ports: Vec<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deny_rules: Option<Vec<L7DenyRuleProfile>>,
#[serde(default, skip_serializing_if = "is_false")]
pub allow_encoded_slash: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub websocket_credential_rewrite: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub request_body_credential_rewrite: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub persisted_queries: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub graphql_persisted_queries: HashMap<String, GraphqlOperationProfile>,
#[serde(default, skip_serializing_if = "is_zero")]
pub graphql_max_body_bytes: u32,
#[serde(default, skip_serializing_if = "is_zero")]
pub json_rpc_max_body_bytes: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp: Option<McpOptionsProfile>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub credential_signing: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub signing_service: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub signing_region: String,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct McpOptionsProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strict_tool_names: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub allow_all_known_mcp_methods: Option<bool>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct L7RuleProfile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub allow: Option<L7AllowProfile>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct L7AllowProfile {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub method: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub command: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub query: HashMap<String, L7QueryMatcherProfile>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub operation_type: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub operation_name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<String>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub params: HashMap<String, L7QueryMatcherProfile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool: Option<L7QueryMatcherProfile>,
}
impl L7AllowProfile {
fn has_tool_selector(&self) -> bool {
self.params.contains_key("name") || self.tool.is_some()
}
fn is_effectively_empty(&self) -> bool {
self.method.is_empty()
&& self.path.is_empty()
&& self.command.is_empty()
&& self.operation_type.is_empty()
&& self.operation_name.is_empty()
&& !self.has_tool_selector()
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct L7DenyRuleProfile {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub method: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub command: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub query: HashMap<String, L7QueryMatcherProfile>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub operation_type: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub operation_name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<String>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub params: HashMap<String, L7QueryMatcherProfile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool: Option<L7QueryMatcherProfile>,
}
impl L7DenyRuleProfile {
fn has_tool_selector(&self) -> bool {
self.params.contains_key("name") || self.tool.is_some()
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct L7QueryMatcherProfile {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub glob: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub any: Vec<String>,
}
impl<'de> Deserialize<'de> for L7QueryMatcherProfile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrObject {
Scalar(String),
Object {
#[serde(default)]
glob: String,
#[serde(default)]
any: Vec<String>,
},
}
match StringOrObject::deserialize(deserializer)? {
StringOrObject::Scalar(s) => Ok(Self {
glob: s,
any: vec![],
}),
StringOrObject::Object { glob, any } => Ok(Self { glob, any }),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct GraphqlOperationProfile {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub operation_type: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub operation_name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinaryProfile {
pub path: String,
pub harness: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct ProviderTypeProfile {
pub id: String,
#[serde(default, skip_serializing_if = "is_u64_zero")]
pub resource_version: u64,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub annotations: HashMap<String, String>,
pub display_name: String,
#[serde(default)]
pub description: String,
#[serde(
default = "default_category",
deserialize_with = "deserialize_category",
serialize_with = "serialize_category"
)]
pub category: ProviderProfileCategory,
#[serde(default)]
pub credentials: Vec<CredentialProfile>,
#[serde(default)]
pub endpoints: Vec<EndpointProfile>,
#[serde(default)]
pub binaries: Vec<BinaryProfile>,
#[serde(default)]
pub inference_capable: bool,
#[serde(default, skip_serializing_if = "discovery_is_empty")]
pub discovery: DiscoveryProfile,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub source: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub scope: String,
}
// Provider profile import/export is expected to be lossless for the network
// policy fields exposed by the protobuf API. Do not collapse these DTOs into a
// narrower shape; direct gRPC imports and CLI YAML imports must preserve the
// same policy intent through storage and JIT composition.
impl ProviderTypeProfile {
#[must_use]
pub fn from_proto(profile: &ProviderProfile) -> Self {
Self {
id: profile.id.clone(),
resource_version: profile.resource_version,
annotations: profile.annotations.clone(),
display_name: profile.display_name.clone(),
description: profile.description.clone(),
category: ProviderProfileCategory::try_from(profile.category)
.unwrap_or(ProviderProfileCategory::Other),
credentials: profile
.credentials
.iter()
.map(|credential| CredentialProfile {
name: credential.name.clone(),
description: credential.description.clone(),
env_vars: credential.env_vars.clone(),
required: credential.required,
auth_style: credential.auth_style.clone(),
header_name: credential.header_name.clone(),
query_param: credential.query_param.clone(),
refresh: credential
.refresh
.as_ref()
.map(credential_refresh_from_proto),
path_template: credential.path_template.clone(),
token_grant: credential.token_grant.as_ref().map(token_grant_from_proto),
})
.collect(),
endpoints: profile.endpoints.iter().map(endpoint_from_proto).collect(),
binaries: profile.binaries.iter().map(binary_from_proto).collect(),
inference_capable: profile.inference_capable,
discovery: profile
.discovery
.as_ref()
.map(discovery_from_proto)
.unwrap_or_default(),
source: profile.source.clone(),
scope: profile.scope.clone(),
}
}
#[must_use]
pub fn credential_env_vars(&self) -> Vec<&str> {
let mut vars = Vec::new();
for credential in &self.credentials {
for env_var in &credential.env_vars {
if !vars.contains(&env_var.as_str()) {
vars.push(env_var.as_str());
}
}
}
vars
}
/// Whether this profile can be created without initial static credentials.
///
/// Empty provider creation is allowed when at least one credential can be
/// resolved at runtime, and every required credential can be resolved at
/// runtime. Runtime-resolvable credentials are either gateway-mintable
/// refresh credentials, sandbox-side dynamic token grants, or additional
/// outputs co-minted by another credential's gateway-mintable refresh.
#[must_use]
pub fn allows_empty_provider_credentials(&self) -> bool {
let co_minted = self.co_minted_credential_names();
let mut has_runtime_resolvable_credential = false;
for credential in &self.credentials {
let is_runtime_resolvable =
credential.is_runtime_resolvable() || co_minted.contains(credential.name.as_str());
if credential.required && !is_runtime_resolvable {
return false;
}
has_runtime_resolvable_credential |= is_runtime_resolvable;
}
has_runtime_resolvable_credential
}
/// Names of credentials produced as `additional_outputs` of a
/// gateway-mintable refresh on some other credential.
fn co_minted_credential_names(&self) -> HashSet<&str> {
self.credentials
.iter()
.filter_map(|credential| credential.refresh.as_ref())
.filter(|refresh| refresh.is_gateway_mintable())
.flat_map(|refresh| refresh.additional_outputs.iter())
.map(|output| output.credential.as_str())
.collect()
}
/// For the credential resolved by `credential_key` (matched by name or env
/// var) that carries a refresh with `additional_outputs`, resolve each
/// output to the concrete env key of its target credential. Returns a map
/// of semantic output id -> env key (empty when there is no such refresh or
/// no additional outputs). Skips outputs whose target credential is missing
/// or does not declare exactly one env var; `validate_profile_set` reports
/// those as errors.
#[must_use]
pub fn resolved_additional_output_keys(&self, credential_key: &str) -> HashMap<String, String> {
let Some(refresh) = self
.credentials
.iter()
.find(|credential| {
credential.name == credential_key
|| credential.env_vars.iter().any(|env| env == credential_key)
})
.and_then(|credential| credential.refresh.as_ref())
else {
return HashMap::new();
};
refresh
.additional_outputs
.iter()
.filter_map(|output| {
let target = self
.credentials
.iter()
.find(|credential| credential.name == output.credential)?;
let [env_key] = target.env_vars.as_slice() else {
return None;
};
Some((output.output.clone(), env_key.clone()))
})
.collect()
}
/// Returns the credential suitable for `--from-gcloud-adc` bootstrap, if any.
///
/// A credential qualifies when its refresh strategy is `Oauth2RefreshToken`
/// and its material declares the three gcloud ADC keys (`client_id`,
/// `client_secret`, `refresh_token`).
#[must_use]
pub fn adc_credential(&self) -> Option<&CredentialProfile> {
const ADC_MATERIAL_KEYS: &[&str] = &["client_id", "client_secret", "refresh_token"];
self.credentials.iter().find(|cred| {
cred.refresh.as_ref().is_some_and(|refresh| {
refresh.strategy == ProviderCredentialRefreshStrategy::Oauth2RefreshToken
&& ADC_MATERIAL_KEYS
.iter()
.all(|key| refresh.material.iter().any(|m| m.name == *key))
})
})
}
#[must_use]
pub fn to_proto(&self) -> ProviderProfile {
ProviderProfile {
id: self.id.clone(),
resource_version: self.resource_version,
annotations: self.annotations.clone(),
display_name: self.display_name.clone(),
description: self.description.clone(),
category: self.category as i32,
credentials: self
.credentials
.iter()
.map(|credential| ProviderProfileCredential {
name: credential.name.clone(),
description: credential.description.clone(),
env_vars: credential.env_vars.clone(),
required: credential.required,
auth_style: credential.auth_style.clone(),
header_name: credential.header_name.clone(),
query_param: credential.query_param.clone(),
refresh: credential.refresh.as_ref().map(credential_refresh_to_proto),
path_template: credential.path_template.clone(),
token_grant: credential.token_grant.as_ref().map(token_grant_to_proto),
})
.collect(),
endpoints: self.endpoints.iter().map(endpoint_to_proto).collect(),
binaries: self.binaries.iter().map(binary_to_proto).collect(),
inference_capable: self.inference_capable,
discovery: (!discovery_is_empty(&self.discovery))
.then(|| discovery_to_proto(&self.discovery)),
source: self.source.clone(),
scope: self.scope.clone(),
}
}
#[must_use]
pub fn network_policy_rule(&self, rule_name: &str) -> NetworkPolicyRule {
NetworkPolicyRule {
name: rule_name.to_string(),
endpoints: self.endpoints.iter().map(endpoint_to_proto).collect(),
binaries: self.binaries.iter().map(binary_to_proto).collect(),
}
}
pub fn validate_before_lowering(&self, source: &str) -> Vec<ProfileValidationDiagnostic> {
let mut diagnostics = Vec::new();
for (index, endpoint) in self.endpoints.iter().enumerate() {
if endpoint.rules.as_ref().is_some_and(Vec::is_empty) {
diagnostics.push(ProfileValidationDiagnostic::error(
source,
&self.id,
format!("endpoints[{index}]"),
"rules list cannot be empty (would deny all traffic). \
Use `access: full` or remove rules.",
));
}
if endpoint.deny_rules.as_ref().is_some_and(Vec::is_empty) {
diagnostics.push(ProfileValidationDiagnostic::error(
source,
&self.id,
format!("endpoints[{index}]"),
"deny_rules list cannot be empty (would have no effect). \
Remove it if no denials are needed.",
));
}
if endpoint.protocol != "mcp" {
continue;
}
if let Some(rules) = &endpoint.rules {
for (rule_idx, rule) in rules.iter().enumerate() {
if rule
.allow
.as_ref()
.is_some_and(|a| a.tool.is_some() && a.params.contains_key("name"))
{
diagnostics.push(ProfileValidationDiagnostic::error(
source,
&self.id,
format!("endpoints[{index}].rules[{rule_idx}].allow"),
"MCP rules must use either tool or params.name, not both",
));
}
}
}
if let Some(deny_rules) = &endpoint.deny_rules {
for (deny_idx, deny_rule) in deny_rules.iter().enumerate() {
if deny_rule.tool.is_some() && deny_rule.params.contains_key("name") {
diagnostics.push(ProfileValidationDiagnostic::error(
source,
&self.id,
format!("endpoints[{index}].deny_rules[{deny_idx}]"),
"MCP rules must use either tool or params.name, not both",
));
}
}
}
}
diagnostics
}
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_u64_zero(value: &u64) -> bool {
*value == 0
}
impl CredentialProfile {
#[must_use]
pub fn is_runtime_resolvable(&self) -> bool {
self.token_grant.is_some()
|| self
.refresh
.as_ref()
.is_some_and(CredentialRefreshProfile::is_gateway_mintable)
}
}
impl CredentialRefreshProfile {
#[must_use]
pub fn is_gateway_mintable(&self) -> bool {
is_gateway_mintable_strategy(self.strategy)
}
}
/// Whether the gateway can mint credentials for this refresh strategy (as
/// opposed to strategies resolved elsewhere, e.g. `Static`/`External`).
///
/// Single source of truth shared with `openshell-server`; keep in sync with the
/// dispatch in `provider_refresh::mint_credential`.
#[must_use]
pub fn is_gateway_mintable_strategy(strategy: ProviderCredentialRefreshStrategy) -> bool {
matches!(
strategy,
ProviderCredentialRefreshStrategy::Oauth2RefreshToken
| ProviderCredentialRefreshStrategy::Oauth2ClientCredentials
| ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt
| ProviderCredentialRefreshStrategy::AwsStsAssumeRole
)
}
/// Semantic output ids a refresh strategy can produce **in addition** to its
/// primary credential, split into required and optional.
///
/// Drives `additional_outputs` validation. Strategies not listed here produce
/// only a single (primary) credential and reject any `additional_outputs`.
#[must_use]
pub fn strategy_output_spec(
strategy: ProviderCredentialRefreshStrategy,
) -> (&'static [&'static str], &'static [&'static str]) {
match strategy {
ProviderCredentialRefreshStrategy::AwsStsAssumeRole => {
(&["secret_access_key", "session_token"], &[])
}
_ => (&[], &[]),
}
}
/// Expected primary env key for strategies that constrain it, or `None` when the
/// strategy accepts any caller-chosen primary key.
///
/// AWS `SigV4` signing looks up `AWS_ACCESS_KEY_ID` by name, so STS pins the
/// primary key.
#[must_use]
pub fn strategy_primary_env_key(
strategy: ProviderCredentialRefreshStrategy,
) -> Option<&'static str> {
match strategy {
ProviderCredentialRefreshStrategy::AwsStsAssumeRole => Some("AWS_ACCESS_KEY_ID"),
_ => None,
}
}
/// Expected concrete env key for a given strategy output, when the strategy
/// constrains it (the `SigV4` signer resolves these by name).
#[must_use]
pub fn strategy_output_env_key(
strategy: ProviderCredentialRefreshStrategy,
output: &str,
) -> Option<&'static str> {
match (strategy, output) {
(ProviderCredentialRefreshStrategy::AwsStsAssumeRole, "secret_access_key") => {
Some("AWS_SECRET_ACCESS_KEY")
}
(ProviderCredentialRefreshStrategy::AwsStsAssumeRole, "session_token") => {
Some("AWS_SESSION_TOKEN")
}
_ => None,
}
}
fn discovery_is_empty(discovery: &DiscoveryProfile) -> bool {
discovery.credentials.is_empty()
}
impl Serialize for BinaryProfile {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if !self.harness {
return serializer.serialize_str(&self.path);
}
let mut state = serializer.serialize_struct("BinaryProfile", 2)?;
state.serialize_field("path", &self.path)?;
state.serialize_field("harness", &self.harness)?;
state.end()
}
}
impl<'de> Deserialize<'de> for BinaryProfile {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum BinaryProfileInput {
Path(String),
Object(BinaryProfileObject),
}
#[derive(Deserialize)]
struct BinaryProfileObject {
path: String,
#[serde(default)]
harness: bool,
}
match BinaryProfileInput::deserialize(deserializer)? {
BinaryProfileInput::Path(path) => Ok(Self {
path,
harness: false,
}),
BinaryProfileInput::Object(binary) => Ok(Self {
path: binary.path,
harness: binary.harness,
}),
}
}
}
fn default_category() -> ProviderProfileCategory {
ProviderProfileCategory::Other
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(value: &bool) -> bool {
!*value
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(value: &u32) -> bool {
*value == 0
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero_i64(value: &i64) -> bool {
*value == 0
}
fn default_refresh_strategy() -> ProviderCredentialRefreshStrategy {
ProviderCredentialRefreshStrategy::Unspecified
}
fn deserialize_category<'de, D>(deserializer: D) -> Result<ProviderProfileCategory, D::Error>
where
D: Deserializer<'de>,
{
let raw = String::deserialize(deserializer)?;
provider_profile_category_from_yaml(&raw)
.ok_or_else(|| de::Error::custom(format!("unsupported provider profile category: {raw}")))
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn serialize_category<S>(
category: &ProviderProfileCategory,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(provider_profile_category_to_yaml(*category))
}
fn deserialize_refresh_strategy<'de, D>(
deserializer: D,
) -> Result<ProviderCredentialRefreshStrategy, D::Error>
where
D: Deserializer<'de>,
{
let raw = String::deserialize(deserializer)?;
provider_refresh_strategy_from_yaml(&raw)
.ok_or_else(|| de::Error::custom(format!("unsupported provider refresh strategy: {raw}")))
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn serialize_refresh_strategy<S>(
strategy: &ProviderCredentialRefreshStrategy,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(provider_refresh_strategy_to_yaml(*strategy))
}
#[must_use]
pub fn provider_profile_category_from_yaml(raw: &str) -> Option<ProviderProfileCategory> {
match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() {
"" | "other" => Some(ProviderProfileCategory::Other),
"inference" => Some(ProviderProfileCategory::Inference),
"agent" => Some(ProviderProfileCategory::Agent),
"source_control" => Some(ProviderProfileCategory::SourceControl),
"messaging" => Some(ProviderProfileCategory::Messaging),
"data" => Some(ProviderProfileCategory::Data),
"knowledge" => Some(ProviderProfileCategory::Knowledge),
_ => None,
}
}
#[must_use]
pub fn provider_profile_category_to_yaml(category: ProviderProfileCategory) -> &'static str {
match category {
ProviderProfileCategory::Inference => "inference",
ProviderProfileCategory::Agent => "agent",
ProviderProfileCategory::SourceControl => "source_control",
ProviderProfileCategory::Messaging => "messaging",
ProviderProfileCategory::Data => "data",
ProviderProfileCategory::Knowledge => "knowledge",
ProviderProfileCategory::Other | ProviderProfileCategory::Unspecified => "other",
}
}
#[must_use]
pub fn provider_refresh_strategy_from_yaml(raw: &str) -> Option<ProviderCredentialRefreshStrategy> {
match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() {
"" => Some(ProviderCredentialRefreshStrategy::Unspecified),
"static" => Some(ProviderCredentialRefreshStrategy::Static),
"external" => Some(ProviderCredentialRefreshStrategy::External),
"oauth2_refresh_token" => Some(ProviderCredentialRefreshStrategy::Oauth2RefreshToken),
"oauth2_client_credentials" => {
Some(ProviderCredentialRefreshStrategy::Oauth2ClientCredentials)
}
"google_service_account_jwt" => {
Some(ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt)
}
"aws_sts_assume_role" => Some(ProviderCredentialRefreshStrategy::AwsStsAssumeRole),
_ => None,
}
}
#[must_use]
pub fn provider_refresh_strategy_to_yaml(
strategy: ProviderCredentialRefreshStrategy,
) -> &'static str {
match strategy {
ProviderCredentialRefreshStrategy::Static => "static",
ProviderCredentialRefreshStrategy::External => "external",
ProviderCredentialRefreshStrategy::Oauth2RefreshToken => "oauth2_refresh_token",
ProviderCredentialRefreshStrategy::Oauth2ClientCredentials => "oauth2_client_credentials",
ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt => "google_service_account_jwt",
ProviderCredentialRefreshStrategy::AwsStsAssumeRole => "aws_sts_assume_role",
ProviderCredentialRefreshStrategy::Unspecified => "unspecified",
}
}
fn credential_refresh_from_proto(refresh: &ProviderCredentialRefresh) -> CredentialRefreshProfile {
CredentialRefreshProfile {
strategy: ProviderCredentialRefreshStrategy::try_from(refresh.strategy)
.unwrap_or(ProviderCredentialRefreshStrategy::Unspecified),
token_url: refresh.token_url.clone(),
scopes: refresh.scopes.clone(),
refresh_before_seconds: refresh.refresh_before_seconds,
max_lifetime_seconds: refresh.max_lifetime_seconds,
material: refresh
.material
.iter()
.map(|material| CredentialRefreshMaterialProfile {
name: material.name.clone(),
description: material.description.clone(),
required: material.required,
secret: material.secret,
})
.collect(),
additional_outputs: refresh
.additional_outputs
.iter()
.map(|output| CredentialRefreshOutputProfile {
output: output.output.clone(),
credential: output.credential.clone(),
})
.collect(),
}
}
fn credential_refresh_to_proto(refresh: &CredentialRefreshProfile) -> ProviderCredentialRefresh {
ProviderCredentialRefresh {
strategy: refresh.strategy as i32,
token_url: refresh.token_url.clone(),
scopes: refresh.scopes.clone(),
refresh_before_seconds: refresh.refresh_before_seconds,
max_lifetime_seconds: refresh.max_lifetime_seconds,
material: refresh
.material
.iter()
.map(|material| ProviderCredentialRefreshMaterial {
name: material.name.clone(),
description: material.description.clone(),
required: material.required,
secret: material.secret,
})
.collect(),
additional_outputs: refresh
.additional_outputs
.iter()
.map(|output| ProviderCredentialRefreshOutput {
output: output.output.clone(),
credential: output.credential.clone(),
})
.collect(),
}
}
fn token_grant_from_proto(
token_grant: &openshell_core::proto::ProviderCredentialTokenGrant,
) -> TokenGrantProfile {
TokenGrantProfile {
token_endpoint: token_grant.token_endpoint.clone(),
audience: token_grant.audience.clone(),
jwt_svid_audience: token_grant.jwt_svid_audience.clone(),
client_assertion_type: token_grant.client_assertion_type.clone(),
scopes: token_grant.scopes.clone(),
cache_ttl_seconds: token_grant.cache_ttl_seconds,
audience_overrides: token_grant
.audience_overrides
.iter()
.map(token_grant_audience_override_from_proto)
.collect(),
}
}
fn token_grant_to_proto(
token_grant: &TokenGrantProfile,
) -> openshell_core::proto::ProviderCredentialTokenGrant {
openshell_core::proto::ProviderCredentialTokenGrant {