lys-pass 0.3.4

Lys pass verification, live permission checks and product draft execution
Documentation
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Shared pass verification and permission contracts for products.

pub mod binding;
pub mod conformance;
pub mod deliberate;
pub mod drafts;
pub mod membership;
pub mod membership_admission;
pub mod membership_conformance;
pub mod membership_pages;
pub mod refusal;
pub mod rights;
#[cfg(feature = "http")]
pub mod signin;
pub mod verify;

pub use membership::{GrantLog, MembershipDecision, MembershipRequest, Subject, Verdict};
pub use refusal::Refusal;
pub use rights::{Claims, Decision, Holder, Mode, Right, Target};
pub use verify::{CLOCK_SKEW, KeySet, VerifiedPass};

#[cfg(feature = "http")]
use reqwest::Client as Http;
use serde::{Deserialize, Serialize};
#[cfg(feature = "http")]
use url::Url;

/// A named refusal at a token, key or live-contract boundary.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The signed audience differs from the product.
    #[error("wrong_audience")]
    WrongAudience,
    /// The signed issuer differs from the trusted issuer.
    #[error("wrong_issuer")]
    WrongIssuer,
    /// The pass has reached its expiry.
    #[error("pass_expired")]
    Expired,
    /// The pass starts beyond the permitted future clock skew.
    #[error(
        "pass_not_yet_valid: clock skew {skew_ms} ms exceeds {limit_ms} ms",
        limit_ms = crate::verify::CLOCK_SKEW * 1000
    )]
    NotYetValid {
        /// The greatest future issue or not-before offset in milliseconds.
        skew_ms: u128,
    },
    /// No published verification key has this id.
    #[error("unpublished_key: {0}")]
    UnpublishedKey(String),
    /// Strict signature verification failed.
    #[error("signature_refused")]
    Signature(#[source] ed25519_dalek::SignatureError),
    /// A compact token segment was not canonical base64url.
    #[error("pass_encoding_refused")]
    Encoding(#[from] base64::DecodeError),
    /// A signed claim or published key could not be read.
    #[error("pass_contract_refused")]
    Json(#[from] serde_json::Error),
    /// A pass contains another application's rights.
    #[error("rights_outside_audience")]
    RightsOutsideAudience,
    /// The issuer omitted rights for this application.
    #[error("rights_truncated: {0}")]
    Truncated(String),
    /// A boundary value violates the published contract.
    #[error("contract_refused: {0}")]
    Invalid(&'static str),
    /// A live request failed before a contract answer was received. The
    /// transport's own error, typed by no HTTP stack, so the variant stands
    /// whether or not the `http` feature is on.
    #[error("Lys could not be asked")]
    Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// A live response is outside the permission contract.
    #[error("Lys could not be asked: {0}")]
    CannotAsk(&'static str),
    /// The token route answered outside its refusal contract.
    #[error("Lys could not be asked: token route answered {status}{suffix}", suffix = .refusal.as_deref().map_or_else(String::new, |name| format!(" {name}")))]
    CannotAskToken {
        /// The HTTP status the route answered.
        status: u16,
        /// A plain refusal name, when its body carried one.
        refusal: Option<String>,
        /// A failure reading the answer, without the response body.
        #[source]
        cause: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// A live client needs the Lys origin, without an API mount or other path.
    #[error("lys_origin_required: the Lys client needs an origin without an API mount or path")]
    LysOriginRequired,
    /// A supplied endpoint is malformed.
    #[error("endpoint_refused")]
    Url(#[from] url::ParseError),
    /// A pass's grant binding is absent, unsupported or not the pass's
    /// (DIRECTORY-089 R2), by its stable name.
    #[error("{name}: {reason}")]
    Binding {
        /// The binding's stable refusal name.
        name: &'static str,
        /// Its words.
        reason: &'static str,
    },
    /// A named issuer refusal of the exchange or refresh.
    #[error("token_refused: {name}: {reason}")]
    TokenRefused {
        /// The issuer's stable refusal name.
        name: String,
        /// The issuer's refusal words.
        reason: String,
    },
}

impl Error {
    /// The stable machine name, without keys, credentials or response bodies.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::WrongAudience => "wrong_audience",
            Self::WrongIssuer => "wrong_issuer",
            Self::Expired => "pass_expired",
            Self::NotYetValid { .. } => "pass_not_yet_valid",
            Self::UnpublishedKey(_) => "unpublished_key",
            Self::Signature(_) => "signature_refused",
            Self::Encoding(_) => "pass_encoding_refused",
            Self::Json(_) | Self::Invalid(_) => "contract_refused",
            Self::RightsOutsideAudience => "rights_outside_audience",
            Self::Truncated(_) => "rights_truncated",
            Self::Transport(_) | Self::CannotAsk(_) | Self::CannotAskToken { .. } => {
                "lys_could_not_be_asked"
            }
            Self::LysOriginRequired => "lys_origin_required",
            Self::Url(_) => "endpoint_refused",
            Self::Binding { name, .. } => name,
            Self::TokenRefused { name, .. } => name,
        }
    }
}

/// A transport supplied by the product, holding no token or credential.
#[cfg(feature = "http")]
#[derive(Clone, Debug)]
pub struct Client {
    http: Http,
    issuer: Url,
}

#[cfg(feature = "http")]
impl Client {
    /// Use the product's configured transport and trusted Lys origin.
    /// Provider routes live at its root; product API routes live under `/api`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] unless the issuer is HTTP or HTTPS with
    /// a host and no credentials, query or fragment. A path other than the
    /// root is [`Error::LysOriginRequired`].
    pub fn new(http: Http, issuer: Url) -> Result<Self, Error> {
        if !matches!(issuer.scheme(), "http" | "https")
            || issuer.host_str().is_none()
            || !issuer.username().is_empty()
            || issuer.password().is_some()
            || issuer.query().is_some()
            || issuer.fragment().is_some()
        {
            return Err(Error::Invalid("issuer is not an HTTP origin"));
        }
        if issuer.path() != "/" {
            return Err(Error::LysOriginRequired);
        }
        Ok(Self { http, issuer })
    }

    fn endpoint(&self, relative: &str) -> Result<Url, Error> {
        Ok(self.issuer.join(relative)?)
    }

    fn api_endpoint(&self, relative: &str) -> Result<Url, Error> {
        self.endpoint(&format!("api/{relative}"))
    }

    /// Fetch the issuer's current keyset explicitly; offline checks never fetch.
    ///
    /// # Errors
    ///
    /// Preserves endpoint, transport, refusal-status and response-reading
    /// failures. A fetched keyset that does not satisfy [`KeySet::from_json`]
    /// is refused before a replacement cache is returned.
    pub async fn fetch_keys(&self) -> Result<KeySet, Error> {
        let response = self
            .http
            .get(self.endpoint("oauth/jwks")?)
            .send()
            .await
            .map_err(|error| Error::Transport(Box::new(error)))?;
        let text = response
            .error_for_status()
            .map_err(|error| Error::Transport(Box::new(error)))?
            .text()
            .await
            .map_err(|error| Error::Transport(Box::new(error)))?;
        KeySet::from_json(&text)
    }

    /// Exchange an authorization code using credentials owned by the caller.
    ///
    /// # Errors
    ///
    /// Refuses a missing client id, secret, code, redirect URI or PKCE
    /// verifier before sending. Preserves endpoint and transport failures
    /// and the issuer's named token refusal. An unreadable or invalid token
    /// answer, or a failure status outside the refusal contract, is returned
    /// as Lys could not be asked.
    pub async fn fetch_token(&self, request: &TokenRequest<'_>) -> Result<TokenResponse, Error> {
        self.token(&code_form(request)?).await
    }

    /// [`Client::fetch_token`], asking Lys for the pass's grant binding
    /// beside it (DIRECTORY-089 R2). An answer without one is refused
    /// `grant_binding_required`, never taken as a pass at revision zero.
    ///
    /// # Errors
    ///
    /// Returns the exchange refusals of [`Self::fetch_token`], and
    /// `grant_binding_required` when the answer has no nonempty binding.
    pub async fn fetch_bound_token(
        &self,
        request: &TokenRequest<'_>,
    ) -> Result<TokenResponse, Error> {
        let mut form = code_form(request)?.to_vec();
        form.push(("grant_binding", binding::BINDING_REQUEST));
        bound(self.token(&form).await?)
    }

    /// [`Client::refresh_token`], asking for the new pass's grant binding.
    ///
    /// # Errors
    ///
    /// Returns the refresh refusals of [`Self::refresh_token`], and
    /// `grant_binding_required` when the new answer has no nonempty binding.
    pub async fn refresh_bound_token(
        &self,
        client_id: &str,
        client_secret: &str,
        refresh_token: &str,
    ) -> Result<TokenResponse, Error> {
        if client_id.is_empty() || client_secret.is_empty() || refresh_token.is_empty() {
            return Err(Error::Invalid("refresh request is incomplete"));
        }
        bound(
            self.token(&[
                ("grant_type", "refresh_token"),
                ("client_id", client_id),
                ("client_secret", client_secret),
                ("refresh_token", refresh_token),
                ("grant_binding", binding::BINDING_REQUEST),
            ])
            .await?,
        )
    }

    /// Ask Lys to refresh from live grants; no timer or cached authority is used.
    ///
    /// # Errors
    ///
    /// Refuses a missing client id, secret or refresh token before sending.
    /// Preserves endpoint and transport failures and the issuer's named
    /// token refusal, including withdrawn live authority. An unreadable or
    /// invalid token answer, or a failure status outside the refusal
    /// contract, is returned as Lys could not be asked.
    pub async fn refresh_token(
        &self,
        client_id: &str,
        client_secret: &str,
        refresh_token: &str,
    ) -> Result<TokenResponse, Error> {
        if client_id.is_empty() || client_secret.is_empty() || refresh_token.is_empty() {
            return Err(Error::Invalid("refresh request is incomplete"));
        }
        self.token(&[
            ("grant_type", "refresh_token"),
            ("client_id", client_id),
            ("client_secret", client_secret),
            ("refresh_token", refresh_token),
        ])
        .await
    }

    async fn token(&self, form: &[(&str, &str)]) -> Result<TokenResponse, Error> {
        let response = self
            .http
            .post(self.endpoint("oauth/token")?)
            .form(form)
            .send()
            .await
            .map_err(|error| Error::Transport(Box::new(error)))?;
        read_token(response, form).await
    }
}

/// The authorization-code exchange form of `request`.
#[cfg(feature = "http")]
fn code_form<'a>(request: &TokenRequest<'a>) -> Result<[(&'static str, &'a str); 6], Error> {
    if request.client_id.is_empty()
        || request.client_secret.is_empty()
        || request.code.is_empty()
        || request.redirect_uri.is_empty()
        || request.code_verifier.is_empty()
    {
        return Err(Error::Invalid("token request is incomplete"));
    }
    Ok([
        ("grant_type", "authorization_code"),
        ("client_id", request.client_id),
        ("client_secret", request.client_secret),
        ("code", request.code),
        ("redirect_uri", request.redirect_uri),
        ("code_verifier", request.code_verifier),
    ])
}

/// `answer`, refused by name when it carries no grant binding.
#[cfg(feature = "http")]
fn bound(answer: TokenResponse) -> Result<TokenResponse, Error> {
    binding::required(answer.grant_binding.as_deref())?;
    Ok(answer)
}

/// A token endpoint's answer: the pass, or the issuer's refusal by name. A
/// refusal without a name is not a contract answer, and neither carries the
/// response body into an error.
#[cfg(feature = "http")]
pub(crate) async fn read_token(
    response: reqwest::Response,
    form: &[(&str, &str)],
) -> Result<TokenResponse, Error> {
    let status = response.status();
    if !status.is_success() {
        let bytes = response
            .bytes()
            .await
            .map_err(|error| Error::CannotAskToken {
                status: status.as_u16(),
                refusal: None,
                cause: Some(Box::new(error.without_url())),
            })?;
        if let Ok(refused) = serde_json::from_slice::<TokenRefusal>(&bytes)
            && !refused.error.is_empty()
            && !refused.refusal.is_empty()
            && refused.reason == refused.error_description
            && !contains_credentials(&refused.refusal, form)
            && !contains_credentials(&refused.error_description, form)
        {
            return Err(Error::TokenRefused {
                name: refused.refusal,
                reason: refused.error_description,
            });
        }
        let refusal = serde_json::from_slice::<RouteRefusal>(&bytes)
            .ok()
            .and_then(|body| body.refusal)
            .filter(|name| {
                name.len() <= 128
                    && !contains_credentials(name, form)
                    && name.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
                    && name
                        .bytes()
                        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
            });
        return Err(Error::CannotAskToken {
            status: status.as_u16(),
            refusal,
            cause: None,
        });
    }
    let answer: TokenResponse = response
        .json()
        .await
        .map_err(|error| Error::Transport(Box::new(error)))?;
    if answer.token_type != "Bearer" || answer.access_token.is_empty() || answer.expires_in == 0 {
        return Err(Error::CannotAsk("invalid token response"));
    }
    Ok(answer)
}

#[cfg(feature = "http")]
fn contains_credentials(text: &str, form: &[(&str, &str)]) -> bool {
    form.iter().any(|(name, value)| {
        matches!(
            *name,
            "client_secret" | "refresh_token" | "code" | "code_verifier"
        ) && !value.is_empty()
            && text.contains(*value)
    })
}

/// Borrowed authorization-code exchange inputs, never retained by the client.
pub struct TokenRequest<'a> {
    /// The registered audience.
    pub client_id: &'a str,
    /// The registered client credential.
    pub client_secret: &'a str,
    /// The one-use authorization code.
    pub code: &'a str,
    /// The registered return address.
    pub redirect_uri: &'a str,
    /// The authorization's PKCE verifier.
    pub code_verifier: &'a str,
}

/// A token response owned by the product that requested it.
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TokenResponse {
    /// The signed access pass.
    pub access_token: String,
    /// The authorization scheme.
    pub token_type: String,
    /// The remaining lifetime in seconds.
    pub expires_in: u64,
    /// The identity assertion, when the exchange includes it.
    pub id_token: Option<String>,
    /// The credential used for a live refresh, when issued.
    pub refresh_token: Option<String>,
    /// The pass's signed grant binding, present only when it was asked for
    /// (DIRECTORY-089 R2).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grant_binding: Option<String>,
}

#[cfg(feature = "http")]
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TokenRefusal {
    error: String,
    error_description: String,
    refusal: String,
    reason: String,
}

#[cfg(feature = "http")]
#[derive(Deserialize)]
struct RouteRefusal {
    refusal: Option<String>,
}