-
Notifications
You must be signed in to change notification settings - Fork 258
Expand file tree
/
Copy pathmod.rs
More file actions
11119 lines (10340 loc) · 420 KB
/
Copy pathmod.rs
File metadata and controls
11119 lines (10340 loc) · 420 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
//! Profile system for pre-configured capability sets
//!
//! Profiles provide named capability configurations for sandboxed processes.
//! They can be built-in (compiled into the binary), installed from registry
//! packs (e.g. nolabs-ai/claude), or user-defined (in `$XDG_CONFIG_HOME/nono/profiles/`).
pub(crate) mod builtin;
mod credential_provider;
pub use credential_provider::{
CredentialProviderDef, CredentialProviderRequestBodyFormat,
CredentialProviderResponseFieldKind, CredentialProviderStore, CredentialRouteDef,
};
#[cfg(test)]
pub use credential_provider::{
CredentialProviderResponseField, CredentialProviderTokenEndpoint, CredentialProviderType,
};
use credential_provider::{
validate_credential_provider_entries, validate_credential_provider_resolved,
};
use crate::command_policy::{
CommandPoliciesConfig, CommandPolicyValidationScope, validate_command_policies,
validate_legacy_blocked_command_interactions,
};
use nono::{NonoError, Result};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
// Re-export InjectMode and OAuth2Config from nono-proxy for use in profiles
pub use nono_proxy::config::{InjectMode, OAuth2Config};
use crate::package::PackageRef;
/// Profile metadata
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
pub struct ProfileMeta {
pub name: String,
#[serde(default)]
pub version: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub author: Option<String>,
}
pub(crate) fn deserialize_conditional_path_vec<'de, D>(
deserializer: D,
) -> std::result::Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
deserialize_conditional_string_vec(deserializer, "path")
}
fn deserialize_conditional_name_vec<'de, D>(
deserializer: D,
) -> std::result::Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
deserialize_conditional_string_vec(deserializer, "name")
}
fn deserialize_conditional_origin_vec<'de, D>(
deserializer: D,
) -> std::result::Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
deserialize_conditional_string_vec(deserializer, "origin")
}
fn deserialize_conditional_string_vec<'de, D>(
deserializer: D,
value_key: &'static str,
) -> std::result::Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
let values = Vec::<serde_json::Value>::deserialize(deserializer)?;
let mut result = Vec::with_capacity(values.len());
for value in values {
match value {
serde_json::Value::String(item) => result.push(item),
serde_json::Value::Object(mut object) => {
let item_value = object.remove(value_key).ok_or_else(|| {
serde::de::Error::custom(format!("conditional entry is missing '{value_key}'"))
})?;
let item = item_value
.as_str()
.ok_or_else(|| {
serde::de::Error::custom(format!(
"conditional entry '{value_key}' must be a string"
))
})?
.to_string();
let when = match object.remove("when") {
Some(when_value) => Some(
crate::platform::When::deserialize(when_value)
.map_err(serde::de::Error::custom)?,
),
None => None,
};
if !object.is_empty() {
let keys = object.keys().cloned().collect::<Vec<_>>().join(", ");
return Err(serde::de::Error::custom(format!(
"conditional entry has unknown field(s): {keys}"
)));
}
if crate::platform::when_matches_current(when.as_ref())
.map_err(serde::de::Error::custom)?
{
result.push(item);
}
}
_ => {
return Err(serde::de::Error::custom(format!(
"conditional entry must be a string or object with '{value_key}'"
)));
}
}
}
Ok(result)
}
/// Filesystem configuration in a profile
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FilesystemConfig {
/// Directories with read+write access
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub allow: Vec<String>,
/// Directories with read-only access
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub read: Vec<String>,
/// Directories with write-only access
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub write: Vec<String>,
/// Single files with read+write access
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub allow_file: Vec<String>,
/// Single files with read-only access
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub read_file: Vec<String>,
/// Single files with write-only access
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub write_file: Vec<String>,
/// Single AF_UNIX socket paths — connect only.
/// Implies read access on the socket path. See issue #685.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub unix_socket: Vec<String>,
/// Single AF_UNIX socket paths — connect and bind.
/// Implies read+write access on the socket path when it exists, or
/// on its parent directory when it does not yet exist (the normal
/// `bind(2)` workflow — the syscall creates the socket file).
/// Dangling symlinks are rejected at grant time. For runtime-generated
/// filenames (e.g. PID-suffixed paths) prefer `unix_socket_dir_bind`
/// so the implied fs grant stays scoped to a dedicated directory.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub unix_socket_bind: Vec<String>,
/// Directories where any direct-child AF_UNIX socket may be connected to.
/// Non-recursive. Implies read access on the directory.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub unix_socket_dir: Vec<String>,
/// Directories where any direct-child AF_UNIX socket may be connected to
/// or bound. Non-recursive. Implies read+write access on the directory.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub unix_socket_dir_bind: Vec<String>,
/// Directories where any descendant AF_UNIX socket may be connected to.
/// Recursive. Implies read access on the directory.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub unix_socket_subtree: Vec<String>,
/// Directories where any descendant AF_UNIX socket may be connected to or
/// bound. Recursive. Implies read+write access on the directory.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub unix_socket_subtree_bind: Vec<String>,
/// Paths denied filesystem access. Canonical location for deny entries
/// in the #594 schema; the legacy deny-access key drains here via
/// `deprecated_schema::LegacyPolicyPatch`.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub deny: Vec<String>,
/// Paths exempted from group-level deny rules.
///
/// **This flag does not implicitly grant access** — `bypass_protection`
/// only removes the deny rule. Each path must also appear in
/// `filesystem.allow`, `filesystem.read`, or `filesystem.write` (or the
/// matching `*_file` variant) to become accessible. CLI equivalent:
/// `--bypass-protection`.
///
/// Renamed from the legacy deny-override key in the #594 schema;
/// the new name makes the "does not grant access" semantics explicit.
#[serde(default, deserialize_with = "deserialize_conditional_path_vec")]
pub bypass_protection: Vec<String>,
/// Paths whose runtime denials should not be offered in the save-profile
/// prompt. This does not grant access, remove deny rules, or hide the
/// diagnostic footer; it only suppresses repeated save suggestions for
/// paths the user has decided not to grant.
/// ALIAS(canonical="suppress_save_prompt", introduced="v0.52.0", remove_by="indefinite", issue="#875")
#[serde(
default,
alias = "ignore",
deserialize_with = "deserialize_conditional_path_vec"
)]
pub suppress_save_prompt: Vec<String>,
}
/// Group composition — include/exclude pair for policy groups.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GroupsConfig {
#[serde(default, deserialize_with = "deserialize_conditional_name_vec")]
pub include: Vec<String>,
#[serde(default, deserialize_with = "deserialize_conditional_name_vec")]
pub exclude: Vec<String>,
}
/// Command allow/deny pair.
///
/// **Deprecated in v0.33.0.** Both fields gate only the directly-invoked
/// startup command. They are not enforced for child processes, so they
/// cannot serve as a security boundary. Configured values still parse and
/// are surfaced via runtime warnings (see [`crate::command_blocking_deprecation`]).
/// Prefer resource-based controls: filesystem deny rules, narrower filesystem
/// grants, `unlink_protection`, and network policy.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CommandsConfig {
/// Startup-only command allowlist override. Not enforced for child
/// processes; prefer resource-based controls.
#[serde(default)]
#[deprecated(
since = "0.33.0",
note = "startup-only, not enforced for child processes; prefer resource-based controls"
)]
pub allow: Vec<String>,
/// Startup-only command denylist extension. Not enforced for child
/// processes; prefer resource-based controls.
#[serde(default)]
#[deprecated(
since = "0.33.0",
note = "startup-only, not enforced for child processes; prefer resource-based controls"
)]
pub deny: Vec<String>,
}
/// Custom credential route definition for reverse proxy.
///
/// Allows users to define their own credential services in profiles,
/// enabling `--proxy-credential` to work with any API without requiring
/// changes to the built-in `network-policy.json`.
///
/// Supports multiple injection modes:
/// - `header`: Inject into HTTP header with format string (default)
/// - `url_path`: Replace pattern in URL path (e.g., Telegram Bot API `/bot{}/`)
/// - `query_param`: Add/replace query parameter (e.g., `?api_key=...`)
/// - `basic_auth`: HTTP Basic Authentication (credential as `username:password`)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CustomCredentialDef {
/// Upstream URL to proxy requests to (e.g., "https://api.telegram.org")
pub upstream: String,
/// Keystore account name for the credential (e.g., "telegram_bot_token").
/// Mutually exclusive with `auth` — use one or the other.
#[serde(default)]
pub credential_key: Option<String>,
/// Optional OAuth2 client_credentials configuration.
/// When present, the proxy handles token exchange automatically.
/// Mutually exclusive with `credential_key` — use one or the other.
#[serde(default)]
pub auth: Option<OAuth2Config>,
/// Injection mode (default: "header")
#[serde(default)]
pub inject_mode: InjectMode,
// --- Header mode fields ---
/// HTTP header to inject the credential into (default: "Authorization")
/// Only used when inject_mode is "header".
#[serde(default = "default_inject_header")]
pub inject_header: String,
/// How the injected header value is built (`{}` is replaced by the secret). Only when `inject_mode` is header.
///
/// If you set this field, that whole string is used as-is — `Authorization` or any other header.
///
/// If you omit it: an `Authorization` header (any capitalization) defaults to `Bearer {}`; any other header defaults to `{}` (secret only, no prefix).
#[serde(default)]
pub credential_format: Option<String>,
// --- URL path mode fields ---
/// Pattern to match in incoming URL path. Use {} as placeholder for phantom token.
/// Example: "/bot{}/" matches "/bot<token>/getMe"
/// Only used when inject_mode is "url_path".
#[serde(default)]
pub path_pattern: Option<String>,
/// Pattern for outgoing URL path. Use {} as placeholder for real credential.
/// Defaults to same as path_pattern if not specified.
/// Only used when inject_mode is "url_path".
#[serde(default)]
pub path_replacement: Option<String>,
// --- Query param mode fields ---
/// Name of the query parameter to add/replace with the credential.
/// Only used when inject_mode is "query_param".
#[serde(default)]
pub query_param_name: Option<String>,
/// Optional overrides for proxy-side phantom token handling.
///
/// When set, these values control how the local proxy validates incoming
/// phantom tokens from the sandboxed process. Outbound upstream injection
/// still uses the top-level fields.
#[serde(default)]
pub proxy: Option<nono_proxy::config::ProxyInjectConfig>,
/// Explicit environment variable name for the phantom token (e.g., "OPENAI_API_KEY").
///
/// When set, the proxy uses this as the SDK API key env var instead of
/// deriving it from `credential_key.to_uppercase()`. Required when
/// `credential_key` is a URI manager reference (`op://`, `bw://`,
/// `apple-password://`, or `file://`).
#[serde(default)]
pub env_var: Option<String>,
/// Optional L7 endpoint rules for method+path filtering.
/// When non-empty, only matching method+path combinations are allowed.
#[serde(default)]
pub endpoint_rules: Vec<nono_proxy::config::EndpointRule>,
/// Optional explicit L7 endpoint policy with allow/deny/approve routes.
#[serde(default)]
pub endpoint_policy: Option<nono_proxy::config::EndpointPolicyConfig>,
/// Optional path to a PEM-encoded CA certificate file for upstream TLS.
///
/// When set, the proxy trusts this CA in addition to the system roots
/// when connecting to the upstream for this route. Required for upstreams
/// with self-signed or private CA certificates (e.g., Kubernetes API servers).
///
/// Supports absolute paths and tilde (`~/…`) expansion. Relative paths
/// resolve against the working directory; prefer absolute paths to avoid
/// ambiguity.
#[serde(default)]
pub tls_ca: Option<String>,
/// Optional path to a PEM-encoded client certificate for upstream mTLS.
///
/// When set together with `tls_client_key`, the proxy presents this
/// certificate to the upstream during TLS handshake. Required for
/// upstreams that enforce mutual TLS (e.g., Kubernetes API servers
/// configured with client-certificate authentication).
#[serde(default)]
pub tls_client_cert: Option<String>,
/// Optional path to a PEM-encoded private key for upstream mTLS.
///
/// Must be set together with `tls_client_cert`. The key must correspond
/// to the certificate in `tls_client_cert`.
#[serde(default)]
pub tls_client_key: Option<String>,
/// Optional AWS SigV4 signing configuration.
///
/// When present, the proxy will sign outbound requests with AWS SigV4
/// credentials resolved from the configured profile (or the default
/// credential chain). Mutually exclusive with `credential_key` and `auth`.
#[serde(default)]
pub aws_auth: Option<nono_proxy::config::AwsAuthConfig>,
/// SPIFFE/SPIRE Workload API auth. Mutually exclusive with `credential_key`, `auth`, and `aws_auth`.
#[serde(default)]
pub spiffe: Option<nono_proxy::config::SpiffeAuthConfig>,
/// Optional per-route request-rate limit (RouteRateLimiter).
///
/// Caps the rate of L7 requests forwarded to this credential's upstream to
/// contain a runaway or compromised agent. Applies only to L7-visible
/// traffic (reverse-proxy routes and TLS-intercepted CONNECT); it has no
/// effect on an opaque CONNECT tunnel.
#[serde(default)]
pub rate_limit: Option<nono_proxy::config::RouteRateLimitConfig>,
}
/// Host-side source that materializes a proxy credential for `cmd://<name>`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CredentialCaptureEntry {
/// Command and arguments. The first element is resolved by the supervisor
/// before execution; no shell is used.
#[serde(default)]
pub command: Vec<String>,
/// External provider subprocess using the typed nono credential-provider
/// protocol. Mutually exclusive with `command`.
#[serde(default)]
pub provider: Option<CredentialCaptureProvider>,
/// Maximum command runtime in seconds.
#[serde(default)]
pub timeout_secs: Option<u64>,
/// In-memory cache TTL in seconds. `0` disables caching.
#[serde(default)]
pub ttl_secs: Option<u64>,
/// In-memory cache TTL in seconds. `0` disables caching. Preferred name
/// for new profiles; `ttl_secs` remains accepted for compatibility.
#[serde(default)]
pub cache_ttl_secs: Option<u64>,
/// Optional regular expression used to derive the cache scope from the
/// request path. The first capture group is used when present.
#[serde(default)]
pub cache_path_regex: Option<String>,
/// Capture command stdin mode. Defaults to `null`.
#[serde(default)]
pub stdin: CredentialCaptureStdinMode,
/// Capture command output mode. Defaults to text.
#[serde(default)]
pub output: CredentialCaptureOutput,
/// Explicit interactive affordances for browser-backed auth flows.
#[serde(default)]
pub interaction: Option<CredentialCaptureInteraction>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CredentialCaptureProvider {
/// Provider executable and arguments. The first element is resolved by the
/// supervisor before execution; no shell is used.
pub command: Vec<String>,
/// Provider-specific configuration sent to the provider in request JSON.
#[serde(default)]
pub config: serde_json::Value,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialCaptureStdinMode {
#[default]
Null,
RequestJson,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CredentialCaptureOutput {
Format(CredentialCaptureOutputFormat),
Config(CredentialCaptureOutputConfig),
}
impl Default for CredentialCaptureOutput {
fn default() -> Self {
Self::Format(CredentialCaptureOutputFormat::Text)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CredentialCaptureOutputFormat {
Text,
Json,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CredentialCaptureOutputConfig {
pub format: CredentialCaptureOutputFormat,
#[serde(default)]
pub allow_headers: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CredentialCaptureInteraction {
/// Allow the capture command to write prompts to the terminal via inherited stderr.
#[serde(default)]
pub stdio: bool,
/// Allow the capture command to read from the terminal via inherited stdin.
/// Only set this when the helper genuinely needs to prompt the user for input.
/// Defaults to false; stdin is `/dev/null` unless explicitly enabled.
#[serde(default)]
pub stdin: bool,
#[serde(default)]
pub open_urls: Option<OpenUrlConfig>,
#[serde(default)]
pub allow_launch_services: bool,
}
fn default_inject_header() -> String {
"Authorization".to_string()
}
/// Check if a character is a valid HTTP header token character.
fn is_http_token_char(c: char) -> bool {
c.is_ascii_alphanumeric()
|| matches!(
c,
'!' | '#'
| '$'
| '%'
| '&'
| '\''
| '*'
| '+'
| '-'
| '.'
| '^'
| '_'
| '`'
| '|'
| '~'
)
}
/// Validate a credential key.
///
/// Accepts either:
/// - A bare keyring account name (alphanumeric + underscores only)
/// - A 1Password `op://` URI (validated by `nono::keystore::validate_op_uri`)
/// - A Bitwarden `bw://` URI (validated by `nono::keystore::validate_bw_uri`)
/// - An Apple Passwords `apple-password://` URI
/// - A `file://` URI pointing to an absolute path (validated by `nono::keystore::validate_file_uri`)
/// - An `env://` URI referencing a host environment variable (validated by `nono::keystore::validate_env_uri`)
fn validate_credential_key(context_name: &str, key: &str) -> Result<()> {
if key.is_empty() {
return Err(NonoError::ProfileParse(format!(
"credential_key for custom credential '{}' cannot be empty",
context_name
)));
}
if nono::keystore::is_op_uri(key) {
// Validate as 1Password URI
nono::keystore::validate_op_uri(key).map_err(|e| {
NonoError::ProfileParse(format!(
"invalid 1Password URI for custom credential '{}': {}",
context_name, e
))
})
} else if nono::keystore::is_bw_uri(key) {
nono::keystore::validate_bw_uri(key).map_err(|e| {
NonoError::ProfileParse(format!(
"invalid Bitwarden URI for custom credential '{}': {}",
context_name, e
))
})
} else if nono::keystore::is_apple_password_uri(key) {
nono::keystore::validate_apple_password_uri(key).map_err(|e| {
NonoError::ProfileParse(format!(
"invalid Apple Passwords URI for custom credential '{}': {}",
context_name, e
))
})
} else if nono::keystore::is_file_uri(key) {
nono::keystore::validate_file_uri(key).map_err(|e| {
NonoError::ProfileParse(format!(
"invalid file:// URI for custom credential '{}': {}",
context_name, e
))
})
} else if nono::keystore::is_cmd_uri(key) {
nono::keystore::validate_cmd_uri(key).map_err(|e| {
NonoError::ProfileParse(format!(
"invalid cmd:// URI for custom credential '{}': {}",
context_name, e
))
})
} else if nono::keystore::is_env_uri(key) {
nono::keystore::validate_env_uri(key).map_err(|e| {
NonoError::ProfileParse(format!(
"invalid env:// URI for custom credential '{}': {}",
context_name, e
))
})
} else {
// Validate as keyring account name (alphanumeric + underscore)
if !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(NonoError::ProfileParse(format!(
"credential_key '{}' for custom credential '{}' must contain only \
alphanumeric characters and underscores (or use op:// / bw:// / apple-password:// / file:// / env:// / cmd:// URI)",
key, context_name
)));
}
Ok(())
}
}
/// Validate a custom credential definition for security issues.
///
/// Checks:
/// - `credential_key` must be alphanumeric + underscores only, or a valid
/// `op://` / `bw://` / `apple-password://` / `file://` / `env://` / `cmd://` URI
/// - `upstream` must be HTTPS (or HTTP for loopback only)
/// - Mode-specific validation:
/// - `header`: inject_header must be valid HTTP token; effective format (see field doc) must not contain CR/LF
/// - `url_path`: path_pattern required, no CRLF in patterns
/// - `query_param`: query_param_name required, valid query param name
/// - `basic_auth`: no additional required fields
fn validate_custom_credential(name: &str, cred: &CustomCredentialDef) -> Result<()> {
// Mutual exclusion: aws_auth is incompatible with credential_key and auth.
if cred.aws_auth.is_some() && (cred.credential_key.is_some() || cred.auth.is_some()) {
return Err(NonoError::ProfileParse(format!(
"custom credential '{}' has 'aws_auth' set together with 'credential_key' or 'auth'; \
aws_auth is mutually exclusive with both — remove the other auth field",
name
)));
}
// Mutual exclusion: credential_key and auth cannot both be set
if cred.credential_key.is_some() && cred.auth.is_some() {
return Err(NonoError::ProfileParse(format!(
"custom credential '{}' has both 'credential_key' and 'auth' set; \
these are mutually exclusive — use one or the other",
name
)));
}
// Mutual exclusion: spiffe is incompatible with credential_key, auth (oauth2), and aws_auth.
if cred.spiffe.is_some()
&& (cred.credential_key.is_some() || cred.auth.is_some() || cred.aws_auth.is_some())
{
return Err(NonoError::ProfileParse(format!(
"custom credential '{}' has 'spiffe' set together with 'credential_key', 'auth' \
(oauth2), or 'aws_auth'; spiffe is mutually exclusive with all other auth fields",
name
)));
}
// At least one auth mechanism must be set
if cred.credential_key.is_none()
&& cred.auth.is_none()
&& cred.aws_auth.is_none()
&& cred.spiffe.is_none()
{
return Err(NonoError::ProfileParse(format!(
"custom credential '{}' must have either 'credential_key', 'auth', 'aws_auth', \
or 'spiffe' set",
name
)));
}
// Validate inject_header for SPIFFE routes (credential_key has its own validate_header_mode()).
if let Some(nono_proxy::config::SpiffeAuthConfig::Jwt {
ref inject_header, ..
}) = cred.spiffe
{
validate_header_name(name, inject_header)?;
}
// Validate OAuth2 auth if present
if let Some(ref auth) = cred.auth {
validate_oauth2_auth(name, auth)?;
}
// Validate aws_auth if present
if let Some(ref aws) = cred.aws_auth {
validate_aws_auth(name, aws)?;
}
// Validate credential_key if present
if let Some(ref key) = cred.credential_key {
validate_credential_key(name, key)?;
// URI manager references (except env://) cannot be meaningfully
// uppercased into an env var name, so env_var is required for them.
// env:// is exempt: the var name is derived from the URI itself.
if (nono::keystore::is_op_uri(key)
|| nono::keystore::is_bw_uri(key)
|| nono::keystore::is_apple_password_uri(key)
|| nono::keystore::is_file_uri(key)
|| nono::keystore::is_cmd_uri(key))
&& cred.env_var.is_none()
{
return Err(NonoError::ProfileParse(format!(
"env_var is required for custom credential '{}' when credential_key is a URI \
manager reference (op://, bw://, apple-password://, file://, or cmd://); \
set it to the SDK API key env var name (e.g., \"OPENAI_API_KEY\")",
name
)));
}
}
// Validate env_var format if specified
if let Some(ref ev) = cred.env_var {
if ev.is_empty() {
return Err(NonoError::ProfileParse(format!(
"env_var for custom credential '{}' cannot be empty",
name
)));
}
if !ev.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(NonoError::ProfileParse(format!(
"env_var '{}' for custom credential '{}' must contain only \
alphanumeric characters and underscores",
ev, name
)));
}
}
// Validate upstream URL (HTTPS required, HTTP only for loopback)
validate_upstream_url(&cred.upstream, name)?;
// Mode-specific validation (only applies to credential_key-based routes,
// not OAuth2 routes which always inject as Bearer header)
if cred.credential_key.is_some() {
match cred.inject_mode {
InjectMode::Header => {
validate_header_mode(name, cred)?;
}
InjectMode::UrlPath => {
validate_url_path_mode(name, cred)?;
}
InjectMode::QueryParam => {
validate_query_param_mode(name, cred)?;
}
InjectMode::BasicAuth => {
// No additional required fields for basic_auth mode
// Credential value is expected to be "username:password" format
}
}
}
validate_proxy_override(name, cred)?;
Ok(())
}
fn validate_proxy_override(name: &str, cred: &CustomCredentialDef) -> Result<()> {
let Some(proxy) = cred.proxy.as_ref() else {
return Ok(());
};
let mode = proxy.inject_mode.as_ref().unwrap_or(&cred.inject_mode);
match mode {
InjectMode::Header | InjectMode::BasicAuth => {
let header = proxy
.inject_header
.as_deref()
.unwrap_or(cred.inject_header.as_str());
if header.is_empty() {
return Err(NonoError::ProfileParse(format!(
"proxy.inject_header for custom credential '{}' cannot be empty",
name
)));
}
if !header.chars().all(is_http_token_char) {
return Err(NonoError::ProfileParse(format!(
"proxy.inject_header '{}' for custom credential '{}' contains invalid characters; \
header names must be valid HTTP tokens (alphanumeric and !#$%&'*+-.^_`|~)",
header, name
)));
}
if *mode == InjectMode::Header {
let parent_resolved = nono_proxy::config::resolved_credential_format(
cred.inject_header.as_str(),
cred.credential_format.as_deref(),
);
let format = proxy
.credential_format
.as_deref()
.unwrap_or(parent_resolved.as_str());
if format.contains('\r') || format.contains('\n') {
return Err(NonoError::ProfileParse(format!(
"proxy.credential_format for custom credential '{}' contains invalid CRLF characters; \
this could enable header injection attacks",
name
)));
}
}
}
InjectMode::UrlPath => {
let pattern = proxy
.path_pattern
.as_deref()
.or(cred.path_pattern.as_deref())
.ok_or_else(|| {
NonoError::ProfileParse(format!(
"proxy.path_pattern is required for custom credential '{}' when effective inject_mode is 'url_path'",
name
))
})?;
if !pattern.contains("{}") {
return Err(NonoError::ProfileParse(format!(
"proxy.path_pattern '{}' for custom credential '{}' must contain {{}} placeholder",
pattern, name
)));
}
if pattern.contains('\r') || pattern.contains('\n') {
return Err(NonoError::ProfileParse(format!(
"proxy.path_pattern for custom credential '{}' contains invalid CRLF characters",
name
)));
}
if let Some(replacement) = proxy
.path_replacement
.as_deref()
.or(cred.path_replacement.as_deref())
{
if !replacement.contains("{}") {
return Err(NonoError::ProfileParse(format!(
"proxy.path_replacement '{}' for custom credential '{}' must contain {{}} placeholder",
replacement, name
)));
}
if replacement.contains('\r') || replacement.contains('\n') {
return Err(NonoError::ProfileParse(format!(
"proxy.path_replacement for custom credential '{}' contains invalid CRLF characters",
name
)));
}
}
}
InjectMode::QueryParam => {
let param_name = proxy
.query_param_name
.as_deref()
.or(cred.query_param_name.as_deref())
.ok_or_else(|| {
NonoError::ProfileParse(format!(
"proxy.query_param_name is required for custom credential '{}' when effective inject_mode is 'query_param'",
name
))
})?;
if param_name.is_empty() {
return Err(NonoError::ProfileParse(format!(
"proxy.query_param_name for custom credential '{}' cannot be empty",
name
)));
}
if !param_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(NonoError::ProfileParse(format!(
"proxy.query_param_name '{}' for custom credential '{}' must contain only \
alphanumeric characters, underscores, and hyphens",
param_name, name
)));
}
}
}
Ok(())
}
/// Validate OAuth2 client_credentials auth configuration.
///
/// Checks:
/// - `token_url` must be HTTPS (or HTTP for loopback addresses)
/// - `client_id` must not be empty
/// - `client_secret` must not be empty and must be a credential reference
/// (env://, file://, op://, bw://, apple-password://) or plain value
fn validate_oauth2_auth(name: &str, auth: &OAuth2Config) -> Result<()> {
// Validate token_url — same rules as upstream URL (HTTPS or loopback HTTP)
validate_upstream_url(&auth.token_url, &format!("{}/auth.token_url", name))?;
// When using client_assertion, client_id/client_secret are not required,
// but the assertion config itself must have valid fields.
if let Some(ref assertion) = auth.client_assertion {
if !auth.client_id.is_empty() || !auth.client_secret.is_empty() {
return Err(NonoError::ProfileParse(format!(
"auth.client_assertion for custom credential '{}' is mutually exclusive with client_id/client_secret",
name
)));
}
match assertion {
nono_proxy::config::ClientAssertionConfig::SpiffeJwt {
workload_api_socket,
audience,
..
} => {
if workload_api_socket.is_empty() {
return Err(NonoError::ProfileParse(format!(
"auth.client_assertion.workload_api_socket for custom credential '{}' cannot be empty",
name
)));
}
if audience.is_empty() {
return Err(NonoError::ProfileParse(format!(
"auth.client_assertion.audience for custom credential '{}' cannot be empty",
name
)));
}
}
}
} else {
if auth.client_id.is_empty() {
return Err(NonoError::ProfileParse(format!(
"auth.client_id for custom credential '{}' cannot be empty",
name
)));
}
if auth.client_secret.is_empty() {
return Err(NonoError::ProfileParse(format!(
"auth.client_secret for custom credential '{}' cannot be empty",
name
)));
}
}
Ok(())
}
/// Validate AWS SigV4 signing configuration subfields.
///
/// - `profile`: non-empty, no whitespace (whitespace breaks the AWS INI config
/// parser; see aws/aws-cli#2806). Mixed case is allowed — profile names are
/// case-sensitive.
/// - `region` / `service`: non-empty, lowercase, no whitespace. The SigV4
/// credential scope requires lowercase region and service codes.
fn validate_aws_auth(name: &str, aws: &nono_proxy::config::AwsAuthConfig) -> Result<()> {
if let Some(ref profile) = aws.profile
&& (profile.is_empty() || profile.contains(char::is_whitespace))
{
return Err(NonoError::ProfileParse(format!(
"aws_auth.profile for custom credential '{}' must be a non-empty string \
with no whitespace; omit the field to use the default credential chain",
name
)));
}
if let Some(ref region) = aws.region
&& (region.is_empty()
|| region.contains(char::is_whitespace)
|| region.chars().any(|c| c.is_uppercase()))
{
return Err(NonoError::ProfileParse(format!(
"aws_auth.region for custom credential '{}' must be a non-empty, \
lowercase string with no whitespace (e.g., \"us-east-1\")",
name
)));
}
if let Some(ref service) = aws.service
&& (service.is_empty()
|| service.contains(char::is_whitespace)
|| service.chars().any(|c| c.is_uppercase()))
{
return Err(NonoError::ProfileParse(format!(
"aws_auth.service for custom credential '{}' must be a non-empty, \
lowercase string with no whitespace (e.g., \"bedrock\", \"s3\")",
name
)));
}
Ok(())
}
/// Validate header injection mode fields.
/// Validate a single header name: non-empty, valid HTTP token characters only.
fn validate_header_name(cred_name: &str, header: &str) -> Result<()> {
if header.is_empty() {
return Err(NonoError::ProfileParse(format!(
"inject_header for custom credential '{}' cannot be empty",
cred_name
)));
}
if !header.chars().all(is_http_token_char) {
return Err(NonoError::ProfileParse(format!(
"inject_header '{}' for custom credential '{}' contains invalid characters; \
header names must be valid HTTP tokens (alphanumeric and !#$%&'*+-.^_`|~)",
header, cred_name
)));
}
Ok(())
}
fn validate_header_mode(name: &str, cred: &CustomCredentialDef) -> Result<()> {
// Validate inject_header
if cred.inject_header.is_empty() {
return Err(NonoError::ProfileParse(format!(
"inject_header for custom credential '{}' cannot be empty",
name
)));
}
if !cred.inject_header.chars().all(is_http_token_char) {
return Err(NonoError::ProfileParse(format!(
"inject_header '{}' for custom credential '{}' contains invalid characters; \
header names must be valid HTTP tokens (alphanumeric and !#$%&'*+-.^_`|~)",
cred.inject_header, name
)));
}
// Validate effective credential_format (no CRLF injection)
let effective_format = nono_proxy::config::resolved_credential_format(
cred.inject_header.as_str(),
cred.credential_format.as_deref(),
);
if effective_format.contains('\r') || effective_format.contains('\n') {
return Err(NonoError::ProfileParse(format!(
"credential_format for custom credential '{}' contains invalid CRLF characters; \
this could enable header injection attacks",
name
)));
}
Ok(())