Skip to main content

kumo_server_common/
authn_authz.rs

1use crate::acct::{log_authz, AuditLogParams};
2use crate::http_server::auth::HttpEndpointResource;
3use async_trait::async_trait;
4use axum::extract::FromRequestParts;
5use axum::http::{StatusCode, Uri};
6use chrono::Utc;
7use cidr_map::CidrSet;
8use config::{
9    any_err, get_or_create_sub_module, load_config, serialize_options, SerdeWrappedValue,
10};
11use data_loader::KeySource;
12use kumo_chrono_helper::DateTime;
13use mlua::prelude::LuaUserData;
14use mlua::{Lua, LuaSerdeExt, UserDataFields, UserDataMethods, UserDataRef};
15use mod_memoize::Memoized;
16use serde::{Deserialize, Serialize};
17use std::collections::HashMap;
18use std::net::{IpAddr, Ipv4Addr};
19use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
20use std::sync::{Arc, LazyLock};
21use std::time::Duration;
22
23static ACL_MAP: LazyLock<AccessControlListMap> =
24    LazyLock::new(|| AccessControlListMap::compiled_default());
25static FALL_BACK_TO_ACL_MAP: AtomicBool = AtomicBool::new(true);
26
27lruttl::declare_cache! {
28static ACL_CACHE: LruCacheWithTtl<String, AccessControlListCacheEntry>::new("acl_definition", 128);
29}
30static ACL_CACHE_TTL_MS: AtomicUsize = AtomicUsize::new(300);
31
32lruttl::declare_cache! {
33static CHECK_CACHE: LruCacheWithTtl<CheckKey, AuditRecord>::new("acl_check", 128);
34}
35static CHECK_CACHE_TTL_MS: AtomicUsize = AtomicUsize::new(300);
36
37config::declare_event! {
38static GET_ACL_DEF_SIG: Multiple(
39    "get_acl_definition",
40    resource: &'static str
41) -> Option<UserDataRef<AccessControlListWrap>>;
42}
43
44// TODO:
45//  * Formalize object mapping. For example, in kumod we should map
46//    scheduled queues to some kind of object hierarchy. The default should
47//    be something like:
48//       scheduled_queues (as a container for all scheduled queues)
49//          tenant_<tenant>_queues (as a container for all of a tenant's queues)
50//             tenant_<tenant>_<campaign>_queues (contains each of the tenant's campaign queues
51//                <queue_name> - a queue inside a tenant-campaign
52//             <queue_name> - a queue inside a tenant but not a campaign
53//          campaign_<campaign>_queues (contains queues that have campaign but not tenant set)
54//             <queue_name> - a queue inside a campaign but not a tenant
55//          <queue_name> - a queue that has no tenant nor campaign
56//
57//    with those resources mapped out, we can then define ACLs with hierarchy.
58//    eg: `mailops` group has `queue:flush`, `queue:inspect`, `queue:summarize`
59//    privs set to allow on `scheduled_queues` at the top, granting those privs
60//    to all queues
61//
62//    `customer_xyz` group has `queue:summarize` and `queue:relay` set on
63//    `tenant_xyz_queues`, allowing those privs to just their tenant.
64//
65//    Need to sit down and think about what specific privileges these are
66//    for the different sorts of objects, because those will need to be encoded
67//    in the rust logic in a number of cases.  eg: in the smtp server, we'll
68//    need to check any privs that we define that control assignment prior to
69//    enqueuing the message.
70//
71//  * Some customers piggy-back on our tenant and/or campaign identifies to further
72//    sub-divide the queue space, so we need to allow them a way to influence
73//    that object mapping.  eg: one encodes `pool_tenant` in the campaign identifier.
74//    Is that neutral wrt. access control?
75//
76//  * Sanity check that we can apply this model to the things that matter:
77//     * mailops doing queue flushing, bouncing, inspecting
78//     * mailops summarizing queue stats
79//     * smtp client being able to inject mail at all
80//     * smtp client being able to relay to a specific destination. OR: tenant
81//       being allowed to relay to a specific destination.
82//     * smtp client being able to assign a specific tenant
83//     * http client being able to use injection API
84//     * smtp/http client being able to set a specific meta item
85//     * smtp/http client OR tenant having access to a dkim/arc key for signing purposes
86//     * machine being allowed to do message transfer
87//     * socks proxy client being allowed to use a specific source address
88//     * socks proxy client being allowed to connect to a specific destination address
89
90#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
91pub struct Identity {
92    pub identity: String,
93    pub context: IdentityContext,
94}
95
96#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize)]
97pub enum IdentityContext {
98    SmtpAuthPlainAuthentication,
99    SmtpAuthPlainAuthorization,
100    HttpBasicAuth,
101    BearerToken,
102    ProxyAuthRfc1929,
103    LocalSystem,
104    GenericAuth,
105}
106
107#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
108pub struct AuthInfo {
109    /// The peer machine, if known
110    #[serde(default)]
111    pub peer_address: Option<IpAddr>,
112    /// Authenticated identities
113    #[serde(default)]
114    pub identities: Vec<Identity>,
115    /// Any groups to which we might belong
116    #[serde(default)]
117    pub groups: Vec<String>,
118}
119
120impl std::fmt::Display for AuthInfo {
121    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
122        write!(fmt, "{}", self.public_descriptor())
123    }
124}
125
126impl AuthInfo {
127    /// Authentication that represents the local system taking action.
128    /// It should be considered to be the most privileged identity
129    pub fn new_local_system() -> Self {
130        Self {
131            peer_address: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
132            identities: vec![Identity {
133                identity: "kumomta.internal".to_string(),
134                context: IdentityContext::LocalSystem,
135            }],
136            groups: vec![],
137        }
138    }
139
140    pub fn summarize_for_http_auth(&self) -> String {
141        if let Some(ident) = self
142            .identities
143            .iter()
144            .find(|ident| ident.context == IdentityContext::HttpBasicAuth)
145        {
146            return ident.identity.to_string();
147        }
148        if let Some(ident) = self.identities.first() {
149            return ident.identity.to_string();
150        }
151        match &self.peer_address {
152            Some(addr) => addr.to_string(),
153            None => "".to_string(),
154        }
155    }
156
157    /// Summarize the info in a form that should be reasonable to report
158    /// back to a connected peer. This form doesn't include any groups
159    /// that may have been added by the server and/or via policy
160    pub fn public_descriptor(&self) -> String {
161        let mut result = String::new();
162
163        if self.identities.is_empty() {
164            result.push_str("<Unauthenticated>");
165        } else {
166            result.push_str("id=[");
167            for (idx, id) in self.identities.iter().enumerate() {
168                if idx > 0 {
169                    result.push_str(", ");
170                }
171                result.push_str(&id.identity);
172            }
173            result.push(']');
174        }
175        if let Some(peer) = &self.peer_address {
176            result.push_str(&format!("@ ip={peer}"));
177        }
178        result
179    }
180
181    /// Merges groups and identities from other, ignoring its peer_address
182    pub fn merge_from(&mut self, mut other: Self) {
183        self.identities.append(&mut other.identities);
184        self.groups.append(&mut other.groups);
185    }
186
187    /// Add an identity to the list
188    pub fn add_identity(&mut self, identity: Identity) {
189        self.identities.push(identity);
190    }
191
192    pub fn add_group(&mut self, group_name: impl Into<String>) {
193        self.groups.push(group_name.into());
194    }
195
196    /// Set the peer address, ignoring and replacing any prior value
197    pub fn set_peer_address(&mut self, peer_address: Option<IpAddr>) {
198        self.peer_address = peer_address;
199    }
200
201    /// Test to see if this AuthInfo matches a specific identity from an ACL entry
202    pub fn matches_identity(&self, identity: &ACLIdentity) -> bool {
203        match identity {
204            ACLIdentity::Any => true,
205            ACLIdentity::Unauthenticated => self.identities.is_empty(),
206            ACLIdentity::Authenticated => !self.identities.is_empty(),
207            ACLIdentity::Individual(candidate_ident) => {
208                for ident in &self.identities {
209                    if ident.identity == *candidate_ident {
210                        return true;
211                    }
212                }
213                false
214            }
215            ACLIdentity::Group(candidate_group) => self.groups.iter().any(|g| g == candidate_group),
216            ACLIdentity::Machine(candidate_ip) => self
217                .peer_address
218                .as_ref()
219                .map(|ip| ip == candidate_ip)
220                .unwrap_or(false),
221            ACLIdentity::MachineSet(cidr_set) => self
222                .peer_address
223                .as_ref()
224                .map(|ip| cidr_set.contains(*ip))
225                .unwrap_or(false),
226        }
227    }
228
229    pub fn matches_criteria(&self, criteria: &ACLRuleTerm) -> bool {
230        match criteria {
231            ACLRuleTerm::Not(term) => !self.matches_criteria(term),
232            ACLRuleTerm::AnyOf(terms) => terms.iter().any(|term| self.matches_criteria(term)),
233            ACLRuleTerm::AllOf(terms) => terms.iter().all(|term| self.matches_criteria(term)),
234            ACLRuleTerm::Identity(ident) => self.matches_identity(ident),
235        }
236    }
237}
238
239impl<B> FromRequestParts<B> for AuthInfo
240where
241    B: Send + Sync,
242{
243    type Rejection = (StatusCode, &'static str);
244
245    async fn from_request_parts(
246        parts: &mut axum::http::request::Parts,
247        _: &B,
248    ) -> Result<Self, Self::Rejection> {
249        match parts.extensions.get::<AuthInfo>() {
250            Some(info) => Ok(info.clone()),
251            None => Ok(AuthInfo::default()),
252        }
253    }
254}
255
256#[derive(Clone, Debug)]
257enum AccessControlListCacheEntry {
258    None,
259    Hit(Arc<AccessControlList>),
260    Err(String),
261}
262
263#[derive(Hash, PartialEq, Eq, Debug, Clone)]
264struct CheckKey {
265    pub target_resource: String,
266    pub privilege: String,
267    pub auth_info: AuthInfo,
268}
269
270#[derive(Debug, Serialize, Deserialize, Clone)]
271pub struct AuditRecord {
272    /// When the event occurred
273    pub timestamp: DateTime<Utc>,
274    /// The resource being accessed
275    pub target_resource: String,
276    /// The privilege requested
277    pub privilege: String,
278    /// Was access granted or denied?
279    pub access: Access,
280    /// The resource whose ACL provided the decision.
281    /// If None, no rules matched and the decision was to deny by default.
282    pub matching_resource: Option<String>,
283    /// A structured representation of the matching ACL rule
284    pub rule: Option<AccessControlRule>,
285    /// A copy of the authentication information used to make the decision
286    pub auth_info: AuthInfo,
287    /// A list of the resource ids that were considered prior to reaching
288    /// this final disposition; these will be on the inheritance path
289    /// between the target_resource and the matching_resource (or the root,
290    /// if there was no matching_resource).
291    pub considered_resources: Vec<String>,
292}
293
294impl AuditRecord {
295    pub fn new(
296        disposition: &ACLQueryDisposition,
297        target_resource: &str,
298        privilege: &str,
299        info: &AuthInfo,
300        considered_resources: Vec<String>,
301    ) -> Self {
302        let (access, matching_resource, rule) = match disposition {
303            ACLQueryDisposition::Allow { rule, resource } => (
304                Access::Allow,
305                Some(resource.to_string()),
306                Some(rule.clone()),
307            ),
308            ACLQueryDisposition::Deny { rule, resource } => {
309                (Access::Deny, Some(resource.to_string()), Some(rule.clone()))
310            }
311            ACLQueryDisposition::DenyByDefault => (Access::Deny, None, None),
312        };
313
314        Self {
315            target_resource: target_resource.to_string(),
316            privilege: privilege.to_string(),
317            access,
318            matching_resource,
319            rule,
320            auth_info: info.clone(),
321            considered_resources,
322            timestamp: DateTime::now(),
323        }
324    }
325
326    pub fn disposition(&self) -> ACLQueryDisposition {
327        match (&self.matching_resource, &self.rule, self.access) {
328            (None, None, Access::Deny) => ACLQueryDisposition::DenyByDefault,
329            (Some(resource), Some(rule), Access::Allow) => ACLQueryDisposition::Allow {
330                rule: rule.clone(),
331                resource: resource.clone(),
332            },
333            (Some(resource), Some(rule), Access::Deny) => ACLQueryDisposition::Deny {
334                rule: rule.clone(),
335                resource: resource.clone(),
336            },
337            _ => ACLQueryDisposition::DenyByDefault,
338        }
339    }
340}
341
342#[derive(Clone)]
343struct AccessControlListWrap {
344    wrapped_acl: Arc<AccessControlList>,
345}
346impl LuaUserData for AccessControlListWrap {}
347
348/// An access control list for a specific resource
349#[derive(Clone, Debug, Serialize, Deserialize)]
350pub struct AccessControlList {
351    /// An ordered set of rules; the first matching rule
352    /// defines the allowed access level.  If we run
353    /// out of rules, then the caller should proceed to evaluate the
354    /// ACL for the parent resource, if any.
355    pub rules: Vec<AccessControlRule>,
356}
357
358impl AccessControlList {
359    pub async fn query_resource_access(
360        resource: &mut impl Resource,
361        info: &AuthInfo,
362        privilege: &str,
363    ) -> anyhow::Result<ACLQueryDisposition> {
364        let key = CheckKey {
365            auth_info: info.clone(),
366            privilege: privilege.to_string(),
367            target_resource: resource.resource_id().to_string(),
368        };
369
370        let lookup = CHECK_CACHE
371            .get_or_try_insert(&key, |_| get_check_cache_ttl(), async move {
372                let mut considered_resources = vec![];
373
374                while let Some(resource_id) = resource.next_resource_id().await {
375                    tracing::trace!("ACL: consider {resource_id} priv={privilege} {info:?}");
376                    if let Some(acl) = Self::load_for_resource(&resource_id).await? {
377                        let result = acl.query_access(resource_id.clone(), info, privilege);
378                        tracing::trace!(
379                            "ACL: check {resource_id} priv={privilege} {info:?} -> {result:?}"
380                        );
381                        if result != ACLQueryDisposition::DenyByDefault {
382                            let record = AuditRecord::new(
383                                &result,
384                                resource.resource_id(),
385                                privilege,
386                                info,
387                                considered_resources,
388                            );
389
390                            return Ok::<_, anyhow::Error>(record);
391                        }
392                    }
393
394                    considered_resources.push(resource_id);
395                }
396
397                Ok(AuditRecord::new(
398                    &ACLQueryDisposition::DenyByDefault,
399                    resource.resource_id(),
400                    privilege,
401                    info,
402                    considered_resources,
403                ))
404            })
405            .await
406            .map_err(|err| anyhow::anyhow!("{err:#}"))?;
407
408        let mut audit_item = lookup.item.clone();
409        audit_item.timestamp = DateTime::now();
410        log_authz(audit_item).await?;
411        Ok(lookup.item.disposition())
412    }
413
414    fn query_access(
415        &self,
416        resource: String,
417        info: &AuthInfo,
418        privilege: &str,
419    ) -> ACLQueryDisposition {
420        for rule in &self.rules {
421            if !info.matches_criteria(&rule.criteria) {
422                continue;
423            }
424            if rule.privilege != privilege {
425                continue;
426            }
427            return match &rule.access {
428                Access::Allow => ACLQueryDisposition::Allow {
429                    rule: rule.clone(),
430                    resource,
431                },
432                Access::Deny => ACLQueryDisposition::Deny {
433                    rule: rule.clone(),
434                    resource,
435                },
436            };
437        }
438
439        ACLQueryDisposition::DenyByDefault
440    }
441
442    async fn load_for_resource_impl(resource: &str) -> anyhow::Result<Option<Arc<Self>>> {
443        let mut config = load_config().await?;
444        let result = config.call_callback(&GET_ACL_DEF_SIG, resource).await?;
445        config.put();
446
447        if let Some(Some(result)) = result.result {
448            return Ok(Some(result.wrapped_acl.clone()));
449        }
450
451        if !result.handler_was_defined || FALL_BACK_TO_ACL_MAP.load(Ordering::Relaxed) {
452            Ok(ACL_MAP.get(resource))
453        } else {
454            Ok(None)
455        }
456    }
457
458    pub async fn load_for_resource(resource: &str) -> anyhow::Result<Option<Arc<Self>>> {
459        let resource = resource.to_string();
460        match ACL_CACHE
461            .get_or_try_insert(&resource, |_| get_acl_cache_ttl(), {
462                let resource = resource.clone();
463                async move {
464                    match Self::load_for_resource_impl(&resource).await {
465                        Err(err) => Ok::<_, anyhow::Error>(AccessControlListCacheEntry::Err(
466                            format!("{err:#}"),
467                        )),
468                        Ok(Some(result)) => Ok(AccessControlListCacheEntry::Hit(result)),
469                        Ok(None) => Ok(AccessControlListCacheEntry::None),
470                    }
471                }
472            })
473            .await
474        {
475            Err(err) => Err(anyhow::anyhow!("{err:#}")),
476            Ok(lookup) => match lookup.item {
477                AccessControlListCacheEntry::Err(err) => Err(anyhow::anyhow!("{err}")),
478                AccessControlListCacheEntry::None => Ok(None),
479                AccessControlListCacheEntry::Hit(res) => Ok(Some(res)),
480            },
481        }
482    }
483}
484
485pub fn get_acl_cache_ttl() -> Duration {
486    Duration::from_millis(ACL_CACHE_TTL_MS.load(Ordering::Relaxed) as u64)
487}
488pub fn get_check_cache_ttl() -> Duration {
489    Duration::from_millis(CHECK_CACHE_TTL_MS.load(Ordering::Relaxed) as u64)
490}
491
492#[derive(PartialEq, Debug)]
493pub enum ACLQueryDisposition {
494    /// An explicit allow rule matched
495    Allow {
496        resource: String,
497        rule: AccessControlRule,
498    },
499    /// An explicit Deny rule matched
500    Deny {
501        resource: String,
502        rule: AccessControlRule,
503    },
504    /// Exhausted the list of rules for this resource,
505    /// so the behavior is to deny as a default.
506    /// If there is a parent resource, the caller should
507    /// proceed to query that one.
508    DenyByDefault,
509}
510
511impl LuaUserData for ACLQueryDisposition {
512    fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
513        fields.add_field_method_get("allow", move |_lua, this| {
514            Ok(matches!(this, Self::Allow { .. }))
515        });
516        fields.add_field_method_get("rule", move |lua, this| match this {
517            Self::Allow { rule, .. } | Self::Deny { rule, .. } => {
518                lua.to_value_with(rule, serialize_options())
519            }
520            Self::DenyByDefault => Ok(mlua::Value::Nil),
521        });
522        fields.add_field_method_get("resource", move |_lua, this| match this {
523            Self::Allow { resource, .. } | Self::Deny { resource, .. } => {
524                Ok(Some(resource.to_string()))
525            }
526            Self::DenyByDefault => Ok(None),
527        });
528    }
529}
530
531#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
532pub enum ACLIdentity {
533    /// An individual identity
534    Individual(String),
535    /// A Group
536    Group(String),
537    /// A machine
538    Machine(IpAddr),
539    /// A set of machines
540    MachineSet(CidrSet),
541    /// wildcard to match any explicitly authenticated individual
542    Authenticated,
543    /// wildcard to match any unauthenticated session
544    Unauthenticated,
545    /// wildcard to match any thing
546    Any,
547}
548
549impl std::fmt::Display for ACLIdentity {
550    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
551        match self {
552            Self::Authenticated => write!(fmt, "Authenticated"),
553            Self::Unauthenticated => write!(fmt, "Unauthenticated"),
554            Self::Any => write!(fmt, "Any"),
555            Self::Individual(user) => write!(fmt, "{user}"),
556            Self::Group(group) => write!(fmt, "group={group}"),
557            Self::Machine(ip) => write!(fmt, "ip={ip}"),
558            Self::MachineSet(cidr) => write!(fmt, "ip={cidr:?}"),
559        }
560    }
561}
562
563#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
564pub enum Access {
565    Allow,
566    Deny,
567}
568
569#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
570pub enum ACLRuleTerm {
571    AllOf(Vec<ACLRuleTerm>),
572    AnyOf(Vec<ACLRuleTerm>),
573    Not(Box<ACLRuleTerm>),
574    Identity(ACLIdentity),
575}
576
577impl std::fmt::Display for ACLRuleTerm {
578    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
579        match self {
580            Self::AllOf(terms) => {
581                write!(fmt, "AllOf [")?;
582                for (idx, t) in terms.iter().enumerate() {
583                    if idx > 0 {
584                        write!(fmt, ", ")?;
585                    }
586                    t.fmt(fmt)?;
587                }
588                write!(fmt, "]")
589            }
590            Self::AnyOf(terms) => {
591                write!(fmt, "AnyOf [")?;
592                for (idx, t) in terms.iter().enumerate() {
593                    if idx > 0 {
594                        write!(fmt, ", ")?;
595                    }
596                    t.fmt(fmt)?;
597                }
598                write!(fmt, "]")
599            }
600            Self::Not(term) => {
601                write!(fmt, "!{term}")
602            }
603            Self::Identity(ident) => {
604                write!(fmt, "{ident}")
605            }
606        }
607    }
608}
609
610#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
611pub struct AccessControlRule {
612    pub criteria: ACLRuleTerm,
613    pub privilege: String,
614    pub access: Access,
615}
616
617impl std::fmt::Display for AccessControlRule {
618    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
619        write!(
620            fmt,
621            "{} {} {}",
622            self.criteria,
623            match self.access {
624                Access::Allow => "allows",
625                Access::Deny => "denies",
626            },
627            self.privilege
628        )
629    }
630}
631
632/// This trait represents a Resource against which we'd like
633/// to perform an access control check.
634/// Each call to next_resource_id() will produce the identifier
635/// of the resource which is being checked, following its
636/// child -> parent relationship.
637///
638/// So a hypothetical filesystem path resource of `/foo/bar/baz`
639/// would return on each successive call:
640///
641/// `Some("/foo/bar/baz")`
642/// `Some("/foo/bar")`
643/// `Some("/foo")`
644/// `Some("/")`
645/// `None`
646///
647/// so that the ACL checker knows how to resolve the resources
648/// up to their containing root.
649///
650/// This trait is essentially an asynchronous iterator.
651#[async_trait]
652pub trait Resource {
653    /// Returns the resource to which access is desired
654    fn resource_id(&self) -> &str;
655    /// Returns the next resource in the inheritance hierarchy;
656    /// starts with the targeted resource_id and walks through
657    /// its parents.
658    async fn next_resource_id(&mut self) -> Option<String>;
659}
660
661#[derive(Clone)]
662struct AccessControlListMapWrap {
663    wrapped_map: Arc<AccessControlListMap>,
664}
665
666impl LuaUserData for AccessControlListMapWrap {
667    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
668        methods.add_method("get", move |_lua, this, resource: String| {
669            Ok(this
670                .wrapped_map
671                .get(&resource)
672                .map(|acl| AccessControlListWrap { wrapped_acl: acl }))
673        });
674
675        Memoized::impl_memoize(methods);
676    }
677}
678
679#[derive(Default)]
680pub struct AccessControlListMap {
681    map: HashMap<String, Arc<AccessControlList>>,
682}
683
684impl AccessControlListMap {
685    pub fn get(&self, resource: &str) -> Option<Arc<AccessControlList>> {
686        self.map.get(resource).cloned()
687    }
688
689    pub fn compiled_default() -> Self {
690        let acl_file: ACLFile = toml::from_str(include_str!("../../../assets/acls/default.toml"))
691            .expect("default ACL is invalid!");
692        acl_file.build_map()
693    }
694}
695
696#[derive(Deserialize, Serialize, Debug, Clone)]
697#[serde(deny_unknown_fields)]
698struct ACLFile {
699    acl: HashMap<String, Vec<ACLFileEntry>>,
700}
701
702impl ACLFile {
703    fn build_map(self) -> AccessControlListMap {
704        let mut map = HashMap::new();
705
706        for (resource_id, entries) in self.acl {
707            let mut rules = vec![];
708            for entry in entries {
709                let access = if entry.allow {
710                    Access::Allow
711                } else {
712                    Access::Deny
713                };
714                for privilege in entry.privileges {
715                    match &entry.condition {
716                        ACLFileCondition::Identity(identity) => {
717                            rules.push(AccessControlRule {
718                                criteria: ACLRuleTerm::Identity(identity.clone()),
719                                privilege,
720                                access,
721                            });
722                        }
723                        ACLFileCondition::Criteria(term) => {
724                            rules.push(AccessControlRule {
725                                criteria: term.clone(),
726                                privilege,
727                                access,
728                            });
729                        }
730                    }
731                }
732            }
733            map.insert(resource_id, Arc::new(AccessControlList { rules }));
734        }
735
736        AccessControlListMap { map }
737    }
738}
739
740#[derive(Deserialize, Serialize, Debug, Clone)]
741#[serde(deny_unknown_fields)]
742struct ACLFileEntry {
743    allow: bool,
744    privileges: Vec<String>,
745    #[serde(flatten)]
746    condition: ACLFileCondition,
747}
748
749#[derive(Deserialize, Serialize, Debug, Clone)]
750enum ACLFileCondition {
751    #[serde(rename = "identity")]
752    Identity(ACLIdentity),
753    #[serde(rename = "criteria")]
754    Criteria(ACLRuleTerm),
755}
756
757pub fn register(lua: &Lua) -> anyhow::Result<()> {
758    let aaa_mod = get_or_create_sub_module(lua, "aaa")?;
759
760    aaa_mod.set(
761        "configure_acct_log",
762        lua.create_async_function(
763            move |_lua, params: SerdeWrappedValue<AuditLogParams>| async move {
764                params.init().await.map_err(any_err)
765            },
766        )?,
767    )?;
768
769    aaa_mod.set(
770        "set_acl_cache_ttl",
771        lua.create_function(move |lua, duration: mlua::Value| {
772            let duration: duration_serde::Wrap<Duration> = lua.from_value(duration)?;
773            ACL_CACHE_TTL_MS.store(
774                duration.into_inner().as_millis().try_into().map_err(|_| {
775                    mlua::Error::external("set_acl_cache_ttl: duration is too large")
776                })?,
777                Ordering::Relaxed,
778            );
779            Ok(())
780        })?,
781    )?;
782    aaa_mod.set(
783        "set_check_cache_ttl",
784        lua.create_function(move |lua, duration: mlua::Value| {
785            let duration: duration_serde::Wrap<Duration> = lua.from_value(duration)?;
786            CHECK_CACHE_TTL_MS.store(
787                duration.into_inner().as_millis().try_into().map_err(|_| {
788                    mlua::Error::external("set_check_cache_ttl: duration is too large")
789                })?,
790                Ordering::Relaxed,
791            );
792            Ok(())
793        })?,
794    )?;
795    aaa_mod.set(
796        "make_access_control_list",
797        lua.create_function(move |lua, rules: mlua::Value| {
798            let rules: Vec<AccessControlRule> = lua.from_value(rules)?;
799            let list = AccessControlList { rules };
800            Ok(AccessControlListWrap {
801                wrapped_acl: Arc::new(list),
802            })
803        })?,
804    )?;
805
806    aaa_mod.set(
807        "set_fall_back_to_acl_map",
808        lua.create_function(move |_lua, fall_back: bool| {
809            FALL_BACK_TO_ACL_MAP.store(fall_back, Ordering::Relaxed);
810            Ok(())
811        })?,
812    )?;
813
814    aaa_mod.set(
815        "load_acl_map",
816        lua.create_async_function(
817            move |_lua, acl_file: SerdeWrappedValue<KeySource>| async move {
818                let data = acl_file.get().await.map_err(any_err)?;
819                let acl_file: ACLFile = toml::from_slice(&data).map_err(|err| {
820                    mlua::Error::external(format!("failed to parse acl map data: {err}"))
821                })?;
822                let map = AccessControlListMapWrap {
823                    wrapped_map: Arc::new(acl_file.build_map()),
824                };
825                Ok(map)
826            },
827        )?,
828    )?;
829
830    #[derive(Clone)]
831    enum ResourceWrap {
832        HttpEndpoint(HttpEndpointResource),
833    }
834    impl LuaUserData for ResourceWrap {}
835    #[async_trait]
836    impl Resource for ResourceWrap {
837        fn resource_id(&self) -> &str {
838            match self {
839                Self::HttpEndpoint(r) => r.resource_id(),
840            }
841        }
842        async fn next_resource_id(&mut self) -> Option<String> {
843            match self {
844                Self::HttpEndpoint(r) => r.next_resource_id().await,
845            }
846        }
847    }
848
849    aaa_mod.set(
850        "make_http_url_resource",
851        lua.create_function(move |_lua, (local_addr, url): (String, String)| {
852            let local_addr: std::net::SocketAddr = local_addr.parse().map_err(any_err)?;
853            let url: Uri = url.parse().map_err(any_err)?;
854            let resource = HttpEndpointResource::new(local_addr, &url).map_err(any_err)?;
855            Ok(ResourceWrap::HttpEndpoint(resource))
856        })?,
857    )?;
858
859    aaa_mod.set(
860        "query_resource_access",
861        lua.create_async_function(
862            move |_lua,
863                  (resource, info, privilege): (
864                UserDataRef<ResourceWrap>,
865                SerdeWrappedValue<AuthInfo>,
866                String,
867            )| async move {
868                let mut resource = resource.clone();
869                AccessControlList::query_resource_access(&mut resource, &info, &privilege)
870                    .await
871                    .map_err(any_err)
872            },
873        )?,
874    )?;
875
876    Ok(())
877}
878
879#[cfg(test)]
880mod test {
881    use super::*;
882    use std::collections::BTreeMap;
883
884    #[test]
885    fn verify_compiled_in_acl_compiles() {
886        LazyLock::force(&ACL_MAP);
887    }
888
889    #[test]
890    fn acl_file_syntax_critiera() {
891        let _: ACLFile = toml::from_str(
892            r#"
893[[acl."http_listener"]]
894allow = true
895privileges = ["GET"]
896[[acl."http_listener".criteria.AllOf]]
897Identity.Authenticated = {}
898[[acl."http_listener".criteria.AllOf]]
899Identity.Machine = "10.0.0.1"
900
901# Alternative criteria syntax
902[[acl."http_listener/*/api/inject"]]
903allow = true
904privileges = ["POST"]
905criteria.AllOf = [{Identity={Individual = "hunter"}}, {Identity={Machine = "10.0.0.1"}}]
906        "#,
907        )
908        .unwrap();
909    }
910
911    #[test]
912    fn acl_file_syntax() {
913        let acl_file: ACLFile = toml::from_str(
914            r#"
915[[acl."http_listener"]]
916allow = true
917privileges = ["GET", "PUT"]
918identity.Individual = "user"
919
920[[acl."http_listener"]]
921allow = false
922privileges = ["POST"]
923identity.Group = "group"
924
925[[acl."http_listener"]]
926allow = true
927privileges = ["GET"]
928identity.Machine = "10.0.0.1"
929
930[[acl."http_listener"]]
931allow = true
932privileges = ["PUT"]
933identity.MachineSet = ["10.0.0.1", "1.2.3.4"]
934
935[[acl."http_listener"]]
936allow = true
937privileges = ["GET"]
938identity.Unauthenticated = {}
939        "#,
940        )
941        .unwrap();
942
943        let ordered = acl_file
944            .build_map()
945            .map
946            .into_iter()
947            .collect::<BTreeMap<_, _>>();
948
949        k9::snapshot!(
950            ordered,
951            r#"
952{
953    "http_listener": AccessControlList {
954        rules: [
955            AccessControlRule {
956                criteria: Identity(
957                    Individual(
958                        "user",
959                    ),
960                ),
961                privilege: "GET",
962                access: Allow,
963            },
964            AccessControlRule {
965                criteria: Identity(
966                    Individual(
967                        "user",
968                    ),
969                ),
970                privilege: "PUT",
971                access: Allow,
972            },
973            AccessControlRule {
974                criteria: Identity(
975                    Group(
976                        "group",
977                    ),
978                ),
979                privilege: "POST",
980                access: Deny,
981            },
982            AccessControlRule {
983                criteria: Identity(
984                    Machine(
985                        10.0.0.1,
986                    ),
987                ),
988                privilege: "GET",
989                access: Allow,
990            },
991            AccessControlRule {
992                criteria: Identity(
993                    MachineSet(
994                        {
995                            "1.2.3.4",
996                            "10.0.0.1",
997                        },
998                    ),
999                ),
1000                privilege: "PUT",
1001                access: Allow,
1002            },
1003            AccessControlRule {
1004                criteria: Identity(
1005                    Unauthenticated,
1006                ),
1007                privilege: "GET",
1008                access: Allow,
1009            },
1010        ],
1011    },
1012}
1013"#
1014        );
1015    }
1016}