1use axum::http::{HeaderMap, header};
2
3use std::net::SocketAddr;
4use std::path::PathBuf;
5use std::time::Duration;
6
7use crate::model::Action;
8use crate::namespace::Namespace;
9
10#[derive(Debug, Clone)]
11pub struct Config {
12 pub bind: SocketAddr,
13 pub storage_root: PathBuf,
14 pub public_url: Option<String>,
15 pub action_lifetime: u32,
16 pub gc_grace: Duration,
17 pub staging_max_age: Duration,
18 pub lock_max_age: Option<Duration>,
22 pub max_object_size: Option<u64>,
23 pub repo_quota: Option<u64>,
24 pub compression: Option<i32>,
25 pub encryption_key_file: Option<PathBuf>,
29 pub storage: Storage,
30 pub auth: Auth,
31}
32
33#[derive(Debug, Clone)]
34pub enum Storage {
35 Local,
36 Bucket {
41 endpoint: String,
42 bucket: String,
43 region: String,
44 access_key: String,
45 secret_key: String,
46 path_style: bool,
47 presign: bool,
52 },
53}
54
55impl Storage {
56 fn from_env() -> Self {
57 if std::env::var("LFSX_STORAGE").as_deref() != Ok("s3") {
58 return Self::Local;
59 }
60
61 let required = |name: &str| {
62 std::env::var(name)
63 .ok()
64 .filter(|value| !value.is_empty())
65 .unwrap_or_else(|| panic!("LFSX_STORAGE=s3 needs {name}"))
66 };
67
68 Self::Bucket {
69 endpoint: required("LFSX_S3_ENDPOINT"),
70 bucket: required("LFSX_S3_BUCKET"),
71 region: std::env::var("LFSX_S3_REGION").unwrap_or_else(|_| "us-east-1".into()),
72 access_key: required("LFSX_S3_ACCESS_KEY"),
73 secret_key: required("LFSX_S3_SECRET_KEY"),
74 path_style: std::env::var("LFSX_S3_PATH_STYLE").as_deref() != Ok("false"),
75 presign: std::env::var("LFSX_S3_PRESIGN").as_deref() == Ok("true"),
76 }
77 }
78}
79
80#[derive(Debug, Clone)]
81pub enum Auth {
82 Forge {
83 provider: Provider,
84 api_url: String,
85 cache_ttl: Duration,
86 rejection_ttl: Duration,
87 anonymous_read: bool,
91 },
92 Disabled,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum Provider {
97 Github,
98 Gitlab,
99}
100
101impl Provider {
102 fn default_api_url(self) -> &'static str {
103 match self {
104 Self::Github => "https://api.github.com",
105 Self::Gitlab => "https://gitlab.com/api/v4",
106 }
107 }
108
109 fn api_url_variable(self) -> &'static str {
110 match self {
111 Self::Github => "LFSX_GITHUB_API_URL",
112 Self::Gitlab => "LFSX_GITLAB_API_URL",
113 }
114 }
115}
116
117const CACHE_TTL: Duration = Duration::from_secs(60);
118const REJECTION_TTL: Duration = Duration::from_secs(10);
119const GC_GRACE: Duration = Duration::from_secs(14 * 24 * 60 * 60);
120const STAGING_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
121
122impl Config {
123 pub fn from_env() -> Self {
124 let bind = std::env::var("LFSX_BIND")
125 .ok()
126 .and_then(|raw| raw.parse().ok())
127 .unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 8080)));
128
129 let storage_root = std::env::var("LFSX_STORAGE_ROOT")
130 .map(PathBuf::from)
131 .unwrap_or_else(|_| PathBuf::from("/var/lib/lfsx"));
132
133 let public_url = std::env::var("LFSX_PUBLIC_URL")
134 .ok()
135 .filter(|url| !url.is_empty())
136 .map(|url| url.trim_end_matches('/').to_owned());
137
138 Self {
139 bind,
140 storage_root,
141 public_url,
142 action_lifetime: 1800,
143 gc_grace: seconds("LFSX_GC_GRACE").unwrap_or(GC_GRACE),
144 staging_max_age: seconds("LFSX_STAGING_MAX_AGE").unwrap_or(STAGING_MAX_AGE),
145 lock_max_age: seconds("LFSX_LOCK_MAX_AGE"),
146 max_object_size: bytes("LFSX_MAX_OBJECT_SIZE"),
147 repo_quota: bytes("LFSX_REPO_QUOTA"),
148 compression: compression(),
149 encryption_key_file: std::env::var("LFSX_ENCRYPTION_KEY_FILE")
150 .ok()
151 .filter(|path| !path.is_empty())
152 .map(PathBuf::from),
153 storage: Storage::from_env(),
154 auth: Auth::from_env(),
155 }
156 }
157
158 pub fn base_url(&self, headers: &HeaderMap) -> String {
159 if let Some(configured) = &self.public_url {
160 return configured.clone();
161 }
162
163 let scheme = headers
164 .get("x-forwarded-proto")
165 .and_then(|value| value.to_str().ok())
166 .and_then(|value| value.split(',').next())
167 .map(str::trim)
168 .filter(|scheme| !scheme.is_empty())
169 .unwrap_or("http");
170
171 let authority = headers
172 .get(header::HOST)
173 .and_then(|value| value.to_str().ok())
174 .map(str::trim)
175 .filter(|host| !host.is_empty())
176 .unwrap_or("localhost");
177
178 format!("{scheme}://{authority}")
179 }
180
181 pub fn object_url(&self, base: &str, ns: &Namespace, oid: &str) -> String {
182 format!("{base}/{ns}/objects/{oid}")
183 }
184
185 pub fn verify_url(&self, base: &str, ns: &Namespace) -> String {
186 format!("{base}/{ns}/objects/verify")
187 }
188
189 pub fn action(&self, href: String) -> Action {
190 Action {
191 href,
192 header: None,
193 expires_in: self.action_lifetime,
194 }
195 }
196
197 pub fn signed_action(&self, href: String, headers: Vec<(String, String)>) -> Action {
198 Action {
199 href,
200 header: Some(headers.into_iter().collect()),
201 expires_in: self.action_lifetime,
202 }
203 }
204}
205
206impl Auth {
207 fn from_env() -> Self {
208 if std::env::var("LFSX_AUTH").as_deref() == Ok("disabled") {
209 tracing::warn!(
210 "LFSX_AUTH=disabled — every request is accepted, run this on a trusted network only"
211 );
212 return Self::Disabled;
213 }
214
215 let provider = match std::env::var("LFSX_AUTH").as_deref() {
216 Ok("gitlab") => Provider::Gitlab,
217 _ => Provider::Github,
218 };
219
220 let api_url = std::env::var(provider.api_url_variable())
221 .unwrap_or_else(|_| provider.default_api_url().to_owned())
222 .trim_end_matches('/')
223 .to_owned();
224
225 Self::Forge {
226 provider,
227 api_url,
228 cache_ttl: seconds("LFSX_AUTH_CACHE_TTL").unwrap_or(CACHE_TTL),
229 rejection_ttl: seconds("LFSX_AUTH_REJECTION_TTL").unwrap_or(REJECTION_TTL),
230 anonymous_read: std::env::var("LFSX_ANONYMOUS_READ").as_deref() != Ok("false"),
231 }
232 }
233}
234
235fn compression() -> Option<i32> {
244 match std::env::var("LFSX_COMPRESSION").ok()?.trim() {
245 "" | "none" | "off" => None,
246 "zstd" => Some(3),
247 other => match other
248 .strip_prefix("zstd:")
249 .and_then(|level| level.parse().ok())
250 {
251 Some(level @ 1..=19) => Some(level),
252 _ => {
253 tracing::warn!(
254 "LFSX_COMPRESSION={other} is not a codec this server knows — storing objects as they arrive"
255 );
256 None
257 }
258 },
259 }
260}
261
262fn bytes(variable: &str) -> Option<u64> {
263 let configured = std::env::var(variable).ok()?.trim().parse().ok()?;
264
265 if configured == 0 {
266 tracing::warn!("{variable}=0 would refuse every upload — ignoring it");
267 return None;
268 }
269
270 Some(configured)
271}
272
273fn seconds(variable: &str) -> Option<Duration> {
274 std::env::var(variable)
275 .ok()
276 .and_then(|raw| raw.parse().ok())
277 .map(Duration::from_secs)
278}