Skip to main content

kaniop_group/
crd.rs

1use kanidm_proto::{
2    constants::{
3        ATTR_ALLOW_PRIMARY_CRED_FALLBACK, ATTR_AUTH_PASSWORD_MINIMUM_LENGTH,
4        ATTR_AUTH_SESSION_EXPIRY, ATTR_CREDENTIAL_TYPE_MINIMUM, ATTR_GIDNUMBER,
5        ATTR_LIMIT_SEARCH_MAX_FILTER_TEST, ATTR_LIMIT_SEARCH_MAX_RESULTS, ATTR_PRIVILEGE_EXPIRY,
6        ATTR_WEBAUTHN_ATTESTATION_CA_LIST, ENTRYCLASS_ACCOUNT_POLICY,
7    },
8    v1::Entry,
9};
10use kaniop_k8s_util::types::get_first_cloned;
11use kaniop_operator::controller::kanidm::KanidmResource;
12use kaniop_operator::crd::KanidmRef;
13use kaniop_operator::kanidm::crd::Kanidm;
14
15use std::fmt;
16
17use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
18use kube::CustomResource;
19#[cfg(feature = "schemars")]
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22
23/// Groups are a collection of other entities that exist within Kanidm.
24/// More info:
25/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
26#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
27#[cfg_attr(feature = "schemars", derive(JsonSchema))]
28#[kube(
29    category = "kaniop",
30    group = "kaniop.rs",
31    version = "v1beta1",
32    kind = "KanidmGroup",
33    plural = "kanidmgroups",
34    singular = "kanidmgroup",
35    shortname = "kg",
36    namespaced,
37    status = "KanidmGroupStatus",
38    doc = r#"The Kanidm group custom resource definition (CRD) defines a group in Kanidm."#,
39    printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".status.kanidmRef"}"#,
40    printcolumn = r#"{"name":"ManagedBy","type":"string","jsonPath":".spec.entryManagedBy"}"#,
41    printcolumn = r#"{"name":"GID","type":"integer","jsonPath":".status.gid"}"#,
42    printcolumn = r#"{"name":"Ready","type":"boolean","jsonPath":".status.ready"}"#,
43    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
44    derive = "Default"
45)]
46#[serde(rename_all = "camelCase")]
47pub struct KanidmGroupSpec {
48    pub kanidm_ref: KanidmRef,
49
50    /// Optional name/spn of a group or account that have entry manager rights over this group.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub entry_managed_by: Option<String>,
53
54    /// Set the exact list of mail addresses that this group is associated with. The first mail
55    /// address in the list is the `primary` and the remainder are aliases. Setting an empty list
56    /// will clear the mail attribute.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub mail: Option<Vec<String>>,
59
60    /// Name or SPN of group members. Set the exact list of members that this group should contain,
61    /// removing any not listed in the set operation.
62    /// If you want to manage members from the database, do not set them here.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub members: Option<Vec<String>>,
65
66    /// POSIX attributes for the group account. When specified, the operator will activate them.
67    /// If omitted, the operator retains the attributes in the database but ceases to manage them.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub posix_attributes: Option<KanidmGroupPosixAttributes>,
70
71    /// Account policy settings for the group.
72    ///
73    /// When set, the operator will enable account policy on this group and configure the specified
74    /// settings. Account policy defines security requirements that accounts must meet when they are
75    /// members of this group.
76    ///
77    /// When an account is affected by multiple policies, the strictest component from each policy
78    /// is applied.
79    ///
80    /// More info: https://kanidm.github.io/kanidm/stable/accounts/account_policy.html
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub account_policy: Option<KanidmGroupAccountPolicy>,
83}
84
85impl KanidmResource for KanidmGroup {
86    #[inline]
87    fn kanidm_ref_spec(&self) -> &KanidmRef {
88        &self.spec.kanidm_ref
89    }
90
91    #[inline]
92    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
93        &kanidm.spec.group_namespace_selector
94    }
95}
96
97/// Kanidm has features that enable its accounts and groups to be consumed on POSIX-like machines,
98/// such as Linux, FreeBSD or others. Both service accounts and person accounts can be used on POSIX
99/// systems.
100///
101/// The attributes defined here are set by the operator. If you want to manage those attributes
102/// from the database, do not set them here.
103/// Additionally, if you unset them here, they will be kept in the database.
104#[derive(Serialize, Deserialize, Clone, Debug, Default)]
105#[cfg_attr(feature = "schemars", derive(JsonSchema))]
106#[serde(rename_all = "camelCase")]
107pub struct KanidmGroupPosixAttributes {
108    /// The group ID number (GID) for the group account.
109    ///
110    /// If omitted, Kanidm will generate it automatically.
111    pub gidnumber: Option<u32>,
112}
113
114impl PartialEq for KanidmGroupPosixAttributes {
115    /// Compare attributes defined in the first object with the second object values.
116    /// If the second object has more attributes defined, they will be ignored.
117    fn eq(&self, other: &Self) -> bool {
118        self.gidnumber.is_none() || self.gidnumber == other.gidnumber
119    }
120}
121
122impl From<Entry> for KanidmGroupPosixAttributes {
123    fn from(entry: Entry) -> Self {
124        KanidmGroupPosixAttributes {
125            gidnumber: get_first_cloned(&entry, ATTR_GIDNUMBER).and_then(|s| s.parse::<u32>().ok()),
126        }
127    }
128}
129
130/// Minimum security strength of credentials that may be assigned to accounts affected by this
131/// policy. In order from weakest to strongest: any < mfa < passkey < attested_passkey.
132///
133/// More info:
134/// https://kanidm.github.io/kanidm/stable/accounts/account_policy.html#credential-type-minimum
135#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
136#[cfg_attr(feature = "schemars", derive(JsonSchema))]
137#[serde(rename_all = "snake_case")]
138pub enum CredentialTypeMinimum {
139    /// Any credential type is allowed (weakest)
140    #[default]
141    Any,
142    /// Multi-factor authentication required
143    Mfa,
144    /// Passkey (WebAuthn) required
145    Passkey,
146    /// Attested passkey required (strongest) - requires configuring WebAuthn attestation CA list
147    AttestedPasskey,
148}
149
150impl fmt::Display for CredentialTypeMinimum {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            CredentialTypeMinimum::Any => write!(f, "any"),
154            CredentialTypeMinimum::Mfa => write!(f, "mfa"),
155            CredentialTypeMinimum::Passkey => write!(f, "passkey"),
156            CredentialTypeMinimum::AttestedPasskey => write!(f, "attested_passkey"),
157        }
158    }
159}
160
161impl CredentialTypeMinimum {
162    /// Parse from Kanidm string value
163    pub fn from_kanidm_str(s: &str) -> Option<Self> {
164        match s.to_lowercase().as_str() {
165            "any" => Some(CredentialTypeMinimum::Any),
166            "mfa" => Some(CredentialTypeMinimum::Mfa),
167            "passkey" => Some(CredentialTypeMinimum::Passkey),
168            "attested_passkey" => Some(CredentialTypeMinimum::AttestedPasskey),
169            _ => None,
170        }
171    }
172}
173
174/// Custom schema for CredentialTypeMinimum that is compatible with Kubernetes CRD structural schema.
175/// Kubernetes doesn't support `anyOf` with nullable, so we generate a flat enum schema with nullable.
176/// We use `x-enum-descriptions` to provide per-option descriptions for documentation generation.
177#[cfg(feature = "schemars")]
178fn credential_type_minimum_schema(
179    _generator: &mut schemars::generate::SchemaGenerator,
180) -> schemars::Schema {
181    schemars::json_schema!({
182        "description": "Minimum security strength of credentials that may be assigned to accounts affected by this policy. In order from weakest to strongest: any < mfa < passkey < attested_passkey.\n\nMore info: https://kanidm.github.io/kanidm/stable/accounts/account_policy.html#credential-type-minimum",
183        "type": "string",
184        "enum": ["any", "mfa", "passkey", "attested_passkey"],
185        "x-enum-descriptions": [
186            "Any credential type is allowed (weakest)",
187            "Multi-factor authentication required",
188            "Passkey (WebAuthn) required",
189            "Attested passkey required (strongest) - requires configuring WebAuthn attestation CA list"
190        ],
191        "nullable": true
192    })
193}
194
195/// Account policy settings for the group.
196///
197/// Account Policy defines the security requirements that accounts must meet and influences users
198/// sessions. Policy is defined on groups so that membership of a group influences the security of
199/// its members. This allows you to express that if you can access a system or resource, then the
200/// account must also meet the policy requirements.
201///
202/// When an account is affected by multiple policies, the strictest component from each policy is
203/// applied.
204///
205/// More info: https://kanidm.github.io/kanidm/stable/accounts/account_policy.html
206#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
207#[cfg_attr(feature = "schemars", derive(JsonSchema))]
208#[serde(rename_all = "camelCase")]
209pub struct KanidmGroupAccountPolicy {
210    /// Maximum length in seconds that an authentication session may exist for.
211    /// After this time, the user must reauthenticate.
212    ///
213    /// This value provides a difficult balance - forcing frequent re-authentications can frustrate
214    /// and annoy users. However extremely long sessions allow a stolen or disclosed session
215    /// token/device to read data for an extended period.
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub auth_session_expiry: Option<u32>,
218
219    /// Minimum security strength of credentials that may be assigned to accounts affected by this
220    /// policy. In order from weakest to strongest: any < mfa < passkey < attested_passkey.
221    ///
222    /// `attested_passkey` requires configuring `webauthnAttestationCaList`.
223    #[serde(skip_serializing_if = "Option::is_none")]
224    #[cfg_attr(
225        feature = "schemars",
226        schemars(schema_with = "credential_type_minimum_schema", default)
227    )]
228    pub credential_type_minimum: Option<CredentialTypeMinimum>,
229
230    /// Minimum length for passwords (if they are allowed by credential_type_minimum).
231    #[serde(skip_serializing_if = "Option::is_none")]
232    pub password_minimum_length: Option<u32>,
233
234    /// Maximum length in seconds that privileges will exist after reauthentication for a read/write
235    /// session. After this time, the session returns to read-only mode.
236    ///
237    /// Maximum allowed value is 3600 (1 hour).
238    #[cfg_attr(feature = "schemars", schemars(extend("x-kubernetes-validations" = [
239        {
240            "message": "privilegeExpiry must be at most 3600 seconds (1 hour)",
241            "rule": "self <= 3600"
242        }
243    ])))]
244    #[serde(skip_serializing_if = "Option::is_none")]
245    pub privilege_expiry: Option<u32>,
246
247    /// WebAuthn attestation CA list. This is the list of certificate authorities and device AAGUIDs
248    /// that must be used by members of this policy. This allows limiting devices to specific models.
249    ///
250    /// Generate this list using `fido-mds-tool` from the webauthn-rs project.
251    ///
252    /// More info:
253    /// https://kanidm.github.io/kanidm/stable/accounts/account_policy.html#setting-webauthn-attestation-ca-lists
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub webauthn_attestation_ca_list: Option<String>,
256
257    /// Allow authenticating with the primary account password when logging in via LDAP.
258    /// If both an LDAP and primary password are specified, Kanidm will only accept the LDAP
259    /// password.
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub allow_primary_cred_fallback: Option<bool>,
262
263    /// Maximum number of results returned from a search operation.
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub limit_search_max_results: Option<u32>,
266
267    /// Maximum number of filter tests allowed in a search operation.
268    #[serde(skip_serializing_if = "Option::is_none")]
269    pub limit_search_max_filter_test: Option<u32>,
270}
271
272/// Account policy attributes as read from Kanidm. Used to compare desired vs current state.
273#[derive(Clone, Debug, Default)]
274pub struct KanidmGroupAccountPolicyAttributes {
275    /// Whether account policy is enabled on this group
276    pub enabled: bool,
277    pub auth_session_expiry: Option<u32>,
278    pub credential_type_minimum: Option<CredentialTypeMinimum>,
279    pub password_minimum_length: Option<u32>,
280    pub privilege_expiry: Option<u32>,
281    pub webauthn_attestation_ca_list: Option<String>,
282    pub allow_primary_cred_fallback: Option<bool>,
283    pub limit_search_max_results: Option<u32>,
284    pub limit_search_max_filter_test: Option<u32>,
285}
286
287impl From<&Entry> for KanidmGroupAccountPolicyAttributes {
288    fn from(entry: &Entry) -> Self {
289        let enabled = entry
290            .attrs
291            .get("class")
292            .is_some_and(|classes| classes.iter().any(|c| c == ENTRYCLASS_ACCOUNT_POLICY));
293
294        KanidmGroupAccountPolicyAttributes {
295            enabled,
296            auth_session_expiry: get_first_cloned(entry, ATTR_AUTH_SESSION_EXPIRY)
297                .and_then(|s| s.parse::<u32>().ok()),
298            credential_type_minimum: get_first_cloned(entry, ATTR_CREDENTIAL_TYPE_MINIMUM)
299                .and_then(|s| CredentialTypeMinimum::from_kanidm_str(&s)),
300            password_minimum_length: get_first_cloned(entry, ATTR_AUTH_PASSWORD_MINIMUM_LENGTH)
301                .and_then(|s| s.parse::<u32>().ok()),
302            privilege_expiry: get_first_cloned(entry, ATTR_PRIVILEGE_EXPIRY)
303                .and_then(|s| s.parse::<u32>().ok()),
304            webauthn_attestation_ca_list: get_first_cloned(
305                entry,
306                ATTR_WEBAUTHN_ATTESTATION_CA_LIST,
307            ),
308            allow_primary_cred_fallback: get_first_cloned(entry, ATTR_ALLOW_PRIMARY_CRED_FALLBACK)
309                .and_then(|s| s.parse::<bool>().ok()),
310            limit_search_max_results: get_first_cloned(entry, ATTR_LIMIT_SEARCH_MAX_RESULTS)
311                .and_then(|s| s.parse::<u32>().ok()),
312            limit_search_max_filter_test: get_first_cloned(
313                entry,
314                ATTR_LIMIT_SEARCH_MAX_FILTER_TEST,
315            )
316            .and_then(|s| s.parse::<u32>().ok()),
317        }
318    }
319}
320
321/// Most recent observed status of the Kanidm Group. Read-only.
322///
323/// More info:
324/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
325#[derive(Serialize, Deserialize, Clone, Debug, Default)]
326#[cfg_attr(feature = "schemars", derive(JsonSchema))]
327#[serde(rename_all = "camelCase")]
328pub struct KanidmGroupStatus {
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub conditions: Option<Vec<Condition>>,
331
332    pub ready: bool,
333
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub gid: Option<u32>,
336
337    pub kanidm_ref: String,
338}