-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathfile.rs
More file actions
257 lines (220 loc) · 8.07 KB
/
Copy pathfile.rs
File metadata and controls
257 lines (220 loc) · 8.07 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
use std::{collections::BTreeMap, str::FromStr};
use snafu::{ResultExt, Snafu};
use stackable_operator::{
builder::{
self,
pod::{
container::ContainerBuilder,
resources::ResourceRequirementsBuilder,
volume::{VolumeBuilder, VolumeMountBuilder},
},
},
commons::product_image_selection::ResolvedProductImage,
crd::authentication::r#static,
k8s_openapi::api::core::v1::{Container, Volume, VolumeMount},
product_logging::{self, spec::AutomaticContainerLogConfig},
utils::COMMON_BASH_TRAP_FUNCTIONS,
v2::types::kubernetes::{SecretName, VolumeName},
};
use crate::{
authentication::password::PASSWORD_AUTHENTICATOR_NAME,
controller::{STACKABLE_LOG_DIR, build::resource::statefulset::LOG_VOLUME_NAME},
};
// mounts
stackable_operator::constant!(PASSWORD_DB_VOLUME_NAME: VolumeName = "users");
pub const PASSWORD_DB_VOLUME_MOUNT_PATH: &str = "/stackable/users";
pub const PASSWORD_AUTHENTICATOR_SECRET_MOUNT_PATH: &str = "/stackable/auth-secrets";
// trino properties
const PASSWORD_AUTHENTICATOR_NAME_FILE: &str = "file";
const FILE_PASSWORD_FILE: &str = "file.password-file";
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("failed to add needed volumeMounts"))]
AddVolumeMounts {
source: builder::pod::container::Error,
},
#[snafu(display("failed to parse user credentials Secret name"))]
ParseSecretName {
source: stackable_operator::v2::macros::attributed_string_type::Error,
},
}
#[derive(Clone, Debug)]
pub struct FileAuthenticator {
name: String,
file: r#static::v1alpha1::AuthenticationProvider,
}
impl FileAuthenticator {
pub fn new(name: String, provider: r#static::v1alpha1::AuthenticationProvider) -> Self {
Self {
name,
file: provider,
}
}
/// Return the name of the authenticator config file to register with Trino
pub fn config_file_name(&self) -> String {
format!("{name}-password-file-auth.properties", name = self.name)
}
/// Return the content of the authenticator config file to register with Trino
pub fn config_file_data(&self) -> BTreeMap<String, String> {
let mut config_data = BTreeMap::new();
config_data.insert(
PASSWORD_AUTHENTICATOR_NAME.to_string(),
PASSWORD_AUTHENTICATOR_NAME_FILE.to_string(),
);
config_data.insert(FILE_PASSWORD_FILE.to_string(), self.password_file_path());
config_data
}
/// Return the name of the Secret providing the usernames and passwords
pub fn secret_name(&self) -> Result<SecretName, Error> {
SecretName::from_str(&self.file.user_credentials_secret.name).context(ParseSecretNameSnafu)
}
/// Build the volume for the user secret
pub fn secret_volume(&self) -> Result<Volume, Error> {
Ok(VolumeBuilder::new(self.secret_volume_name())
.with_secret(self.secret_name()?, false)
.build())
}
/// Build the volume mount for the user secret
pub fn secret_volume_mount(&self) -> VolumeMount {
VolumeMountBuilder::new(self.secret_volume_name(), self.secret_class_mount_path()).build()
}
/// Build the volume for the user password db
pub fn password_db_volume() -> Volume {
VolumeBuilder::new(&*PASSWORD_DB_VOLUME_NAME)
.with_empty_dir(None::<String>, None)
.build()
}
/// Build the volume mount for the user password db
pub fn password_db_volume_mount() -> VolumeMount {
VolumeMountBuilder::new(&*PASSWORD_DB_VOLUME_NAME, PASSWORD_DB_VOLUME_MOUNT_PATH).build()
}
fn password_file_name(&self) -> String {
format!("{auth_class}.db", auth_class = self.name,)
}
fn password_file_path(&self) -> String {
format!(
"{mount}/{file_name}",
mount = PASSWORD_DB_VOLUME_MOUNT_PATH,
file_name = self.password_file_name()
)
}
fn secret_volume_name(&self) -> String {
self.name.to_string()
}
fn secret_class_mount_path(&self) -> String {
format!(
"{PASSWORD_AUTHENTICATOR_SECRET_MOUNT_PATH}/{volume_name}",
volume_name = self.secret_volume_name()
)
}
}
pub fn build_password_file_update_container(
resolved_product_image: &ResolvedProductImage,
volume_mounts: Vec<VolumeMount>,
) -> Result<Container, Error> {
let mut cb_pw_file_updater = ContainerBuilder::new(
&crate::crd::Container::PasswordFileUpdater.to_string(),
)
.expect("Invalid container name. This should not happen, as the container name is fixed");
let mut commands = vec![];
commands.push(product_logging::framework::capture_shell_output(
STACKABLE_LOG_DIR,
&crate::crd::Container::PasswordFileUpdater.to_string(),
// we do not access any of the crd config options for this and just log it to file
&AutomaticContainerLogConfig::default(),
));
commands.push(format!(
r###"
cat << 'EOF' > /tmp/build_password_db.sh
#!/bin/bash
build_user_dbs() {{
echo "[$(date --utc +%FT%T.%3NZ)] Detected changes. Start recreating user password databases from secrets..."
for secret in {stackable_auth_secret_dir}/*;
do
credentials=""
secret_name="$(basename ${{secret}})"
echo "[$(date --utc +%FT%T.%3NZ)] Processing secret [$secret_name] ..."
for user in ${{secret}}/*; do
user_name=$(basename ${{user}})
password=$(cat ${{user}})
credentials+="$(htpasswd -nbBC 12 ${{user_name}} ${{password}})"
credentials+=" "
done
echo "${{credentials}}" | tr " " "\n" > "{stackable_password_db_dir}/${{secret_name}}.db"
done
}}
# Once initial run after start / restart
build_user_dbs
while inotifywait -s -r -e create -e delete -e modify {stackable_auth_secret_dir};
do
build_user_dbs
echo "[$(date --utc +%FT%T.%3NZ)] All databases recreated. Waiting for changes..."
done
EOF
chmod +x /tmp/build_password_db.sh
{COMMON_BASH_TRAP_FUNCTIONS}
prepare_signal_handlers
/tmp/build_password_db.sh &
wait_for_termination $!
"###,
stackable_password_db_dir = PASSWORD_DB_VOLUME_MOUNT_PATH,
stackable_auth_secret_dir = PASSWORD_AUTHENTICATOR_SECRET_MOUNT_PATH,
));
Ok(cb_pw_file_updater
.image_from_product_image(resolved_product_image)
// calculated mounts
.add_volume_mounts(volume_mounts)
.context(AddVolumeMountsSnafu)?
// fixed
.add_volume_mount(&*LOG_VOLUME_NAME, STACKABLE_LOG_DIR)
.context(AddVolumeMountsSnafu)?
.resources(
ResourceRequirementsBuilder::new()
.with_cpu_request("100m")
.with_cpu_limit("200m")
.with_memory_request("32Mi")
.with_memory_limit("32Mi")
.build(),
)
.command(vec![
"/bin/bash".to_string(),
"-x".to_string(),
"-euo".to_string(),
"pipefail".to_string(),
"-c".to_string(),
])
.args(vec![commands.join("\n")])
.build())
}
#[cfg(test)]
mod tests {
use stackable_operator::crd::authentication::r#static;
use super::*;
const AUTH_CLASS_NAME: &str = "test-auth";
#[test]
fn test_file_authenticator() {
let authenticator = FileAuthenticator::new(
AUTH_CLASS_NAME.to_string(),
r#static::v1alpha1::AuthenticationProvider {
user_credentials_secret: r#static::v1alpha1::UserCredentialsSecretRef {
name: "user_credentials".to_string(),
},
},
);
let file_name = authenticator.config_file_name();
assert_eq!(
file_name,
format!("{AUTH_CLASS_NAME}-password-file-auth.properties",)
);
assert_eq!(
authenticator
.config_file_data()
.get(PASSWORD_AUTHENTICATOR_NAME),
Some(PASSWORD_AUTHENTICATOR_NAME_FILE.to_string()).as_ref()
);
assert_eq!(
authenticator.config_file_data().get(FILE_PASSWORD_FILE),
Some(authenticator.password_file_path()).as_ref()
);
}
}