-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathoidc.rs
More file actions
220 lines (197 loc) · 7.67 KB
/
Copy pathoidc.rs
File metadata and controls
220 lines (197 loc) · 7.67 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
use std::collections::BTreeMap;
use rand::{RngExt, distr::Alphanumeric};
use snafu::{OptionExt, ResultExt, Snafu};
use stackable_operator::{
builder::meta::ObjectMetaBuilder,
client::Client,
commons::tls_verification::{CaCert, TlsServerVerification, TlsVerification},
crd::authentication::oidc,
k8s_openapi::api::core::v1::Secret,
kube::{ResourceExt, runtime::reflector::ObjectRef},
};
use crate::{crd::v1alpha1, security::authentication::STACKABLE_ADMIN_USERNAME};
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("the NiFi object defines no namespace"))]
ObjectHasNoNamespace,
#[snafu(display("failed to fetch or create OIDC admin password secret"))]
OidcAdminPasswordSecret {
source: stackable_operator::client::Error,
},
#[snafu(display(
"found existing admin password secret {secret:?}, but the key {STACKABLE_ADMIN_USERNAME} is missing",
))]
MissingAdminPasswordKey { secret: ObjectRef<Secret> },
#[snafu(display("invalid well-known OIDC configuration URL"))]
InvalidWellKnownConfigUrl {
source: stackable_operator::crd::authentication::oidc::v1alpha1::Error,
},
#[snafu(display("Nifi doesn't support skipping the OIDC TLS verification"))]
SkippingTlsVerificationNotSupported {},
}
/// Generate a secret containing the password for the admin user that can access the API.
///
/// This admin user is the same as for SingleUser authentication.
pub(crate) async fn check_or_generate_oidc_admin_password(
client: &Client,
nifi: &v1alpha1::NifiCluster,
) -> Result<bool, Error> {
let namespace: &str = &nifi.namespace().context(ObjectHasNoNamespaceSnafu)?;
tracing::debug!("Checking for OIDC admin password configuration");
match client
.get_opt::<Secret>(&build_oidc_admin_password_secret_name(nifi), namespace)
.await
.context(OidcAdminPasswordSecretSnafu)?
{
Some(secret) => {
let admin_password_present = secret
.data
.iter()
.flat_map(|data| data.keys())
.any(|key| key == STACKABLE_ADMIN_USERNAME);
if admin_password_present {
Ok(false)
} else {
MissingAdminPasswordKeySnafu {
secret: ObjectRef::from_obj(&secret),
}
.fail()?
}
}
None => {
tracing::info!("No existing oidc admin password secret found, generating new one");
let password: String = rand::rng()
.sample_iter(&Alphanumeric)
.take(15)
.map(char::from)
.collect();
let mut secret_data = BTreeMap::new();
secret_data.insert("admin".to_string(), password);
let new_secret = Secret {
metadata: ObjectMetaBuilder::new()
.namespace(namespace)
.name(build_oidc_admin_password_secret_name(nifi))
.build(),
string_data: Some(secret_data),
..Secret::default()
};
client
.create(&new_secret)
.await
.context(OidcAdminPasswordSecretSnafu)?;
Ok(true)
}
}
}
pub fn build_oidc_admin_password_secret_name(nifi: &v1alpha1::NifiCluster) -> String {
format!("{}-oidc-admin-password", nifi.name_any())
}
/// Adds all the required configuration properties to enable OIDC authentication.
pub fn add_oidc_config_to_properties(
provider: &oidc::v1alpha1::AuthenticationProvider,
client_auth_options: &oidc::v1alpha1::ClientAuthenticationOptions,
properties: &mut BTreeMap<String, String>,
) -> Result<(), Error> {
let well_known_url = provider
.well_known_config_url()
.context(InvalidWellKnownConfigUrlSnafu)?;
properties.insert(
"nifi.security.user.oidc.discovery.url".to_string(),
well_known_url.to_string(),
);
let (oidc_client_id_env, oidc_client_secret_env) =
oidc::v1alpha1::AuthenticationProvider::client_credentials_env_names(
&client_auth_options.client_credentials_secret_ref,
);
properties.insert(
"nifi.security.user.oidc.client.id".to_string(),
format!("${{env:{oidc_client_id_env}}}").to_string(),
);
properties.insert(
"nifi.security.user.oidc.client.secret".to_string(),
format!("${{env:{oidc_client_secret_env}}}").to_string(),
);
let scopes = provider.scopes.join(",");
properties.insert(
"nifi.security.user.oidc.additional.scopes".to_string(),
scopes.to_string(),
);
properties.insert(
"nifi.security.user.oidc.claim.identifying.user".to_string(),
provider.principal_claim.to_string(),
);
if let Some(tls) = &provider.tls.tls {
let truststore_strategy = match tls.verification {
TlsVerification::None {} => SkippingTlsVerificationNotSupportedSnafu.fail()?,
TlsVerification::Server(TlsServerVerification {
ca_cert: CaCert::SecretClass(_),
}) => "NIFI", // The cert get's added to the stackable truststore
TlsVerification::Server(TlsServerVerification {
ca_cert: CaCert::WebPki {},
}) => "JDK", // The cert needs to be in the system truststore
};
properties.insert(
"nifi.security.user.oidc.truststore.strategy".to_owned(),
truststore_strategy.to_owned(),
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use stackable_operator::commons::tls_verification::{Tls, TlsClientDetails};
use super::*;
#[rstest]
#[case("/realms/sdp")]
#[case("/realms/sdp/")]
#[case("/realms/sdp/////")]
fn test_add_oidc_config(#[case] root_path: String) {
let mut properties = BTreeMap::new();
let provider = oidc::v1alpha1::AuthenticationProvider::new(
"keycloak.mycorp.org".to_owned().try_into().unwrap(),
Some(443),
root_path,
TlsClientDetails {
tls: Some(Tls {
verification: TlsVerification::Server(TlsServerVerification {
ca_cert: CaCert::WebPki {},
}),
}),
},
"preferred_username".to_owned(),
vec!["openid".to_owned()],
None,
);
let oidc = oidc::v1alpha1::ClientAuthenticationOptions {
client_credentials_secret_ref: "nifi-keycloak-client".to_owned(),
extra_scopes: vec![],
client_authentication_method: Default::default(),
product_specific_fields: (),
};
add_oidc_config_to_properties(&provider, &oidc, &mut properties)
.expect("OIDC config adding failed");
assert_eq!(
properties.get("nifi.security.user.oidc.additional.scopes"),
Some(&"openid".to_owned())
);
assert_eq!(
properties.get("nifi.security.user.oidc.claim.identifying.user"),
Some(&"preferred_username".to_owned())
);
assert_eq!(
properties.get("nifi.security.user.oidc.discovery.url"),
Some(
&"https://keycloak.mycorp.org/realms/sdp/.well-known/openid-configuration"
.to_owned()
)
);
assert_eq!(
properties.get("nifi.security.user.oidc.truststore.strategy"),
Some(&"JDK".to_owned())
);
assert!(properties.contains_key("nifi.security.user.oidc.client.id"));
assert!(properties.contains_key("nifi.security.user.oidc.client.secret"));
}
}