Skip to content

Commit 29eb027

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.
1 parent fbae4f8 commit 29eb027

37 files changed

Lines changed: 1485 additions & 67 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
@@ -739,6 +739,11 @@ fn import_local_package_mtls_bundle(name: &str) -> Result<Option<PathBuf>> {
739739
client_key_pem: std::fs::read_to_string(&key)
740740
.into_diagnostic()
741741
.wrap_err_with(|| format!("failed to read {}", key.display()))?,
742+
// CLI never holds the gateway's JWT signing material — only the
743+
// gateway needs it. Fill the JWT fields with placeholders.
744+
jwt_signing_key_pem: String::new(),
745+
jwt_public_key_pem: String::new(),
746+
jwt_key_id: String::new(),
742747
};
743748
openshell_bootstrap::mtls::store_pki_bundle(name, &bundle)
744749
.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
@@ -490,6 +490,13 @@ impl OpenShell for TestOpenShell {
490490
Err(Status::unimplemented("not implemented in test"))
491491
}
492492

493+
async fn issue_sandbox_token(
494+
&self,
495+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
496+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
497+
Err(Status::unimplemented("not implemented in test"))
498+
}
499+
493500
async fn connect_supervisor(
494501
&self,
495502
_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
@@ -397,6 +397,13 @@ impl OpenShell for TestOpenShell {
397397
Err(Status::unimplemented("not implemented in test"))
398398
}
399399

400+
async fn issue_sandbox_token(
401+
&self,
402+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
403+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
404+
Err(Status::unimplemented("not implemented in test"))
405+
}
406+
400407
async fn connect_supervisor(
401408
&self,
402409
_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
@@ -637,6 +637,13 @@ impl OpenShell for TestOpenShell {
637637
Err(Status::unimplemented("not implemented in test"))
638638
}
639639

640+
async fn issue_sandbox_token(
641+
&self,
642+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
643+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
644+
Err(Status::unimplemented("not implemented in test"))
645+
}
646+
640647
async fn connect_supervisor(
641648
&self,
642649
_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
@@ -577,6 +577,13 @@ impl OpenShell for TestOpenShell {
577577
Err(Status::unimplemented("not implemented in test"))
578578
}
579579

580+
async fn issue_sandbox_token(
581+
&self,
582+
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,
583+
) -> Result<Response<openshell_core::proto::IssueSandboxTokenResponse>, Status> {
584+
Err(Status::unimplemented("not implemented in test"))
585+
}
586+
580587
async fn connect_supervisor(
581588
&self,
582589
_request: tonic::Request<tonic::Streaming<SupervisorMessage>>,

0 commit comments

Comments
 (0)