appguard_client_authentication/
context.rs1use crate::cache::Cache;
2use crate::control_channel::start_control_stream;
3use crate::storage::{Secret, Storage};
4use crate::token_provider::TokenProvider;
5use nullnet_libappguard::AppGuardGrpcInterface;
6use nullnet_libappguard::appguard_commands::FirewallDefaults;
7use nullnet_liberror::{Error, ErrorHandler, Location, location};
8use std::sync::Arc;
9use tokio::sync::Mutex;
10
11#[derive(Clone)]
12pub struct Context {
13 pub token_provider: TokenProvider,
14 pub server: AppGuardGrpcInterface,
15 pub firewall_defaults: Arc<Mutex<FirewallDefaults>>,
16 pub cache: Arc<Mutex<Cache>>,
17}
18
19impl Context {
20 #[allow(clippy::missing_errors_doc)]
21 pub async fn new(r#type: String) -> Result<Self, Error> {
22 let host = std::env::var("CONTROL_SERVICE_ADDR").handle_err(location!())?;
23 let port_str = std::env::var("CONTROL_SERVICE_PORT").handle_err(location!())?;
24 let port = port_str.parse::<u16>().handle_err(location!())?;
25
26 let mut server = AppGuardGrpcInterface::new(&host, port, false)
27 .await
28 .handle_err(location!())?;
29
30 Storage::init().await?;
31
32 let mut installation_code_res = std::env::var("INSTALLATION_CODE").handle_err(location!());
33 if installation_code_res.is_err() {
34 installation_code_res = Storage::get_value(Secret::InstallationCode)
35 .await
36 .ok_or("Installation code not set")
37 .handle_err(location!());
38 }
39 let installation_code = installation_code_res?;
40 Storage::set_value(Secret::InstallationCode, &installation_code).await?;
41
42 let token_provider = TokenProvider::new();
43
44 let ctx = Self {
45 token_provider: token_provider.clone(),
46 server: server.clone(),
47 firewall_defaults: Arc::new(Mutex::new(FirewallDefaults::default())),
48 cache: Arc::new(Mutex::new(Cache::new(FirewallDefaults::default()))),
49 };
50
51 start_control_stream(ctx.clone(), installation_code, r#type).await;
52
53 let mut token = token_provider.get().await.unwrap_or_default();
54 while token.is_empty() {
55 tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
56 token = token_provider.get().await.unwrap_or_default();
57 }
58
59 let firewall_defaults = server
60 .firewall_defaults_request(token)
61 .await
62 .handle_err(location!())?;
63 *ctx.firewall_defaults.lock().await = firewall_defaults;
64 *ctx.cache.lock().await = Cache::new(firewall_defaults);
65
66 Ok(ctx)
67 }
68}