-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathsilo_group.rs
More file actions
826 lines (730 loc) · 28 KB
/
Copy pathsilo_group.rs
File metadata and controls
826 lines (730 loc) · 28 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! [`DataStore`] methods related to [`SiloGroup`]s.
use super::DataStore;
use crate::authz;
use crate::context::OpContext;
use crate::db::IncompleteOnConflictExt;
use crate::db::datastore::RunnableQueryNoReturn;
use crate::db::model;
use crate::db::model::Silo;
use crate::db::model::SiloGroupMembership;
use crate::db::model::UserProvisionType;
use crate::db::model::to_db_typed_uuid;
use crate::db::pagination::paginated;
use async_bb8_diesel::AsyncRunQueryDsl;
use chrono::DateTime;
use chrono::Utc;
use diesel::prelude::*;
use nexus_db_errors::ErrorHandler;
use nexus_db_errors::TransactionError;
use nexus_db_errors::public_error_from_diesel;
use nexus_types::external_api::user;
use nexus_types::identity::Asset;
use omicron_common::api::external::CreateResult;
use omicron_common::api::external::DataPageParams;
use omicron_common::api::external::DeleteResult;
use omicron_common::api::external::Error;
use omicron_common::api::external::InternalContext;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupResult;
use omicron_common::api::external::UpdateResult;
use omicron_uuid_kinds::SiloGroupUuid;
use omicron_uuid_kinds::SiloUserUuid;
use uuid::Uuid;
/// The datastore crate's SiloGroup is intended to provide type safety above the
/// database model, as the same database model is used to store semantically
/// different group types. Higher level parts of Nexus should use this type
/// instead.
#[derive(Debug, Clone)]
pub enum SiloGroup {
/// A Group created via the API
ApiOnly(SiloGroupApiOnly),
/// A Group created during an authenticated SAML login
Jit(SiloGroupJit),
/// A Group created by a SCIM provisioning client
Scim(SiloGroupScim),
}
impl SiloGroup {
pub fn id(&self) -> SiloGroupUuid {
match &self {
SiloGroup::ApiOnly(u) => u.id,
SiloGroup::Jit(u) => u.id,
SiloGroup::Scim(u) => u.id,
}
}
pub fn silo_id(&self) -> Uuid {
match &self {
SiloGroup::ApiOnly(u) => u.silo_id,
SiloGroup::Jit(u) => u.silo_id,
SiloGroup::Scim(u) => u.silo_id,
}
}
}
impl From<model::SiloGroup> for SiloGroup {
fn from(record: model::SiloGroup) -> SiloGroup {
match record.user_provision_type {
UserProvisionType::ApiOnly => {
SiloGroup::ApiOnly(SiloGroupApiOnly {
id: record.id(),
time_created: record.time_created(),
time_modified: record.time_modified(),
time_deleted: record.time_deleted,
silo_id: record.silo_id,
external_id: record.external_id.expect(
"the constraint `external_id_consistency` prevents a \
group with provision type 'api_only' from having a \
null external_id",
),
})
}
UserProvisionType::Jit => SiloGroup::Jit(SiloGroupJit {
id: record.id(),
time_created: record.time_created(),
time_modified: record.time_modified(),
time_deleted: record.time_deleted,
silo_id: record.silo_id,
external_id: record.external_id.expect(
"the constraint `external_id_consistency` prevents a \
group with provision type 'jit' from having a null \
external_id",
),
}),
UserProvisionType::Scim => SiloGroup::Scim(SiloGroupScim {
id: record.id(),
time_created: record.time_created(),
time_modified: record.time_modified(),
time_deleted: record.time_deleted,
silo_id: record.silo_id,
display_name: record.display_name.expect(
"the constraint `display_name_consistency` prevents a \
group with provision type 'scim' from having a null \
display_name",
),
external_id: record.external_id,
}),
}
}
}
impl From<SiloGroup> for model::SiloGroup {
fn from(u: SiloGroup) -> model::SiloGroup {
match u {
SiloGroup::ApiOnly(u) => u.into(),
SiloGroup::Jit(u) => u.into(),
SiloGroup::Scim(u) => u.into(),
}
}
}
impl From<SiloGroup> for user::Group {
fn from(u: SiloGroup) -> user::Group {
match u {
SiloGroup::ApiOnly(u) => u.into(),
SiloGroup::Jit(u) => u.into(),
SiloGroup::Scim(u) => u.into(),
}
}
}
impl From<SiloGroup> for user::UserGroup {
fn from(u: SiloGroup) -> user::UserGroup {
let group = user::Group::from(u);
user::UserGroup { id: group.id, display_name: group.display_name }
}
}
#[derive(Debug, Clone)]
pub struct SiloGroupApiOnly {
pub id: SiloGroupUuid,
pub time_created: DateTime<Utc>,
pub time_modified: DateTime<Utc>,
pub time_deleted: Option<DateTime<Utc>>,
pub silo_id: Uuid,
/// The identity provider's ID for this group.
pub external_id: String,
}
impl SiloGroupApiOnly {
pub fn new(silo_id: Uuid, id: SiloGroupUuid, external_id: String) -> Self {
Self {
id,
time_created: Utc::now(),
time_modified: Utc::now(),
time_deleted: None,
silo_id,
external_id,
}
}
}
impl From<SiloGroupApiOnly> for model::SiloGroup {
fn from(u: SiloGroupApiOnly) -> model::SiloGroup {
model::SiloGroup {
identity: model::SiloGroupIdentity {
id: u.id.into(),
time_created: u.time_created,
time_modified: u.time_modified,
},
time_deleted: u.time_deleted,
silo_id: u.silo_id,
external_id: Some(u.external_id),
user_provision_type: UserProvisionType::ApiOnly,
display_name: None,
}
}
}
impl From<SiloGroupApiOnly> for SiloGroup {
fn from(u: SiloGroupApiOnly) -> SiloGroup {
SiloGroup::ApiOnly(u)
}
}
impl From<SiloGroupApiOnly> for user::Group {
fn from(u: SiloGroupApiOnly) -> user::Group {
user::Group {
id: u.id,
// TODO the use of external_id as display_name is temporary
display_name: u.external_id,
silo_id: u.silo_id,
time_created: u.time_created,
time_modified: u.time_modified,
}
}
}
#[derive(Debug, Clone)]
pub struct SiloGroupJit {
pub id: SiloGroupUuid,
pub time_created: DateTime<Utc>,
pub time_modified: DateTime<Utc>,
pub time_deleted: Option<DateTime<Utc>>,
pub silo_id: Uuid,
/// The identity provider's ID for this user.
pub external_id: String,
}
impl SiloGroupJit {
pub fn new(silo_id: Uuid, id: SiloGroupUuid, external_id: String) -> Self {
Self {
id,
time_created: Utc::now(),
time_modified: Utc::now(),
time_deleted: None,
silo_id,
external_id,
}
}
}
impl From<SiloGroupJit> for model::SiloGroup {
fn from(u: SiloGroupJit) -> model::SiloGroup {
model::SiloGroup {
identity: model::SiloGroupIdentity {
id: u.id.into(),
time_created: u.time_created,
time_modified: u.time_modified,
},
time_deleted: u.time_deleted,
silo_id: u.silo_id,
external_id: Some(u.external_id),
user_provision_type: UserProvisionType::Jit,
display_name: None,
}
}
}
impl From<SiloGroupJit> for SiloGroup {
fn from(u: SiloGroupJit) -> SiloGroup {
SiloGroup::Jit(u)
}
}
impl From<SiloGroupJit> for user::Group {
fn from(u: SiloGroupJit) -> user::Group {
user::Group {
id: u.id,
// TODO the use of external_id as display_name is temporary
display_name: u.external_id,
silo_id: u.silo_id,
time_created: u.time_created,
time_modified: u.time_modified,
}
}
}
#[derive(Debug, Clone)]
pub struct SiloGroupScim {
pub id: SiloGroupUuid,
pub time_created: DateTime<Utc>,
pub time_modified: DateTime<Utc>,
pub time_deleted: Option<DateTime<Utc>>,
pub silo_id: Uuid,
/// The identity provider's ID for this group.
pub display_name: String,
pub external_id: Option<String>,
}
impl SiloGroupScim {
pub fn new(
silo_id: Uuid,
id: SiloGroupUuid,
display_name: String,
external_id: Option<String>,
) -> Self {
Self {
id,
time_created: Utc::now(),
time_modified: Utc::now(),
time_deleted: None,
silo_id,
display_name,
external_id,
}
}
}
impl From<SiloGroupScim> for model::SiloGroup {
fn from(u: SiloGroupScim) -> model::SiloGroup {
model::SiloGroup {
identity: model::SiloGroupIdentity {
id: u.id.into(),
time_created: u.time_created,
time_modified: u.time_modified,
},
time_deleted: u.time_deleted,
silo_id: u.silo_id,
external_id: u.external_id,
user_provision_type: UserProvisionType::Scim,
display_name: Some(u.display_name),
}
}
}
impl From<SiloGroupScim> for SiloGroup {
fn from(u: SiloGroupScim) -> SiloGroup {
SiloGroup::Scim(u)
}
}
impl From<SiloGroupScim> for user::Group {
fn from(u: SiloGroupScim) -> user::Group {
user::Group {
id: u.id,
// TODO the use of display name as display_name is temporary
display_name: u.display_name,
silo_id: u.silo_id,
time_created: u.time_created,
time_modified: u.time_modified,
}
}
}
/// Different types of group have different fields that are considered unique,
/// and therefore lookup needs to be typed as well.
#[derive(Debug)]
pub enum SiloGroupLookup<'a> {
ApiOnly { external_id: &'a str },
Jit { external_id: &'a str },
Scim { display_name: &'a str },
}
impl<'a> SiloGroupLookup<'a> {
pub fn user_provision_type(&self) -> UserProvisionType {
match &self {
SiloGroupLookup::ApiOnly { .. } => UserProvisionType::ApiOnly,
SiloGroupLookup::Jit { .. } => UserProvisionType::Jit,
SiloGroupLookup::Scim { .. } => UserProvisionType::Scim,
}
}
}
impl DataStore {
pub(super) async fn silo_group_ensure_query(
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_group: model::SiloGroup,
) -> Result<impl RunnableQueryNoReturn + use<>, Error> {
opctx.authorize(authz::Action::CreateChild, authz_silo).await?;
use nexus_db_schema::schema::silo_group::dsl;
Ok(diesel::insert_into(dsl::silo_group)
.values(silo_group)
.on_conflict((dsl::silo_id, dsl::external_id))
.as_partial_index()
.do_nothing())
}
pub async fn silo_group_ensure(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_group: SiloGroup,
) -> CreateResult<SiloGroup> {
let conn = self.pool_connection_authorized(opctx).await?;
let group_id = silo_group.id();
let model: model::SiloGroup = silo_group.into();
// Check the user's provision type matches the silo
let silo = {
use nexus_db_schema::schema::silo::dsl;
dsl::silo
.filter(dsl::id.eq(authz_silo.id()))
.select(model::Silo::as_select())
.get_result_async::<model::Silo>(&*conn)
.await
.map_err(|e| {
public_error_from_diesel(
e,
ErrorHandler::NotFoundByResource(authz_silo),
)
})?
};
if silo.user_provision_type != model.user_provision_type {
error!(
self.log,
"silo {} provision type {:?} does not match silo group {} \
provision type {:?}",
authz_silo.id(),
silo.user_provision_type,
model.id(),
model.user_provision_type,
);
return Err(Error::internal_error(&format!(
"user provision type of silo ({:?}) does not match \
silo group ({:?})",
silo.user_provision_type, model.user_provision_type,
)));
}
DataStore::silo_group_ensure_query(opctx, authz_silo, model)
.await?
.execute_async(&*conn)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?;
let silo_group = {
use nexus_db_schema::schema::silo_group::dsl;
let maybe_silo_group = dsl::silo_group
.filter(dsl::silo_id.eq(authz_silo.id()))
.filter(dsl::id.eq(to_db_typed_uuid(group_id)))
.select(model::SiloGroup::as_select())
.first_async(&*conn)
.await
.optional()
.map_err(|e| {
public_error_from_diesel(e, ErrorHandler::Server)
})?;
// This function is _not_ transactional, meaning two types of delete
// could race between the ensure query and the lookup:
//
// - a silo delete could win the race, which will delete all the
// groups in that silo (including this newly created one).
//
// - a silo group delete (probably preceded by a silo group lookup
// by name) could win the race, which will delete this specific
// group.
//
// If either deletes win, return a conflict instead of a not found.
let Some(silo_group) = maybe_silo_group else {
return Err(Error::conflict(format!(
"group {group_id} deleted"
)));
};
silo_group
};
Ok(silo_group.into())
}
pub async fn silo_group_optional_lookup<'a>(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_group_lookup: &'a SiloGroupLookup<'a>,
) -> LookupResult<Option<SiloGroup>> {
opctx.authorize(authz::Action::ListChildren, authz_silo).await?;
// Check the silo's provision type matches the lookup.
let conn = self.pool_connection_authorized(opctx).await?;
let silo = {
use nexus_db_schema::schema::silo::dsl;
dsl::silo
.filter(dsl::id.eq(authz_silo.id()))
.select(Silo::as_select())
.get_result_async::<Silo>(&*conn)
.await
.map_err(|e| {
public_error_from_diesel(
e,
ErrorHandler::NotFoundByResource(authz_silo),
)
})?
};
let lookup_user_provision_type =
silo_group_lookup.user_provision_type();
if silo.user_provision_type != lookup_user_provision_type {
error!(
self.log,
"silo {} provision type {:?} does not match lookup provision \
type {:?}",
authz_silo.id(),
silo.user_provision_type,
lookup_user_provision_type,
);
return Err(Error::internal_error(&format!(
"user provision type of silo ({:?}) does not match \
lookup ({:?})",
silo.user_provision_type, lookup_user_provision_type,
)));
}
use nexus_db_schema::schema::silo_group::dsl;
let maybe_silo_group = match silo_group_lookup {
SiloGroupLookup::ApiOnly { external_id }
| SiloGroupLookup::Jit { external_id } => dsl::silo_group
.filter(dsl::silo_id.eq(authz_silo.id()))
.filter(dsl::user_provision_type.eq(lookup_user_provision_type))
.filter(dsl::external_id.eq(external_id.to_string()))
.filter(dsl::time_deleted.is_null())
.select(model::SiloGroup::as_select())
.first_async(&*conn)
.await
.optional()
.map_err(|e| {
public_error_from_diesel(e, ErrorHandler::Server)
})?,
SiloGroupLookup::Scim { display_name } => dsl::silo_group
.filter(dsl::silo_id.eq(authz_silo.id()))
.filter(dsl::user_provision_type.eq(lookup_user_provision_type))
.filter(dsl::display_name.eq(display_name.to_string()))
.filter(dsl::time_deleted.is_null())
.select(model::SiloGroup::as_select())
.first_async(&*conn)
.await
.optional()
.map_err(|e| {
public_error_from_diesel(e, ErrorHandler::Server)
})?,
};
Ok(maybe_silo_group.map(|group| group.into()))
}
pub async fn silo_group_membership_for_user(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_user_id: SiloUserUuid,
) -> ListResultVec<SiloGroupMembership> {
opctx.authorize(authz::Action::ListChildren, authz_silo).await?;
use nexus_db_schema::schema::silo_group_membership::dsl;
dsl::silo_group_membership
.filter(dsl::silo_user_id.eq(to_db_typed_uuid(silo_user_id)))
.select(SiloGroupMembership::as_returning())
.get_results_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))
}
pub async fn silo_group_membership_for_group(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_group_id: SiloGroupUuid,
) -> ListResultVec<SiloGroupMembership> {
opctx.authorize(authz::Action::ListChildren, authz_silo).await?;
use nexus_db_schema::schema::silo_group_membership::dsl;
dsl::silo_group_membership
.filter(dsl::silo_group_id.eq(to_db_typed_uuid(silo_group_id)))
.select(SiloGroupMembership::as_returning())
.get_results_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))
}
/// Fetch the groups that each of the given users is a member of, for
/// embedding group memberships in `User` views
pub async fn silo_groups_for_users(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_user_ids: &[SiloUserUuid],
) -> ListResultVec<(SiloUserUuid, SiloGroup)> {
// Match the authz check used to list the silo's groups
// (silo_groups_list_by_id): anyone who can read the silo can see the
// groups in it.
opctx.authorize(authz::Action::Read, authz_silo).await?;
use nexus_db_schema::schema::{
silo_group as sg, silo_group_membership as sgm,
};
let user_ids: Vec<_> =
silo_user_ids.iter().map(|id| to_db_typed_uuid(*id)).collect();
Ok(sgm::dsl::silo_group_membership
.inner_join(sg::table.on(sg::id.eq(sgm::silo_group_id)))
.filter(sgm::silo_user_id.eq_any(user_ids))
.filter(sg::time_deleted.is_null())
.select((
SiloGroupMembership::as_select(),
model::SiloGroup::as_select(),
))
.get_results_async::<(SiloGroupMembership, model::SiloGroup)>(
&*self.pool_connection_authorized(opctx).await?,
)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?
.into_iter()
.map(|(membership, group)| {
(membership.silo_user_id.into(), group.into())
})
.collect())
}
pub async fn silo_groups_for_self(
&self,
opctx: &OpContext,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<SiloGroup> {
// Similar to session_hard_delete (see comment there), we do not do a
// typical authz check, instead effectively encoding the policy here
// that any user is allowed to fetch their own group memberships
let &actor = opctx
.authn
.actor_required()
.internal_context("fetching current user's group memberships")?;
let silo_user_id = match actor.silo_user_id() {
Some(silo_user_id) => silo_user_id,
None => {
return Err(Error::non_resourcetype_not_found(
"could not find silo user",
))?;
}
};
use nexus_db_schema::schema::{
silo_group as sg, silo_group_membership as sgm,
};
let page = paginated(sg::dsl::silo_group, sg::id, pagparams)
.inner_join(sgm::table.on(sgm::silo_group_id.eq(sg::id)))
.filter(sgm::silo_user_id.eq(to_db_typed_uuid(silo_user_id)))
.filter(sg::time_deleted.is_null())
.select(model::SiloGroup::as_returning())
.get_results_async(&*self.pool_connection_authorized(opctx).await?)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?
.into_iter()
.map(|group: model::SiloGroup| group.into())
.collect::<Vec<SiloGroup>>();
Ok(page)
}
/// Update a silo user's group membership:
///
/// - add the user to groups they are supposed to be a member of, and
/// - remove the user from groups if they no longer have membership
///
/// Do this as one transaction that deletes all current memberships for a
/// user, then adds back the ones they are in. This avoids the scenario
/// where a crash half way through causes the resulting group memberships to
/// be incorrect.
pub async fn silo_group_membership_replace_for_user(
&self,
opctx: &OpContext,
authz_silo_user: &authz::SiloUser,
silo_group_ids: Vec<SiloGroupUuid>,
) -> UpdateResult<()> {
opctx.authorize(authz::Action::Modify, authz_silo_user).await?;
let conn = self.pool_connection_authorized(opctx).await?;
self.transaction_retry_wrapper("silo_group_membership_replace_for_user")
.transaction(&conn, |conn| {
let silo_group_ids = silo_group_ids.clone();
async move {
use nexus_db_schema::schema::silo_group_membership::dsl;
// Delete existing memberships for user
let silo_user_id = authz_silo_user.id();
diesel::delete(dsl::silo_group_membership)
.filter(
dsl::silo_user_id
.eq(to_db_typed_uuid(silo_user_id)),
)
.execute_async(&conn)
.await?;
// Create new memberships for user
let silo_group_memberships: Vec<
model::SiloGroupMembership,
> = silo_group_ids
.iter()
.map(|group_id| model::SiloGroupMembership {
silo_group_id: to_db_typed_uuid(*group_id),
silo_user_id: to_db_typed_uuid(silo_user_id),
})
.collect();
diesel::insert_into(dsl::silo_group_membership)
.values(silo_group_memberships)
.execute_async(&conn)
.await?;
Ok(())
}
})
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))
}
pub async fn silo_group_delete(
&self,
opctx: &OpContext,
authz_silo_group: &authz::SiloGroup,
) -> DeleteResult {
opctx.authorize(authz::Action::Delete, authz_silo_group).await?;
#[derive(Debug, thiserror::Error)]
enum SiloDeleteError {
#[error("group {0} still has memberships")]
GroupStillHasMemberships(SiloGroupUuid),
}
type TxnError = TransactionError<SiloDeleteError>;
let group_id = authz_silo_group.id();
let conn = self.pool_connection_authorized(opctx).await?;
// Prefer to use "transaction_retry_wrapper"
self.transaction_non_retry_wrapper("silo_group_delete")
.transaction(&conn, |conn| async move {
use nexus_db_schema::schema::silo_group_membership;
// Don't delete groups that still have memberships
let group_memberships =
silo_group_membership::dsl::silo_group_membership
.filter(
silo_group_membership::dsl::silo_group_id
.eq(to_db_typed_uuid(group_id)),
)
.select(SiloGroupMembership::as_returning())
.limit(1)
.load_async(&conn)
.await?;
if !group_memberships.is_empty() {
return Err(TxnError::CustomError(
SiloDeleteError::GroupStillHasMemberships(group_id),
));
}
// Delete silo group
use nexus_db_schema::schema::silo_group::dsl;
diesel::update(dsl::silo_group)
.filter(dsl::id.eq(to_db_typed_uuid(group_id)))
.filter(dsl::time_deleted.is_null())
.set(dsl::time_deleted.eq(Utc::now()))
.execute_async(&conn)
.await?;
Ok(())
})
.await
.map_err(|e| match e {
TxnError::CustomError(
SiloDeleteError::GroupStillHasMemberships(id),
) => Error::invalid_request(&format!(
"group {0} still has memberships",
id
)),
TxnError::Database(error) => {
public_error_from_diesel(error, ErrorHandler::Server)
}
})
}
pub async fn silo_groups_list_by_id(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<SiloGroup> {
use nexus_db_schema::schema::silo_group::dsl;
opctx.authorize(authz::Action::Read, authz_silo).await?;
let conn = self.pool_connection_authorized(opctx).await?;
let silo = {
use nexus_db_schema::schema::silo::dsl;
dsl::silo
.filter(dsl::id.eq(authz_silo.id()))
.select(model::Silo::as_select())
.get_result_async::<model::Silo>(&*conn)
.await
.map_err(|e| {
public_error_from_diesel(
e,
ErrorHandler::NotFoundByResource(authz_silo),
)
})?
};
let page = paginated(dsl::silo_group, dsl::id, pagparams)
.filter(dsl::silo_id.eq(authz_silo.id()))
.filter(dsl::time_deleted.is_null())
.filter(dsl::user_provision_type.eq(silo.user_provision_type))
.select(model::SiloGroup::as_select())
.load_async::<model::SiloGroup>(&*conn)
.await
.map_err(|e| public_error_from_diesel(e, ErrorHandler::Server))?
.into_iter()
.map(|group: model::SiloGroup| group.into())
.collect::<Vec<SiloGroup>>();
Ok(page)
}
}