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