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
//! Built and ready-to-launch Runique application.
use axum::Router;
use std::net::SocketAddr;
use tokio::signal;
use crate::config::RuniqueConfig;
use crate::utils::aliases::AEngine;
use crate::utils::trad::{t, tf};
use super::builder::RuniqueAppBuilder;
// ═══════════════════════════════════════════════════════════════
// RuniqueApp — Built application, ready to be launched
// ═══════════════════════════════════════════════════════════════
/// Compiled application: engine + router ready to serve HTTP requests.
pub struct RuniqueApp {
/// Shared engine containing config, Tera, DB, and security policies.
pub engine: AEngine,
/// Axum router with all attached middlewares.
pub router: Router,
/// Keeps the non-blocking log file writers alive for the app's lifetime.
/// Dropping these flushes and stops the background writer threads.
pub _log_guards: Vec<tracing_appender::non_blocking::WorkerGuard>,
}
impl RuniqueApp {
/// Creates a new builder to configure the application.
///
/// Shortcut to [`RuniqueAppBuilder::new`].
pub fn builder(config: RuniqueConfig) -> RuniqueAppBuilder {
RuniqueAppBuilder::new(config)
}
/// Launches the server.
/// - If `ACME_ENABLED=true`: provisions TLS via Let's Encrypt and serves HTTPS on port 443.
/// - Otherwise: serves HTTP on the configured port.
pub async fn run(self) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(not(feature = "acme"))]
if std::env::var("ACME_ENABLED").as_deref() == Ok("true") {
eprintln!("⚠ {}", t("server.acme_not_compiled"));
eprintln!(" {}", t("server.acme_add_feature"));
}
#[cfg(feature = "acme")]
if self.engine.config.security.acme_enabled {
return self.run_with_acme().await;
}
self.run_http().await
}
/// Standard HTTP server (no TLS).
async fn run_http(self) -> Result<(), Box<dyn std::error::Error>> {
let addr = format!(
"{}:{}",
self.engine.config.server.ip_server, self.engine.config.server.port
);
println!(" {}", t("server.operational"));
println!(
" └──> {}",
tf("server.launched", &[format!("http://{addr}")])
);
#[cfg(feature = "orm")]
{
let moteur_db = self.engine.db.get_database_backend();
let db_name = std::env::var("DB_NAME").unwrap_or_else(|_| "runique_db".to_string());
println!(
" └──> {}",
tf("server.connected_db", &[format!("{moteur_db:?}"), db_name])
);
println!(" └──> {}", t("server.stop_hint"));
}
let listener = tokio::net::TcpListener::bind(&addr).await?;
axum::serve(
listener,
self.router
.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async {
signal::ctrl_c().await.expect("Error signal Ctrl+C");
println!("\n{}", t("server.shutting_down"));
})
.await?;
Ok(())
}
/// Returns true if the certificate should be renewed (missing or past renewal date).
#[cfg(feature = "acme")]
async fn _cert_needs_renewal_placeholder() {}
}
#[cfg(feature = "acme")]
async fn cert_needs_renewal(expires_path: &std::path::Path) -> bool {
let Ok(content) = tokio::fs::read_to_string(expires_path).await else {
return true;
};
let Ok(renew_after) = content.trim().parse::<chrono::DateTime<chrono::Utc>>() else {
return true;
};
chrono::Utc::now() >= renew_after
}
impl RuniqueApp {
/// HTTPS server with automatic Let's Encrypt certificate (ACME HTTP-01).
///
/// Flow:
/// 1. Start HTTP server on port 80 (ACME challenge + redirect to HTTPS)
/// 2. Obtain certificate from Let's Encrypt (or load existing from ./certs/)
/// 3. Start HTTPS server on port 443
#[cfg(feature = "acme")]
async fn run_with_acme(self) -> Result<(), Box<dyn std::error::Error>> {
let _ = rustls::crypto::ring::default_provider().install_default();
use crate::utils::acme::{ChallengeStore, obtain_certificate};
use axum::{
extract::{Path, State},
response::Redirect,
routing::get,
};
use std::{collections::HashMap, path::Path as FsPath, sync::Arc};
use tokio::sync::RwLock;
let domain = self
.engine
.config
.security
.acme_domain
.as_deref()
.ok_or("ACME_ENABLED=true but ACME_DOMAIN is not set")?
.to_string();
let email = self
.engine
.config
.security
.acme_email
.as_deref()
.ok_or("ACME_ENABLED=true but ACME_EMAIL is not set")?
.to_string();
let ip = self.engine.config.server.ip_server.clone();
// Shared store for ACME HTTP-01 tokens
let challenge_store: ChallengeStore = Arc::new(RwLock::new(HashMap::new()));
// HTTP server on port 80: serves ACME challenges + redirects to HTTPS
let store_clone = challenge_store.clone();
let domain_clone = domain.clone();
let http_app = Router::new()
.route(
"/.well-known/acme-challenge/{token}",
get(
|Path(token): Path<String>, State(store): State<ChallengeStore>| async move {
let map = store.read().await;
match map.get(&token) {
Some(key_auth) => key_auth.clone(),
None => String::from("not found"),
}
},
),
)
.fallback(move || {
let domain = domain_clone.clone();
async move { Redirect::permanent(&format!("https://{domain}")) }
})
.with_state(store_clone);
let http_addr = format!("{ip}:80");
let http_listener = tokio::net::TcpListener::bind(&http_addr).await?;
tokio::spawn(async move {
axum::serve(http_listener, http_app).await.ok();
});
// Load existing cert or run ACME flow
let certs_dir = &self.engine.config.security.acme_certs_dir;
let cert_str = format!("{certs_dir}/cert.pem");
let key_str = format!("{certs_dir}/key.pem");
let expires_str = format!("{certs_dir}/expires.txt");
let cert_path = FsPath::new(&cert_str);
let key_path = FsPath::new(&key_str);
let expires_path = FsPath::new(&expires_str);
let needs_renewal =
!cert_path.exists() || !key_path.exists() || cert_needs_renewal(expires_path).await;
let (cert_pem, key_pem) = if !needs_renewal {
tracing::info!(certs_dir, "Loading existing TLS certificate");
(
tokio::fs::read(cert_path).await?,
tokio::fs::read(key_path).await?,
)
} else {
match obtain_certificate(
&domain,
&email,
challenge_store,
false, // production — use true for testing
)
.await
{
Ok((cert, key)) => {
// Persist to disk for future restarts
tokio::fs::create_dir_all(certs_dir).await?;
tokio::fs::write(&cert_path, &cert).await?;
tokio::fs::write(&key_path, &key).await?;
// Store renewal date: Let's Encrypt certs last 90 days, renew after 60
let renew_after = chrono::Utc::now() + chrono::Duration::days(60);
tokio::fs::write(expires_path, renew_after.to_rfc3339()).await?;
tracing::info!(
"Certificate will be renewed after {}",
renew_after.format("%Y-%m-%d")
);
(cert, key)
}
Err(e) => {
// ACME failed (rate-limit, network issue, etc.)
// Fall back to the existing cert on disk if available
if cert_path.exists() && key_path.exists() {
tracing::warn!(
error = %e,
"ACME renewal failed — using existing certificate from ./certs/"
);
(
tokio::fs::read(cert_path).await?,
tokio::fs::read(key_path).await?,
)
} else {
return Err(e);
}
}
}
};
// Start HTTPS server on port 443
let https_addr = format!("{ip}:443");
let tls_config = axum_server::tls_rustls::RustlsConfig::from_pem(cert_pem, key_pem).await?;
println!(" {}", t("server.operational"));
println!(
" └──> {}",
tf("server.launched", &[format!("https://{domain}")])
);
#[cfg(feature = "orm")]
{
let moteur_db = self.engine.db.get_database_backend();
let db_name = std::env::var("DB_NAME").unwrap_or_else(|_| "runique_db".to_string());
println!(
" └──> {}",
tf("server.connected_db", &[format!("{moteur_db:?}"), db_name])
);
}
println!(" └──> ctrl + c to stop");
// ConnectInfo must be propagated so `trusted_proxies` sees the real peer IP.
// Without it, conn_ip defaults to loopback (trusted) and X-Forwarded-For
// becomes spoofable in standalone-TLS mode (no reverse proxy).
axum_server::bind_rustls(https_addr.parse()?, tls_config)
.serve(
self.router
.into_make_service_with_connect_info::<std::net::SocketAddr>(),
)
.await?;
Ok(())
}
}