-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauthentication.rs
More file actions
966 lines (902 loc) · 35.5 KB
/
authentication.rs
File metadata and controls
966 lines (902 loc) · 35.5 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
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
use std::{collections::BTreeSet, future::Future, mem};
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu, ensure};
use stackable_operator::{
client::Client,
crd::authentication::{core as auth_core, ldap, oidc},
schemars::{self, JsonSchema},
};
use tracing::info;
const SUPPORTED_AUTHENTICATION_CLASS_PROVIDERS: [&str; 2] = ["LDAP", "OIDC"];
const SUPPORTED_OIDC_PROVIDERS: &[oidc::v1alpha1::IdentityProviderHint] =
&[oidc::v1alpha1::IdentityProviderHint::Keycloak];
// The assumed OIDC provider if no hint is given in the AuthClass
pub const DEFAULT_OIDC_PROVIDER: oidc::v1alpha1::IdentityProviderHint =
oidc::v1alpha1::IdentityProviderHint::Keycloak;
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display(
"The AuthenticationClass {auth_class_name:?} is referenced several times which is not allowed."
))]
DuplicateAuthenticationClassReferencesNotAllowed { auth_class_name: String },
#[snafu(display("Failed to retrieve AuthenticationClass"))]
AuthenticationClassRetrievalFailed {
source: stackable_operator::client::Error,
},
// TODO: Adapt message if multiple authentication classes are supported simultaneously
#[snafu(display("Only one authentication class is currently supported at a time"))]
MultipleAuthenticationClassesProvided,
#[snafu(display(
"Failed to use authentication provider [{provider}] for authentication class [{auth_class_name}] - supported providers: {SUPPORTED_AUTHENTICATION_CLASS_PROVIDERS:?}",
))]
AuthenticationProviderNotSupported {
auth_class_name: String,
provider: String,
},
#[snafu(display(
"Only one authentication type at a time is supported by Airflow, see https://github.com/dpgaspar/Flask-AppBuilder/issues/1924."
))]
MultipleAuthenticationTypesNotSupported,
#[snafu(display("Only one LDAP provider at a time is supported by Airflow."))]
MultipleLdapProvidersNotSupported,
#[snafu(display(
"The OIDC provider {oidc_provider:?} is not yet supported (AuthenticationClass {auth_class_name:?})."
))]
OidcProviderNotSupported {
auth_class_name: String,
oidc_provider: String,
},
#[snafu(display(
"TLS verification cannot be disabled in Airflow (AuthenticationClass {auth_class_name:?})."
))]
TlsVerificationCannotBeDisabled { auth_class_name: String },
#[snafu(display(
"The userRegistrationRole settings must not differ between the authentication entries.",
))]
DifferentUserRegistrationRoleSettingsNotAllowed,
#[snafu(display(
"The userRegistration settings must not differ between the authentication entries.",
))]
DifferentUserRegistrationSettingsNotAllowed,
#[snafu(display(
"The syncRolesAt settings must not differ between the authentication entries.",
))]
DifferentSyncRolesAtSettingsNotAllowed,
#[snafu(display("Invalid OIDC configuration"))]
OidcConfigurationInvalid { source: auth_core::v1alpha1::Error },
#[snafu(display(
"{configured:?} is not a supported principalClaim in Airflow for the Keycloak OIDC provider. Please use {supported:?} in the AuthenticationClass {auth_class_name:?}"
))]
OidcPrincipalClaimNotSupported {
configured: String,
supported: String,
auth_class_name: String,
},
}
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AirflowClientAuthenticationDetails {
#[serde(flatten)]
pub common: auth_core::v1alpha1::ClientAuthenticationDetails<()>,
/// Allow users who are not already in the FAB DB.
/// Gets mapped to `AUTH_USER_REGISTRATION`
#[serde(default = "default_user_registration")]
pub user_registration: bool,
/// This role will be given in addition to any AUTH_ROLES_MAPPING.
/// Gets mapped to `AUTH_USER_REGISTRATION_ROLE`
#[serde(default = "default_user_registration_role")]
pub user_registration_role: String,
/// If we should replace ALL the user's roles each login, or only on registration.
/// Gets mapped to `AUTH_ROLES_SYNC_AT_LOGIN`
#[serde(default)]
pub sync_roles_at: FlaskRolesSyncMoment,
}
pub fn default_user_registration() -> bool {
true
}
pub fn default_user_registration_role() -> String {
"Public".to_string()
}
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, Default)]
pub enum FlaskRolesSyncMoment {
#[default]
Registration,
Login,
}
/// Resolved and validated counter part for `AirflowClientAuthenticationDetails`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AirflowClientAuthenticationDetailsResolved {
pub authentication_classes_resolved: Vec<AirflowAuthenticationClassResolved>,
pub user_registration: bool,
pub user_registration_role: String,
pub sync_roles_at: FlaskRolesSyncMoment,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AirflowAuthenticationClassResolved {
Ldap {
provider: ldap::v1alpha1::AuthenticationProvider,
},
Oidc {
provider: oidc::v1alpha1::AuthenticationProvider,
oidc: oidc::v1alpha1::ClientAuthenticationOptions<()>,
},
}
impl AirflowClientAuthenticationDetailsResolved {
pub async fn from(
auth_details: &[AirflowClientAuthenticationDetails],
client: &Client,
) -> Result<AirflowClientAuthenticationDetailsResolved> {
let resolve_auth_class =
|auth_details: auth_core::v1alpha1::ClientAuthenticationDetails| async move {
auth_details.resolve_class(client).await
};
AirflowClientAuthenticationDetailsResolved::resolve(auth_details, resolve_auth_class).await
}
pub async fn resolve<R>(
auth_details: &[AirflowClientAuthenticationDetails],
resolve_auth_class: impl Fn(auth_core::v1alpha1::ClientAuthenticationDetails) -> R,
) -> Result<AirflowClientAuthenticationDetailsResolved>
where
R: Future<
Output = Result<
auth_core::v1alpha1::AuthenticationClass,
stackable_operator::client::Error,
>,
>,
{
let mut resolved_auth_classes: Vec<AirflowAuthenticationClassResolved> = Vec::new();
let mut user_registration = None;
let mut user_registration_role = None;
let mut sync_roles_at = None;
let mut auth_class_names = BTreeSet::new();
for entry in auth_details {
let auth_class_name = entry.common.authentication_class_name();
let is_new_auth_class = auth_class_names.insert(auth_class_name);
ensure!(
is_new_auth_class,
DuplicateAuthenticationClassReferencesNotAllowedSnafu { auth_class_name }
);
let auth_class = resolve_auth_class(entry.common.clone())
.await
.context(AuthenticationClassRetrievalFailedSnafu)?;
match &auth_class.spec.provider {
auth_core::v1alpha1::AuthenticationClassProvider::Ldap(provider) => {
let resolved_auth_class = AirflowAuthenticationClassResolved::Ldap {
provider: provider.to_owned(),
};
if let Some(other) = resolved_auth_classes.first() {
ensure!(
mem::discriminant(other) == mem::discriminant(&resolved_auth_class),
MultipleAuthenticationTypesNotSupportedSnafu
);
}
ensure!(
resolved_auth_classes.is_empty(),
MultipleLdapProvidersNotSupportedSnafu
);
resolved_auth_classes.push(resolved_auth_class);
}
auth_core::v1alpha1::AuthenticationClassProvider::Oidc(provider) => {
let resolved_auth_class =
AirflowClientAuthenticationDetailsResolved::from_oidc(
auth_class_name,
provider,
entry,
)?;
if let Some(other) = resolved_auth_classes.first() {
ensure!(
mem::discriminant(other) == mem::discriminant(&resolved_auth_class),
MultipleAuthenticationTypesNotSupportedSnafu
);
}
resolved_auth_classes.push(resolved_auth_class);
//`&Static(_)`, `&Tls(_)` and `&Kerberos(_)` not covered
}
auth_core::v1alpha1::AuthenticationClassProvider::Kerberos(_)
| auth_core::v1alpha1::AuthenticationClassProvider::Static(_)
| auth_core::v1alpha1::AuthenticationClassProvider::Tls(_) => {
return Err(Error::AuthenticationProviderNotSupported {
auth_class_name: auth_class_name.to_owned(),
provider: auth_class.spec.provider.to_string(),
});
}
}
match user_registration {
Some(user_registration) => {
ensure!(
user_registration == entry.user_registration,
DifferentUserRegistrationSettingsNotAllowedSnafu
);
}
None => user_registration = Some(entry.user_registration),
}
match &user_registration_role {
Some(user_registration_role) => {
ensure!(
user_registration_role == &entry.user_registration_role,
DifferentUserRegistrationRoleSettingsNotAllowedSnafu
);
}
None => user_registration_role = Some(entry.user_registration_role.to_owned()),
}
match &sync_roles_at {
Some(sync_roles_at) => {
ensure!(
sync_roles_at == &entry.sync_roles_at,
DifferentSyncRolesAtSettingsNotAllowedSnafu
);
}
None => sync_roles_at = Some(entry.sync_roles_at.to_owned()),
}
}
Ok(AirflowClientAuthenticationDetailsResolved {
authentication_classes_resolved: resolved_auth_classes,
user_registration: user_registration.unwrap_or_else(default_user_registration),
user_registration_role: user_registration_role
.unwrap_or_else(default_user_registration_role),
sync_roles_at: sync_roles_at.unwrap_or_else(FlaskRolesSyncMoment::default),
})
}
fn from_oidc(
auth_class_name: &str,
provider: &oidc::v1alpha1::AuthenticationProvider,
auth_details: &AirflowClientAuthenticationDetails,
) -> Result<AirflowAuthenticationClassResolved> {
let oidc_provider = match &provider.provider_hint {
None => {
info!(
"No OIDC provider hint given in AuthClass {auth_class_name}, assuming {default_oidc_provider_name}",
default_oidc_provider_name =
serde_json::to_string(&DEFAULT_OIDC_PROVIDER).unwrap()
);
DEFAULT_OIDC_PROVIDER
}
Some(oidc_provider) => oidc_provider.to_owned(),
};
ensure!(
SUPPORTED_OIDC_PROVIDERS.contains(&oidc_provider),
OidcProviderNotSupportedSnafu {
auth_class_name,
oidc_provider: serde_json::to_string(&oidc_provider).unwrap(),
}
);
// We have to enforce preferred_username here due to the flask implementation
// https://github.com/dpgaspar/Flask-AppBuilder/blob/6d44e6d581433dcea475764c4bb1270c24bbd6de/flask_appbuilder/security/manager.py#L719
match oidc_provider {
oidc::v1alpha1::IdentityProviderHint::Keycloak => {
ensure!(
&provider.principal_claim == "preferred_username",
OidcPrincipalClaimNotSupportedSnafu {
configured: provider.principal_claim.clone(),
supported: "preferred_username".to_owned(),
auth_class_name,
}
);
}
}
ensure!(
!provider.tls.uses_tls() || provider.tls.uses_tls_verification(),
TlsVerificationCannotBeDisabledSnafu { auth_class_name }
);
Ok(AirflowAuthenticationClassResolved::Oidc {
provider: provider.to_owned(),
oidc: auth_details
.common
.oidc_or_error(auth_class_name)
.context(OidcConfigurationInvalidSnafu)?
.clone(),
})
}
}
#[cfg(test)]
mod tests {
use std::pin::Pin;
use indoc::indoc;
use stackable_operator::{
commons::{
networking::HostName,
tls_verification::{
CaCert, Tls, TlsClientDetails, TlsServerVerification, TlsVerification,
},
},
kube,
};
use super::*;
#[tokio::test]
async fn resolve_without_authentication_details() {
let auth_details_resolved = test_resolve_and_expect_success("[]", "").await;
assert_eq!(
AirflowClientAuthenticationDetailsResolved {
authentication_classes_resolved: Vec::default(),
user_registration: default_user_registration(),
user_registration_role: default_user_registration_role(),
sync_roles_at: FlaskRolesSyncMoment::default()
},
auth_details_resolved
);
}
#[tokio::test]
async fn resolve_ldap_with_all_authentication_details() {
// Avoid using defaults here
let auth_details_resolved = test_resolve_and_expect_success(
indoc! {"
- authenticationClass: ldap
userRegistration: false
userRegistrationRole: Gamma
syncRolesAt: Login
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: ldap
spec:
provider:
ldap:
hostname: my.ldap.server
"},
)
.await;
assert_eq!(
AirflowClientAuthenticationDetailsResolved {
authentication_classes_resolved: vec![AirflowAuthenticationClassResolved::Ldap {
provider: serde_yaml::from_str("hostname: my.ldap.server").unwrap()
}],
user_registration: false,
user_registration_role: "Gamma".into(),
sync_roles_at: FlaskRolesSyncMoment::Login
},
auth_details_resolved
);
}
#[tokio::test]
async fn resolve_oidc_with_all_authentication_details() {
// Avoid using defaults here
let auth_details_resolved = test_resolve_and_expect_success(
indoc! {"
- authenticationClass: oidc1
oidc:
clientCredentialsSecret: airflow-oidc-client1
extraScopes:
- groups
userRegistration: false
userRegistrationRole: Gamma
syncRolesAt: Login
- authenticationClass: oidc2
oidc:
clientCredentialsSecret: airflow-oidc-client2
userRegistration: false
userRegistrationRole: Gamma
syncRolesAt: Login
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc1
spec:
provider:
oidc:
hostname: first.oidc.server
port: 443
rootPath: /realms/main
principalClaim: preferred_username
scopes:
- openid
- email
- profile
providerHint: Keycloak
tls:
verification:
server:
caCert:
secretClass: tls
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc2
spec:
provider:
oidc:
hostname: second.oidc.server
rootPath: /realms/test
principalClaim: preferred_username
scopes:
- openid
- email
- profile
"},
)
.await;
assert_eq!(
AirflowClientAuthenticationDetailsResolved {
authentication_classes_resolved: vec![
AirflowAuthenticationClassResolved::Oidc {
provider: oidc::v1alpha1::AuthenticationProvider::new(
HostName::try_from("first.oidc.server".to_string()).unwrap(),
Some(443),
"/realms/main".into(),
TlsClientDetails {
tls: Some(Tls {
verification: TlsVerification::Server(TlsServerVerification {
ca_cert: CaCert::SecretClass("tls".into())
})
})
},
"preferred_username".into(),
vec!["openid".into(), "email".into(), "profile".into()],
Some(oidc::v1alpha1::IdentityProviderHint::Keycloak)
),
oidc: oidc::v1alpha1::ClientAuthenticationOptions {
client_credentials_secret_ref: "airflow-oidc-client1".into(),
extra_scopes: vec!["groups".into()],
client_authentication_method: Default::default(),
product_specific_fields: ()
}
},
AirflowAuthenticationClassResolved::Oidc {
provider: oidc::v1alpha1::AuthenticationProvider::new(
HostName::try_from("second.oidc.server".to_string()).unwrap(),
None,
"/realms/test".into(),
TlsClientDetails { tls: None },
"preferred_username".into(),
vec!["openid".into(), "email".into(), "profile".into()],
None
),
oidc: oidc::v1alpha1::ClientAuthenticationOptions {
client_credentials_secret_ref: "airflow-oidc-client2".into(),
extra_scopes: Vec::new(),
client_authentication_method: Default::default(),
product_specific_fields: ()
}
}
],
user_registration: false,
user_registration_role: "Gamma".into(),
sync_roles_at: FlaskRolesSyncMoment::Login
},
auth_details_resolved
);
}
#[tokio::test]
async fn reject_duplicate_authentication_class_references() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc
oidc:
clientCredentialsSecret: airflow-oidc-client1
- authenticationClass: oidc
oidc:
clientCredentialsSecret: airflow-oidc-client2
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc
spec:
provider:
oidc:
hostname: my.oidc.server
principalClaim: preferred_username
scopes: []
"},
)
.await;
assert_eq!(
r#"The AuthenticationClass "oidc" is referenced several times which is not allowed."#,
error_message
);
}
#[tokio::test]
async fn reject_different_authentication_types() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc
oidc:
clientCredentialsSecret: airflow-oidc-client
- authenticationClass: ldap
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc
spec:
provider:
oidc:
hostname: my.oidc.server
principalClaim: preferred_username
scopes: []
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: ldap
spec:
provider:
ldap:
hostname: my.ldap.server
"},
)
.await;
assert_eq!(
"Only one authentication type at a time is supported by Airflow, see https://github.com/dpgaspar/Flask-AppBuilder/issues/1924.",
error_message
);
}
#[tokio::test]
async fn reject_multiple_ldap_providers() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: ldap1
- authenticationClass: ldap2
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: ldap1
spec:
provider:
ldap:
hostname: first.ldap.server
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: ldap2
spec:
provider:
ldap:
hostname: second.ldap.server
"},
)
.await;
assert_eq!(
"Only one LDAP provider at a time is supported by Airflow.",
error_message
);
}
#[tokio::test]
async fn reject_different_user_registration_settings() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc1
oidc:
clientCredentialsSecret: superset-oidc-client1
- authenticationClass: oidc2
oidc:
clientCredentialsSecret: superset-oidc-client2
userRegistration: false
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc1
spec:
provider:
oidc:
hostname: first.oidc.server
principalClaim: preferred_username
scopes: []
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc2
spec:
provider:
oidc:
hostname: second.oidc.server
principalClaim: preferred_username
scopes: []
"},
)
.await;
assert_eq!(
"The userRegistration settings must not differ between the authentication entries.",
error_message
);
}
#[tokio::test]
async fn reject_different_user_registration_role_settings() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc1
oidc:
clientCredentialsSecret: airflow-oidc-client1
- authenticationClass: oidc2
oidc:
clientCredentialsSecret: airflow-oidc-client2
userRegistrationRole: Gamma
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc1
spec:
provider:
oidc:
hostname: first.oidc.server
principalClaim: preferred_username
scopes: []
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc2
spec:
provider:
oidc:
hostname: second.oidc.server
principalClaim: preferred_username
scopes: []
"},
)
.await;
assert_eq!(
"The userRegistrationRole settings must not differ between the authentication entries.",
error_message
);
}
#[tokio::test]
async fn reject_different_sync_roles_at_settings() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc1
oidc:
clientCredentialsSecret: airflow-oidc-client1
- authenticationClass: oidc2
oidc:
clientCredentialsSecret: airflow-oidc-client2
syncRolesAt: Login
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc1
spec:
provider:
oidc:
hostname: first.oidc.server
principalClaim: preferred_username
scopes: []
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc2
spec:
provider:
oidc:
hostname: second.oidc.server
principalClaim: preferred_username
scopes: []
"},
)
.await;
assert_eq!(
"The syncRolesAt settings must not differ between the authentication entries.",
error_message
);
}
#[tokio::test]
async fn reject_if_oidc_details_are_missing() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc
spec:
provider:
oidc:
hostname: my.oidc.server
principalClaim: preferred_username
scopes: []
"},
)
.await;
assert_eq!(
indoc! { r#"
Invalid OIDC configuration
Caused by this error:
1: authentication details for OIDC were not specified. The AuthenticationClass "oidc" uses an OIDC provider, you need to specify OIDC authentication details (such as client credentials) as well"# },
error_message
);
}
#[tokio::test]
async fn reject_wrong_principal_claim() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc
oidc:
clientCredentialsSecret: airflow-oidc-client
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc
spec:
provider:
oidc:
hostname: my.oidc.server
principalClaim: sub
scopes: []
"},
)
.await;
assert_eq!(
r#""sub" is not a supported principalClaim in Airflow for the Keycloak OIDC provider. Please use "preferred_username" in the AuthenticationClass "oidc""#,
error_message
);
}
#[tokio::test]
async fn reject_disabled_tls_verification() {
let error_message = test_resolve_and_expect_error(
indoc! {"
- authenticationClass: oidc
oidc:
clientCredentialsSecret: airflow-oidc-client
"},
indoc! {"
---
apiVersion: authentication.stackable.tech/v1alpha1
kind: AuthenticationClass
metadata:
name: oidc
spec:
provider:
oidc:
hostname: my.oidc.server
principalClaim: preferred_username
scopes: []
tls:
verification:
none: {}
"},
)
.await;
assert_eq!(
r#"TLS verification cannot be disabled in Airflow (AuthenticationClass "oidc")."#,
error_message
);
}
/// Call `AirflowClientAuthenticationDetailsResolved::resolve` with
/// the given lists of `AirflowClientAuthenticationDetails` and
/// `AuthenticationClass`es and return the
/// `AirflowClientAuthenticationDetailsResolved`.
///
/// The parameters are meant to be valid and resolvable. Just fail
/// if there is an error.
async fn test_resolve_and_expect_success(
auth_details_yaml: &str,
auth_classes_yaml: &str,
) -> AirflowClientAuthenticationDetailsResolved {
test_resolve(auth_details_yaml, auth_classes_yaml)
.await
.expect("The AirflowClientAuthenticationDetails should be resolvable.")
}
/// Call `AirflowClientAuthenticationDetailsResolved::resolve` with
/// the given lists of `AirflowClientAuthenticationDetails` and
/// `AuthenticationClass`es and return the error message.
///
/// The parameters are meant to be invalid or not resolvable. Just
/// fail if there is no error.
async fn test_resolve_and_expect_error(
auth_details_yaml: &str,
auth_classes_yaml: &str,
) -> String {
let error = test_resolve(auth_details_yaml, auth_classes_yaml)
.await
.expect_err(
"The AirflowClientAuthenticationDetails are invalid and should not be resolvable.",
);
snafu::Report::from_error(error)
.to_string()
.trim_end()
.to_owned()
}
/// Call `AirflowClientAuthenticationDetailsResolved::resolve` with
/// the given lists of `AirflowClientAuthenticationDetails` and
/// `AuthenticationClass`es and return the result.
async fn test_resolve(
auth_details_yaml: &str,
auth_classes_yaml: &str,
) -> Result<AirflowClientAuthenticationDetailsResolved> {
let auth_details = deserialize_airflow_client_authentication_details(auth_details_yaml);
let auth_classes = deserialize_auth_classes(auth_classes_yaml);
let resolve_auth_class = create_auth_class_resolver(auth_classes);
AirflowClientAuthenticationDetailsResolved::resolve(&auth_details, resolve_auth_class).await
}
/// Deserialize the given list of
/// `AirflowClientAuthenticationDetails`.
///
/// Fail if the given string cannot be deserialized.
fn deserialize_airflow_client_authentication_details(
input: &str,
) -> Vec<AirflowClientAuthenticationDetails> {
serde_yaml::from_str(input)
.expect("The definition of the authentication configuration should be valid.")
}
/// Deserialize the given `AuthenticationClass` YAML documents.
///
/// Fail if the given string cannot be deserialized.
fn deserialize_auth_classes(input: &str) -> Vec<auth_core::v1alpha1::AuthenticationClass> {
if input.is_empty() {
Vec::new()
} else {
let deserializer = serde_yaml::Deserializer::from_str(input);
deserializer
.map(|d| {
serde_yaml::with::singleton_map_recursive::deserialize(d)
.expect("The definition of the AuthenticationClass should be valid.")
})
.collect()
}
}
/// Returns a function which resolves `AuthenticationClass` names to
/// the given list of `AuthenticationClass`es.
///
/// Use this function in the tests to replace
/// `stackable_operator::commons::authentication::ClientAuthenticationDetails`
/// which requires a Kubernetes client.
fn create_auth_class_resolver(
auth_classes: Vec<auth_core::v1alpha1::AuthenticationClass>,
) -> impl Fn(
auth_core::v1alpha1::ClientAuthenticationDetails,
) -> Pin<
Box<
dyn Future<
Output = Result<
auth_core::v1alpha1::AuthenticationClass,
stackable_operator::client::Error,
>,
>,
>,
> {
move |auth_details: auth_core::v1alpha1::ClientAuthenticationDetails| {
let auth_classes = auth_classes.clone();
Box::pin(async move {
auth_classes
.iter()
.find(|auth_class| {
auth_class.metadata.name.as_ref()
== Some(auth_details.authentication_class_name())
})
.cloned()
.ok_or_else(|| stackable_operator::client::Error::ListResources {
source: kube::Error::Api(Box::new(kube::core::Status {
status: None,
code: 404,
message: "AuthenticationClass not found".to_owned(),
metadata: None,
reason: "NotFound".to_owned(),
details: None,
})),
})
})
}
}
}