entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Conditional-access policy evaluation. Pure.
//!
//! A tenant defines a set of [`Policy`] rules. Each rule has [`Conditions`]
//! (who / which app / from where / device state / risk) and, when they all
//! match a sign-in, an [`Effect`] — either block the sign-in outright or grant
//! it subject to a set of [`GrantControl`]s the session must satisfy (MFA, a
//! passkey, a compliant device).
//!
//! [`evaluate`] combines every matching policy into one [`Verdict`] with a
//! fail-closed precedence: **any block wins**; otherwise the required grant
//! controls from all matching grant policies are unioned, the ones the session
//! already satisfies are removed, and what remains is a step-up requirement.
//! No matching policy means "allow" (the tenant opted every uncovered sign-in
//! through) — callers that want deny-by-default add a catch-all block policy.
//!
//! The evaluator is transport- and storage-free: the caller resolves the
//! sign-in facts (the principal's groups, the client IP, whether the device is
//! compliant, the risk score) into an [`AccessRequest`] and owns any writes.
#![allow(clippy::doc_markdown)]

use core::fmt;
use std::net::IpAddr;

/// Device posture the caller resolved for this sign-in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeviceState {
    /// The device is not registered in the directory.
    Unknown,
    /// The device is registered but not attested compliant.
    Registered,
    /// The device is registered and meets the compliance bar.
    Compliant,
}

/// Risk level the caller resolved for this sign-in (ascending severity).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum RiskLevel {
    /// No elevated risk detected.
    None,
    /// Low risk.
    Low,
    /// Medium risk.
    Medium,
    /// High risk.
    High,
}

/// Authentication strength already satisfied by the current session.
#[derive(Debug, Clone, Copy, Default)]
pub struct AuthnStrength {
    /// A second factor (TOTP / etc.) has been verified this session.
    pub mfa: bool,
    /// A passkey / WebAuthn assertion has been verified this session.
    pub passkey: bool,
}

/// The resolved facts of one sign-in, evaluated against the policy set.
#[derive(Debug, Clone, Copy)]
pub struct AccessRequest<'a> {
    /// The signing-in user's id.
    pub user_id: &'a str,
    /// The user's effective group ids.
    pub group_ids: &'a [String],
    /// The target application (OAuth client id) being accessed.
    pub client_id: &'a str,
    /// The client IP, if known (used by network conditions).
    pub ip: Option<IpAddr>,
    /// The device posture.
    pub device: DeviceState,
    /// The resolved risk level.
    pub risk: RiskLevel,
    /// Authentication strength already satisfied this session.
    pub authn: AuthnStrength,
}

/// A set of principals / apps a condition includes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Selector {
    /// Matches every principal / app.
    All,
    /// Matches only the listed ids.
    Ids(Vec<String>),
}

impl Selector {
    /// Whether `id` is selected, or `id` is any of `ids` (group membership).
    fn matches_any(&self, ids: &[&str]) -> bool {
        match self {
            Self::All => true,
            Self::Ids(list) => list.iter().any(|l| ids.contains(&l.as_str())),
        }
    }
}

/// An IPv4 or IPv6 CIDR block for network conditions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IpCidr {
    /// The network address.
    base: IpAddr,
    /// The prefix length in bits.
    prefix: u8,
}

impl IpCidr {
    /// Parse a `addr/prefix` CIDR (e.g. `10.0.0.0/8`, `2001:db8::/32`). A bare
    /// address with no `/` is treated as a host route (`/32` or `/128`).
    ///
    /// # Errors
    ///
    /// Returns [`CidrParseError`] if the address or prefix is malformed or the
    /// prefix exceeds the address width.
    pub fn parse(s: &str) -> Result<Self, CidrParseError> {
        let (addr_str, prefix) = match s.split_once('/') {
            Some((a, p)) => (a, Some(p)),
            None => (s, None),
        };
        let base: IpAddr = addr_str.parse().map_err(|_| CidrParseError::Address)?;
        let max = if base.is_ipv4() { 32 } else { 128 };
        let prefix = match prefix {
            Some(p) => p.parse::<u8>().map_err(|_| CidrParseError::Prefix)?,
            None => max,
        };
        if prefix > max {
            return Err(CidrParseError::Prefix);
        }
        Ok(Self { base, prefix })
    }

    /// Whether `ip` falls within this CIDR block. A v4/v6 family mismatch is
    /// never a match.
    #[must_use]
    pub fn contains(&self, ip: IpAddr) -> bool {
        match (self.base, ip) {
            (IpAddr::V4(base), IpAddr::V4(ip)) => masked(&base.octets(), &ip.octets(), self.prefix),
            (IpAddr::V6(base), IpAddr::V6(ip)) => masked(&base.octets(), &ip.octets(), self.prefix),
            _ => false,
        }
    }
}

/// Compare the first `prefix` bits of two big-endian address byte strings.
fn masked(base: &[u8], ip: &[u8], prefix: u8) -> bool {
    let full = usize::from(prefix / 8);
    if base[..full] != ip[..full] {
        return false;
    }
    let rem = prefix % 8;
    if rem == 0 {
        return true;
    }
    let mask = 0xffu8 << (8 - rem);
    (base[full] & mask) == (ip[full] & mask)
}

/// Why a CIDR string failed to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CidrParseError {
    /// The address part is not a valid IPv4/IPv6 address.
    Address,
    /// The prefix is not a valid length for the address family.
    Prefix,
}

impl fmt::Display for CidrParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Address => f.write_str("invalid CIDR address"),
            Self::Prefix => f.write_str("invalid CIDR prefix length"),
        }
    }
}

impl std::error::Error for CidrParseError {}

/// The conditions that must ALL hold for a policy to apply to a sign-in.
///
/// Every field is optional in effect: an `All` selector, an empty exclude
/// list, an empty network / device list, or a `None` risk floor imposes no
/// constraint on that dimension.
#[derive(Debug, Clone)]
pub struct Conditions {
    /// Users the policy targets.
    pub include_users: Selector,
    /// Users exempt from the policy (wins over `include_users`).
    pub exclude_users: Vec<String>,
    /// Groups the policy targets (matched against the request's group ids).
    pub include_groups: Selector,
    /// Groups exempt from the policy.
    pub exclude_groups: Vec<String>,
    /// Apps the policy targets.
    pub include_apps: Selector,
    /// Apps exempt from the policy.
    pub exclude_apps: Vec<String>,
    /// If non-empty, the sign-in IP must fall in one of these blocks. A
    /// request with no IP never matches a non-empty network list.
    pub include_networks: Vec<IpCidr>,
    /// If the sign-in IP falls in one of these blocks the policy does not
    /// apply (trusted-network exemption).
    pub exclude_networks: Vec<IpCidr>,
    /// If non-empty, the device posture must be one of these states.
    pub device_in: Vec<DeviceState>,
    /// If set, the policy applies only when risk is at least this level.
    pub min_risk: Option<RiskLevel>,
}

impl Default for Conditions {
    /// An unconstrained condition set (matches every sign-in).
    fn default() -> Self {
        Self {
            include_users: Selector::All,
            exclude_users: Vec::new(),
            include_groups: Selector::All,
            exclude_groups: Vec::new(),
            include_apps: Selector::All,
            exclude_apps: Vec::new(),
            include_networks: Vec::new(),
            exclude_networks: Vec::new(),
            device_in: Vec::new(),
            min_risk: None,
        }
    }
}

impl Conditions {
    /// Whether every condition holds for `req`.
    #[must_use]
    pub fn matches(&self, req: &AccessRequest<'_>) -> bool {
        // Users: include must hold, exclude must not.
        if !self.include_users.matches_any(&[req.user_id]) {
            return false;
        }
        if self.exclude_users.iter().any(|u| u == req.user_id) {
            return false;
        }
        // Groups: the request carries the principal's group ids.
        let groups: Vec<&str> = req.group_ids.iter().map(String::as_str).collect();
        if !self.include_groups.matches_any(&groups) {
            return false;
        }
        if self
            .exclude_groups
            .iter()
            .any(|g| groups.contains(&g.as_str()))
        {
            return false;
        }
        // Apps.
        if !self.include_apps.matches_any(&[req.client_id]) {
            return false;
        }
        if self.exclude_apps.iter().any(|a| a == req.client_id) {
            return false;
        }
        // Networks: an exclude match exempts; a non-empty include must match.
        if let Some(ip) = req.ip {
            if self.exclude_networks.iter().any(|c| c.contains(ip)) {
                return false;
            }
        }
        if !self.include_networks.is_empty() {
            let Some(ip) = req.ip else { return false };
            if !self.include_networks.iter().any(|c| c.contains(ip)) {
                return false;
            }
        }
        // Device posture.
        if !self.device_in.is_empty() && !self.device_in.contains(&req.device) {
            return false;
        }
        // Risk floor.
        if let Some(min) = self.min_risk {
            if req.risk < min {
                return false;
            }
        }
        true
    }
}

/// A control the session must satisfy for a grant policy to allow the sign-in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GrantControl {
    /// Require multi-factor authentication.
    Mfa,
    /// Require a passkey / WebAuthn assertion.
    Passkey,
    /// Require a directory-compliant device.
    CompliantDevice,
}

impl GrantControl {
    /// A short, stable diagnostic string.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Mfa => "mfa",
            Self::Passkey => "passkey",
            Self::CompliantDevice => "compliant_device",
        }
    }

    /// Whether the sign-in already satisfies this control.
    fn satisfied_by(self, req: &AccessRequest<'_>) -> bool {
        match self {
            Self::Mfa => req.authn.mfa,
            Self::Passkey => req.authn.passkey,
            Self::CompliantDevice => req.device == DeviceState::Compliant,
        }
    }
}

/// What a matching policy does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
    /// Block the sign-in outright.
    Block,
    /// Allow the sign-in subject to satisfying every listed control.
    Grant(Vec<GrantControl>),
}

/// One conditional-access rule.
#[derive(Debug, Clone)]
pub struct Policy {
    /// A stable identifier (surfaced in the verdict when a policy blocks).
    pub id: String,
    /// Whether the policy is active (disabled policies are skipped).
    pub enabled: bool,
    /// The conditions under which the policy applies.
    pub conditions: Conditions,
    /// The effect when the conditions match.
    pub effect: Effect,
}

/// The combined outcome of evaluating the policy set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// Allow the sign-in with no further requirement.
    Allow,
    /// Block the sign-in; carries the id of the first policy that blocked.
    Block {
        /// The id of the blocking policy.
        policy_id: String,
    },
    /// Allow only after the session satisfies these still-unmet controls.
    StepUp(Vec<GrantControl>),
}

/// Evaluate every policy against `req` and combine into one verdict. Pure.
///
/// Precedence (fail-closed): any matching [`Effect::Block`] yields
/// [`Verdict::Block`]. Otherwise the required controls of all matching
/// [`Effect::Grant`] policies are unioned; those the session already satisfies
/// are dropped; any remaining controls yield [`Verdict::StepUp`], else
/// [`Verdict::Allow`]. Disabled policies and non-matching policies are ignored.
#[must_use]
pub fn evaluate(policies: &[Policy], req: &AccessRequest<'_>) -> Verdict {
    let mut required: Vec<GrantControl> = Vec::new();
    for p in policies {
        if !p.enabled || !p.conditions.matches(req) {
            continue;
        }
        match &p.effect {
            Effect::Block => {
                return Verdict::Block {
                    policy_id: p.id.clone(),
                };
            }
            Effect::Grant(controls) => {
                for &c in controls {
                    if !required.contains(&c) {
                        required.push(c);
                    }
                }
            }
        }
    }
    let unmet: Vec<GrantControl> = required
        .into_iter()
        .filter(|c| !c.satisfied_by(req))
        .collect();
    if unmet.is_empty() {
        Verdict::Allow
    } else {
        Verdict::StepUp(unmet)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn req<'a>(groups: &'a [String], client: &'a str) -> AccessRequest<'a> {
        AccessRequest {
            user_id: "u1",
            group_ids: groups,
            client_id: client,
            ip: None,
            device: DeviceState::Unknown,
            risk: RiskLevel::None,
            authn: AuthnStrength::default(),
        }
    }

    fn grant(id: &str, conditions: Conditions, controls: Vec<GrantControl>) -> Policy {
        Policy {
            id: id.to_string(),
            enabled: true,
            conditions,
            effect: Effect::Grant(controls),
        }
    }

    #[test]
    fn no_policies_allows() {
        let g = vec![];
        assert_eq!(evaluate(&[], &req(&g, "app")), Verdict::Allow);
    }

    #[test]
    fn block_wins_over_grant() {
        let g = vec![];
        let policies = vec![
            grant("g", Conditions::default(), vec![GrantControl::Mfa]),
            Policy {
                id: "block".into(),
                enabled: true,
                conditions: Conditions::default(),
                effect: Effect::Block,
            },
        ];
        assert_eq!(
            evaluate(&policies, &req(&g, "app")),
            Verdict::Block {
                policy_id: "block".into()
            }
        );
    }

    #[test]
    fn unmet_control_steps_up() {
        let g = vec![];
        let p = vec![grant(
            "g",
            Conditions::default(),
            vec![GrantControl::Mfa, GrantControl::Passkey],
        )];
        assert_eq!(
            evaluate(&p, &req(&g, "app")),
            Verdict::StepUp(vec![GrantControl::Mfa, GrantControl::Passkey])
        );
    }

    #[test]
    fn satisfied_control_allows() {
        let g = vec![];
        let mut r = req(&g, "app");
        r.authn.mfa = true;
        let p = vec![grant("g", Conditions::default(), vec![GrantControl::Mfa])];
        assert_eq!(evaluate(&p, &r), Verdict::Allow);
    }

    #[test]
    fn disabled_policy_ignored() {
        let g = vec![];
        let p = vec![Policy {
            id: "b".into(),
            enabled: false,
            conditions: Conditions::default(),
            effect: Effect::Block,
        }];
        assert_eq!(evaluate(&p, &req(&g, "app")), Verdict::Allow);
    }

    #[test]
    fn group_scoped_policy_matches_only_members() {
        let admins = vec!["g-admin".to_string()];
        let others = vec!["g-other".to_string()];
        let c = Conditions {
            include_groups: Selector::Ids(vec!["g-admin".into()]),
            ..Conditions::default()
        };
        let p = vec![grant("g", c, vec![GrantControl::Mfa])];
        assert_eq!(
            evaluate(&p, &req(&admins, "app")),
            Verdict::StepUp(vec![GrantControl::Mfa])
        );
        assert_eq!(evaluate(&p, &req(&others, "app")), Verdict::Allow);
    }

    #[test]
    fn exclude_user_exempts() {
        let g = vec![];
        let c = Conditions {
            exclude_users: vec!["u1".into()],
            ..Conditions::default()
        };
        let p = vec![Policy {
            id: "b".into(),
            enabled: true,
            conditions: c,
            effect: Effect::Block,
        }];
        assert_eq!(evaluate(&p, &req(&g, "app")), Verdict::Allow);
    }

    #[test]
    fn cidr_v4_contains() {
        let c = IpCidr::parse("10.0.0.0/8").unwrap();
        assert!(c.contains("10.1.2.3".parse().unwrap()));
        assert!(!c.contains("11.0.0.1".parse().unwrap()));
    }

    #[test]
    fn cidr_v6_and_host_route() {
        let c = IpCidr::parse("2001:db8::/32").unwrap();
        assert!(c.contains("2001:db8::1".parse().unwrap()));
        assert!(!c.contains("2001:dead::1".parse().unwrap()));
        let host = IpCidr::parse("192.168.1.5").unwrap();
        assert!(host.contains("192.168.1.5".parse().unwrap()));
        assert!(!host.contains("192.168.1.6".parse().unwrap()));
        assert!(!c.contains("10.0.0.1".parse().unwrap())); // family mismatch
    }

    #[test]
    fn network_include_requires_ip_in_block() {
        let g = vec![];
        let c = Conditions {
            include_networks: vec![IpCidr::parse("203.0.113.0/24").unwrap()],
            ..Conditions::default()
        };
        let p = vec![Policy {
            id: "b".into(),
            enabled: true,
            conditions: c,
            effect: Effect::Block,
        }];
        let mut inside = req(&g, "app");
        inside.ip = Some("203.0.113.9".parse().unwrap());
        assert!(matches!(evaluate(&p, &inside), Verdict::Block { .. }));
        let mut outside = req(&g, "app");
        outside.ip = Some("198.51.100.1".parse().unwrap());
        assert_eq!(evaluate(&p, &outside), Verdict::Allow);
        // No IP never matches a network-scoped policy.
        assert_eq!(evaluate(&p, &req(&g, "app")), Verdict::Allow);
    }

    #[test]
    fn risk_floor_gates() {
        let g = vec![];
        let c = Conditions {
            min_risk: Some(RiskLevel::Medium),
            ..Conditions::default()
        };
        let p = vec![grant("g", c, vec![GrantControl::Mfa])];
        let mut low = req(&g, "app");
        low.risk = RiskLevel::Low;
        assert_eq!(evaluate(&p, &low), Verdict::Allow);
        let mut high = req(&g, "app");
        high.risk = RiskLevel::High;
        assert_eq!(
            evaluate(&p, &high),
            Verdict::StepUp(vec![GrantControl::Mfa])
        );
    }

    #[test]
    fn compliant_device_control() {
        let g = vec![];
        let p = vec![grant(
            "g",
            Conditions::default(),
            vec![GrantControl::CompliantDevice],
        )];
        let mut unknown = req(&g, "app");
        unknown.device = DeviceState::Registered;
        assert_eq!(
            evaluate(&p, &unknown),
            Verdict::StepUp(vec![GrantControl::CompliantDevice])
        );
        let mut ok = req(&g, "app");
        ok.device = DeviceState::Compliant;
        assert_eq!(evaluate(&p, &ok), Verdict::Allow);
    }
}