Skip to main content

stateknot_core/
identity.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Exact external issuer/subject identities for authenticated principals.
5
6use std::{borrow::Borrow, fmt, str::FromStr};
7
8use fluent_uri::Uri;
9use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
10use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
11use thiserror::Error;
12
13const ISSUER_ID_PATTERN: &str = "^[Hh][Tt][Tt][Pp][Ss]://[^/?#@]+(?:/[^?#]*)?$";
14const SUBJECT_ID_PATTERN: &str = r"^[\u0020-\u007E]{1,255}$";
15
16/// An exact, case-sensitive OIDC/OAuth issuer identifier.
17///
18/// The value is an absolute HTTPS URI with a host and optional port/path. It
19/// contains no user information, query, or fragment. Equality deliberately
20/// performs no URI normalization: OIDC requires the configured issuer,
21/// discovery metadata, and token `iss` claim to match exactly.
22///
23/// This type is identity data only. Constructing or deserializing it does not
24/// authenticate a token and never performs discovery or network access.
25#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
26pub struct IssuerId(Box<str>);
27
28impl IssuerId {
29    /// Maximum encoded length in bytes.
30    pub const MAX_LEN: usize = 512;
31
32    /// Validates and constructs an exact issuer identifier.
33    ///
34    /// # Errors
35    ///
36    /// Returns [`IssuerIdError`] when `value` is not a bounded HTTPS issuer
37    /// URI with the required OIDC/OAuth components.
38    pub fn new(value: impl Into<String>) -> Result<Self, IssuerIdError> {
39        let value = value.into();
40        validate_issuer_id(&value)?;
41        Ok(Self(value.into_boxed_str()))
42    }
43
44    /// Returns the exact issuer text used for security comparison.
45    #[must_use]
46    pub fn as_str(&self) -> &str {
47        &self.0
48    }
49}
50
51impl AsRef<str> for IssuerId {
52    fn as_ref(&self) -> &str {
53        self.as_str()
54    }
55}
56
57impl Borrow<str> for IssuerId {
58    fn borrow(&self) -> &str {
59        self.as_str()
60    }
61}
62
63impl fmt::Debug for IssuerId {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        formatter
66            .debug_tuple("IssuerId")
67            .field(&self.as_str())
68            .finish()
69    }
70}
71
72impl fmt::Display for IssuerId {
73    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
74        formatter.write_str(self.as_str())
75    }
76}
77
78impl FromStr for IssuerId {
79    type Err = IssuerIdError;
80
81    fn from_str(value: &str) -> Result<Self, Self::Err> {
82        Self::new(value)
83    }
84}
85
86impl TryFrom<String> for IssuerId {
87    type Error = IssuerIdError;
88
89    fn try_from(value: String) -> Result<Self, Self::Error> {
90        Self::new(value)
91    }
92}
93
94impl TryFrom<&str> for IssuerId {
95    type Error = IssuerIdError;
96
97    fn try_from(value: &str) -> Result<Self, Self::Error> {
98        Self::new(value)
99    }
100}
101
102impl From<IssuerId> for String {
103    fn from(value: IssuerId) -> Self {
104        value.0.into()
105    }
106}
107
108impl Serialize for IssuerId {
109    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
110    where
111        S: Serializer,
112    {
113        serializer.serialize_str(self.as_str())
114    }
115}
116
117impl<'de> Deserialize<'de> for IssuerId {
118    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
119    where
120        D: Deserializer<'de>,
121    {
122        deserializer.deserialize_string(IssuerIdVisitor)
123    }
124}
125
126struct IssuerIdVisitor;
127
128impl de::Visitor<'_> for IssuerIdVisitor {
129    type Value = IssuerId;
130
131    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132        formatter.write_str("an exact HTTPS OIDC/OAuth issuer identifier")
133    }
134
135    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
136    where
137        E: de::Error,
138    {
139        IssuerId::try_from(value).map_err(E::custom)
140    }
141
142    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
143    where
144        E: de::Error,
145    {
146        IssuerId::try_from(value).map_err(E::custom)
147    }
148}
149
150impl JsonSchema for IssuerId {
151    fn schema_name() -> std::borrow::Cow<'static, str> {
152        "IssuerId".into()
153    }
154
155    fn schema_id() -> std::borrow::Cow<'static, str> {
156        concat!(module_path!(), "::IssuerId").into()
157    }
158
159    fn json_schema(_: &mut SchemaGenerator) -> Schema {
160        json_schema!({
161            "type": "string",
162            "format": "uri",
163            "minLength": 9,
164            "maxLength": 512,
165            "pattern": ISSUER_ID_PATTERN
166        })
167    }
168
169    fn inline_schema() -> bool {
170        true
171    }
172}
173
174/// Validation failure for an [`IssuerId`].
175#[derive(Clone, Debug, Eq, Error, PartialEq)]
176#[non_exhaustive]
177pub enum IssuerIdError {
178    /// The identifier contained no bytes.
179    #[error("issuer identifier must not be empty")]
180    Empty,
181
182    /// The identifier exceeded [`IssuerId::MAX_LEN`].
183    #[error("issuer identifier is {actual} bytes; maximum is {max}")]
184    TooLong {
185        /// Maximum accepted byte length.
186        max: usize,
187        /// Observed byte length.
188        actual: usize,
189    },
190
191    /// The text was not an RFC 3986 URI.
192    #[error("issuer identifier must be an RFC 3986 URI")]
193    InvalidUri,
194
195    /// The URI did not use the HTTPS scheme.
196    #[error("issuer identifier must use HTTPS")]
197    UnsupportedScheme,
198
199    /// The URI did not contain a non-empty authority host.
200    #[error("issuer identifier must contain an HTTPS authority host")]
201    MissingAuthority,
202
203    /// A port was empty or outside the `u16` range used by HTTPS transports.
204    #[error("issuer identifier port must be an integer from 0 through 65535")]
205    InvalidPort,
206
207    /// URI user information was present.
208    #[error("issuer identifier must not contain user information")]
209    UserInfoNotAllowed,
210
211    /// A query component was present, including an empty query.
212    #[error("issuer identifier must not contain a query")]
213    QueryNotAllowed,
214
215    /// A fragment component was present, including an empty fragment.
216    #[error("issuer identifier must not contain a fragment")]
217    FragmentNotAllowed,
218}
219
220fn validate_issuer_id(value: &str) -> Result<(), IssuerIdError> {
221    if value.is_empty() {
222        return Err(IssuerIdError::Empty);
223    }
224    if value.len() > IssuerId::MAX_LEN {
225        return Err(IssuerIdError::TooLong {
226            max: IssuerId::MAX_LEN,
227            actual: value.len(),
228        });
229    }
230
231    let uri = Uri::parse(value).map_err(|_| IssuerIdError::InvalidUri)?;
232    if !uri.scheme().as_str().eq_ignore_ascii_case("https") {
233        return Err(IssuerIdError::UnsupportedScheme);
234    }
235
236    let authority = uri.authority().ok_or(IssuerIdError::MissingAuthority)?;
237    if authority.host().is_empty() {
238        return Err(IssuerIdError::MissingAuthority);
239    }
240    if authority.userinfo().is_some() {
241        return Err(IssuerIdError::UserInfoNotAllowed);
242    }
243    if authority
244        .port()
245        .is_some_and(|port| port.is_empty() || authority.port_to_u16().is_err())
246    {
247        return Err(IssuerIdError::InvalidPort);
248    }
249    if uri.query().is_some() {
250        return Err(IssuerIdError::QueryNotAllowed);
251    }
252    if uri.fragment().is_some() {
253        return Err(IssuerIdError::FragmentNotAllowed);
254    }
255
256    Ok(())
257}
258
259/// A bounded, case-sensitive OIDC subject identifier.
260///
261/// Subject IDs contain 1 to 255 printable ASCII bytes. OIDC allows at most 255
262/// ASCII characters; `StateKnot` additionally rejects control bytes so the
263/// value is safe to persist across supported database/text boundaries. The
264/// value remains opaque and is never normalized or treated as a username.
265#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
266pub struct SubjectId(Box<str>);
267
268impl SubjectId {
269    /// Maximum encoded length in bytes.
270    pub const MAX_LEN: usize = 255;
271
272    /// Validates and constructs an opaque subject identifier.
273    ///
274    /// # Errors
275    ///
276    /// Returns [`SubjectIdError`] when `value` is empty, too long, non-ASCII,
277    /// or contains an ASCII control byte.
278    pub fn new(value: impl Into<String>) -> Result<Self, SubjectIdError> {
279        let value = value.into();
280        validate_subject_id(&value)?;
281        Ok(Self(value.into_boxed_str()))
282    }
283
284    /// Returns the exact, case-sensitive subject value.
285    #[must_use]
286    pub fn as_str(&self) -> &str {
287        &self.0
288    }
289}
290
291impl AsRef<str> for SubjectId {
292    fn as_ref(&self) -> &str {
293        self.as_str()
294    }
295}
296
297impl Borrow<str> for SubjectId {
298    fn borrow(&self) -> &str {
299        self.as_str()
300    }
301}
302
303impl fmt::Debug for SubjectId {
304    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
305        formatter
306            .debug_struct("SubjectId")
307            .field("byte_len", &self.as_str().len())
308            .field("value", &"<redacted>")
309            .finish()
310    }
311}
312
313impl FromStr for SubjectId {
314    type Err = SubjectIdError;
315
316    fn from_str(value: &str) -> Result<Self, Self::Err> {
317        Self::new(value)
318    }
319}
320
321impl TryFrom<String> for SubjectId {
322    type Error = SubjectIdError;
323
324    fn try_from(value: String) -> Result<Self, Self::Error> {
325        Self::new(value)
326    }
327}
328
329impl TryFrom<&str> for SubjectId {
330    type Error = SubjectIdError;
331
332    fn try_from(value: &str) -> Result<Self, Self::Error> {
333        Self::new(value)
334    }
335}
336
337impl From<SubjectId> for String {
338    fn from(value: SubjectId) -> Self {
339        value.0.into()
340    }
341}
342
343impl Serialize for SubjectId {
344    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
345    where
346        S: Serializer,
347    {
348        serializer.serialize_str(self.as_str())
349    }
350}
351
352impl<'de> Deserialize<'de> for SubjectId {
353    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
354    where
355        D: Deserializer<'de>,
356    {
357        deserializer.deserialize_string(SubjectIdVisitor)
358    }
359}
360
361struct SubjectIdVisitor;
362
363impl de::Visitor<'_> for SubjectIdVisitor {
364    type Value = SubjectId;
365
366    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
367        formatter.write_str("a bounded printable-ASCII OIDC subject identifier")
368    }
369
370    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
371    where
372        E: de::Error,
373    {
374        SubjectId::try_from(value).map_err(E::custom)
375    }
376
377    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
378    where
379        E: de::Error,
380    {
381        SubjectId::try_from(value).map_err(E::custom)
382    }
383}
384
385impl JsonSchema for SubjectId {
386    fn schema_name() -> std::borrow::Cow<'static, str> {
387        "SubjectId".into()
388    }
389
390    fn schema_id() -> std::borrow::Cow<'static, str> {
391        concat!(module_path!(), "::SubjectId").into()
392    }
393
394    fn json_schema(_: &mut SchemaGenerator) -> Schema {
395        json_schema!({
396            "type": "string",
397            "minLength": 1,
398            "maxLength": 255,
399            "pattern": SUBJECT_ID_PATTERN
400        })
401    }
402
403    fn inline_schema() -> bool {
404        true
405    }
406}
407
408/// Validation failure for a [`SubjectId`].
409#[derive(Clone, Debug, Eq, Error, PartialEq)]
410#[non_exhaustive]
411pub enum SubjectIdError {
412    /// The identifier contained no bytes.
413    #[error("subject identifier must not be empty")]
414    Empty,
415
416    /// The identifier exceeded [`SubjectId::MAX_LEN`].
417    #[error("subject identifier is {actual} bytes; maximum is {max}")]
418    TooLong {
419        /// Maximum accepted byte length.
420        max: usize,
421        /// Observed byte length.
422        actual: usize,
423    },
424
425    /// A byte was not printable ASCII.
426    #[error("subject identifier contains a non-printable-ASCII byte at offset {index}")]
427    InvalidByte {
428        /// Zero-based byte offset of the first invalid byte.
429        index: usize,
430    },
431}
432
433fn validate_subject_id(value: &str) -> Result<(), SubjectIdError> {
434    if value.is_empty() {
435        return Err(SubjectIdError::Empty);
436    }
437    if value.len() > SubjectId::MAX_LEN {
438        return Err(SubjectIdError::TooLong {
439            max: SubjectId::MAX_LEN,
440            actual: value.len(),
441        });
442    }
443
444    if let Some((index, _)) = value
445        .bytes()
446        .enumerate()
447        .find(|(_, byte)| !(0x20..=0x7e).contains(byte))
448    {
449        return Err(SubjectIdError::InvalidByte { index });
450    }
451
452    Ok(())
453}
454
455/// The stable external identity of an authenticated principal.
456///
457/// OIDC guarantees uniqueness and stability only for the issuer/subject pair.
458/// Tenant boundaries remain separate and must still be included in storage
459/// keys and authorization decisions.
460#[derive(
461    Clone, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
462)]
463#[serde(deny_unknown_fields)]
464pub struct PrincipalIdentity {
465    issuer: IssuerId,
466    subject: SubjectId,
467}
468
469impl PrincipalIdentity {
470    /// Constructs an identity from already validated components.
471    #[must_use]
472    pub const fn new(issuer: IssuerId, subject: SubjectId) -> Self {
473        Self { issuer, subject }
474    }
475
476    /// Returns the exact authenticated issuer.
477    #[must_use]
478    pub const fn issuer(&self) -> &IssuerId {
479        &self.issuer
480    }
481
482    /// Returns the issuer-local subject.
483    #[must_use]
484    pub const fn subject(&self) -> &SubjectId {
485        &self.subject
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use serde_json::{Value, from_value, json, to_value};
493
494    const ISSUER: &str = "https://issuer.example.com/tenant";
495
496    #[test]
497    fn issuer_ids_preserve_exact_oidc_identity_text() {
498        for value in [
499            "https://issuer.example.com",
500            "https://issuer.example.com/",
501            ISSUER,
502            "https://issuer.example.com:8443/tenant",
503            "HTTPS://ISSUER.example.com:443/a/../tenant",
504            "https://issuer.example.com/%7Etenant",
505        ] {
506            let issuer = value.parse::<IssuerId>().unwrap();
507            assert_eq!(issuer.as_str(), value);
508            assert_eq!(issuer.to_string(), value);
509            assert_eq!(to_value(&issuer).unwrap(), Value::from(value));
510        }
511
512        let lowercase = "https://issuer.example.com".parse::<IssuerId>().unwrap();
513        let uppercase = "HTTPS://ISSUER.example.com".parse::<IssuerId>().unwrap();
514        let slash = "https://issuer.example.com/".parse::<IssuerId>().unwrap();
515        let default_port = "https://issuer.example.com:443"
516            .parse::<IssuerId>()
517            .unwrap();
518        assert_ne!(lowercase, uppercase);
519        assert_ne!(lowercase, slash);
520        assert_ne!(lowercase, default_port);
521
522        let prefix = "https://issuer.example.com/";
523        let maximum = format!("{prefix}{}", "a".repeat(IssuerId::MAX_LEN - prefix.len()));
524        assert_eq!(maximum.len(), IssuerId::MAX_LEN);
525        assert_eq!(maximum.parse::<IssuerId>().unwrap().as_str(), maximum);
526    }
527
528    #[test]
529    fn issuer_ids_reject_non_oidc_urls() {
530        for value in [
531            "issuer.example.com",
532            "http://issuer.example.com",
533            "https:/issuer.example.com",
534            "https://",
535            "https://issuer.example.com:",
536            "https://issuer.example.com:65536",
537            "https://user@issuer.example.com",
538            "https://issuer.example.com?",
539            "https://issuer.example.com?tenant=one",
540            "https://issuer.example.com#",
541            "https://issuer.example.com#fragment",
542            "https://例子.example.com",
543        ] {
544            assert!(value.parse::<IssuerId>().is_err(), "accepted {value:?}");
545        }
546
547        let oversized = format!(
548            "https://issuer.example.com/{}",
549            "a".repeat(IssuerId::MAX_LEN)
550        );
551        assert_eq!(
552            oversized.parse::<IssuerId>(),
553            Err(IssuerIdError::TooLong {
554                max: IssuerId::MAX_LEN,
555                actual: oversized.len(),
556            })
557        );
558    }
559
560    #[test]
561    fn issuer_id_serde_and_schema_enforce_the_wire_contract() {
562        let issuer = ISSUER.parse::<IssuerId>().unwrap();
563        assert_eq!(from_value::<IssuerId>(json!(ISSUER)).unwrap(), issuer);
564        assert!(from_value::<IssuerId>(json!(42)).is_err());
565        assert!(from_value::<IssuerId>(Value::Null).is_err());
566
567        let schema = to_value(schemars::schema_for!(IssuerId)).unwrap();
568        assert_eq!(schema["type"], "string");
569        assert_eq!(schema["format"], "uri");
570        assert_eq!(schema["minLength"], 9);
571        assert_eq!(schema["maxLength"], IssuerId::MAX_LEN);
572        assert_eq!(schema["pattern"], ISSUER_ID_PATTERN);
573    }
574
575    #[test]
576    fn subject_ids_are_opaque_case_sensitive_and_redacted_in_debug() {
577        let all_printable_ascii = (0x20_u8..=0x7e).map(char::from).collect::<String>();
578        assert_eq!(
579            all_printable_ascii.parse::<SubjectId>().unwrap().as_str(),
580            all_printable_ascii
581        );
582
583        for value in [
584            "24400320",
585            "AItOawmwtWwcT0k51BayewNvutrJUqsvl6qs7A4",
586            "User Name",
587            "subject:\"quoted\"\\opaque",
588        ] {
589            let subject = value.parse::<SubjectId>().unwrap();
590            assert_eq!(subject.as_str(), value);
591            assert_eq!(to_value(&subject).unwrap(), Value::from(value));
592            let debug = format!("{subject:?}");
593            assert!(!debug.contains(value));
594            assert!(debug.contains("<redacted>"));
595        }
596
597        assert_ne!(
598            "subject".parse::<SubjectId>().unwrap(),
599            "Subject".parse::<SubjectId>().unwrap()
600        );
601
602        let maximum = "a".repeat(SubjectId::MAX_LEN);
603        assert_eq!(maximum.parse::<SubjectId>().unwrap().as_str(), maximum);
604    }
605
606    #[test]
607    fn subject_ids_reject_empty_control_unicode_and_oversized_values() {
608        assert_eq!("".parse::<SubjectId>(), Err(SubjectIdError::Empty));
609        assert_eq!(
610            "a".repeat(SubjectId::MAX_LEN + 1).parse::<SubjectId>(),
611            Err(SubjectIdError::TooLong {
612                max: SubjectId::MAX_LEN,
613                actual: SubjectId::MAX_LEN + 1,
614            })
615        );
616
617        for byte in 0_u8..=0x7f {
618            if (0x20..=0x7e).contains(&byte) {
619                continue;
620            }
621            let value = String::from_utf8(vec![byte]).unwrap();
622            assert_eq!(
623                value.parse::<SubjectId>(),
624                Err(SubjectIdError::InvalidByte { index: 0 }),
625                "accepted ASCII byte 0x{byte:02x}"
626            );
627        }
628        assert_eq!(
629            "用户".parse::<SubjectId>(),
630            Err(SubjectIdError::InvalidByte { index: 0 })
631        );
632    }
633
634    #[test]
635    fn subject_id_serde_and_schema_enforce_the_wire_contract() {
636        let subject = "subject-42".parse::<SubjectId>().unwrap();
637        assert_eq!(
638            from_value::<SubjectId>(json!(subject.as_str())).unwrap(),
639            subject
640        );
641        assert!(from_value::<SubjectId>(json!(42)).is_err());
642        assert!(from_value::<SubjectId>(Value::Null).is_err());
643
644        let schema = to_value(schemars::schema_for!(SubjectId)).unwrap();
645        assert_eq!(schema["type"], "string");
646        assert_eq!(schema["minLength"], 1);
647        assert_eq!(schema["maxLength"], SubjectId::MAX_LEN);
648        assert_eq!(schema["pattern"], SUBJECT_ID_PATTERN);
649    }
650
651    #[test]
652    fn principal_identity_requires_the_exact_issuer_subject_pair() {
653        let issuer = ISSUER.parse::<IssuerId>().unwrap();
654        let subject = "subject-42".parse::<SubjectId>().unwrap();
655        let identity = PrincipalIdentity::new(issuer.clone(), subject.clone());
656
657        assert_eq!(identity.issuer(), &issuer);
658        assert_eq!(identity.subject(), &subject);
659        assert_eq!(
660            to_value(&identity).unwrap(),
661            json!({ "issuer": ISSUER, "subject": "subject-42" })
662        );
663        let debug = format!("{identity:?}");
664        assert!(debug.contains(ISSUER));
665        assert!(!debug.contains(subject.as_str()));
666        assert!(debug.contains("<redacted>"));
667        assert_ne!(
668            identity,
669            PrincipalIdentity::new(
670                "https://other.example.com".parse().unwrap(),
671                subject.clone()
672            )
673        );
674
675        for invalid in [
676            json!({ "issuer": ISSUER }),
677            json!({ "subject": "subject-42" }),
678            json!({ "issuer": ISSUER, "subject": "subject-42", "extra": true }),
679            json!({ "issuer": "http://issuer.example.com", "subject": "subject-42" }),
680            json!({ "issuer": ISSUER, "subject": "subject\n42" }),
681            Value::Null,
682        ] {
683            assert!(
684                from_value::<PrincipalIdentity>(invalid.clone()).is_err(),
685                "PrincipalIdentity accepted {invalid}"
686            );
687        }
688
689        let schema = to_value(schemars::schema_for!(PrincipalIdentity)).unwrap();
690        assert_eq!(schema["type"], "object");
691        assert_eq!(schema["additionalProperties"], false);
692        assert_eq!(schema["required"], json!(["issuer", "subject"]));
693        assert_eq!(schema["properties"]["issuer"]["pattern"], ISSUER_ID_PATTERN);
694        assert_eq!(
695            schema["properties"]["subject"]["pattern"],
696            SUBJECT_ID_PATTERN
697        );
698    }
699}