Skip to content

Commit 5465846

Browse files
committed
feat(server): gateway-minted sandbox JWTs and IssueSandboxToken RPC
Adds the gateway-side infrastructure for per-sandbox identity tokens (the PR-2 step of the series resolving #1354): - New Ed25519 keypair generated by `certgen` alongside the existing PKI. Local mode writes `<dir>/jwt/{signing.pem,public.pem,kid}`; K8s mode creates an Opaque `<release>-jwt-keys` Secret. - `SandboxJwtIssuer` mints tokens with EdDSA-signed claims (SPIFFE-shaped `sub`, denormalised `sandbox_id`, 24h default TTL, `jti` for revocation). - `SandboxJwtAuthenticator` validates tokens through the Authenticator chain and yields `Principal::Sandbox(BootstrapJwt {..})`. Tokens with a different `kid` fall through so non-matching Bearer headers reach the OIDC authenticator unchanged. - `K8sServiceAccountAuthenticator` is path-scoped to `IssueSandboxToken`; consumes a projected SA token and produces a `K8sServiceAccount` sandbox principal that the new `IssueSandboxToken` handler exchanges for a fresh gateway JWT. - In-memory `RevocationSet` with TTL pruning, ready for the PR-3 delete-side hook and PR-5 refresh. - Helm chart mounts the JWT secret on the gateway pod and wires `[openshell.gateway.gateway_jwt]` into the rendered TOML. PR 2 is additive: no driver yet writes a sandbox token, no supervisor yet presents a Bearer JWT. PR 3 wires the consumer ends and removes the legacy path-based sandbox marker. Signed-off-by: Taylor Mutch <[email protected]>
1 parent e79766b commit 5465846

33 files changed

Lines changed: 1462 additions & 71 deletions

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/openshell-bootstrap/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ bytes = { workspace = true }
1616
futures = { workspace = true }
1717
miette = { workspace = true }
1818
rcgen = { workspace = true }
19+
sha2 = { workspace = true }
1920
serde = { workspace = true }
2021
serde_json = { workspace = true }
2122
tar = "0.4"
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! Gateway-minted JWT signing-key generation.
5+
//!
6+
//! The gateway mints per-sandbox identity tokens (see PR 2 of the
7+
//! per-sandbox identity series, issue #1354) signed with an Ed25519
8+
//! keypair generated once at gateway init and persisted alongside the
9+
//! existing PKI bundle. The signing key never leaves the gateway; the
10+
//! public key plus a stable `kid` are consumed by the gateway's own
11+
//! validator and any future external verifiers.
12+
13+
use miette::{IntoDiagnostic, Result, WrapErr};
14+
use rcgen::{KeyPair, PKCS_ED25519};
15+
use sha2::{Digest, Sha256};
16+
17+
/// All PEM-encoded material needed to mint and validate sandbox JWTs.
18+
///
19+
/// The signing key stays in the gateway process. The public key is shared
20+
/// across gateway replicas (so any replica can validate a JWT minted by
21+
/// any other replica). The `kid` is published in every minted JWT's
22+
/// header so the validator can pick the right key after a future rotation.
23+
pub struct JwtKeyMaterial {
24+
/// PKCS#8 PEM-encoded Ed25519 private key.
25+
pub signing_key_pem: String,
26+
/// `SubjectPublicKeyInfo` PEM-encoded Ed25519 public key.
27+
pub public_key_pem: String,
28+
/// Stable identifier derived from the public key (SHA-256 hex prefix).
29+
/// Embedded in every minted JWT's `kid` header so future rotation can
30+
/// be performed in-place by adding a second key without breaking
31+
/// in-flight tokens.
32+
pub kid: String,
33+
}
34+
35+
/// Generate a fresh Ed25519 JWT signing key.
36+
///
37+
/// Output PEM is in the formats `jsonwebtoken` consumes via
38+
/// `EncodingKey::from_ed_pem` (signing) and `DecodingKey::from_ed_pem`
39+
/// (validation), so the gateway can round-trip its own tokens with no
40+
/// further conversion.
41+
pub fn generate_jwt_key() -> Result<JwtKeyMaterial> {
42+
let keypair = KeyPair::generate_for(&PKCS_ED25519)
43+
.into_diagnostic()
44+
.wrap_err("failed to generate Ed25519 JWT signing key")?;
45+
let signing_key_pem = keypair.serialize_pem();
46+
let public_key_pem = keypair.public_key_pem();
47+
let kid = kid_from_public_key_der(&keypair.public_key_der());
48+
Ok(JwtKeyMaterial {
49+
signing_key_pem,
50+
public_key_pem,
51+
kid,
52+
})
53+
}
54+
55+
/// Stable `kid` derived from the SHA-256 of the public-key DER.
56+
///
57+
/// First 16 bytes hex-encoded — collision-resistant for the small N of
58+
/// signing keys a single deployment ever has, while staying short enough
59+
/// to keep JWT headers compact.
60+
fn kid_from_public_key_der(public_key_der: &[u8]) -> String {
61+
let digest = Sha256::digest(public_key_der);
62+
hex_encode_prefix(&digest, 16)
63+
}
64+
65+
fn hex_encode_prefix(bytes: &[u8], n: usize) -> String {
66+
use std::fmt::Write as _;
67+
let mut out = String::with_capacity(n * 2);
68+
for byte in bytes.iter().take(n) {
69+
let _ = write!(out, "{byte:02x}");
70+
}
71+
out
72+
}
73+
74+
#[cfg(test)]
75+
mod tests {
76+
use super::*;
77+
78+
#[test]
79+
fn generate_jwt_key_produces_parseable_pem() {
80+
let material = generate_jwt_key().expect("generate_jwt_key");
81+
assert!(material.signing_key_pem.contains("BEGIN PRIVATE KEY"));
82+
assert!(material.public_key_pem.contains("BEGIN PUBLIC KEY"));
83+
assert_eq!(material.kid.len(), 32, "kid is 16 bytes hex-encoded");
84+
assert!(material.kid.chars().all(|c| c.is_ascii_hexdigit()));
85+
}
86+
87+
#[test]
88+
fn kid_is_stable_for_identical_public_keys() {
89+
// Same input -> same kid. Hash of a fixed byte string.
90+
let kid_a = kid_from_public_key_der(b"abc");
91+
let kid_b = kid_from_public_key_der(b"abc");
92+
assert_eq!(kid_a, kid_b);
93+
}
94+
95+
#[test]
96+
fn kid_differs_for_different_public_keys() {
97+
let kid_a = kid_from_public_key_der(b"first");
98+
let kid_b = kid_from_public_key_der(b"second");
99+
assert_ne!(kid_a, kid_b);
100+
}
101+
102+
#[test]
103+
fn generated_keys_are_unique() {
104+
let a = generate_jwt_key().expect("generate_jwt_key");
105+
let b = generate_jwt_key().expect("generate_jwt_key");
106+
assert_ne!(
107+
a.kid, b.kid,
108+
"fresh keypairs must produce distinct public keys"
109+
);
110+
assert_ne!(a.signing_key_pem, b.signing_key_pem);
111+
}
112+
}

‎crates/openshell-bootstrap/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
pub mod build;
55
pub mod edge_token;
6+
pub mod jwt;
67
pub mod oidc_token;
78

89
mod metadata;

‎crates/openshell-bootstrap/src/pki.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
22
// SPDX-License-Identifier: Apache-2.0
33

4+
use crate::jwt::{JwtKeyMaterial, generate_jwt_key};
45
use miette::{IntoDiagnostic, Result, WrapErr};
56
use rcgen::{BasicConstraints, CertificateParams, DnType, Ia5String, IsCa, KeyPair, SanType};
67
use std::net::IpAddr;
@@ -15,6 +16,12 @@ pub struct PkiBundle {
1516
pub server_key_pem: String,
1617
pub client_cert_pem: String,
1718
pub client_key_pem: String,
19+
/// PKCS#8 PEM Ed25519 private key for minting per-sandbox JWTs.
20+
pub jwt_signing_key_pem: String,
21+
/// SPKI PEM Ed25519 public key, paired with `jwt_signing_key_pem`.
22+
pub jwt_public_key_pem: String,
23+
/// Stable identifier embedded in the `kid` header of every minted JWT.
24+
pub jwt_key_id: String,
1825
}
1926

2027
/// Default SANs always included on the server certificate. Covers the host
@@ -99,13 +106,23 @@ pub fn generate_pki(extra_sans: &[String]) -> Result<PkiBundle> {
99106
.into_diagnostic()
100107
.wrap_err("failed to sign client certificate")?;
101108

109+
// --- JWT signing key (Ed25519, used to mint per-sandbox identity tokens) ---
110+
let JwtKeyMaterial {
111+
signing_key_pem: jwt_signing_key_pem,
112+
public_key_pem: jwt_public_key_pem,
113+
kid: jwt_key_id,
114+
} = generate_jwt_key().wrap_err("failed to generate JWT signing key")?;
115+
102116
Ok(PkiBundle {
103117
ca_cert_pem: ca_cert.pem(),
104118
ca_key_pem: ca_key.serialize_pem(),
105119
server_cert_pem: server_cert.pem(),
106120
server_key_pem: server_key.serialize_pem(),
107121
client_cert_pem: client_cert.pem(),
108122
client_key_pem: client_key.serialize_pem(),
123+
jwt_signing_key_pem,
124+
jwt_public_key_pem,
125+
jwt_key_id,
109126
})
110127
}
111128

@@ -148,6 +165,9 @@ mod tests {
148165
assert!(bundle.server_key_pem.contains("BEGIN PRIVATE KEY"));
149166
assert!(bundle.client_cert_pem.contains("BEGIN CERTIFICATE"));
150167
assert!(bundle.client_key_pem.contains("BEGIN PRIVATE KEY"));
168+
assert!(bundle.jwt_signing_key_pem.contains("BEGIN PRIVATE KEY"));
169+
assert!(bundle.jwt_public_key_pem.contains("BEGIN PUBLIC KEY"));
170+
assert_eq!(bundle.jwt_key_id.len(), 32, "kid is 16 bytes hex-encoded");
151171
}
152172

153173
#[test]

‎crates/openshell-cli/src/run.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -743,6 +743,11 @@ fn import_local_package_mtls_bundle(name: &str) -> Result<Option<PathBuf>> {
743743
client_key_pem: std::fs::read_to_string(&key)
744744
.into_diagnostic()
745745
.wrap_err_with(|| format!("failed to read {}", key.display()))?,
746+
// CLI never holds the gateway's JWT signing material — only the
747+
// gateway needs it. Fill the JWT fields with placeholders.
748+
jwt_signing_key_pem: String::new(),
749+
jwt_public_key_pem: String::new(),
750+
jwt_key_id: String::new(),
746751
};
747752
openshell_bootstrap::mtls::store_pki_bundle(name, &bundle)
748753
.wrap_err_with(|| format!("failed to store mTLS bundle for gateway '{name}'"))?;

‎crates/openshell-cli/tests/ensure_providers_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,13 @@ impl OpenShell for TestOpenShell {
535535
Err(Status::unimplemented("not implemented in test"))
536536
}
537537

538+
async fn issue_sandbox_token(
539+
&self,
540+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
541+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
542+
Err(Status::unimplemented("not implemented in test"))
543+
}
544+
538545
async fn connect_supervisor(
539546
&self,
540547
_request: tonic::Request<tonic::Streaming<SupervisorMessage>>,

‎crates/openshell-cli/tests/mtls_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,13 @@ impl OpenShell for TestOpenShell {
424424
Err(Status::unimplemented("not implemented in test"))
425425
}
426426

427+
async fn issue_sandbox_token(
428+
&self,
429+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
430+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
431+
Err(Status::unimplemented("not implemented in test"))
432+
}
433+
427434
async fn connect_supervisor(
428435
&self,
429436
_request: tonic::Request<tonic::Streaming<openshell_core::proto::SupervisorMessage>>,

‎crates/openshell-cli/tests/provider_commands_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,13 @@ impl OpenShell for TestOpenShell {
800800
Err(Status::unimplemented("not implemented in test"))
801801
}
802802

803+
async fn issue_sandbox_token(
804+
&self,
805+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
806+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
807+
Err(Status::unimplemented("not implemented in test"))
808+
}
809+
803810
async fn connect_supervisor(
804811
&self,
805812
_request: tonic::Request<tonic::Streaming<SupervisorMessage>>,

‎crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,13 @@ impl OpenShell for TestOpenShell {
604604
Err(Status::unimplemented("not implemented in test"))
605605
}
606606

607+
async fn issue_sandbox_token(
608+
&self,
609+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
610+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
611+
Err(Status::unimplemented("not implemented in test"))
612+
}
613+
607614
async fn connect_supervisor(
608615
&self,
609616
_request: tonic::Request<tonic::Streaming<SupervisorMessage>>,

0 commit comments

Comments
 (0)