-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
241 lines (231 loc) · 9.03 KB
/
mod.rs
File metadata and controls
241 lines (231 loc) · 9.03 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
mod app;
mod group;
mod provider;
#[cfg(test)]
mod test;
use std::sync::Mutex;
use crate::CLIENT;
use anyhow::bail;
use app::{check_app_result, compare_app_provider, get_application};
use beam_lib::reqwest::{self, Url};
use clap::Parser;
use group::create_groups;
use provider::{compare_provider, generate_provider_values, get_provider};
use reqwest::{Response, StatusCode};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use shared::{OIDCConfig, SecretResult};
use tracing::{debug, info};
use crate::auth::authentik::provider::{check_set_federation_id, generate_provider, update_provider};
use crate::auth::generate_secret;
#[derive(Debug, Parser, Clone)]
pub struct AuthentikConfig {
/// authentik url
#[clap(long, env)]
pub authentik_url: Url,
// Service Account with api token and all permissions
#[clap(long, env)]
pub authentik_service_api_key: String,
#[clap(long, env, value_parser, value_delimiter = ',', default_values_t = [] as [String; 0])]
pub authentik_groups_per_bh: Vec<String>,
#[clap(long, env, value_parser, value_delimiter = ',', default_values_t = [] as [String; 0])]
pub authentik_property_names: Vec<String>,
#[clap(long, env, value_parser, value_delimiter = ',', default_values_t = [] as [String; 0])]
pub authentik_federation_names: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FlowPropertymapping {
pub authorization_flow: String,
pub invalidation_flow: String,
pub property_mapping: Vec<String>,
pub federation_mapping: Vec<String>
}
impl FlowPropertymapping {
async fn new(conf: &AuthentikConfig) -> reqwest::Result<Self> {
static PROPERTY_MAPPING_CACHE: Mutex<Option<FlowPropertymapping>> = Mutex::new(None);
if let Some(flow) = PROPERTY_MAPPING_CACHE.lock().unwrap().as_ref() {
return Ok(flow.clone());
}
let flow_auth = "Authorize Application";
let flow_invalidation = "Logged out of application";
let property_keys = conf.authentik_property_names.clone();
let jwt_federation_sources = conf.authentik_federation_names.clone();
//let flow_url = "/api/v3/flows/instances/?name=...";
//let property_url = "/api/v3/propertymappings/all/?name=...";
let flow_url = conf
.authentik_url
.join("api/v3/flows/instances/")
.unwrap();
let property_url = conf
.authentik_url
.join("api/v3/propertymappings/all/")
.unwrap();
let federation_url = conf
.authentik_url
.join("api/v3/sources/all/")
.unwrap();
let property_mapping = get_mappings_uuids(&property_url, property_keys, conf).await;
let federation_mapping = get_mappings_uuids(&federation_url, jwt_federation_sources, conf).await;
let authorization_flow = get_uuid(&flow_url, flow_auth, conf)
.await
.expect("No default flow present"); // flow uuid
let invalidation_flow = get_uuid(&flow_url, flow_invalidation, conf)
.await
.expect("No default flow present"); // flow uuid
let mapping = FlowPropertymapping {
authorization_flow,
invalidation_flow,
property_mapping,
federation_mapping
};
*PROPERTY_MAPPING_CACHE.lock().unwrap() = Some(mapping.clone());
Ok(mapping)
}
}
pub async fn validate_application(
name: &str,
oidc_client_config: &OIDCConfig,
secret: &str,
conf: &AuthentikConfig,
) -> anyhow::Result<bool> {
compare_app_provider(name, oidc_client_config, secret, conf).await
}
pub async fn create_app_provider(
name: &str,
oidc_client_config: &OIDCConfig,
conf: &AuthentikConfig,
) -> anyhow::Result<SecretResult> {
let client_id = client_type(oidc_client_config, name);
let secret = if !oidc_client_config.is_public {
generate_secret()
} else {
String::with_capacity(0)
};
let generated_provider: Value =
generate_provider_values(&client_id, oidc_client_config, &secret, conf).await?;
debug!("Provider Values: {:#?}", generated_provider);
let provider_res: Response = generate_provider(&generated_provider, conf).await?;
// Create groups for this client
create_groups(name, conf).await?;
debug!("Result Provider: {:#?}", provider_res);
match provider_res.status() {
StatusCode::CREATED => {
let res_provider: serde_json::Value = provider_res.json().await?;
let provider_id = res_provider["pk"].as_i64().expect("provider_id have to be present");
let provider_name = res_provider["name"].as_str().expect("provider_name have to be present");
// check and set federation_id
check_set_federation_id(&name, provider_id, conf, oidc_client_config).await?;
debug!("{:?}", provider_id);
info!("Provider for {provider_name} created.");
if check_app_result(&client_id, provider_id, conf).await? {
Ok(SecretResult::Created(secret))
} else {
bail!(
"Unexpected Conflict {name} while overwriting authentik app. {:?}",
get_application(&client_id, conf).await?
);
}
}
StatusCode::BAD_REQUEST => {
let conflicting_provider =
get_provider(&client_id, conf).await?;
debug!("{:#?}", conflicting_provider);
let app = conflicting_provider
.get("name")
.and_then(|v| v.as_str())
.unwrap();
if compare_provider(&client_id, oidc_client_config, conf, &secret).await? {
info!("Provider {app} existed.");
if check_app_result(
&client_id,
conflicting_provider
.get("pk")
.and_then(|v| v.as_i64())
.expect("pk id not found"),
conf,
)
.await?
{
Ok(SecretResult::AlreadyExisted(
conflicting_provider
.as_object()
.and_then(|o| o.get("client_secret"))
.and_then(Value::as_str)
.unwrap_or("")
.to_owned(),
))
} else {
bail!(
"Unexpected Conflict {name} while overwriting authentik app. {:?}",
get_application(&client_id, conf).await?
);
}
} else {
let res = update_provider(&generated_provider, &client_id, conf)
.await?
.status()
.is_success()
.then_some(SecretResult::AlreadyExisted(secret))
.expect("We know the provider already exists so updating should be successful");
info!("Provider {app} updated");
if check_app_result(
&client_id,
conflicting_provider["pk"]
.as_i64()
.expect("app id - pk must be present"),
conf,
)
.await?
{
Ok(res)
} else {
bail!(
"Unexpected Conflict {name} while overwriting authentik app. {:?}",
get_application(&client_id, conf).await?
);
}
}
}
s => bail!(
"Unexpected statuscode {s} while creating authentik app and provider. {provider_res:?}"
),
}
}
async fn get_uuid(target_url: &Url, search_name: &str, conf: &AuthentikConfig) -> Option<String> {
let target_value: serde_json::Value = CLIENT
.get(target_url.to_owned())
.query(&[("name", search_name)])
.bearer_auth(&conf.authentik_service_api_key)
.send()
.await
.ok()?
.json()
.await
.ok()?;
debug!("Value search key {search_name}: {:?}", &target_value);
// pk is the uuid for this result
Some(target_value["results"][0]["pk"].as_str()?.to_owned())
}
async fn get_mappings_uuids(
target_url: &Url,
search_key: Vec<String>,
conf: &AuthentikConfig,
) -> Vec<String> {
// TODO: async iter to collect
let mut result: Vec<String> = vec![];
for key in search_key {
result.push(
get_uuid(target_url, &key, conf)
.await
.expect(&format!("Property: {:?}", key)),
);
}
result
}
pub fn client_type(oidc_client_config: &OIDCConfig, name: &str) -> String {
format!("{}-{}", name, if oidc_client_config.is_public { "public" } else { "private" })
}
//use case federation id
pub fn flipped_client_type(oidc_client_config: &OIDCConfig, name: &str) -> String {
format!("{}-{}", name, if oidc_client_config.is_public { "private" } else { "public" })
}