Skip to main content

kanidmd_lib/repl/
supplier.rs

1use super::{
2    proto::{
3        ReplEntryV1, ReplIncrementalContext, ReplIncrementalEntryV1, ReplRefreshContext,
4        ReplRuvRange,
5    },
6    ruv::{RangeDiffStatus, ReplicationUpdateVector, ReplicationUpdateVectorTransaction},
7};
8use crate::{
9    be::{
10        keystorage::{KeyHandle, KeyHandleId},
11        BackendTransaction,
12    },
13    prelude::*,
14};
15use crypto_glue::{
16    der::SecretDocument,
17    ecdsa_p256::{self, EcdsaP256DerSignature, EcdsaP256SigningKey, EcdsaP256VerifyingKey},
18    traits::Pkcs8EncodePrivateKey,
19    x509::{
20        self, profile::cabf::tls::*, Builder, Certificate, CertificateBuilder, GeneralName,
21        GeneralizedTime, Ia5String, OctetString, SubjectAltName, SubjectPublicKeyInfoOwned,
22        Validity,
23    },
24};
25use rustls::pki_types::{IpAddr, ServerName};
26use std::str::FromStr;
27
28impl QueryServerWriteTransaction<'_> {
29    fn supplier_generate_key_cert(
30        &mut self,
31        domain_name: &str,
32    ) -> Result<(SecretDocument, Certificate), OperationError> {
33        // Invalid, must need to re-generate.
34        let s_uuid = self.get_server_uuid();
35
36        let private_key = ecdsa_p256::new_key();
37        let signing_key = EcdsaP256SigningKey::from(&private_key);
38        let verifying_key = EcdsaP256VerifyingKey::from(&signing_key);
39
40        let pub_key = SubjectPublicKeyInfoOwned::from_key(&verifying_key).map_err(|err| {
41            error!(?err, "Unable to create public key from private key");
42            OperationError::CryptographyError
43        })?;
44
45        let not_before = GeneralizedTime::from_unix_duration(self.get_curtime())
46            .map(x509::Time::from)
47            .map_err(|err| {
48                error!(?err, "Unable to convert current time to GeneralizedTime");
49                OperationError::CryptographyError
50            })?;
51        let not_after = GeneralizedTime::from_unix_duration(
52            self.get_curtime() + Duration::from_secs(REPL_MTLS_CERTIFICATE_EXPIRY),
53        )
54        .map(x509::Time::from)
55        .map_err(|err| {
56            error!(?err, "Unable to convert current time to GeneralizedTime");
57            OperationError::CryptographyError
58        })?;
59
60        let validity = Validity::new(not_before, not_after);
61
62        let serial_number = x509::uuid_to_serial(s_uuid);
63        // Important - for some reason O= here doesn't propogate to issuer, I suspect
64        // due to being a CAB profile.
65        let subject = x509::Name::from_str(&format!("CN={s_uuid}")).map_err(|err| {
66            error!(?err, "Unable to parse subject dn");
67            OperationError::CryptographyError
68        })?;
69
70        // Subject Alt Name
71        // We need to understand how rustls treats this to issue the correct SAN value.
72        // How does rustls interpret this name?
73        let Ok(server_name) = ServerName::try_from(domain_name.to_owned()) else {
74            error!("Invalid server name for replication");
75            return Err(OperationError::CryptographyError);
76        };
77
78        let names = match server_name {
79            ServerName::DnsName(_) => {
80                let alt_name = Ia5String::new(domain_name).map_err(|err| {
81                    error!(?err, "Invalid subject alt name");
82                    OperationError::CryptographyError
83                })?;
84                vec![GeneralName::DnsName(alt_name)]
85            }
86            ServerName::IpAddress(IpAddr::V4(ipv4_addr)) => {
87                let ip_address = OctetString::new(*ipv4_addr.as_ref()).map_err(|err| {
88                    error!(?err, "Unable to convert ipv4 address to octet string");
89                    OperationError::CryptographyError
90                })?;
91                vec![GeneralName::IpAddress(ip_address)]
92            }
93            ServerName::IpAddress(IpAddr::V6(ipv6_addr)) => {
94                let ip_address = OctetString::new(*ipv6_addr.as_ref()).map_err(|err| {
95                    error!(?err, "Unable to convert ipv6 address to octet string");
96                    OperationError::CryptographyError
97                })?;
98                vec![GeneralName::IpAddress(ip_address)]
99            }
100
101            _ => return Err(OperationError::CryptographyError),
102        };
103
104        let subject_alt_name = SubjectAltName(names.clone());
105
106        let certificate_type =
107            CertificateType::domain_validated(subject.clone(), names).map_err(|err| {
108                error!(?err, "Unable to construct certificate type");
109                OperationError::CryptographyError
110            })?;
111
112        let profile = Subscriber {
113            certificate_type,
114            issuer: subject,
115            client_auth: true,
116            tls12_options: Default::default(),
117            enable_data_encipherment: Default::default(),
118        };
119
120        let mut x509_builder = CertificateBuilder::new(profile, serial_number, validity, pub_key)
121            .map_err(|err| {
122            error!(?err, "Unable to construct certificate builder");
123            OperationError::CryptographyError
124        })?;
125
126        x509_builder
127            .add_extension(&subject_alt_name)
128            .map_err(|err| {
129                error!(?err, "Unable to add subject alt name");
130                OperationError::CryptographyError
131            })?;
132
133        let x509 = x509_builder
134            .build::<EcdsaP256SigningKey, EcdsaP256DerSignature>(&signing_key)
135            .map_err(|err| {
136                error!(?err, "Unable to generate self signed key/cert");
137                OperationError::CryptographyError
138            })?;
139
140        let private = private_key.to_pkcs8_der().map_err(|err| {
141            error!(?err, "Unable to encode private key");
142            OperationError::CryptographyError
143        })?;
144
145        let kh = KeyHandle::X509Key {
146            private: private.clone(),
147            x509: x509.clone(),
148        };
149
150        self.get_be_txn()
151            .set_key_handle(KeyHandleId::ReplicationKey, kh)
152            .map_err(|err| {
153                error!(?err, "Unable to persist replication key");
154                err
155            })
156            .map(|()| (private, x509))
157    }
158
159    #[instrument(level = "info", skip_all)]
160    pub fn supplier_renew_key_cert(&mut self, domain_name: &str) -> Result<(), OperationError> {
161        self.supplier_generate_key_cert(domain_name).map(|_| ())
162    }
163
164    #[instrument(level = "debug", skip_all)]
165    pub fn supplier_get_key_cert(
166        &mut self,
167        domain_name: &str,
168    ) -> Result<(SecretDocument, Certificate), OperationError> {
169        // Later we need to put this through a HSM or similar, but we will always need a way
170        // to persist a handle, so we still need the db write and load components.
171
172        // Does the handle exist?
173        let maybe_key_handle = self
174            .get_be_txn()
175            .get_key_handle(KeyHandleId::ReplicationKey)
176            .map_err(|err| {
177                error!(?err, "Unable to access replication key");
178                err
179            })?;
180
181        // Can you process the keyhandle?
182        let key_cert = match maybe_key_handle {
183            Some(KeyHandle::X509Key { private, x509 }) => (private, x509),
184            /*
185            Some(Keyhandle::...) => {
186                // invalid key
187                // error? regenerate?
188            }
189            */
190            None => self.supplier_generate_key_cert(domain_name)?,
191        };
192
193        Ok(key_cert)
194    }
195}
196
197impl QueryServerReadTransaction<'_> {
198    // Given a consumers state, calculate the differential of changes they
199    // need to be sent to bring them to the equivalent state.
200
201    // We use the RUV or Cookie to determine if:
202    // * The consumer requires a full-reinit.
203    // * Which entry attr-states need to be sent, if any
204
205    #[instrument(level = "debug", skip_all)]
206    pub fn supplier_provide_changes(
207        &mut self,
208        ctx_ruv: ReplRuvRange,
209    ) -> Result<ReplIncrementalContext, OperationError> {
210        // Convert types if needed. This way we can compare ruv's correctly.
211        let (ctx_domain_uuid, ctx_ranges) = match ctx_ruv {
212            ReplRuvRange::V1 {
213                domain_uuid,
214                ranges,
215            } => (domain_uuid, ranges),
216        };
217
218        if ctx_domain_uuid != self.d_info.d_uuid {
219            error!("Replication - Consumer Domain UUID does not match our local domain uuid.");
220            debug!(consumer_domain_uuid = ?ctx_domain_uuid, supplier_domain_uuid = ?self.d_info.d_uuid);
221            return Ok(ReplIncrementalContext::DomainMismatch);
222        }
223
224        // This is a reasonably tricky part of the code, because we are attempting to do a
225        // distributed and async liveness check. What content has the consumer seen? What
226        // could they have trimmed from their own RUV?
227        //
228        // Since tombstone purging always creates an anchor, then there are always "pings"
229        // effectively going out of "empty" changes that drive the RUV forward. This assists us
230        // to detect this situation.
231        //
232        // If a server has been replicating correctly, then it should have at least *some* overlap
233        // with us since content has always advanced.
234        //
235        // If a server has "stalled" then it will have *no* overlap. This can manifest as a need
236        // to supply all ranges as though they were new because the lagging consumer has trimmed out
237        // all the old content.
238        //
239        // When a server is newly added it will have overlap because it will have refreshed from
240        // another server.
241        //
242        // When a server is "trimmed" from the RUV, it no longer influences the overlap decision
243        // because the other servers will have continued to advance.
244
245        let trim_cid = self.trim_cid().clone();
246
247        let supplier_ruv = self.get_be_txn().get_ruv();
248
249        let our_ranges = supplier_ruv.filter_ruv_range(&trim_cid).map_err(|e| {
250            error!(err = ?e, "Unable to access supplier RUV range");
251            e
252        })?;
253
254        // Compare this to our internal ranges - work out the list of entry
255        // id's that are now different.
256
257        let supply_ranges = ReplicationUpdateVector::range_diff(&ctx_ranges, &our_ranges);
258
259        // If empty, return an empty set of changes!
260
261        let ranges = match supply_ranges {
262            RangeDiffStatus::Ok(ranges) => ranges,
263            RangeDiffStatus::Refresh { lag_range } => {
264                error!("Replication - Consumer is lagging and must be refreshed.");
265                debug!(?lag_range);
266                debug!(consumer_ranges = ?ctx_ranges);
267                debug!(supplier_ranges = ?our_ranges);
268                return Ok(ReplIncrementalContext::RefreshRequired);
269            }
270            RangeDiffStatus::Unwilling { adv_range } => {
271                error!("Replication - Supplier is lagging and must be investigated.");
272                debug!(?adv_range);
273                debug!(consumer_ranges = ?ctx_ranges);
274                debug!(supplier_ranges = ?our_ranges);
275                return Ok(ReplIncrementalContext::UnwillingToSupply);
276            }
277            RangeDiffStatus::Critical {
278                lag_range,
279                adv_range,
280            } => {
281                error!(?adv_range, ?lag_range, "Replication Critical - Consumers are advanced of us, and also lagging! This must be immediately investigated!");
282                debug!(consumer_ranges = ?ctx_ranges);
283                debug!(supplier_ranges = ?our_ranges);
284                return Ok(ReplIncrementalContext::UnwillingToSupply);
285            }
286            RangeDiffStatus::NoRUVOverlap => {
287                error!("Replication Critical - Consumers RUV has desynchronised and diverged! This must be immediately investigated!");
288                debug!(consumer_ranges = ?ctx_ranges);
289                debug!(supplier_ranges = ?our_ranges);
290                return Ok(ReplIncrementalContext::UnwillingToSupply);
291            }
292        };
293
294        debug!("these ranges will be supplied");
295        debug!(supply_ranges = ?ranges);
296        debug!(consumer_ranges = ?ctx_ranges);
297        debug!(supplier_ranges = ?our_ranges);
298
299        if ranges.is_empty() {
300            debug!("No Changes Available");
301            return Ok(ReplIncrementalContext::NoChangesAvailable);
302        }
303
304        // From the set of change id's, fetch those entries.
305        // This is done by supplying the ranges to the be which extracts
306        // the entries affected by the idls in question.
307        let entries = self.get_be_txn().retrieve_range(&ranges).map_err(|e| {
308            admin_error!(?e, "backend failure");
309            OperationError::Backend
310        })?;
311
312        // Separate the entries into schema, meta and remaining.
313        let (schema_entries, rem_entries): (Vec<_>, Vec<_>) = entries.into_iter().partition(|e| {
314            e.get_ava_set(Attribute::Class)
315                .map(|cls| {
316                    cls.contains(&EntryClass::AttributeType.into() as &PartialValue)
317                        || cls.contains(&EntryClass::ClassType.into() as &PartialValue)
318                })
319                .unwrap_or(false)
320        });
321
322        let (meta_entries, entries): (Vec<_>, Vec<_>) = rem_entries.into_iter().partition(|e| {
323            e.get_ava_set(Attribute::Class)
324                .map(|cls| {
325                    cls.contains(&EntryClass::DomainInfo.into() as &PartialValue)
326                        || cls.contains(&EntryClass::SystemInfo.into() as &PartialValue)
327                        || cls.contains(&EntryClass::SystemConfig.into() as &PartialValue)
328                        || cls.contains(&EntryClass::KeyProvider.into() as &PartialValue)
329                })
330                .unwrap_or(false)
331        });
332
333        trace!(?schema_entries);
334        trace!(?meta_entries);
335        trace!(?entries);
336
337        // For each entry, determine the changes that exist on the entry that fall
338        // into the ruv range - reduce to a incremental set of changes.
339
340        let schema = self.get_schema();
341        let domain_version = self.d_info.d_vers;
342        let domain_patch_level = if self.d_info.d_devel_taint {
343            u32::MAX
344        } else {
345            self.d_info.d_patch_level
346        };
347        let domain_uuid = self.d_info.d_uuid;
348
349        let schema_entries: Vec<_> = schema_entries
350            .into_iter()
351            .map(|e| ReplIncrementalEntryV1::new(e.as_ref(), schema, &ranges))
352            .collect();
353
354        let meta_entries: Vec<_> = meta_entries
355            .into_iter()
356            .map(|e| ReplIncrementalEntryV1::new(e.as_ref(), schema, &ranges))
357            .collect();
358
359        let entries: Vec<_> = entries
360            .into_iter()
361            .map(|e| ReplIncrementalEntryV1::new(e.as_ref(), schema, &ranges))
362            .collect();
363
364        // Finally, populate the ranges with anchors from the RUV
365        let supplier_ruv = self.get_be_txn().get_ruv();
366        let ranges = supplier_ruv.get_anchored_ranges(ranges)?;
367
368        // Build the incremental context.
369        Ok(ReplIncrementalContext::V1 {
370            domain_version,
371            domain_patch_level,
372            domain_uuid,
373            ranges,
374            schema_entries,
375            meta_entries,
376            entries,
377        })
378    }
379
380    #[instrument(level = "debug", skip_all)]
381    pub fn supplier_provide_refresh(&mut self) -> Result<ReplRefreshContext, OperationError> {
382        // Get the current schema. We use this for attribute and entry filtering.
383        let schema = self.get_schema();
384
385        // A refresh must provide
386        //
387        // * the current domain version
388        let domain_version = self.d_info.d_vers;
389        let domain_devel = self.d_info.d_devel_taint;
390        let domain_uuid = self.d_info.d_uuid;
391
392        let trim_cid = self.trim_cid().clone();
393
394        // What is the set of data we are providing?
395        let ranges = self
396            .get_be_txn()
397            .get_ruv()
398            .filter_ruv_range(&trim_cid)
399            .map_err(|e| {
400                error!(err = ?e, "Unable to access supplier RUV range");
401                e
402            })?;
403
404        // * the domain uuid
405        // * the set of schema entries
406        // * the set of non-schema entries
407        // - We must exclude certain entries and attributes!
408        //   * schema defines what we exclude!
409
410        let schema_filter_inner = f_or!([
411            f_eq(Attribute::Class, EntryClass::AttributeType.into()),
412            f_eq(Attribute::Class, EntryClass::ClassType.into()),
413        ]);
414
415        let schema_filter = filter!(schema_filter_inner.clone());
416
417        let meta_filter_inner = f_or!([
418            f_eq(Attribute::Class, EntryClass::DomainInfo.into()),
419            f_eq(Attribute::Class, EntryClass::SystemInfo.into()),
420            f_eq(Attribute::Class, EntryClass::SystemConfig.into()),
421            f_eq(Attribute::Class, EntryClass::KeyProvider.into()),
422        ]);
423
424        let meta_filter = filter!(meta_filter_inner.clone());
425
426        let entry_filter = filter_all!(f_or!([
427            f_and!([
428                f_pres(Attribute::Class),
429                f_andnot(f_or(vec![schema_filter_inner, meta_filter_inner])),
430            ]),
431            f_eq(Attribute::Class, EntryClass::Tombstone.into()),
432            f_eq(Attribute::Class, EntryClass::Recycled.into()),
433        ]));
434
435        let schema_entries = self
436            .internal_search(schema_filter)
437            .map(|ent| {
438                ent.into_iter()
439                    .map(|e| ReplEntryV1::new(e.as_ref(), schema))
440                    .collect()
441            })
442            .inspect_err(|err| {
443                error!(?err, "Failed to access schema entries");
444            })?;
445
446        let meta_entries = self
447            .internal_search(meta_filter)
448            .map(|ent| {
449                ent.into_iter()
450                    .map(|e| ReplEntryV1::new(e.as_ref(), schema))
451                    .collect()
452            })
453            .inspect_err(|err| {
454                error!(?err, "Failed to access meta entries");
455            })?;
456
457        let entries = self
458            .internal_search(entry_filter)
459            .map(|ent| {
460                ent.into_iter()
461                    .map(|e| ReplEntryV1::new(e.as_ref(), schema))
462                    .collect()
463            })
464            .inspect_err(|err| {
465                error!(?err, "Failed to access entries");
466            })?;
467
468        // Finally, populate the ranges with anchors from the RUV
469        let supplier_ruv = self.get_be_txn().get_ruv();
470        let ranges = supplier_ruv.get_anchored_ranges(ranges)?;
471
472        Ok(ReplRefreshContext::V1 {
473            domain_version,
474            domain_devel,
475            domain_uuid,
476            ranges,
477            schema_entries,
478            meta_entries,
479            entries,
480        })
481    }
482}