Skip to main content

kaniop_radius/reconcile/
error.rs

1//! Typed errors of the RADIUS executors and of one reconcile pass.
2//!
3//! Display text names objects and operations only: never a token, Secret
4//! value or NAS credential. Transient API failures keep their source through
5//! [`ExecError::Api`] and [`Failure::Transient`] so the controller backoff can
6//! classify them; everything else is an expected [`RadiusBlock`] the
7//! reconciler reports on a condition with a stable reason.
8
9use std::time::Duration;
10
11use kaniop_k8s_util::error::Error;
12use thiserror::Error;
13
14use crate::reconcile::identity::RadiusIdentityError;
15use crate::reconcile::image::RadiusImageError;
16use crate::reconcile::inputs::{InputsError, RadiusPreflightError};
17use crate::reconcile::status::ConditionKind;
18use crate::reconcile::token::MAX_TOKENS;
19use crate::reconcile::workload::RadiusWorkloadError;
20
21/// Requeue after a block that clears without a change in the world.
22const RETRY_CONCURRENT: Duration = Duration::from_secs(5);
23const RETRY_CANDIDATE: Duration = Duration::from_secs(30);
24const RETRY_TOKEN_BOUND: Duration = Duration::from_secs(60);
25
26#[derive(Debug, Error)]
27pub enum ExecError {
28    /// The Kanidm account for this CR UID exists but lacks our ownership
29    /// marker. It is never adopted, updated or deleted.
30    #[error("Kanidm account {account} exists but is not owned by this resource")]
31    AccountNotOwned { account: String },
32    /// A Kubernetes object with a name we need is controlled by something else.
33    #[error("{kind} {namespace}/{name} exists but is not controlled by this resource")]
34    ForeignObject {
35        kind: String,
36        namespace: String,
37        name: String,
38    },
39    /// A create-only config Secret exists with different content or shape.
40    #[error("config Secret {namespace}/{name} exists with different content")]
41    SecretConflict { namespace: String, name: String },
42    /// A delete precondition (UID or resourceVersion) failed: the object
43    /// changed after it was read. Re-observe and retry.
44    #[error("{kind} {namespace}/{name} changed while it was being deleted")]
45    ConcurrentMutation {
46        kind: String,
47        namespace: String,
48        name: String,
49    },
50    /// Kanidm did not accept a freshly minted token (`whoami` failed).
51    #[error("Kanidm rejected the newly minted token for account {account}")]
52    CandidateRejected { account: String },
53    /// The token list after a mint does not contain exactly one new token
54    /// with the label we issued.
55    #[error("cannot identify the newly minted token on account {account}")]
56    MintedTokenNotFound { account: String },
57    /// The object is missing metadata the executor needs (name, namespace,
58    /// UID or resourceVersion).
59    #[error("{kind} is missing {field}")]
60    MissingMetadata {
61        kind: &'static str,
62        field: &'static str,
63    },
64    /// A Kubernetes or Kanidm API call failed; the source is kept.
65    #[error(transparent)]
66    Api(#[from] Error),
67}
68
69pub type ExecResult<T> = Result<T, ExecError>;
70
71/// Wrap a Kanidm SDK error with the operation and entity, keeping the source.
72pub(crate) fn kanidm_error(
73    operation: &str,
74    entity: &str,
75    error: kanidm_client::ClientError,
76) -> ExecError {
77    ExecError::Api(Error::KanidmClientError(
78        format!("failed to {operation} {entity}"),
79        Box::new(error),
80    ))
81}
82
83/// Wrap a Kubernetes client error with the operation and object, keeping the
84/// source.
85pub(crate) fn kube_error(
86    operation: &str,
87    kind: &str,
88    namespace: &str,
89    name: &str,
90    error: kube::Error,
91) -> ExecError {
92    ExecError::Api(Error::kube_error(operation, kind, namespace, name, error))
93}
94
95/// An expected reason a reconcile pass stops. Each variant maps to the
96/// condition it is reported on and a stable reason string; the Display text
97/// is the condition message.
98#[derive(Debug, Error)]
99pub enum RadiusBlock {
100    #[error("referenced Kanidm {kanidm} does not exist")]
101    KanidmNotFound { kanidm: String },
102    #[error("namespace is not selected by radiusServerNamespaceSelector of Kanidm {kanidm}")]
103    NamespaceNotWatched { kanidm: String },
104    #[error("{0}")]
105    Inputs(#[from] RadiusPreflightError),
106    #[error("{0}")]
107    Image(#[from] RadiusImageError),
108    #[error("{0}")]
109    Workload(#[from] RadiusWorkloadError),
110    #[error("{0}")]
111    Identity(#[from] RadiusIdentityError),
112    #[error(
113        "a new token is needed but the account already holds {MAX_TOKENS} tokens; waiting for \
114         unused tokens to be revoked"
115    )]
116    TooManyTokens,
117    #[error("the config Secret of the Deployment template has no readable token")]
118    BearerUnreadable,
119    /// An executor block (never [`ExecError::Api`]; see [`Failure::exec`])
120    /// raised while establishing `stage`.
121    #[error("{error}")]
122    Exec {
123        #[source]
124        error: ExecError,
125        stage: ConditionKind,
126    },
127}
128
129impl RadiusBlock {
130    /// Stable condition reason.
131    pub fn reason(&self) -> &'static str {
132        match self {
133            Self::KanidmNotFound { .. } => "KanidmNotFound",
134            Self::NamespaceNotWatched { .. } => "NamespaceNotWatched",
135            Self::Inputs(error) => error.reason(),
136            Self::Image(_) => "ImageUnresolved",
137            Self::Workload(_) => "InvalidWorkload",
138            Self::Identity(_) => "InvalidIdentity",
139            Self::TooManyTokens => "TooManyTokens",
140            Self::BearerUnreadable => "BearerUnreadable",
141            Self::Exec { error, .. } => match error {
142                ExecError::AccountNotOwned { .. } => "OwnershipConflict",
143                ExecError::ForeignObject { .. } => "ForeignObject",
144                ExecError::SecretConflict { .. } => "SecretConflict",
145                ExecError::ConcurrentMutation { .. } => "ConcurrentMutation",
146                ExecError::CandidateRejected { .. } => "CandidateRejected",
147                ExecError::MintedTokenNotFound { .. } => "MintedTokenNotFound",
148                ExecError::MissingMetadata { .. } => "MissingMetadata",
149                ExecError::Api(_) => "TransientError",
150            },
151        }
152    }
153
154    /// The condition this block is reported on. An executor block lands on
155    /// the condition of the object it concerns (account, Deployment,
156    /// Service, a rotation-only failure), otherwise on the stage that raised
157    /// it.
158    pub fn condition(&self) -> ConditionKind {
159        match self {
160            Self::KanidmNotFound { .. } | Self::NamespaceNotWatched { .. } | Self::Identity(_) => {
161                ConditionKind::IdentityReady
162            }
163            Self::TooManyTokens | Self::BearerUnreadable => ConditionKind::Rotating,
164            Self::Inputs(_) | Self::Image(_) | Self::Workload(_) => {
165                ConditionKind::ConfigurationReady
166            }
167            Self::Exec { error, stage } => match error {
168                ExecError::AccountNotOwned { .. } => ConditionKind::IdentityReady,
169                ExecError::ForeignObject { kind, .. } if kind == "Deployment" => {
170                    ConditionKind::Available
171                }
172                ExecError::ForeignObject { kind, .. } if kind == "Service" => {
173                    ConditionKind::Exposed
174                }
175                ExecError::CandidateRejected { .. } | ExecError::MintedTokenNotFound { .. } => {
176                    ConditionKind::Rotating
177                }
178                _ => *stage,
179            },
180        }
181    }
182
183    /// Requeue delay for blocks expected to clear on their own; `None` waits
184    /// for a watch event or the periodic reconcile.
185    pub fn retry_after(&self) -> Option<Duration> {
186        match self {
187            Self::Exec {
188                error: ExecError::ConcurrentMutation { .. },
189                ..
190            } => Some(RETRY_CONCURRENT),
191            Self::Exec {
192                error: ExecError::CandidateRejected { .. },
193                ..
194            } => Some(RETRY_CANDIDATE),
195            Self::TooManyTokens => Some(RETRY_TOKEN_BOUND),
196            _ => None,
197        }
198    }
199}
200
201/// Why a reconcile pass stopped early.
202#[derive(Debug, Error)]
203pub enum Failure {
204    /// Expected: reported on a condition, requeued without backoff.
205    #[error(transparent)]
206    Block(#[from] RadiusBlock),
207    /// A Kubernetes or Kanidm API call failed. The condition of the stage is
208    /// written first, then the error (with its source) drives backoff.
209    #[error("{error}")]
210    Transient {
211        condition: ConditionKind,
212        error: Error,
213    },
214}
215
216impl Failure {
217    /// Classify an executor error raised while establishing `condition`.
218    pub fn exec(condition: ConditionKind) -> impl FnOnce(ExecError) -> Failure {
219        move |error| match error {
220            ExecError::Api(error) => Failure::Transient { condition, error },
221            error => Failure::Block(RadiusBlock::Exec {
222                error,
223                stage: condition,
224            }),
225        }
226    }
227
228    /// Classify an input preparation error.
229    pub fn inputs(error: InputsError) -> Failure {
230        match error {
231            InputsError::Invalid(error) => Failure::Block(RadiusBlock::Inputs(error)),
232            InputsError::Api(error) => Failure::Transient {
233                condition: ConditionKind::ConfigurationReady,
234                error,
235            },
236        }
237    }
238
239    /// A transient failure raised while establishing `condition`.
240    pub fn transient(condition: ConditionKind) -> impl FnOnce(Error) -> Failure {
241        move |error| Failure::Transient { condition, error }
242    }
243}