Repository navigation
Expand file tree
/
Copy pathcli.rs
More file actions
1955 lines (1738 loc) · 67 KB
/
Copy pathcli.rs
File metadata and controls
1955 lines (1738 loc) · 67 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
//! Shared CLI entrypoint for the gateway binaries.
use clap::parser::ValueSource;
use clap::{ArgAction, ArgMatches, Command, CommandFactory, FromArgMatches, Parser};
use miette::{IntoDiagnostic, Result};
use openshell_core::ComputeDriverKind;
use openshell_core::config::DEFAULT_SERVER_PORT;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use tracing::{error, info, warn};
use tracing_subscriber::EnvFilter;
use crate::certgen;
use crate::compute::driver_config::GuestTlsPaths;
use crate::config_file::{self, ConfigFile, GatewayFileSection};
use crate::defaults::{self, LocalTlsPaths};
use crate::{
ComputeDriverRegistry, ServerStartupConfig, configured_compute_driver_for_startup,
install_default_compute_drivers, run_server, tracing_bus::TracingLogBus,
};
/// `OpenShell` gateway process - gRPC and HTTP server with protocol multiplexing.
///
/// Top-level CLI. When invoked without a subcommand the binary runs the
/// gateway server using `RunArgs`. The `generate-certs` subcommand is used by
/// the Helm pre-install hook to bootstrap mTLS Secrets.
#[derive(Parser, Debug)]
#[command(version = openshell_core::VERSION)]
#[command(about = "OpenShell gRPC/HTTP server", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
#[command(flatten)]
run: RunArgs,
}
#[derive(clap::Subcommand, Debug)]
enum Commands {
/// Generate mTLS PKI and write Kubernetes Secrets (Helm pre-install hook).
GenerateCerts(certgen::CertgenArgs),
}
#[derive(clap::Args, Debug)]
#[allow(clippy::struct_excessive_bools)]
struct RunArgs {
/// Path to a TOML configuration file (see RFC 0003).
///
/// When set, gateway-wide settings and per-driver tables are read from
/// the file. Gateway command-line flags and `OPENSHELL_*` environment
/// variables continue to take precedence over gateway file values.
#[arg(long, env = "OPENSHELL_GATEWAY_CONFIG")]
config: Option<PathBuf>,
/// IP address to bind the server, health, and metrics listeners to.
#[arg(long, default_value = "127.0.0.1", env = "OPENSHELL_BIND_ADDRESS")]
bind_address: IpAddr,
/// Port to bind the server to.
#[arg(long, default_value_t = DEFAULT_SERVER_PORT, env = "OPENSHELL_SERVER_PORT")]
port: u16,
/// Port for unauthenticated health endpoints (healthz, readyz).
/// Set to 0 to disable the dedicated health listener.
#[arg(long, default_value_t = 0, env = "OPENSHELL_HEALTH_PORT")]
health_port: u16,
/// Port for the Prometheus metrics endpoint (/metrics).
/// Set to 0 to disable the dedicated metrics listener.
#[arg(long, default_value_t = 0, env = "OPENSHELL_METRICS_PORT")]
metrics_port: u16,
/// Log level (trace, debug, info, warn, error).
#[arg(long, default_value = "info", env = "OPENSHELL_LOG_LEVEL")]
log_level: String,
/// Path to TLS certificate file (required unless --disable-tls).
#[arg(long, env = "OPENSHELL_TLS_CERT")]
tls_cert: Option<PathBuf>,
/// Path to TLS private key file (required unless --disable-tls).
#[arg(long, env = "OPENSHELL_TLS_KEY")]
tls_key: Option<PathBuf>,
/// Path to CA certificate for client certificate verification (mTLS).
#[arg(long, env = "OPENSHELL_TLS_CLIENT_CA")]
tls_client_ca: Option<PathBuf>,
/// Database URL for persistence.
///
/// When unset, the gateway stores state under the `XDG` state
/// directory. Kept as an Option at the clap layer so the `generate-certs`
/// subcommand can run without gateway runtime defaults.
#[arg(long, env = "OPENSHELL_DB_URL")]
db_url: Option<String>,
/// Compute drivers configured for this gateway.
///
/// Accepts a comma-delimited list such as `kubernetes` or
/// `kubernetes,podman`. The configuration format is future-proofed for
/// multiple drivers, but the gateway currently requires exactly one.
/// When unset, the gateway auto-detects the driver based on the runtime
/// environment (Kubernetes → Podman → Docker). VM is never
/// auto-detected and requires explicit configuration.
#[arg(
long,
alias = "driver",
env = "OPENSHELL_DRIVERS",
value_delimiter = ',',
value_parser = parse_compute_driver
)]
drivers: Vec<String>,
/// Path to a Unix domain socket served by a remote compute driver
/// implementing `compute_driver.proto`.
///
/// When set, the socket is associated with the single driver name supplied
/// by `--drivers` or `OPENSHELL_DRIVERS` and replaces normal construction
/// for that selected name, including canonical built-in names. The gateway
/// connects to this operator-provided endpoint; it does not provision the
/// remote driver.
#[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")]
compute_driver_socket: Option<PathBuf>,
/// Disable TLS entirely — listen on plaintext HTTP.
/// Use this when the gateway sits behind a reverse proxy or tunnel
/// (e.g. Cloudflare Tunnel) that terminates TLS at the edge.
#[arg(long, env = "OPENSHELL_DISABLE_TLS")]
disable_tls: bool,
/// OIDC issuer URL for JWT-based authentication.
/// When set, the server validates `authorization: Bearer` tokens on gRPC
/// requests against the issuer's JWKS endpoint.
#[arg(long, env = "OPENSHELL_OIDC_ISSUER")]
oidc_issuer: Option<String>,
/// Enable mTLS client certificate authentication for local single-user gateways.
///
/// When unset, this defaults on for Docker, Podman, and VM gateways that
/// have client certificate verification configured and no OIDC issuer.
/// Kubernetes deployments must use OIDC or fronting-proxy auth instead.
#[arg(
long = "enable-mtls-auth",
env = "OPENSHELL_ENABLE_MTLS_AUTH",
default_value_t = false,
action = ArgAction::Set
)]
enable_mtls_auth: bool,
/// Expected OIDC audience claim (typically the client ID).
#[arg(long, env = "OPENSHELL_OIDC_AUDIENCE", default_value = "openshell-cli")]
oidc_audience: String,
/// JWKS key cache TTL in seconds.
#[arg(long, env = "OPENSHELL_OIDC_JWKS_TTL", default_value_t = 3600)]
oidc_jwks_ttl: u64,
/// Dot-separated path to the roles array in the JWT claims.
/// Keycloak: `realm_access.roles` (default). Entra ID: "roles". Okta: "groups".
#[arg(
long,
env = "OPENSHELL_OIDC_ROLES_CLAIM",
default_value = "realm_access.roles"
)]
oidc_roles_claim: String,
/// Role name that grants admin access.
#[arg(
long,
env = "OPENSHELL_OIDC_ADMIN_ROLE",
default_value = "openshell-admin"
)]
oidc_admin_role: String,
/// Role name that grants standard user access.
#[arg(
long,
env = "OPENSHELL_OIDC_USER_ROLE",
default_value = "openshell-user"
)]
oidc_user_role: String,
/// Dot-separated path to the scopes value in the JWT claims.
/// When set, the server enforces scope-based permissions on top of roles.
/// Keycloak: "scope". Okta: "scp". Leave empty to disable scope enforcement.
#[arg(long, env = "OPENSHELL_OIDC_SCOPES_CLAIM", default_value = "")]
oidc_scopes_claim: String,
/// Maximum gRPC requests allowed per rate-limit window. Set to 0 to disable.
#[arg(long, env = "OPENSHELL_GRPC_RATE_LIMIT_REQUESTS")]
grpc_rate_limit_requests: Option<u64>,
/// gRPC rate-limit window length in seconds. Set to 0 to disable.
#[arg(long, env = "OPENSHELL_GRPC_RATE_LIMIT_WINDOW_SECONDS")]
grpc_rate_limit_window_seconds: Option<u64>,
/// Subject Alternative Names configured on the gateway server certificate.
/// Wildcard DNS SANs also enable sandbox service URLs under that domain.
#[arg(
long = "server-san",
env = "OPENSHELL_SERVER_SAN",
value_delimiter = ','
)]
server_sans: Vec<String>,
/// Enable plaintext HTTP routing for loopback sandbox service URLs.
#[arg(
long,
env = "OPENSHELL_ENABLE_LOOPBACK_SERVICE_HTTP",
default_value_t = true,
action = ArgAction::Set
)]
enable_loopback_service_http: bool,
}
pub fn command() -> Command {
Cli::command()
.name("openshell-gateway")
.bin_name("openshell-gateway")
}
pub async fn run_cli() -> Result<()> {
run_cli_with_compute_drivers(install_default_compute_drivers()).await
}
/// Run the gateway CLI with the compute drivers linked by the binary.
pub async fn run_cli_with_compute_drivers(compute_drivers: ComputeDriverRegistry) -> Result<()> {
rustls::crypto::ring::default_provider()
.install_default()
.map_err(|e| miette::miette!("failed to install rustls crypto provider: {e:?}"))?;
let matches = command().get_matches();
let cli = Cli::from_arg_matches(&matches).expect("clap validated args");
match cli.command {
Some(Commands::GenerateCerts(args)) => certgen::run(args).await,
None => Box::pin(run_from_args(cli.run, matches, compute_drivers)).await,
}
}
fn prepare_server_config(
args: &mut RunArgs,
matches: &ArgMatches,
compute_drivers: &ComputeDriverRegistry,
) -> Result<ServerStartupConfig> {
// Load TOML when explicitly requested, or from the default XDG location
// when that file exists. Missing default config is not an error: runtime
// defaults and OPENSHELL_* env vars are enough for package-managed starts.
let config_path = resolve_config_path(args)?;
let file: Option<ConfigFile> = if let Some(path) = config_path {
Some(config_file::load(&path).map_err(|e| miette::miette!("{e}"))?)
} else {
None
};
if let Some(file) = file.as_ref() {
merge_file_into_args(args, &file.openshell.gateway, matches);
}
normalize_compute_driver_socket_args(args, matches)?;
let compute_driver = compute_drivers
.select(&args.drivers)
.map_err(|error| miette::miette!("{error}"))?;
let compute_driver_kind = compute_driver.name().parse::<ComputeDriverKind>().ok();
let local_tls = apply_runtime_defaults(args)?;
let guest_tls = local_tls.as_ref().map(GuestTlsPaths::from);
let local_jwt = defaults::complete_local_jwt_config()?;
let bind = SocketAddr::new(args.bind_address, args.port);
let has_client_ca = args.tls_client_ca.is_some();
let has_oidc = args.oidc_issuer.is_some();
let mtls_auth_enabled =
resolve_mtls_auth_enabled(args, matches, file.as_ref(), compute_driver_kind);
if args.disable_tls && has_client_ca {
return Err(miette::miette!(
"--disable-tls and --tls-client-ca are mutually exclusive. Client certificate verification requires that TLS be enabled."
));
}
if mtls_auth_enabled && args.disable_tls {
return Err(miette::miette!(
"mTLS user authentication requires TLS. Remove --disable-tls or disable --enable-mtls-auth."
));
}
if mtls_auth_enabled && !has_client_ca {
return Err(miette::miette!(
"mTLS user authentication requires --tls-client-ca so client certificates can be verified."
));
}
if mtls_auth_enabled && matches!(compute_driver_kind, Some(ComputeDriverKind::Kubernetes)) {
return Err(miette::miette!(
"mTLS user authentication is not supported with the Kubernetes compute driver. Configure OIDC or a trusted fronting proxy for user authentication."
));
}
let tls = if args.disable_tls {
None
} else {
let cert_path = args.tls_cert.clone().ok_or_else(|| {
miette::miette!(
"--tls-cert is required when TLS is enabled (use --disable-tls to skip)"
)
})?;
let key_path = args.tls_key.clone().ok_or_else(|| {
miette::miette!("--tls-key is required when TLS is enabled (use --disable-tls to skip)")
})?;
// External cert config (SNI-based dual cert) is only configurable
// via the TOML file, not CLI flags — it's a deployment-time setting.
let (ext_cert, ext_key, ext_names) = file
.as_ref()
.and_then(|f| f.openshell.gateway.tls.as_ref())
.map(|tls| {
(
tls.external_cert_path.clone(),
tls.external_key_path.clone(),
tls.external_server_names.clone(),
)
})
.unwrap_or_default();
Some(openshell_core::TlsConfig {
cert_path,
key_path,
require_client_auth: has_client_ca && !has_oidc,
client_ca_path: args.tls_client_ca.clone(),
external_cert_path: ext_cert,
external_key_path: ext_key,
external_server_names: ext_names,
})
};
let db_url = args
.db_url
.clone()
.expect("runtime defaults populate db_url");
let mut config = openshell_core::Config::new(tls)
.with_bind_address(bind)
.with_log_level(&args.log_level);
if let Some(auth) = file.as_ref().and_then(|f| f.openshell.gateway.auth.clone()) {
config.auth = auth;
}
config.mtls_auth.enabled = mtls_auth_enabled;
// Listener addresses for the health and metrics endpoints. The file may
// pin a different interface than the main listener (e.g. health on
// 127.0.0.1 while gRPC binds 0.0.0.0); the full `SocketAddr` from the
// file is preserved unless CLI/env supplied an explicit `--health-port` /
// `--metrics-port`, in which case the port overrides the file value
// while the IP defaults to `args.bind_address`.
let file_gateway = file.as_ref().map(|f| &f.openshell.gateway);
let health_bind = resolve_aux_listener(
args.bind_address,
args.health_port,
matches,
"health_port",
|| file_gateway.and_then(|g| g.health_bind_address),
);
let metrics_bind = resolve_aux_listener(
args.bind_address,
args.metrics_port,
matches,
"metrics_port",
|| file_gateway.and_then(|g| g.metrics_bind_address),
);
if let Some(addr) = health_bind {
if args.port == addr.port() {
return Err(miette::miette!(
"--port and --health-port must be different (both set to {})",
args.port
));
}
config = config.with_health_bind_address(addr);
}
if let Some(addr) = metrics_bind {
if args.port == addr.port() {
return Err(miette::miette!(
"--port and --metrics-port must be different (both set to {})",
args.port
));
}
if let Some(health) = health_bind
&& health.port() == addr.port()
{
return Err(miette::miette!(
"--health-port and --metrics-port must be different (both set to {})",
health.port()
));
}
config = config.with_metrics_bind_address(addr);
}
config = config
.with_database_url(db_url)
.with_compute_drivers(args.drivers.clone())
.with_grpc_rate_limit(
args.grpc_rate_limit_requests,
args.grpc_rate_limit_window_seconds,
)
.with_gateway_interceptors(
file.as_ref()
.map(|f| f.openshell.gateway.interceptors.clone())
.unwrap_or_default(),
)
.with_server_sans(args.server_sans.clone())
.with_loopback_service_http(args.enable_loopback_service_http);
if let Some(sources) = file
.as_ref()
.and_then(|file| file.openshell.gateway.provider_profile_sources.clone())
{
config = config.with_provider_profile_sources(sources);
}
if let Some(gateway_file) = file.as_ref().map(|f| &f.openshell.gateway) {
if let Some(drivers) = &gateway_file.credential_drivers {
config = config.with_credential_drivers(drivers.clone());
}
if let Some(default_driver) = &gateway_file.default_credential_driver {
config = config.with_default_credential_driver(Some(default_driver.clone()));
}
}
validate_grpc_rate_limit_args(
args.grpc_rate_limit_requests,
args.grpc_rate_limit_window_seconds,
)?;
if let Some(socket) = args.compute_driver_socket.clone() {
let driver = args
.drivers
.first()
.expect("normalize_compute_driver_socket_args sets a driver for socket endpoints");
config = config.with_compute_driver_endpoint(driver.clone(), socket);
}
if let Some(ttl) = file
.as_ref()
.and_then(|f| f.openshell.gateway.ssh_session_ttl_secs)
{
config = config.with_ssh_session_ttl_secs(ttl);
}
if let Some(mode) = file
.as_ref()
.and_then(|f| f.openshell.gateway.policy_validation_failure_mode)
{
config.policy_validation_failure_mode = mode;
}
if let Some(issuer) = args.oidc_issuer.clone() {
config = config.with_oidc(openshell_core::OidcConfig {
issuer,
audience: args.oidc_audience.clone(),
jwks_ttl_secs: args.oidc_jwks_ttl,
roles_claim: args.oidc_roles_claim.clone(),
admin_role: args.oidc_admin_role.clone(),
user_role: args.oidc_user_role.clone(),
scopes_claim: args.oidc_scopes_claim.clone(),
});
}
// `gateway_jwt` is configured through TOML in cluster deployments. Local
// package-managed starts also auto-detect the JWT bundle written next to
// the generated TLS bundle so upgrades pick up sandbox auth without a
// user-authored config file.
if let Some(jwt) = file
.as_ref()
.and_then(|f| f.openshell.gateway.gateway_jwt.clone())
{
config.gateway_jwt = Some(jwt);
} else if let Some(jwt) = local_jwt {
config.gateway_jwt = Some(jwt);
}
Ok(ServerStartupConfig {
config,
config_file: file,
guest_tls,
compute_driver,
})
}
async fn run_from_args(
mut args: RunArgs,
matches: ArgMatches,
compute_drivers: ComputeDriverRegistry,
) -> Result<()> {
let prepared = prepare_server_config(&mut args, &matches, &compute_drivers)?;
let compute_driver = configured_compute_driver_for_startup(&compute_drivers, &prepared)?;
let tracing_log_bus = TracingLogBus::new();
let otlp_config = prepared
.config_file
.as_ref()
.and_then(|f| f.openshell.gateway.otlp.as_ref());
let (tracing_handle, setup_error) = crate::tracing_setup::install(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new(&prepared.config.log_level)),
&tracing_log_bus,
otlp_config,
crate::tracing_setup::podman_export_enabled(&compute_driver),
);
let has_client_ca = prepared
.config
.tls
.as_ref()
.and_then(|tls| tls.client_ca_path.as_ref())
.is_some();
let has_oidc = prepared.config.oidc.is_some();
if prepared.config.tls.is_none() {
warn!("TLS disabled — listening on plaintext HTTP");
} else {
info!("TLS enabled — listening on encrypted HTTPS");
}
if has_client_ca {
info!("TLS client certificate verification enabled");
}
if prepared.config.mtls_auth.enabled {
info!("mTLS user authentication enabled");
}
if has_oidc {
info!("OIDC authentication enabled");
}
if let Some(err) = &setup_error {
error!(
error = %err,
"OTLP exporting is configured but could not be started; continuing without it"
);
} else if let Some(otlp) = prepared
.config_file
.as_ref()
.and_then(|f| f.openshell.gateway.otlp.as_ref())
{
info!(endpoint = %otlp.endpoint, "OTLP exporting enabled");
}
if prepared.config.auth.allow_unauthenticated_users {
warn!(
"Unauthenticated user access enabled — only use this for trusted local development or a fully trusted fronting proxy"
);
}
if !prepared.config.auth.allow_unauthenticated_users
&& !prepared.config.mtls_auth.enabled
&& !has_oidc
&& prepared.config.gateway_jwt.is_none()
{
warn!(
"Neither mTLS user auth nor OIDC nor sandbox JWT auth is configured — \
the gateway has no authentication mechanism"
);
}
info!(bind = %prepared.config.bind_address, "Starting OpenShell server");
let result = Box::pin(run_server(prepared, compute_driver, tracing_log_bus)).await;
tracing_handle.shutdown();
result.into_diagnostic()
}
fn parse_compute_driver(value: &str) -> std::result::Result<String, String> {
openshell_core::config::normalize_compute_driver_name(value)
}
fn resolve_config_path(args: &RunArgs) -> Result<Option<PathBuf>> {
if let Some(path) = args.config.clone() {
return Ok(Some(path));
}
let default_path = defaults::default_gateway_config_path()?;
Ok(default_path.is_file().then_some(default_path))
}
fn apply_runtime_defaults(args: &mut RunArgs) -> Result<Option<LocalTlsPaths>> {
let local_tls = if args.disable_tls {
None
} else {
defaults::complete_local_tls_paths()?
};
if args.db_url.is_none() {
args.db_url = Some(defaults::default_database_url()?);
}
if !args.disable_tls
&& args.tls_cert.is_none()
&& args.tls_key.is_none()
&& args.tls_client_ca.is_none()
&& let Some(paths) = &local_tls
{
args.tls_cert = Some(paths.server_cert.clone());
args.tls_key = Some(paths.server_key.clone());
args.tls_client_ca = Some(paths.ca.clone());
}
Ok(local_tls)
}
/// Returns `true` when an argument's value came from clap's built-in default
/// (or was never supplied at all). When the predicate is `true`, the loader
/// is free to replace the value with one read from the TOML config file.
fn arg_defaulted(matches: &ArgMatches, id: &str) -> bool {
matches!(
matches.value_source(id),
None | Some(ValueSource::DefaultValue)
)
}
/// Resolve the bind address for an auxiliary listener (health / metrics).
///
/// The precedence is:
/// 1. CLI flag or `OPENSHELL_*` env var explicitly set on the corresponding
/// port argument → `bind_address:port` (port from CLI, IP from the main
/// listener interface).
/// 2. Full `SocketAddr` from `[openshell.gateway].{health,metrics}_bind_address`
/// → used as-is (this is how operators pin a loopback-only health port
/// on a gateway whose gRPC listener is bound publicly).
/// 3. Otherwise the listener is disabled (returns `None`).
fn resolve_aux_listener(
bind_ip: IpAddr,
port_arg: u16,
matches: &ArgMatches,
port_id: &str,
file_addr: impl FnOnce() -> Option<SocketAddr>,
) -> Option<SocketAddr> {
if !arg_defaulted(matches, port_id) {
if port_arg == 0 {
return None;
}
return Some(SocketAddr::new(bind_ip, port_arg));
}
if let Some(addr) = file_addr() {
return Some(addr);
}
if port_arg == 0 {
None
} else {
Some(SocketAddr::new(bind_ip, port_arg))
}
}
/// Apply gateway-wide values from `[openshell.gateway]` onto `RunArgs` for
/// every argument that is still sourced from clap's built-in default.
///
/// The function intentionally does not touch `database_url` — that secret is
/// env-only and the loader already rejected it when it appears in the file.
fn merge_file_into_args(args: &mut RunArgs, file: &GatewayFileSection, matches: &ArgMatches) {
if let Some(addr) = file.bind_address {
if arg_defaulted(matches, "bind_address") {
args.bind_address = addr.ip();
}
if arg_defaulted(matches, "port") {
args.port = addr.port();
}
}
// Note: file's full health_bind_address / metrics_bind_address are
// consumed in `run_from_args`'s listener-resolution block so the IP
// half of the SocketAddr is preserved. Copying only the port here
// would silently relocate a loopback-intended listener onto the
// public bind address.
if let Some(level) = &file.log_level
&& arg_defaulted(matches, "log_level")
{
args.log_level.clone_from(level);
}
if let Some(drivers) = &file.compute_drivers
&& arg_defaulted(matches, "drivers")
{
args.drivers.clone_from(drivers);
}
if let Some(sans) = &file.server_sans
&& args.server_sans.is_empty()
&& arg_defaulted(matches, "server_sans")
{
args.server_sans.clone_from(sans);
}
if let Some(enabled) = file.enable_loopback_service_http
&& arg_defaulted(matches, "enable_loopback_service_http")
{
args.enable_loopback_service_http = enabled;
}
if let Some(mtls_auth) = &file.mtls_auth
&& arg_defaulted(matches, "enable_mtls_auth")
{
args.enable_mtls_auth = mtls_auth.enabled;
}
if let Some(disabled) = file.disable_tls
&& arg_defaulted(matches, "disable_tls")
{
args.disable_tls = disabled;
}
// TLS gateway listener fields
if let Some(tls) = &file.tls {
if args.tls_cert.is_none() && arg_defaulted(matches, "tls_cert") {
args.tls_cert = Some(tls.cert_path.clone());
}
if args.tls_key.is_none() && arg_defaulted(matches, "tls_key") {
args.tls_key = Some(tls.key_path.clone());
}
if args.tls_client_ca.is_none() && arg_defaulted(matches, "tls_client_ca") {
args.tls_client_ca.clone_from(&tls.client_ca_path);
}
}
// OIDC fields
if let Some(oidc) = &file.oidc {
if args.oidc_issuer.is_none() && arg_defaulted(matches, "oidc_issuer") {
args.oidc_issuer = Some(oidc.issuer.clone());
}
if arg_defaulted(matches, "oidc_audience") {
args.oidc_audience.clone_from(&oidc.audience);
}
if arg_defaulted(matches, "oidc_jwks_ttl") {
args.oidc_jwks_ttl = oidc.jwks_ttl_secs;
}
if arg_defaulted(matches, "oidc_roles_claim") {
args.oidc_roles_claim.clone_from(&oidc.roles_claim);
}
if arg_defaulted(matches, "oidc_admin_role") {
args.oidc_admin_role.clone_from(&oidc.admin_role);
}
if arg_defaulted(matches, "oidc_user_role") {
args.oidc_user_role.clone_from(&oidc.user_role);
}
if arg_defaulted(matches, "oidc_scopes_claim") {
args.oidc_scopes_claim.clone_from(&oidc.scopes_claim);
}
}
if let Some(requests) = file.grpc_rate_limit_requests
&& args.grpc_rate_limit_requests.is_none()
&& arg_defaulted(matches, "grpc_rate_limit_requests")
{
args.grpc_rate_limit_requests = Some(requests);
}
if let Some(window) = file.grpc_rate_limit_window_seconds
&& args.grpc_rate_limit_window_seconds.is_none()
&& arg_defaulted(matches, "grpc_rate_limit_window_seconds")
{
args.grpc_rate_limit_window_seconds = Some(window);
}
}
fn validate_grpc_rate_limit_args(requests: Option<u64>, window_seconds: Option<u64>) -> Result<()> {
let disabled = matches!(requests, Some(0)) || matches!(window_seconds, Some(0));
if disabled {
return Ok(());
}
if matches!(
(requests, window_seconds),
(Some(requests), None) if requests > 0
) || matches!(
(requests, window_seconds),
(None, Some(window_seconds)) if window_seconds > 0
) {
return Err(miette::miette!(
"gRPC rate limiting requires both --grpc-rate-limit-requests and --grpc-rate-limit-window-seconds (TOML keys grpc_rate_limit_requests and grpc_rate_limit_window_seconds) to be positive; set either value to 0 to disable"
));
}
Ok(())
}
fn normalize_compute_driver_socket_args(args: &mut RunArgs, matches: &ArgMatches) -> Result<()> {
let Some(socket) = args.compute_driver_socket.as_ref() else {
return Ok(());
};
if socket.as_os_str().is_empty() {
return Err(miette::miette!(
"--compute-driver-socket must not be an empty path"
));
}
if arg_defaulted(matches, "drivers") {
return Err(miette::miette!(
"--compute-driver-socket requires --drivers <name> or OPENSHELL_DRIVERS=<name> to select a compute driver name"
));
}
match args.drivers.as_slice() {
[driver] => {
let driver = openshell_core::config::normalize_compute_driver_name(driver)
.map_err(|err| miette::miette!("{err}"))?;
args.drivers[0] = driver;
Ok(())
}
drivers => Err(miette::miette!(
"--compute-driver-socket requires exactly one compute driver name, got: {}",
drivers.join(",")
)),
}
}
fn is_singleplayer_driver(driver: Option<ComputeDriverKind>) -> bool {
matches!(
driver,
Some(ComputeDriverKind::Docker | ComputeDriverKind::Podman | ComputeDriverKind::Vm)
)
}
fn resolve_mtls_auth_enabled(
args: &RunArgs,
matches: &ArgMatches,
file: Option<&ConfigFile>,
compute_driver: Option<ComputeDriverKind>,
) -> bool {
let file_configured = file
.and_then(|f| f.openshell.gateway.mtls_auth.as_ref())
.is_some();
if file_configured || !arg_defaulted(matches, "enable_mtls_auth") {
return args.enable_mtls_auth;
}
if args.disable_tls || args.tls_client_ca.is_none() || args.oidc_issuer.is_some() {
return false;
}
is_singleplayer_driver(compute_driver)
}
#[cfg(test)]
mod tests {
use super::{Cli, command};
use crate::TEST_ENV_LOCK as ENV_LOCK;
use clap::Parser;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::atomic::{AtomicUsize, Ordering};
static REGISTRY_DETECTION_CALLS: AtomicUsize = AtomicUsize::new(0);
fn detect_registered_docker() -> bool {
REGISTRY_DETECTION_CALLS.fetch_add(1, Ordering::SeqCst);
true
}
#[derive(Clone, Copy)]
struct TestComputeDriverFactory;
#[async_trait::async_trait]
impl crate::ComputeDriverFactory for TestComputeDriverFactory {
async fn build(
&self,
_context: crate::ComputeDriverBuildContext<'_>,
) -> openshell_core::Result<crate::ComputeDriverBuildOutput> {
unreachable!("configuration tests do not construct the driver")
}
}
fn detected_docker_registry() -> crate::ComputeDriverRegistry {
let mut registry = crate::ComputeDriverRegistry::new();
registry
.install(
crate::ComputeDriverRegistration::new(
"docker",
100,
Some(detect_registered_docker),
TestComputeDriverFactory,
)
.unwrap(),
)
.unwrap();
registry
}
struct EnvVarGuard {
key: &'static str,
original: Option<String>,
}
impl EnvVarGuard {
#[allow(unsafe_code)]
fn set(key: &'static str, value: &str) -> Self {
let original = std::env::var(key).ok();
// SAFETY: tests serialize environment mutation with ENV_LOCK.
unsafe { std::env::set_var(key, value) };
Self { key, original }
}
#[allow(unsafe_code)]
fn remove(key: &'static str) -> Self {
let original = std::env::var(key).ok();
// SAFETY: tests serialize environment mutation with ENV_LOCK.
unsafe { std::env::remove_var(key) };
Self { key, original }
}
}
impl Drop for EnvVarGuard {
#[allow(unsafe_code)]
fn drop(&mut self) {
match self.original.as_deref() {
// SAFETY: tests serialize environment mutation with ENV_LOCK.
Some(value) => unsafe { std::env::set_var(self.key, value) },
// SAFETY: tests serialize environment mutation with ENV_LOCK.
None => unsafe { std::env::remove_var(self.key) },
}
}
}
#[test]
fn command_uses_gateway_binary_name() {
let mut help = Vec::new();
command().write_long_help(&mut help).unwrap();
let help = String::from_utf8(help).unwrap();
assert!(help.contains("openshell-gateway"));
}
#[test]
fn command_exposes_version() {
let cmd = command();
let version = cmd.get_version().unwrap();
assert_eq!(version.to_string(), openshell_core::VERSION);
}
#[test]
fn command_defaults_bind_address_to_loopback() {
let _lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _guard = EnvVarGuard::remove("OPENSHELL_BIND_ADDRESS");
let cli =
Cli::try_parse_from(["openshell-gateway", "--db-url", "sqlite::memory:"]).unwrap();
assert_eq!(cli.run.bind_address, IpAddr::V4(Ipv4Addr::LOCALHOST));
}
#[test]
fn command_parses_bind_address() {
let _lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _guard = EnvVarGuard::remove("OPENSHELL_BIND_ADDRESS");
let cli = Cli::try_parse_from([
"openshell-gateway",
"--db-url",
"sqlite::memory:",
"--bind-address",
"127.0.0.1",
])
.unwrap();
assert_eq!(cli.run.bind_address, IpAddr::V4(Ipv4Addr::LOCALHOST));
}
#[test]
fn command_reads_bind_address_from_env() {
let _lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _guard = EnvVarGuard::set("OPENSHELL_BIND_ADDRESS", "0.0.0.0");
let cli = Cli::try_parse_from(["openshell-gateway", "--db-url", "sqlite::memory:"])
.expect("env should provide bind address");
assert_eq!(cli.run.bind_address, IpAddr::V4(Ipv4Addr::UNSPECIFIED));
}
#[test]
fn command_enables_loopback_service_http_by_default() {
let _lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _guard = EnvVarGuard::remove("OPENSHELL_ENABLE_LOOPBACK_SERVICE_HTTP");
let cli =
Cli::try_parse_from(["openshell-gateway", "--db-url", "sqlite::memory:"]).unwrap();
assert!(cli.run.enable_loopback_service_http);
}
#[test]
fn command_disables_loopback_service_http_with_false_value() {
let _lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _guard = EnvVarGuard::remove("OPENSHELL_ENABLE_LOOPBACK_SERVICE_HTTP");
let cli = Cli::try_parse_from([
"openshell-gateway",
"--db-url",
"sqlite::memory:",
"--enable-loopback-service-http=false",
])
.unwrap();
assert!(!cli.run.enable_loopback_service_http);
}
#[test]
fn command_reads_loopback_service_http_from_env() {
let _lock = ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let _guard = EnvVarGuard::set("OPENSHELL_ENABLE_LOOPBACK_SERVICE_HTTP", "false");
let cli =
Cli::try_parse_from(["openshell-gateway", "--db-url", "sqlite::memory:"]).unwrap();
assert!(!cli.run.enable_loopback_service_http);
}