use crate::scope::{Scope, ScopeExpr};
use base64::Engine as _;
use core::str::FromStr as _;
pub(crate) const MAX_JWT_PAYLOAD_BYTES: usize = 8192;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum UnverifiedScopeObservation {
ContainsRequiredScope,
DoesNotContainRequiredScope,
Indeterminate,
}
fn scp_items(access_token: &str) -> Option<Vec<String>> {
let mut parts = access_token.split('.');
let (Some(_header), Some(payload_b64), Some(_sig), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return None;
};
if payload_b64.len() > MAX_JWT_PAYLOAD_BYTES {
return None;
}
let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
let Ok(payload) = engine.decode(payload_b64) else {
return None;
};
debug_assert!(
payload.len() <= MAX_JWT_PAYLOAD_BYTES,
"the invariant that the encoding bound implies the decoded length is broken"
);
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&payload) else {
return None;
};
let items = value.get("scp").and_then(serde_json::Value::as_array)?;
if items.is_empty() {
return None;
}
if items.iter().any(|v| !v.is_string()) {
return None;
}
Some(
items
.iter()
.filter_map(serde_json::Value::as_str)
.map(str::to_owned)
.collect(),
)
}
pub(crate) fn observe_scopes(
access_token: &str,
required: &ScopeExpr,
) -> UnverifiedScopeObservation {
use UnverifiedScopeObservation::Indeterminate;
let Some(items) = scp_items(access_token) else {
return Indeterminate;
};
let held: Vec<Scope> = items
.iter()
.filter_map(|s| Scope::from_str(s).ok())
.collect();
if required.is_satisfied_by(&held) {
UnverifiedScopeObservation::ContainsRequiredScope
} else {
UnverifiedScopeObservation::DoesNotContainRequiredScope
}
}
const FORBIDDEN_COMMAND_SCOPES: [&str; 3] =
["vehicle_cmds", "vehicle_charging_cmds", "energy_cmds"];
pub(crate) fn observe_forbidden(access_token: &str) -> UnverifiedScopeObservation {
let Some(items) = scp_items(access_token) else {
return UnverifiedScopeObservation::Indeterminate;
};
if items
.iter()
.any(|s| FORBIDDEN_COMMAND_SCOPES.contains(&s.as_str()))
{
UnverifiedScopeObservation::ContainsRequiredScope
} else {
UnverifiedScopeObservation::DoesNotContainRequiredScope
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scope::{Scope, ScopeExpr};
fn jwt_with_payload(payload: &serde_json::Value) -> String {
let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
let header = engine.encode(br#"{"alg":"RS256","typ":"JWT"}"#);
let body = engine.encode(serde_json::to_vec(payload).expect("payload"));
format!("{header}.{body}.not-a-real-signature")
}
fn required_device_data() -> ScopeExpr {
ScopeExpr::One(Scope::VehicleDeviceData)
}
#[test]
fn forbidden_command_scopes_are_observed() {
let t = jwt_with_payload(&serde_json::json!({
"scp": ["openid", "vehicle_device_data", "vehicle_charging_cmds"]
}));
assert_eq!(
observe_forbidden(&t),
UnverifiedScopeObservation::ContainsRequiredScope
);
let ok = jwt_with_payload(&serde_json::json!({
"scp": ["openid", "vehicle_device_data", "vehicle_location"]
}));
assert_eq!(
observe_forbidden(&ok),
UnverifiedScopeObservation::DoesNotContainRequiredScope
);
for name in ["vehicle_cmds", "energy_cmds"] {
let t = jwt_with_payload(&serde_json::json!({ "scp": ["openid", name] }));
assert_eq!(
observe_forbidden(&t),
UnverifiedScopeObservation::ContainsRequiredScope
);
}
}
#[test]
fn forbidden_check_is_indeterminate_when_unreadable() {
for t in [
"opaque".to_owned(),
jwt_with_payload(&serde_json::json!({})),
jwt_with_payload(&serde_json::json!({ "scp": [] })),
jwt_with_payload(&serde_json::json!({ "scp": ["vehicle_cmds", 1] })),
] {
assert_eq!(
observe_forbidden(&t),
UnverifiedScopeObservation::Indeterminate
);
}
}
#[test]
fn real_tesla_scp_shape_is_recognized_including_unmodeled_scopes() {
let token = jwt_with_payload(&serde_json::json!({
"scp": ["offline_access", "openid", "vehicle_device_data", "vehicle_location"]
}));
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::ContainsRequiredScope
);
}
#[test]
fn missing_required_scope_is_the_only_path_that_skips_a_request() {
let token = jwt_with_payload(&serde_json::json!({ "scp": ["openid"] }));
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::DoesNotContainRequiredScope
);
}
#[test]
fn every_ambiguous_shape_is_indeterminate_not_a_skip() {
let opaque = "NA_9f2b1c7d8e4a5b6c7d8e9f0a";
let two_segments = "eyJhbGciOiJSUzI1NiJ9.eyJzY3AiOltdfQ";
let bad_base64 = "eyJhbGciOiJSUzI1NiJ9.!!!not-base64!!!.sig";
let not_json = {
let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
format!("eyJhbGciOiJSUzI1NiJ9.{}.sig", engine.encode(b"plain text"))
};
let scp_absent = jwt_with_payload(&serde_json::json!({ "sub": "abc" }));
let scp_is_string = jwt_with_payload(&serde_json::json!({ "scp": "vehicle_device_data" }));
let scp_has_non_strings = jwt_with_payload(&serde_json::json!({ "scp": [1, 2] }));
for (label, token) in [
("opaque token", opaque.to_owned()),
("two segments", two_segments.to_owned()),
("undecodable payload", bad_base64.to_owned()),
("payload is not json", not_json),
("scp claim absent", scp_absent),
("scp is a string not an array", scp_is_string),
("scp holds non-strings", scp_has_non_strings),
] {
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::Indeterminate,
"{label} must be Indeterminate — blocking the request breaks fail-open"
);
}
}
#[test]
fn an_oversized_payload_is_indeterminate() {
let huge = jwt_with_payload(&serde_json::json!({
"scp": ["vehicle_device_data"],
"padding": "A".repeat(MAX_JWT_PAYLOAD_BYTES * 2),
}));
assert_eq!(
observe_scopes(&huge, &required_device_data()),
UnverifiedScopeObservation::Indeterminate
);
}
#[test]
fn all_expression_requires_every_scope() {
let token = jwt_with_payload(&serde_json::json!({
"scp": ["vehicle_device_data"]
}));
let required = ScopeExpr::All(vec![
ScopeExpr::One(Scope::VehicleDeviceData),
ScopeExpr::One(Scope::VehicleLocation),
]);
assert_eq!(
observe_scopes(&token, &required),
UnverifiedScopeObservation::DoesNotContainRequiredScope
);
}
#[test]
fn any_expression_is_satisfied_by_a_single_held_scope() {
let token = jwt_with_payload(&serde_json::json!({ "scp": ["vehicle_location"] }));
let either = ScopeExpr::Any(vec![
ScopeExpr::One(Scope::VehicleDeviceData),
ScopeExpr::One(Scope::VehicleLocation),
]);
assert_eq!(
observe_scopes(&token, &either),
UnverifiedScopeObservation::ContainsRequiredScope
);
let neither = ScopeExpr::Any(vec![
ScopeExpr::One(Scope::UserData),
ScopeExpr::One(Scope::Openid),
]);
assert_eq!(
observe_scopes(&token, &neither),
UnverifiedScopeObservation::DoesNotContainRequiredScope
);
}
#[test]
fn only_a_three_segment_token_is_read_at_all() {
let three = jwt_with_payload(&serde_json::json!({ "scp": ["vehicle_device_data"] }));
assert_eq!(
observe_scopes(&three, &required_device_data()),
UnverifiedScopeObservation::ContainsRequiredScope
);
for (label, token) in [
("four segments", format!("{three}.extra")),
("five segments (JWE shape)", format!("{three}.extra.more")),
] {
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::Indeterminate,
"{label} is not a compact JWS — index 1 must not be read as the payload"
);
}
}
#[test]
fn the_length_bound_is_checked_on_the_encoded_form_before_any_buffer_is_allocated() {
let token = jwt_with_payload(&serde_json::json!({
"scp": ["vehicle_device_data"],
"padding": "A".repeat(MAX_JWT_PAYLOAD_BYTES * 7 / 8),
}));
let payload_b64 = token.split('.').nth(1).expect("payload segment");
let decoded_len = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(payload_b64)
.expect("decodable")
.len();
assert!(
payload_b64.len() > MAX_JWT_PAYLOAD_BYTES,
"the encoded length must exceed the bound for this test to be meaningful"
);
assert!(
decoded_len <= MAX_JWT_PAYLOAD_BYTES,
"the decoded length must be at or under the bound — otherwise a check after \
decoding would catch this input too"
);
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::Indeterminate
);
}
#[test]
fn an_empty_scp_array_is_as_indeterminate_as_an_absent_claim() {
let empty = jwt_with_payload(&serde_json::json!({ "scp": [] }));
assert_eq!(
observe_scopes(&empty, &required_device_data()),
UnverifiedScopeObservation::Indeterminate,
"an empty array is read as a sign of an upstream anomaly, not as a statement by \
the issuer"
);
let absent = jwt_with_payload(&serde_json::json!({ "sub": "abc" }));
assert_eq!(
observe_scopes(&absent, &required_device_data()),
UnverifiedScopeObservation::Indeterminate
);
let stated = jwt_with_payload(&serde_json::json!({ "scp": ["openid"] }));
assert_eq!(
observe_scopes(&stated, &required_device_data()),
UnverifiedScopeObservation::DoesNotContainRequiredScope
);
}
#[test]
fn an_array_mixing_strings_and_non_strings_is_indeterminate() {
let token = jwt_with_payload(&serde_json::json!({ "scp": ["vehicle_device_data", 1] }));
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::Indeterminate,
"picking only the strings out of a structure we did not understand is pretending \
to understand it"
);
}
#[test]
fn the_header_is_never_inspected() {
let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
let body = engine.encode(
serde_json::to_vec(&serde_json::json!({ "scp": ["vehicle_device_data"] }))
.expect("payload"),
);
for header in [
"!!not-base64-at-all!!".to_owned(),
engine.encode(b"plain text"),
engine.encode(br#"{"alg":"none"}"#),
] {
assert_eq!(
observe_scopes(&format!("{header}.{body}.sig"), &required_device_data()),
UnverifiedScopeObservation::ContainsRequiredScope,
"the verdict must not change based on the header"
);
}
}
#[test]
fn the_payload_is_decoded_with_the_url_safe_alphabet() {
let token = jwt_with_payload(&serde_json::json!({
"scp": ["vehicle_device_data"],
"padding": "?>".repeat(6),
}));
let payload_b64 = token.split('.').nth(1).expect("payload segment");
assert!(
payload_b64.contains('-') && payload_b64.contains('_'),
"this test is vacuous if the payload has no URL-safe-only characters: {payload_b64}"
);
assert_eq!(
observe_scopes(&token, &required_device_data()),
UnverifiedScopeObservation::ContainsRequiredScope
);
}
#[test]
fn the_verdict_carries_no_token_derived_data() {
assert_eq!(
size_of::<UnverifiedScopeObservation>(),
1,
"if a variant carries data, that value soon flows out into logs and errors"
);
let token = jwt_with_payload(&serde_json::json!({
"scp": ["offline_access", "vehicle_device_data"]
}));
assert_eq!(
format!("{:?}", observe_scopes(&token, &required_device_data())),
"ContainsRequiredScope"
);
}
}