pgroles-operator 0.10.0-alpha.1

Kubernetes operator for pgroles — reconciles PostgresPolicy CRDs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Watch-fed indexes for ephemeral access requests.
//!
//! The request controller and this index consume the same watcher stream. A
//! request therefore enters the index before its reconcile can activate access,
//! while finalizers keep deleted requests present until revocation completes.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use kube::ResourceExt;
use kube::runtime::reflector::ObjectRef;
use kube::runtime::watcher::Event;
use tokio::sync::Notify;

use crate::crd::EphemeralAccessRequest;

type NamespacedKey = (String, String);

/// How long a lookup waits for the initial watch sync before giving up.
///
/// `compose_effective_graph` calls into this index from the PostgresPolicy
/// reconciler *after* both database locks are held. An unbounded wait would
/// therefore keep a PostgreSQL advisory lock for as long as the request watch
/// stayed broken, stalling every replica and every policy sharing that
/// database rather than only the ephemeral paths. Failing the lookup instead
/// lets the reconcile unwind, drop its locks, and requeue with backoff.
const READY_TIMEOUT: Duration = Duration::from_secs(30);

/// The request watch had not completed its initial sync in time.
#[derive(Debug, thiserror::Error)]
#[error("ephemeral request index did not sync within {waited:?}")]
pub struct IndexNotReady {
    waited: Duration,
}

#[derive(Default)]
struct IndexState {
    objects: HashMap<ObjectRef<EphemeralAccessRequest>, Arc<EphemeralAccessRequest>>,
    by_access_policy_name: HashMap<NamespacedKey, HashSet<ObjectRef<EphemeralAccessRequest>>>,
    by_access_policy_uid: HashMap<NamespacedKey, HashSet<ObjectRef<EphemeralAccessRequest>>>,
    by_target_policy_uid: HashMap<NamespacedKey, HashSet<ObjectRef<EphemeralAccessRequest>>>,
}

impl IndexState {
    fn remove(&mut self, object_ref: &ObjectRef<EphemeralAccessRequest>) {
        let Some(request) = self.objects.remove(object_ref) else {
            return;
        };
        remove_ref(
            &mut self.by_access_policy_name,
            &namespaced_key(&request, &request.spec.access_policy_ref.name),
            object_ref,
        );
        if let Some(resolved) = request
            .status
            .as_ref()
            .and_then(|status| status.resolved_access.as_ref())
        {
            remove_ref(
                &mut self.by_access_policy_uid,
                &namespaced_key(&request, &resolved.access_policy_uid),
                object_ref,
            );
            remove_ref(
                &mut self.by_target_policy_uid,
                &namespaced_key(&request, &resolved.target_policy_uid),
                object_ref,
            );
        }
    }

    fn upsert(&mut self, request: &EphemeralAccessRequest) {
        let object_ref = ObjectRef::from_obj(request);
        self.remove(&object_ref);
        let request = Arc::new(request.clone());
        self.by_access_policy_name
            .entry(namespaced_key(
                &request,
                &request.spec.access_policy_ref.name,
            ))
            .or_default()
            .insert(object_ref.clone());
        if let Some(resolved) = request
            .status
            .as_ref()
            .and_then(|status| status.resolved_access.as_ref())
        {
            self.by_access_policy_uid
                .entry(namespaced_key(&request, &resolved.access_policy_uid))
                .or_default()
                .insert(object_ref.clone());
            self.by_target_policy_uid
                .entry(namespaced_key(&request, &resolved.target_policy_uid))
                .or_default()
                .insert(object_ref.clone());
        }
        self.objects.insert(object_ref, request);
    }

    fn values_for(
        &self,
        index: &HashMap<NamespacedKey, HashSet<ObjectRef<EphemeralAccessRequest>>>,
        key: &NamespacedKey,
    ) -> Vec<Arc<EphemeralAccessRequest>> {
        index
            .get(key)
            .into_iter()
            .flatten()
            .filter_map(|object_ref| self.objects.get(object_ref).cloned())
            .collect()
    }
}

fn namespaced_key(request: &EphemeralAccessRequest, value: &str) -> NamespacedKey {
    (request.namespace().unwrap_or_default(), value.to_string())
}

fn remove_ref(
    index: &mut HashMap<NamespacedKey, HashSet<ObjectRef<EphemeralAccessRequest>>>,
    key: &NamespacedKey,
    object_ref: &ObjectRef<EphemeralAccessRequest>,
) {
    let remove_key = if let Some(refs) = index.get_mut(key) {
        refs.remove(object_ref);
        refs.is_empty()
    } else {
        false
    };
    if remove_key {
        index.remove(key);
    }
}

/// An atomically refreshed, watch-fed request index.
#[derive(Clone, Default)]
pub struct RequestIndex {
    live: Arc<RwLock<IndexState>>,
    initializing: Arc<RwLock<Option<IndexState>>>,
    ready: Arc<AtomicBool>,
    ready_notify: Arc<Notify>,
}

impl RequestIndex {
    /// Observe one event before it is passed to the controller reflector.
    pub fn observe(&self, event: &Event<EphemeralAccessRequest>) {
        match event {
            Event::Apply(request) => self
                .live
                .write()
                .expect("request index poisoned")
                .upsert(request),
            Event::Delete(request) => self
                .live
                .write()
                .expect("request index poisoned")
                .remove(&ObjectRef::from_obj(request)),
            Event::Init => {
                *self.initializing.write().expect("request index poisoned") =
                    Some(IndexState::default());
            }
            Event::InitApply(request) => {
                if let Some(buffer) = self
                    .initializing
                    .write()
                    .expect("request index poisoned")
                    .as_mut()
                {
                    buffer.upsert(request);
                }
            }
            Event::InitDone => {
                if let Some(buffer) = self
                    .initializing
                    .write()
                    .expect("request index poisoned")
                    .take()
                {
                    *self.live.write().expect("request index poisoned") = buffer;
                }
                self.ready.store(true, Ordering::Release);
                self.ready_notify.notify_waiters();
            }
        }
    }

    async fn wait_ready(&self) -> Result<(), IndexNotReady> {
        let synced = async {
            while !self.ready.load(Ordering::Acquire) {
                // Register interest before re-checking, so an InitDone landing
                // between the check and the await is not a lost wakeup.
                let notified = self.ready_notify.notified();
                if self.ready.load(Ordering::Acquire) {
                    break;
                }
                notified.await;
            }
        };
        tokio::time::timeout(READY_TIMEOUT, synced)
            .await
            .map_err(|_| IndexNotReady {
                waited: READY_TIMEOUT,
            })
    }

    pub async fn for_access_policy_name(
        &self,
        namespace: &str,
        name: &str,
    ) -> Result<Vec<Arc<EphemeralAccessRequest>>, IndexNotReady> {
        self.wait_ready().await?;
        let state = self.live.read().expect("request index poisoned");
        Ok(state.values_for(
            &state.by_access_policy_name,
            &(namespace.to_string(), name.to_string()),
        ))
    }

    pub async fn for_access_policy_uid(
        &self,
        namespace: &str,
        uid: &str,
    ) -> Result<Vec<Arc<EphemeralAccessRequest>>, IndexNotReady> {
        self.wait_ready().await?;
        let state = self.live.read().expect("request index poisoned");
        Ok(state.values_for(
            &state.by_access_policy_uid,
            &(namespace.to_string(), uid.to_string()),
        ))
    }

    pub async fn for_target_policy_uid(
        &self,
        namespace: &str,
        uid: &str,
    ) -> Result<Vec<Arc<EphemeralAccessRequest>>, IndexNotReady> {
        self.wait_ready().await?;
        let state = self.live.read().expect("request index poisoned");
        Ok(state.values_for(
            &state.by_target_policy_uid,
            &(namespace.to_string(), uid.to_string()),
        ))
    }

    pub fn len(&self) -> usize {
        self.live
            .read()
            .expect("request index poisoned")
            .objects
            .len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crd::{
        DecisionActor, EphemeralAccessRequestSpec, EphemeralAccessRequestStatus,
        EphemeralAccessSubject, LocalObjectReference, ResolvedEphemeralAccess,
    };

    fn request(
        name: &str,
        access_name: &str,
        access_uid: &str,
        target_uid: &str,
    ) -> EphemeralAccessRequest {
        let mut request = EphemeralAccessRequest::new(
            name,
            EphemeralAccessRequestSpec {
                access_policy_ref: LocalObjectReference {
                    name: access_name.into(),
                },
                subject: EphemeralAccessSubject {
                    role: "alice".into(),
                },
                requested_by: DecisionActor {
                    username: "user".into(),
                    uid: None,
                    groups: vec![],
                },
                requested_duration: None,
                justification: None,
            },
        );
        request.metadata.namespace = Some("ns".into());
        if !access_uid.is_empty() {
            request.status = Some(EphemeralAccessRequestStatus {
                resolved_access: Some(ResolvedEphemeralAccess {
                    access_policy_uid: access_uid.into(),
                    access_policy_generation: 1,
                    target_policy_uid: target_uid.into(),
                    target_policy_generation: 1,
                    target_database_fingerprint: "sha256:test".into(),
                    granted_duration: "1h".into(),
                    bundle_encoding: "test".into(),
                    bundle_hash: "sha256:test".into(),
                    memberships: vec![],
                }),
                ..Default::default()
            });
        }
        request
    }

    #[tokio::test]
    async fn indexes_names_and_resolved_uids_and_replaces_on_restart() {
        let index = RequestIndex::default();
        let first = request("one", "access", "access-uid", "target-uid");
        index.observe(&Event::Init);
        index.observe(&Event::InitApply(first.clone()));
        index.observe(&Event::InitDone);
        assert_eq!(
            index
                .for_access_policy_name("ns", "access")
                .await
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            index
                .for_access_policy_uid("ns", "access-uid")
                .await
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            index
                .for_target_policy_uid("ns", "target-uid")
                .await
                .unwrap()
                .len(),
            1
        );

        index.observe(&Event::Init);
        index.observe(&Event::InitDone);
        assert_eq!(index.len(), 0);
    }

    #[tokio::test(start_paused = true)]
    async fn lookups_fail_instead_of_hanging_when_the_watch_never_syncs() {
        // A request watch that never reaches InitDone previously blocked every
        // lookup forever. compose_effective_graph runs with both database locks
        // held, so that hang stranded a PostgreSQL advisory lock and wedged the
        // other replicas rather than failing this one reconcile.
        let index = RequestIndex::default();
        index.observe(&Event::Init);
        assert!(
            index
                .for_target_policy_uid("ns", "target-uid")
                .await
                .is_err()
        );
    }

    #[tokio::test(start_paused = true)]
    async fn lookups_unblock_as_soon_as_the_watch_syncs() {
        let index = RequestIndex::default();
        let waiter = {
            let index = index.clone();
            tokio::spawn(async move { index.for_access_policy_name("ns", "access").await })
        };
        tokio::task::yield_now().await;
        index.observe(&Event::Init);
        index.observe(&Event::InitApply(request("one", "access", "", "")));
        index.observe(&Event::InitDone);
        assert_eq!(waiter.await.expect("waiter panicked").unwrap().len(), 1);
    }

    #[tokio::test]
    async fn unresolved_requests_are_indexed_by_policy_name() {
        let index = RequestIndex::default();
        index.observe(&Event::Init);
        index.observe(&Event::InitApply(request("one", "access", "", "")));
        index.observe(&Event::InitDone);
        assert_eq!(
            index
                .for_access_policy_name("ns", "access")
                .await
                .unwrap()
                .len(),
            1
        );
        assert!(
            index
                .for_access_policy_uid("ns", "access-uid")
                .await
                .unwrap()
                .is_empty()
        );
    }

    #[tokio::test]
    async fn lookup_ignores_irrelevant_requests_and_forged_labels() {
        let index = RequestIndex::default();
        index.observe(&Event::Init);
        for sequence in 0..1_000 {
            let mut irrelevant = request(
                &format!("irrelevant-{sequence}"),
                "other-access",
                "other-access-uid",
                "other-target-uid",
            );
            irrelevant.metadata.namespace = Some(if sequence % 2 == 0 {
                "ns".into()
            } else {
                "other-ns".into()
            });
            index.observe(&Event::InitApply(irrelevant));
        }
        let mut relevant = request("relevant", "access", "access-uid", "target-uid");
        relevant.labels_mut().insert(
            crate::crd::LABEL_TARGET_POLICY_UID.into(),
            "forged-uid".into(),
        );
        index.observe(&Event::InitApply(relevant));
        index.observe(&Event::InitDone);

        let matches = index
            .for_target_policy_uid("ns", "target-uid")
            .await
            .unwrap();
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].name_any(), "relevant");
        assert!(
            index
                .for_target_policy_uid("ns", "forged-uid")
                .await
                .unwrap()
                .is_empty()
        );
    }
}