k8s_openapi/v1_32/api/admissionregistration/v1/
validation.rs

1// Generated from definition io.k8s.api.admissionregistration.v1.Validation
2
3/// Validation specifies the CEL expression which is used to apply the validation.
4#[derive(Clone, Debug, Default, PartialEq)]
5pub struct Validation {
6    /// Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:
7    ///
8    /// - 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request(\[ref\](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.
9    ///   For example, a variable named 'foo' can be accessed as 'variables.foo'.
10    /// - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
11    ///   See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
12    /// - 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the
13    ///   request resource.
14    ///
15    /// The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.
16    ///
17    /// Only property names of the form `\[a-zA-Z_.-/\]\[a-zA-Z0-9_.-/\]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:
18    ///       "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if",
19    ///       "import", "let", "loop", "package", "namespace", "return".
20    /// Examples:
21    ///   - Expression accessing a property named "namespace": {"Expression": "object.__namespace__ \> 0"}
22    ///   - Expression accessing a property named "x-prop": {"Expression": "object.x__dash__prop \> 0"}
23    ///   - Expression accessing a property named "redact__d": {"Expression": "object.redact__underscores__d \> 0"}
24    ///
25    /// Equality on arrays with list type of 'set' or 'map' ignores element order, i.e. \[1, 2\] == \[2, 1\]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:
26    ///   - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and
27    ///     non-intersecting elements in `Y` are appended, retaining their partial order.
28    ///   - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values
29    ///     are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with
30    ///     non-intersecting keys are appended, retaining their partial order.
31    /// Required.
32    pub expression: String,
33
34    /// Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is "failed rule: {Rule}". e.g. "must be a URL with the host matching spec.host" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is "failed Expression: {Expression}".
35    pub message: Option<String>,
36
37    /// messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'. Example: "object.x must be less than max ("+string(params.max)+")"
38    pub message_expression: Option<String>,
39
40    /// Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: "Unauthorized", "Forbidden", "Invalid", "RequestEntityTooLarge". If not set, StatusReasonInvalid is used in the response to the client.
41    pub reason: Option<String>,
42}
43
44impl crate::DeepMerge for Validation {
45    fn merge_from(&mut self, other: Self) {
46        crate::DeepMerge::merge_from(&mut self.expression, other.expression);
47        crate::DeepMerge::merge_from(&mut self.message, other.message);
48        crate::DeepMerge::merge_from(&mut self.message_expression, other.message_expression);
49        crate::DeepMerge::merge_from(&mut self.reason, other.reason);
50    }
51}
52
53impl<'de> crate::serde::Deserialize<'de> for Validation {
54    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
55        #[allow(non_camel_case_types)]
56        enum Field {
57            Key_expression,
58            Key_message,
59            Key_message_expression,
60            Key_reason,
61            Other,
62        }
63
64        impl<'de> crate::serde::Deserialize<'de> for Field {
65            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
66                struct Visitor;
67
68                impl crate::serde::de::Visitor<'_> for Visitor {
69                    type Value = Field;
70
71                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72                        f.write_str("field identifier")
73                    }
74
75                    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
76                        Ok(match v {
77                            "expression" => Field::Key_expression,
78                            "message" => Field::Key_message,
79                            "messageExpression" => Field::Key_message_expression,
80                            "reason" => Field::Key_reason,
81                            _ => Field::Other,
82                        })
83                    }
84                }
85
86                deserializer.deserialize_identifier(Visitor)
87            }
88        }
89
90        struct Visitor;
91
92        impl<'de> crate::serde::de::Visitor<'de> for Visitor {
93            type Value = Validation;
94
95            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96                f.write_str("Validation")
97            }
98
99            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
100                let mut value_expression: Option<String> = None;
101                let mut value_message: Option<String> = None;
102                let mut value_message_expression: Option<String> = None;
103                let mut value_reason: Option<String> = None;
104
105                while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
106                    match key {
107                        Field::Key_expression => value_expression = crate::serde::de::MapAccess::next_value(&mut map)?,
108                        Field::Key_message => value_message = crate::serde::de::MapAccess::next_value(&mut map)?,
109                        Field::Key_message_expression => value_message_expression = crate::serde::de::MapAccess::next_value(&mut map)?,
110                        Field::Key_reason => value_reason = crate::serde::de::MapAccess::next_value(&mut map)?,
111                        Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
112                    }
113                }
114
115                Ok(Validation {
116                    expression: value_expression.unwrap_or_default(),
117                    message: value_message,
118                    message_expression: value_message_expression,
119                    reason: value_reason,
120                })
121            }
122        }
123
124        deserializer.deserialize_struct(
125            "Validation",
126            &[
127                "expression",
128                "message",
129                "messageExpression",
130                "reason",
131            ],
132            Visitor,
133        )
134    }
135}
136
137impl crate::serde::Serialize for Validation {
138    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
139        let mut state = serializer.serialize_struct(
140            "Validation",
141            1 +
142            self.message.as_ref().map_or(0, |_| 1) +
143            self.message_expression.as_ref().map_or(0, |_| 1) +
144            self.reason.as_ref().map_or(0, |_| 1),
145        )?;
146        crate::serde::ser::SerializeStruct::serialize_field(&mut state, "expression", &self.expression)?;
147        if let Some(value) = &self.message {
148            crate::serde::ser::SerializeStruct::serialize_field(&mut state, "message", value)?;
149        }
150        if let Some(value) = &self.message_expression {
151            crate::serde::ser::SerializeStruct::serialize_field(&mut state, "messageExpression", value)?;
152        }
153        if let Some(value) = &self.reason {
154            crate::serde::ser::SerializeStruct::serialize_field(&mut state, "reason", value)?;
155        }
156        crate::serde::ser::SerializeStruct::end(state)
157    }
158}
159
160#[cfg(feature = "schemars")]
161impl crate::schemars::JsonSchema for Validation {
162    fn schema_name() -> String {
163        "io.k8s.api.admissionregistration.v1.Validation".to_owned()
164    }
165
166    fn json_schema(__gen: &mut crate::schemars::gen::SchemaGenerator) -> crate::schemars::schema::Schema {
167        crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
168            metadata: Some(Box::new(crate::schemars::schema::Metadata {
169                description: Some("Validation specifies the CEL expression which is used to apply the validation.".to_owned()),
170                ..Default::default()
171            })),
172            instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
173            object: Some(Box::new(crate::schemars::schema::ObjectValidation {
174                properties: [
175                    (
176                        "expression".to_owned(),
177                        crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
178                            metadata: Some(Box::new(crate::schemars::schema::Metadata {
179                                description: Some("Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n  For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n  See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n  request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t  \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t  \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n  - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n  - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n  - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n  - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n    non-intersecting elements in `Y` are appended, retaining their partial order.\n  - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n    are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n    non-intersecting keys are appended, retaining their partial order.\nRequired.".to_owned()),
180                                ..Default::default()
181                            })),
182                            instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
183                            ..Default::default()
184                        }),
185                    ),
186                    (
187                        "message".to_owned(),
188                        crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
189                            metadata: Some(Box::new(crate::schemars::schema::Metadata {
190                                description: Some("Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is \"failed Expression: {Expression}\".".to_owned()),
191                                ..Default::default()
192                            })),
193                            instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
194                            ..Default::default()
195                        }),
196                    ),
197                    (
198                        "messageExpression".to_owned(),
199                        crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
200                            metadata: Some(Box::new(crate::schemars::schema::Metadata {
201                                description: Some("messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'. Example: \"object.x must be less than max (\"+string(params.max)+\")\"".to_owned()),
202                                ..Default::default()
203                            })),
204                            instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
205                            ..Default::default()
206                        }),
207                    ),
208                    (
209                        "reason".to_owned(),
210                        crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
211                            metadata: Some(Box::new(crate::schemars::schema::Metadata {
212                                description: Some("Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: \"Unauthorized\", \"Forbidden\", \"Invalid\", \"RequestEntityTooLarge\". If not set, StatusReasonInvalid is used in the response to the client.".to_owned()),
213                                ..Default::default()
214                            })),
215                            instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::String))),
216                            ..Default::default()
217                        }),
218                    ),
219                ].into(),
220                required: [
221                    "expression".to_owned(),
222                ].into(),
223                ..Default::default()
224            })),
225            ..Default::default()
226        })
227    }
228}