mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
## Why A guest alias needs to expose only the claims selected by policy. Refresh also needs a way to detect changes to claims the guest never sees. ## What changed Add a test-only helper that reads expiry from a trusted source JWT and builds fresh JWT-shaped aliases containing only selected scalar claims. Each alias uses a random placeholder in the signature segment. Hash all stable claims, including undisclosed ones, in deterministic JSON order. Exclude `exp`, `nbf`, `iat`, and `jti` so changes to those fields during refresh preserve the digest. ## Testing Cover selective disclosure, alias freshness, and refresh comparisons. Exercise rejection of malformed tokens, duplicate keys, invalid validity fields, ambiguous numbers, and disallowed disclosures. GitOrigin-RevId: 48bc19ac57601e28d5c2cb8881f0ac0f5563aca9
236 lines
7.9 KiB
Rust
236 lines
7.9 KiB
Rust
//! Projects a trusted source's JWT into a stable set of guest-visible claims.
|
|
//! Issuer authentication and destination selection belong to the source and broker.
|
|
|
|
use base64::Engine as _;
|
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
|
use jsonwebtoken::Algorithm;
|
|
use jsonwebtoken::Header;
|
|
use serde::Deserialize;
|
|
use serde::Deserializer;
|
|
use serde::de::MapAccess;
|
|
use serde::de::SeqAccess;
|
|
use serde::de::Visitor;
|
|
use serde_json::Value;
|
|
use serde_json::value::RawValue;
|
|
use sha2::Digest as _;
|
|
use sha2::Sha256;
|
|
use std::collections::BTreeMap;
|
|
use std::fmt;
|
|
|
|
pub(crate) const MAX_SOURCE_JWT_BYTES: usize = 16 * 1024;
|
|
const MAX_DISCLOSED_CLAIMS: usize = 8;
|
|
const MAX_CLAIM_NAME_BYTES: usize = 128;
|
|
const MAX_CLAIM_TEXT_BYTES: usize = 256;
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(transparent)]
|
|
struct SourceMembers(
|
|
#[serde(with = "serde_with::rust::maps_duplicate_key_is_error")]
|
|
BTreeMap<String, Box<RawValue>>,
|
|
);
|
|
|
|
impl SourceMembers {
|
|
fn decode(segment: &str) -> Option<BTreeMap<String, Box<RawValue>>> {
|
|
let bytes = URL_SAFE_NO_PAD.decode(segment).ok()?;
|
|
let Self(members) = serde_json::from_slice(&bytes).ok()?;
|
|
if members
|
|
.keys()
|
|
.any(|name| name.starts_with("$serde_json::private::"))
|
|
{
|
|
return None;
|
|
}
|
|
Some(members)
|
|
}
|
|
}
|
|
|
|
// Parse each stable claim before hashing or disclosure. A plain Value would lose duplicate
|
|
// keys and could round numbers before we can reject them.
|
|
struct Claim(Value);
|
|
|
|
impl<'de> Deserialize<'de> for Claim {
|
|
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
deserializer.deserialize_any(ClaimVisitor)
|
|
}
|
|
}
|
|
|
|
struct ClaimVisitor;
|
|
|
|
impl<'de> Visitor<'de> for ClaimVisitor {
|
|
type Value = Claim;
|
|
|
|
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str("a JSON claim with unique keys and integer-only numbers")
|
|
}
|
|
|
|
fn visit_unit<E>(self) -> Result<Claim, E> {
|
|
Ok(Claim(Value::Null))
|
|
}
|
|
|
|
fn visit_bool<E>(self, value: bool) -> Result<Claim, E> {
|
|
Ok(Claim(value.into()))
|
|
}
|
|
|
|
fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Claim, E> {
|
|
// serde_json sends 0 to visit_u64. With arbitrary_precision, -0 arrives here
|
|
// instead of visit_f64, which already rejects it.
|
|
if value == 0 {
|
|
return Err(E::custom("negative zero in JWT claim"));
|
|
}
|
|
Ok(Claim(value.into()))
|
|
}
|
|
|
|
fn visit_u64<E>(self, value: u64) -> Result<Claim, E> {
|
|
Ok(Claim(value.into()))
|
|
}
|
|
|
|
fn visit_str<E>(self, value: &str) -> Result<Claim, E> {
|
|
Ok(Claim(value.into()))
|
|
}
|
|
|
|
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Claim, A::Error> {
|
|
let mut values = Vec::new();
|
|
while let Some(Claim(value)) = seq.next_element()? {
|
|
values.push(value);
|
|
}
|
|
Ok(Claim(Value::Array(values)))
|
|
}
|
|
|
|
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Claim, A::Error> {
|
|
let mut object = serde_json::Map::new();
|
|
while let Some(key) = map.next_key::<String>()? {
|
|
if key.starts_with("$serde_json::private::") || object.contains_key(&key) {
|
|
return Err(serde::de::Error::custom(
|
|
"invalid or duplicate JWT claim key",
|
|
));
|
|
}
|
|
let Claim(value) = map.next_value()?;
|
|
object.insert(key, value);
|
|
}
|
|
// Some workspace builds enable serde_json's preserve_order feature.
|
|
object.sort_keys();
|
|
Ok(Claim(Value::Object(object)))
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Eq)]
|
|
pub(crate) struct JwtProjection {
|
|
encoded_payload: String,
|
|
authority_digest: [u8; 32],
|
|
}
|
|
|
|
impl fmt::Debug for JwtProjection {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("JwtProjection").finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
impl JwtProjection {
|
|
/// Creates a fresh broker alias. An ES256 signature must be 64 bytes (RFC 7518 §3.4).
|
|
pub(crate) fn new_alias(&self) -> serde_json::Result<String> {
|
|
let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&Header::new(Algorithm::ES256))?);
|
|
let sentinel = URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>());
|
|
Ok(format!("{header}.{}.{sentinel}", self.encoded_payload))
|
|
}
|
|
}
|
|
|
|
/// Reads validity dates and the exact scalar claims selected by trusted policy. The caller
|
|
/// must authenticate the token source. The returned expiry may be in the past so an initial
|
|
/// expired grant can establish identity for refresh. Redemption must enforce the expiry.
|
|
pub(crate) fn parse_source_jwt(
|
|
token: &str,
|
|
disclose: &[String],
|
|
now_unix_seconds: i64,
|
|
) -> Option<(i64, JwtProjection)> {
|
|
if token.len() > MAX_SOURCE_JWT_BYTES || disclose.len() > MAX_DISCLOSED_CLAIMS {
|
|
return None;
|
|
}
|
|
// The host authenticates the source. Read the raw JOSE members here because the
|
|
// library's typed header drops extensions and excludes provider-defined algorithms.
|
|
let (header, rest) = token.split_once('.')?;
|
|
let (payload, signature) = rest.split_once('.')?;
|
|
if signature.is_empty() || URL_SAFE_NO_PAD.decode(signature).is_err() {
|
|
return None;
|
|
}
|
|
let header = SourceMembers::decode(header)?;
|
|
let alg: String = serde_json::from_str(header.get("alg")?.get()).ok()?;
|
|
if alg.is_empty()
|
|
|| alg.eq_ignore_ascii_case("none")
|
|
|| !alg.bytes().all(|b| b.is_ascii_graphic())
|
|
|| header.contains_key("crit")
|
|
|| header.get("b64").is_some_and(|value| value.get() != "true")
|
|
{
|
|
return None;
|
|
}
|
|
|
|
let mut claims = SourceMembers::decode(payload)?;
|
|
let expires_at = numeric_date(claims.get("exp")?)?;
|
|
if let Some(nbf) = claims.get("nbf") {
|
|
let not_before = numeric_date(nbf)?;
|
|
if not_before > now_unix_seconds || not_before >= expires_at {
|
|
return None;
|
|
}
|
|
}
|
|
if let Some(iat) = claims.get("iat") {
|
|
numeric_date(iat)?;
|
|
}
|
|
if let Some(jti) = claims.get("jti") {
|
|
serde_json::from_str::<String>(jti.get()).ok()?;
|
|
}
|
|
for volatile in ["exp", "nbf", "iat", "jti"] {
|
|
claims.remove(volatile);
|
|
}
|
|
|
|
let stable = claims
|
|
.iter()
|
|
.map(|(name, raw)| {
|
|
let Claim(value) = serde_json::from_str(raw.get()).ok()?;
|
|
Some((name, value))
|
|
})
|
|
.collect::<Option<BTreeMap<_, _>>>()?;
|
|
let mut disclosed = BTreeMap::new();
|
|
for name in disclose {
|
|
if name.is_empty()
|
|
|| name.len() > MAX_CLAIM_NAME_BYTES
|
|
|| !name.bytes().all(|b| b.is_ascii_graphic())
|
|
|| matches!(
|
|
name.as_str(),
|
|
"access_token" | "refresh_token" | "id_token" | "client_secret"
|
|
)
|
|
{
|
|
return None;
|
|
}
|
|
let value = stable.get(name)?;
|
|
match value {
|
|
Value::String(text)
|
|
if text.len() <= MAX_CLAIM_TEXT_BYTES
|
|
&& serde_json::to_vec(text).ok()?.len() <= MAX_CLAIM_TEXT_BYTES + 2
|
|
&& text.bytes().all(|b| b == b' ' || b.is_ascii_graphic()) => {}
|
|
Value::Bool(_) | Value::Number(_) => {}
|
|
Value::Null | Value::Array(_) | Value::Object(_) | Value::String(_) => return None,
|
|
}
|
|
if disclosed.insert(name, value).is_some() {
|
|
return None;
|
|
}
|
|
}
|
|
let encoded_payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&disclosed).ok()?);
|
|
let authority_digest = Sha256::digest(serde_json::to_vec(&stable).ok()?).into();
|
|
Some((
|
|
expires_at,
|
|
JwtProjection {
|
|
encoded_payload,
|
|
authority_digest,
|
|
},
|
|
))
|
|
}
|
|
|
|
/// The broker clock and its supported source tokens use integral Unix seconds.
|
|
fn numeric_date(raw: &RawValue) -> Option<i64> {
|
|
let seconds: i64 = serde_json::from_str(raw.get()).ok()?;
|
|
time::OffsetDateTime::from_unix_timestamp(seconds).ok()?;
|
|
Some(seconds)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "jwt_presentation_tests.rs"]
|
|
mod tests;
|