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
//! OAuth scopes and scope-satisfaction expressions.
use serde::{Deserialize, Serialize};
/// A Tesla Fleet API OAuth scope.
///
/// The serde representation is the **wire** form — Tesla's OAuth `scope`
/// string is space-delimited `snake_case` (`vehicle_device_data
/// vehicle_location openid`), and a token response is where these values are
/// actually parsed from. Final fix wave (F4): without
/// `rename_all = "snake_case"` the derive emitted serde's default variant
/// name (`"VehicleDeviceData"`), which round-trips against itself but
/// matches nothing Tesla ever sends or accepts. It went unnoticed because
/// none of this module's tests serialized or deserialized a `Scope` at all —
/// see `serde_wire_form_is_snake_case_for_every_variant`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Scope {
/// `vehicle_device_data` — vehicle telemetry/data.
VehicleDeviceData,
/// `vehicle_location` — precise location (double opt-in).
VehicleLocation,
/// `user_data` — user-context endpoints.
UserData,
/// `openid` — base identity.
Openid,
}
/// The error returned when a wire string is none of the modeled [`Scope`]s.
///
/// Tesla also issues scopes that this crate does not model (for example `offline_access`).
/// That is **normal**, not an error condition, and the caller can simply drop such an entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnknownScope;
impl core::fmt::Display for UnknownScope {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
// The scope string itself is not included, so that no token-derived value is carried
// in the error.
f.write_str("unrecognized scope")
}
}
impl core::error::Error for UnknownScope {}
impl core::str::FromStr for Scope {
type Err = UnknownScope;
/// Converts a string in Tesla's wire form (snake_case) into a [`Scope`].
///
/// Case is not normalized — the wire form is fixed as lowercase, and arbitrary
/// normalization risks folding scopes that are actually different into the same one.
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"openid" => Ok(Scope::Openid),
"user_data" => Ok(Scope::UserData),
"vehicle_device_data" => Ok(Scope::VehicleDeviceData),
"vehicle_location" => Ok(Scope::VehicleLocation),
_ => Err(UnknownScope),
}
}
}
/// A boolean expression over required scopes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeExpr {
/// All sub-expressions must hold.
All(Vec<ScopeExpr>),
/// At least one sub-expression must hold.
Any(Vec<ScopeExpr>),
/// A single required scope.
One(Scope),
}
impl ScopeExpr {
/// Whether `held` scopes satisfy this expression.
pub fn is_satisfied_by(&self, held: &[Scope]) -> bool {
match self {
ScopeExpr::One(s) => held.contains(s),
ScopeExpr::All(v) => v.iter().all(|e| e.is_satisfied_by(held)),
ScopeExpr::Any(v) => v.iter().any(|e| e.is_satisfied_by(held)),
}
}
/// Returns the **entire required expression** (a clone of `self`) when
/// `held` does not satisfy it, or `None` when it does — for advisory
/// pre-checks.
///
/// Whatever `held` a caller passes here is only as trustworthy as its
/// source. `crate::client::Client::send`'s own pre-check (A3 Task 9,
/// design §10) never actually holds a `held: &[Scope]` to call this
/// with — it goes through `crate::auth`'s unverified, signature-free
/// token observation instead, which reports a pass/fail/indeterminate
/// verdict rather than a scope list (see [`crate::error::Error::MissingScope`]'s
/// doc). Either way, a scope observed on an **unverified** access token
/// proves nothing about actual authorization — it is an advisory cost
/// guard against paying for a call the server will reject, never a
/// substitute for the server's own 403.
///
/// Note what this is not (final fix wave / F13b): it does **not** narrow
/// the result down to the unsatisfied part of the expression. Given
/// `All([One(Openid), One(UserData)])` and `held = [Openid]`, the return
/// value is the whole `All([...])`, not the `One(UserData)` that is
/// actually missing. The earlier doc said it returns "Some(self)", which
/// is also literally wrong — `self` is `&ScopeExpr` and the value
/// returned is an owned clone. The method name is a known mismatch with
/// this behaviour and is being left alone deliberately; renaming it is a
/// separate, deferred API decision.
pub fn missing(&self, held: &[Scope]) -> Option<ScopeExpr> {
if self.is_satisfied_by(held) {
None
} else {
Some(self.clone())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_requires_every_scope() {
let e = ScopeExpr::All(vec![
ScopeExpr::One(Scope::VehicleDeviceData),
ScopeExpr::One(Scope::VehicleLocation),
]);
assert!(!e.is_satisfied_by(&[Scope::VehicleDeviceData]));
assert!(e.is_satisfied_by(&[Scope::VehicleDeviceData, Scope::VehicleLocation]));
}
#[test]
fn any_requires_one() {
let e = ScopeExpr::Any(vec![
ScopeExpr::One(Scope::UserData),
ScopeExpr::One(Scope::Openid),
]);
assert!(e.is_satisfied_by(&[Scope::Openid]));
assert!(!e.is_satisfied_by(&[Scope::VehicleLocation]));
}
#[test]
fn one_matches_only_held_scope() {
let e = ScopeExpr::One(Scope::UserData);
assert!(e.is_satisfied_by(&[Scope::UserData]));
assert!(!e.is_satisfied_by(&[Scope::Openid]));
assert!(!e.is_satisfied_by(&[]));
}
#[test]
fn missing_is_none_when_satisfied() {
let e = ScopeExpr::One(Scope::Openid);
assert_eq!(e.missing(&[Scope::Openid]), None);
}
#[test]
fn missing_returns_self_when_unsatisfied() {
let e = ScopeExpr::All(vec![
ScopeExpr::One(Scope::Openid),
ScopeExpr::One(Scope::UserData),
]);
assert_eq!(e.missing(&[Scope::Openid]), Some(e.clone()));
}
#[test]
fn nested_all_any_composes() {
// All(Any(VehicleDeviceData, VehicleLocation), One(Openid))
let e = ScopeExpr::All(vec![
ScopeExpr::Any(vec![
ScopeExpr::One(Scope::VehicleDeviceData),
ScopeExpr::One(Scope::VehicleLocation),
]),
ScopeExpr::One(Scope::Openid),
]);
assert!(e.is_satisfied_by(&[Scope::VehicleLocation, Scope::Openid]));
assert!(!e.is_satisfied_by(&[Scope::VehicleLocation]));
assert!(!e.is_satisfied_by(&[Scope::Openid]));
}
#[test]
fn all_of_empty_is_vacuously_true() {
assert!(ScopeExpr::All(vec![]).is_satisfied_by(&[]));
}
#[test]
fn any_of_empty_is_vacuously_false() {
assert!(!ScopeExpr::Any(vec![]).is_satisfied_by(&[]));
}
/// Final fix wave (F4): `Scope`'s serde encoding must be Tesla's wire
/// form, not serde's default variant name. Every variant is covered, and
/// the expected string comes from an **exhaustive `match`** rather than a
/// parallel array — so adding a variant without deciding its wire
/// spelling is a compile error here, not a silent gap. (An enumerated
/// list falling behind the shapes it must cover is exactly how two other
/// defects on this branch happened.)
#[test]
fn serde_wire_form_is_snake_case_for_every_variant() {
let all = [
Scope::VehicleDeviceData,
Scope::VehicleLocation,
Scope::UserData,
Scope::Openid,
];
for scope in all {
let wire = match scope {
Scope::VehicleDeviceData => "vehicle_device_data",
Scope::VehicleLocation => "vehicle_location",
Scope::UserData => "user_data",
Scope::Openid => "openid",
};
let json = format!("\"{wire}\"");
assert_eq!(
serde_json::to_string(&scope).unwrap(),
json,
"{scope:?} does not serialize to Tesla's wire form"
);
assert_eq!(
serde_json::from_str::<Scope>(&json).unwrap(),
scope,
"{wire} does not deserialize back to {scope:?}"
);
}
}
/// The discriminating half: serde's **default** (variant-name) encoding
/// must be rejected. Without this, a regression that dropped
/// `rename_all` would still pass the round-trip test above, since a
/// round-trip is self-consistent under any naming convention — that
/// self-consistency is precisely why the bug was invisible.
#[test]
fn serde_rejects_the_default_variant_name_encoding() {
assert!(serde_json::from_str::<Scope>("\"VehicleDeviceData\"").is_err());
assert!(serde_json::from_str::<Scope>("\"UserData\"").is_err());
assert!(serde_json::from_str::<Scope>("\"Openid\"").is_err());
}
#[test]
fn from_str_accepts_every_modeled_scope_in_wire_form() {
use core::str::FromStr;
// Derive the expected values independently from Tesla's wire strings, not from Scope
// itself.
let pairs = [
("openid", Scope::Openid),
("user_data", Scope::UserData),
("vehicle_device_data", Scope::VehicleDeviceData),
("vehicle_location", Scope::VehicleLocation),
];
for (wire, expected) in pairs {
assert_eq!(Scope::from_str(wire), Ok(expected), "wire form {wire}");
}
}
#[test]
fn from_str_rejects_unknown_scope_without_panicking() {
use core::str::FromStr;
// A value that really is in the measured token's scp, and that is not modeled.
assert!(Scope::from_str("offline_access").is_err());
assert!(Scope::from_str("").is_err());
assert!(Scope::from_str("VehicleDeviceData").is_err()); // PascalCase is not the wire form
}
/// `from_str` must accept the **same** set of strings as the serde wire form.
/// If the two paths diverge, Task 6's `scp` parsing and the token response's `scope`
/// parsing reach different verdicts. The expected strings come from an **exhaustive
/// `match`** rather than a parallel array, so adding a variant while leaving out its
/// `from_str` arm becomes a compile error/failure instead of a silent hole (the same
/// discipline as the F4 test).
#[test]
fn from_str_agrees_with_serde_wire_form_for_every_variant() {
use core::str::FromStr;
let all = [
Scope::VehicleDeviceData,
Scope::VehicleLocation,
Scope::UserData,
Scope::Openid,
];
for scope in all {
let wire = match scope {
Scope::VehicleDeviceData => "vehicle_device_data",
Scope::VehicleLocation => "vehicle_location",
Scope::UserData => "user_data",
Scope::Openid => "openid",
};
// First pin that serde really emits that string,
let serialized = serde_json::to_string(&scope).unwrap();
assert_eq!(serialized, format!("\"{wire}\""));
// then check that from_str takes the same string as the same variant.
assert_eq!(
Scope::from_str(wire),
Ok(scope),
"from_str disagrees with the serde wire form of {scope:?}"
);
}
}
/// Pins down that no normalization, trimming or partial matching is done.
/// If any one of these passed, different scopes would be folded into the same one
/// (`to_lowercase`), or a whole space-separated string would be mistaken for a single
/// scope.
#[test]
fn from_str_does_not_normalize_or_trim_or_partial_match() {
use core::str::FromStr;
for bad in [
"OPENID", // no uppercase normalization
"Openid", // serde's default variant-name encoding
"VEHICLE_DEVICE_DATA", // uppercase snake
"vehicleDeviceData", // camelCase
" openid", // leading space: no trim
"openid ", // trailing space: no trim
"openid\n", // newline
"open id", // inserted space
"openidx", // a prefix match alone must not pass
"id", // a suffix match alone must not pass
"openid vehicle_device_data", // the whole space-separated string
"offline_access", // the unknown scope in the measured token
"vehicle_cmds", // command scope: this crate does not model it
"",
] {
assert!(
Scope::from_str(bad).is_err(),
"{bad:?} must not parse as a scope"
);
}
}
/// The error value does not carry the scope string (REQ-18: no exposure of
/// token-derived values).
#[test]
fn unknown_scope_error_does_not_leak_the_offending_string() {
use core::str::FromStr;
let secret = "offline_access";
let err = Scope::from_str(secret).unwrap_err();
assert!(!format!("{err}").contains(secret));
assert!(!format!("{err:?}").contains(secret));
}
/// The real evidence behind this task: the `scp` claim of a Tesla access token measured
/// on this machine. `offline_access` is not modeled, so it must be **dropped**, and the
/// other 3 must survive. Treating this as a failure of the whole would make Task 6's
/// pre-check useless.
#[test]
fn real_token_scp_claim_drops_unknown_and_keeps_the_rest() {
use core::str::FromStr;
let scp = [
"offline_access",
"openid",
"vehicle_device_data",
"vehicle_location",
];
let held: Vec<Scope> = scp.iter().filter_map(|s| Scope::from_str(s).ok()).collect();
assert_eq!(
held,
vec![
Scope::Openid,
Scope::VehicleDeviceData,
Scope::VehicleLocation
],
);
// Dropping the unknown scope leaves the verdict on the known required scopes unchanged.
let required = ScopeExpr::All(vec![
ScopeExpr::One(Scope::VehicleDeviceData),
ScopeExpr::One(Scope::VehicleLocation),
]);
assert!(required.is_satisfied_by(&held));
assert_eq!(required.missing(&held), None);
// A scope that is not held still stays unsatisfied.
assert!(!ScopeExpr::One(Scope::UserData).is_satisfied_by(&held));
}
/// A realistic parse of Tesla's space-delimited `scope` string from a
/// token response, which is where these values actually arrive.
#[test]
fn tesla_token_scope_string_parses_into_scopes() {
let raw = "openid vehicle_device_data vehicle_location user_data";
let parsed: Vec<Scope> = raw
.split(' ')
.map(|s| serde_json::from_str::<Scope>(&format!("\"{s}\"")).unwrap())
.collect();
assert_eq!(
parsed,
vec![
Scope::Openid,
Scope::VehicleDeviceData,
Scope::VehicleLocation,
Scope::UserData,
]
);
}
}