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