-
Notifications
You must be signed in to change notification settings - Fork 40
/
silo.rs
887 lines (812 loc) · 31.7 KB
/
silo.rs
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
// 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/.
//! Silos, Users, and SSH Keys.
use crate::authz::ApiResource;
use crate::db::identity::{Asset, Resource};
use crate::db::lookup::LookupPath;
use crate::db::model::Name;
use crate::db::model::SshKey;
use crate::db::{self, lookup};
use crate::external_api::params;
use crate::external_api::shared;
use crate::{authn, authz};
use anyhow::Context;
use nexus_db_model::{DnsGroup, UserProvisionType};
use nexus_db_queries::context::OpContext;
use nexus_db_queries::db::datastore::DnsVersionUpdateBuilder;
use nexus_types::internal_api::params::DnsRecord;
use omicron_common::api::external::http_pagination::PaginatedBy;
use omicron_common::api::external::ListResultVec;
use omicron_common::api::external::LookupResult;
use omicron_common::api::external::UpdateResult;
use omicron_common::api::external::{CreateResult, LookupType};
use omicron_common::api::external::{DataPageParams, ResourceType};
use omicron_common::api::external::{DeleteResult, NameOrId};
use omicron_common::api::external::{Error, InternalContext};
use omicron_common::bail_unless;
use ref_cast::RefCast;
use std::net::IpAddr;
use std::str::FromStr;
use uuid::Uuid;
impl super::Nexus {
// Silos
pub fn current_silo_lookup<'a>(
&'a self,
opctx: &'a OpContext,
) -> LookupResult<lookup::Silo<'a>> {
let silo = opctx
.authn
.silo_required()
.internal_context("looking up current silo")?;
let silo = self.silo_lookup(opctx, NameOrId::Id(silo.id()))?;
Ok(silo)
}
pub fn silo_lookup<'a>(
&'a self,
opctx: &'a OpContext,
silo: NameOrId,
) -> LookupResult<lookup::Silo<'a>> {
match silo {
NameOrId::Id(id) => {
let silo =
LookupPath::new(opctx, &self.db_datastore).silo_id(id);
Ok(silo)
}
NameOrId::Name(name) => {
let silo = LookupPath::new(opctx, &self.db_datastore)
.silo_name_owned(name.into());
Ok(silo)
}
}
}
/// Returns the (relative) DNS name for this Silo's API and console endpoints
/// _within_ the control plane DNS zone (i.e., without that zone's suffix)
///
/// This specific naming scheme is determined under RFD 357.
pub(crate) fn silo_dns_name(
name: &omicron_common::api::external::Name,
) -> String {
// RFD 4 constrains resource names (including Silo names) to DNS-safe
// strings, which is why it's safe to directly put the name of the
// resource into the DNS name rather than doing any kind of escaping.
format!("{}.sys", name)
}
pub async fn silo_create(
&self,
opctx: &OpContext,
new_silo_params: params::SiloCreate,
) -> CreateResult<db::model::Silo> {
// Silo group creation happens as Nexus's "external authn" context,
// not the user's context here. The user may not have permission to
// create arbitrary groups in the Silo, but we allow them to create
// this one in this case.
let external_authn_opctx = self.opctx_external_authn();
let datastore = self.datastore();
// Set up an external DNS name for this Silo's API and console
// endpoints (which are the same endpoint).
let dns_records: Vec<DnsRecord> = datastore
.nexus_external_addresses(external_authn_opctx)
.await?
.into_iter()
.map(|addr| match addr {
IpAddr::V4(addr) => DnsRecord::A(addr),
IpAddr::V6(addr) => DnsRecord::Aaaa(addr),
})
.collect();
let silo_name = &new_silo_params.identity.name;
let mut dns_update = DnsVersionUpdateBuilder::new(
DnsGroup::External,
format!("create silo: {:?}", silo_name),
self.id.to_string(),
);
dns_update.add_name(Self::silo_dns_name(silo_name), dns_records)?;
let silo = datastore
.silo_create(
&opctx,
&external_authn_opctx,
new_silo_params,
dns_update,
)
.await?;
self.background_tasks
.activate(&self.background_tasks.task_external_dns_config);
Ok(silo)
}
pub async fn silos_list(
&self,
opctx: &OpContext,
pagparams: &PaginatedBy<'_>,
) -> ListResultVec<db::model::Silo> {
self.db_datastore.silos_list(opctx, pagparams).await
}
pub async fn silo_delete(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
) -> DeleteResult {
let dns_opctx = self.opctx_external_authn();
let datastore = self.datastore();
let (.., authz_silo, db_silo) =
silo_lookup.fetch_for(authz::Action::Delete).await?;
let mut dns_update = DnsVersionUpdateBuilder::new(
DnsGroup::External,
format!("delete silo: {:?}", db_silo.name()),
self.id.to_string(),
);
dns_update.remove_name(Self::silo_dns_name(&db_silo.name()))?;
datastore
.silo_delete(opctx, &authz_silo, &db_silo, dns_opctx, dns_update)
.await?;
self.background_tasks
.activate(&self.background_tasks.task_external_dns_config);
Ok(())
}
// Role assignments
pub async fn silo_fetch_policy(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
) -> LookupResult<shared::Policy<authz::SiloRole>> {
let (.., authz_silo) =
silo_lookup.lookup_for(authz::Action::ReadPolicy).await?;
let role_assignments = self
.db_datastore
.role_assignment_fetch_visible(opctx, &authz_silo)
.await?
.into_iter()
.map(|r| r.try_into().context("parsing database role assignment"))
.collect::<Result<Vec<_>, _>>()
.map_err(|error| Error::internal_error(&format!("{:#}", error)))?;
Ok(shared::Policy { role_assignments })
}
pub async fn silo_update_policy(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
policy: &shared::Policy<authz::SiloRole>,
) -> UpdateResult<shared::Policy<authz::SiloRole>> {
let (.., authz_silo) =
silo_lookup.lookup_for(authz::Action::ModifyPolicy).await?;
let role_assignments = self
.db_datastore
.role_assignment_replace_visible(
opctx,
&authz_silo,
&policy.role_assignments,
)
.await?
.into_iter()
.map(|r| r.try_into())
.collect::<Result<Vec<_>, _>>()?;
Ok(shared::Policy { role_assignments })
}
// Users
/// Helper function for looking up a user in a Silo
///
/// `LookupPath` lets you look up users directly, regardless of what Silo
/// they're in. This helper validates that they're in the expected Silo.
async fn silo_user_lookup_by_id(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
silo_user_id: Uuid,
action: authz::Action,
) -> LookupResult<(authz::SiloUser, db::model::SiloUser)> {
let (_, authz_silo_user, db_silo_user) =
LookupPath::new(opctx, self.datastore())
.silo_user_id(silo_user_id)
.fetch_for(action)
.await?;
if db_silo_user.silo_id != authz_silo.id() {
return Err(authz_silo_user.not_found());
}
Ok((authz_silo_user, db_silo_user))
}
/// List the users in a Silo
pub async fn silo_list_users(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
pagparams: &DataPageParams<'_, Uuid>,
) -> ListResultVec<db::model::SiloUser> {
let (authz_silo,) = silo_lookup.lookup_for(authz::Action::Read).await?;
let authz_silo_user_list = authz::SiloUserList::new(authz_silo);
self.db_datastore
.silo_users_list(opctx, &authz_silo_user_list, pagparams)
.await
}
/// Fetch a user in a Silo
pub async fn silo_user_fetch(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
silo_user_id: Uuid,
) -> LookupResult<db::model::SiloUser> {
let (authz_silo,) = silo_lookup.lookup_for(authz::Action::Read).await?;
let (_, db_silo_user) = self
.silo_user_lookup_by_id(
opctx,
&authz_silo,
silo_user_id,
authz::Action::Read,
)
.await?;
Ok(db_silo_user)
}
// The "local" identity provider (available only in `LocalOnly` Silos)
/// Helper function for looking up a LocalOnly Silo by name
///
/// This is called from contexts that are trying to access the "local"
/// identity provider. On failure, it returns a 404 for that identity
/// provider.
async fn local_idp_fetch_silo(
&self,
silo_lookup: &lookup::Silo<'_>,
) -> LookupResult<(authz::Silo, db::model::Silo)> {
let (authz_silo, db_silo) = silo_lookup.fetch().await?;
if db_silo.user_provision_type != UserProvisionType::ApiOnly {
return Err(Error::not_found_by_name(
ResourceType::IdentityProvider,
&omicron_common::api::external::Name::from_str("local")
.unwrap(),
));
}
Ok((authz_silo, db_silo))
}
/// Create a user in a Silo's local identity provider
pub async fn local_idp_create_user(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
new_user_params: params::UserCreate,
) -> CreateResult<db::model::SiloUser> {
let (authz_silo, db_silo) =
self.local_idp_fetch_silo(silo_lookup).await?;
let authz_silo_user_list = authz::SiloUserList::new(authz_silo.clone());
// TODO-cleanup This authz check belongs in silo_user_create().
opctx
.authorize(authz::Action::CreateChild, &authz_silo_user_list)
.await?;
let silo_user = db::model::SiloUser::new(
authz_silo.id(),
Uuid::new_v4(),
new_user_params.external_id.as_ref().to_owned(),
);
// TODO These two steps should happen in a transaction.
let (_, db_silo_user) =
self.datastore().silo_user_create(&authz_silo, silo_user).await?;
let authz_silo_user = authz::SiloUser::new(
authz_silo.clone(),
db_silo_user.id(),
LookupType::ById(db_silo_user.id()),
);
self.silo_user_password_set_internal(
opctx,
&db_silo,
&authz_silo_user,
&db_silo_user,
new_user_params.password,
)
.await?;
Ok(db_silo_user)
}
/// Delete a user in a Silo's local identity provider
pub async fn local_idp_delete_user(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
silo_user_id: Uuid,
) -> DeleteResult {
let (authz_silo, _) = self.local_idp_fetch_silo(silo_lookup).await?;
let (authz_silo_user, _) = self
.silo_user_lookup_by_id(
opctx,
&authz_silo,
silo_user_id,
authz::Action::Delete,
)
.await?;
self.db_datastore.silo_user_delete(opctx, &authz_silo_user).await
}
/// Based on an authenticated subject, fetch or create a silo user
pub async fn silo_user_from_authenticated_subject(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
db_silo: &db::model::Silo,
authenticated_subject: &authn::silos::AuthenticatedSubject,
) -> LookupResult<Option<db::model::SiloUser>> {
// XXX create user permission?
opctx.authorize(authz::Action::CreateChild, authz_silo).await?;
opctx.authorize(authz::Action::ListChildren, authz_silo).await?;
let fetch_result = self
.datastore()
.silo_user_fetch_by_external_id(
opctx,
&authz_silo,
&authenticated_subject.external_id,
)
.await?;
let (authz_silo_user, db_silo_user) =
if let Some(existing_silo_user) = fetch_result {
existing_silo_user
} else {
// In this branch, no user exists for the authenticated subject
// external id. The next action depends on the silo's user
// provision type.
match db_silo.user_provision_type {
// If the user provision type is ApiOnly, do not create a
// new user if one does not exist.
db::model::UserProvisionType::ApiOnly => {
return Ok(None);
}
// If the user provision type is JIT, then create the user if
// one does not exist
db::model::UserProvisionType::Jit => {
let silo_user = db::model::SiloUser::new(
authz_silo.id(),
Uuid::new_v4(),
authenticated_subject.external_id.clone(),
);
self.db_datastore
.silo_user_create(&authz_silo, silo_user)
.await?
}
}
};
// Gather a list of groups that the user is part of based on what the
// IdP sent us. Also, if the silo user provision type is Jit, create
// silo groups if new groups from the IdP are seen.
let mut silo_user_group_ids: Vec<Uuid> =
Vec::with_capacity(authenticated_subject.groups.len());
for group in &authenticated_subject.groups {
let silo_group = match db_silo.user_provision_type {
db::model::UserProvisionType::ApiOnly => {
self.db_datastore
.silo_group_optional_lookup(
opctx,
&authz_silo,
group.clone(),
)
.await?
}
db::model::UserProvisionType::Jit => {
let silo_group = self
.silo_group_lookup_or_create_by_name(
opctx,
&authz_silo,
&group,
)
.await?;
Some(silo_group)
}
};
if let Some(silo_group) = silo_group {
silo_user_group_ids.push(silo_group.id());
}
}
// Update the user's group memberships
self.db_datastore
.silo_group_membership_replace_for_user(
opctx,
&authz_silo_user,
silo_user_group_ids,
)
.await?;
Ok(Some(db_silo_user))
}
// Silo user passwords
/// Set or invalidate a Silo user's password
///
/// If `password` is `UserPassword::Password`, the password is set to the
/// requested value. Otherwise, any existing password is invalidated so
/// that it cannot be used for authentication any more.
pub async fn local_idp_user_set_password(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
silo_user_id: Uuid,
password_value: params::UserPassword,
) -> UpdateResult<()> {
let (authz_silo, db_silo) =
self.local_idp_fetch_silo(silo_lookup).await?;
let (authz_silo_user, db_silo_user) = self
.silo_user_lookup_by_id(
opctx,
&authz_silo,
silo_user_id,
authz::Action::Modify,
)
.await?;
self.silo_user_password_set_internal(
opctx,
&db_silo,
&authz_silo_user,
&db_silo_user,
password_value,
)
.await
}
/// Internal helper for setting a user's password
///
/// The caller should have already verified that this is a `LocalOnly` Silo
/// and that the specified user is in that Silo.
async fn silo_user_password_set_internal(
&self,
opctx: &OpContext,
db_silo: &db::model::Silo,
authz_silo_user: &authz::SiloUser,
db_silo_user: &db::model::SiloUser,
password_value: params::UserPassword,
) -> UpdateResult<()> {
let password_hash = match password_value {
params::UserPassword::InvalidPassword => None,
params::UserPassword::Password(password) => {
let mut hasher = nexus_passwords::Hasher::default();
let password_hash = hasher
.create_password(password.as_ref())
.map_err(|e| {
Error::internal_error(&format!("setting password: {:#}", e))
})?;
Some(db::model::SiloUserPasswordHash::new(
authz_silo_user.id(),
nexus_db_model::PasswordHashString::from(password_hash),
))
}
};
self.datastore()
.silo_user_password_hash_set(
opctx,
db_silo,
authz_silo_user,
db_silo_user,
password_hash,
)
.await
}
/// Verify a Silo user's password
///
/// To prevent timing attacks that would allow an attacker to learn the
/// identity of a valid user, it's important that password verification take
/// the same amount of time whether a user exists or not. To achieve that,
/// callers are expected to invoke this function during authentication even
/// if they've found no user to match the requested credentials. That's why
/// this function accepts `Option<SiloUser>` rather than just a `SiloUser`.
pub async fn silo_user_password_verify(
&self,
opctx: &OpContext,
maybe_authz_silo_user: Option<&authz::SiloUser>,
password: &nexus_passwords::Password,
) -> Result<bool, Error> {
let maybe_hash = match maybe_authz_silo_user {
None => None,
Some(authz_silo_user) => {
self.datastore()
.silo_user_password_hash_fetch(opctx, authz_silo_user)
.await?
}
};
let mut hasher = nexus_passwords::Hasher::default();
match maybe_hash {
None => {
// If the user or their password hash does not exist, create a
// dummy password hash anyway. This avoids exposing a timing
// attack where an attacker can learn that a user exists by
// seeing how fast it took a login attempt to fail.
let _ = hasher.create_password(password);
Ok(false)
}
Some(silo_user_password_hash) => Ok(hasher
.verify_password(password, &silo_user_password_hash.hash)
.map_err(|e| {
Error::internal_error(&format!(
"verifying password: {:#}",
e
))
})?),
}
}
/// Given a silo name and username/password credentials, verify the
/// credentials and return the corresponding SiloUser.
pub async fn login_local(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
credentials: params::UsernamePasswordCredentials,
) -> Result<Option<db::model::SiloUser>, Error> {
let (authz_silo, _) = self.local_idp_fetch_silo(silo_lookup).await?;
// NOTE: It's very important that we not bail out early if we fail to
// find a user with this external id. See the note in
// silo_user_password_verify().
// TODO-security There may still be some vulnerability to timing attack
// here, in that we'll do one fewer database lookup if a user does not
// exist. Rate limiting might help. See omicron#2184.
let fetch_user = self
.datastore()
.silo_user_fetch_by_external_id(
opctx,
&authz_silo,
credentials.username.as_ref(),
)
.await?;
let verified = self
.silo_user_password_verify(
opctx,
fetch_user.as_ref().map(|(authz_silo_user, _)| authz_silo_user),
credentials.password.as_ref(),
)
.await?;
if verified {
bail_unless!(
fetch_user.is_some(),
"passed password verification without a valid user"
);
let db_user = fetch_user.unwrap().1;
Ok(Some(db_user))
} else {
Ok(None)
}
}
// Silo groups
pub async fn silo_group_lookup_or_create_by_name(
&self,
opctx: &OpContext,
authz_silo: &authz::Silo,
external_id: &String,
) -> LookupResult<db::model::SiloGroup> {
match self
.db_datastore
.silo_group_optional_lookup(opctx, authz_silo, external_id.clone())
.await?
{
Some(silo_group) => Ok(silo_group),
None => {
self.db_datastore
.silo_group_ensure(
opctx,
authz_silo,
db::model::SiloGroup::new(
Uuid::new_v4(),
authz_silo.id(),
external_id.clone(),
),
)
.await
}
}
}
// SSH Keys
pub fn ssh_key_lookup<'a>(
&'a self,
opctx: &'a OpContext,
ssh_key_selector: &'a params::SshKeySelector,
) -> LookupResult<lookup::SshKey<'a>> {
match ssh_key_selector {
params::SshKeySelector {
silo_user_id: _,
ssh_key: NameOrId::Id(id),
} => {
let ssh_key =
LookupPath::new(opctx, &self.db_datastore).ssh_key_id(*id);
Ok(ssh_key)
}
params::SshKeySelector {
silo_user_id,
ssh_key: NameOrId::Name(name),
} => {
let ssh_key = LookupPath::new(opctx, &self.db_datastore)
.silo_user_id(*silo_user_id)
.ssh_key_name(Name::ref_cast(name));
Ok(ssh_key)
}
}
}
pub async fn ssh_key_create(
&self,
opctx: &OpContext,
silo_user_id: Uuid,
params: params::SshKeyCreate,
) -> CreateResult<db::model::SshKey> {
let ssh_key = db::model::SshKey::new(silo_user_id, params);
let (.., authz_user) = LookupPath::new(opctx, &self.datastore())
.silo_user_id(silo_user_id)
.lookup_for(authz::Action::CreateChild)
.await?;
assert_eq!(authz_user.id(), silo_user_id);
self.db_datastore.ssh_key_create(opctx, &authz_user, ssh_key).await
}
pub async fn ssh_keys_list(
&self,
opctx: &OpContext,
silo_user_id: Uuid,
page_params: &PaginatedBy<'_>,
) -> ListResultVec<SshKey> {
let (.., authz_user) = LookupPath::new(opctx, &self.datastore())
.silo_user_id(silo_user_id)
.lookup_for(authz::Action::ListChildren)
.await?;
assert_eq!(authz_user.id(), silo_user_id);
self.db_datastore.ssh_keys_list(opctx, &authz_user, page_params).await
}
pub async fn ssh_key_delete(
&self,
opctx: &OpContext,
silo_user_id: Uuid,
ssh_key_lookup: &lookup::SshKey<'_>,
) -> DeleteResult {
let (.., authz_silo_user, authz_ssh_key) =
ssh_key_lookup.lookup_for(authz::Action::Delete).await?;
assert_eq!(authz_silo_user.id(), silo_user_id);
self.db_datastore.ssh_key_delete(opctx, &authz_ssh_key).await
}
// identity providers
pub fn saml_identity_provider_lookup<'a>(
&'a self,
opctx: &'a OpContext,
saml_identity_provider_selector: params::SamlIdentityProviderSelector,
) -> LookupResult<lookup::SamlIdentityProvider<'a>> {
match saml_identity_provider_selector {
params::SamlIdentityProviderSelector {
saml_identity_provider: NameOrId::Id(id),
silo: None,
} => {
let saml_provider = LookupPath::new(opctx, &self.db_datastore)
.saml_identity_provider_id(id);
Ok(saml_provider)
}
params::SamlIdentityProviderSelector {
saml_identity_provider: NameOrId::Name(name),
silo: Some(silo),
} => {
let saml_provider = self
.silo_lookup(opctx, silo)?
.saml_identity_provider_name_owned(name.into());
Ok(saml_provider)
}
params::SamlIdentityProviderSelector {
saml_identity_provider: NameOrId::Id(_),
silo: _,
} => Err(Error::invalid_request("when providing provider as an ID, silo should not be specified")),
_ => Err(Error::invalid_request("provider should either be a UUID or silo should be specified"))
}
}
pub async fn identity_provider_list(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
pagparams: &PaginatedBy<'_>,
) -> ListResultVec<db::model::IdentityProvider> {
// TODO-security: This should likely be lookup_for ListChildren on the silo
let (.., authz_silo, _) = silo_lookup.fetch().await?;
let authz_idp_list = authz::SiloIdentityProviderList::new(authz_silo);
self.db_datastore
.identity_provider_list(opctx, &authz_idp_list, pagparams)
.await
}
// Silo authn identity providers
pub async fn saml_identity_provider_create(
&self,
opctx: &OpContext,
silo_lookup: &lookup::Silo<'_>,
params: params::SamlIdentityProviderCreate,
) -> CreateResult<db::model::SamlIdentityProvider> {
// TODO-security: This should likely be fetch_for CreateChild on the silo
let (authz_silo, db_silo) = silo_lookup.fetch().await?;
let authz_idp_list = authz::SiloIdentityProviderList::new(authz_silo);
if db_silo.user_provision_type != UserProvisionType::Jit {
return Err(Error::invalid_request(
"cannot create identity providers in this kind of Silo",
));
}
// This check is not strictly necessary yet. We'll check this
// permission in the DataStore when we actually update the list.
// But we check now to protect the code that fetches the descriptor from
// an external source.
opctx.authorize(authz::Action::CreateChild, &authz_idp_list).await?;
// The authentication mode is immutable so it's safe to check this here
// and bail out.
if db_silo.authentication_mode
!= nexus_db_model::AuthenticationMode::Saml
{
return Err(Error::invalid_request(&format!(
"cannot create SAML identity provider for this Silo type \
(expected authentication mode {:?}, found {:?})",
nexus_db_model::AuthenticationMode::Saml,
&db_silo.authentication_mode,
)));
}
let idp_metadata_document_string = match ¶ms.idp_metadata_source {
params::IdpMetadataSource::Url { url } => {
// Download the SAML IdP descriptor, and write it into the DB.
// This is so that it can be deserialized later.
//
// Importantly, do this only once and store it. It would
// introduce attack surface to download it each time it was
// required.
let dur = std::time::Duration::from_secs(5);
let client = reqwest::ClientBuilder::new()
.connect_timeout(dur)
.timeout(dur)
.build()
.map_err(|e| {
Error::internal_error(&format!(
"failed to build reqwest client: {}",
e
))
})?;
let response = client.get(url).send().await.map_err(|e| {
Error::InvalidValue {
label: String::from("url"),
message: format!("error querying url: {}", e),
}
})?;
if !response.status().is_success() {
return Err(Error::InvalidValue {
label: String::from("url"),
message: format!(
"querying url returned: {}",
response.status()
),
});
}
response.text().await.map_err(|e| Error::InvalidValue {
label: String::from("url"),
message: format!("error getting text from url: {}", e),
})?
}
params::IdpMetadataSource::Base64EncodedXml { data } => {
let bytes = base64::Engine::decode(
&base64::engine::general_purpose::STANDARD,
data,
)
.map_err(|e| Error::InvalidValue {
label: String::from("data"),
message: format!(
"error getting decoding base64 data: {}",
e
),
})?;
String::from_utf8_lossy(&bytes).into_owned()
}
};
let provider = db::model::SamlIdentityProvider {
identity: db::model::SamlIdentityProviderIdentity::new(
Uuid::new_v4(),
params.identity,
),
silo_id: db_silo.id(),
idp_metadata_document_string,
idp_entity_id: params.idp_entity_id,
sp_client_id: params.sp_client_id,
acs_url: params.acs_url,
slo_url: params.slo_url,
technical_contact_email: params.technical_contact_email,
public_cert: params
.signing_keypair
.as_ref()
.map(|x| x.public_cert.clone()),
private_key: params
.signing_keypair
.as_ref()
.map(|x| x.private_key.clone()),
group_attribute_name: params.group_attribute_name.clone(),
};
let _authn_provider: authn::silos::SamlIdentityProvider =
provider.clone().try_into().map_err(|e: anyhow::Error|
// If an error is encountered converting from the model to the
// authn type here, this is a request error: something about the
// parameters of this request doesn't work.
Error::invalid_request(&e.to_string()))?;
self.db_datastore
.saml_identity_provider_create(opctx, &authz_idp_list, provider)
.await
}
pub fn silo_group_lookup<'a>(
&'a self,
opctx: &'a OpContext,
group_id: &'a Uuid,
) -> db::lookup::SiloGroup<'a> {
LookupPath::new(opctx, &self.db_datastore).silo_group_id(*group_id)
}
}