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 },
88 Disabled,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Provider {
93 Github,
94 Gitlab,
95}
96
97impl Provider {
98 fn default_api_url(self) -> &'static str {
99 match self {
100 Self::Github => "https://api.github.com",
101 Self::Gitlab => "https://gitlab.com/api/v4",
102 }
103 }
104
105 fn api_url_variable(self) -> &'static str {
106 match self {
107 Self::Github => "LFSX_GITHUB_API_URL",
108 Self::Gitlab => "LFSX_GITLAB_API_URL",
109 }
110 }
111}
112
113const CACHE_TTL: Duration = Duration::from_secs(60);
114const REJECTION_TTL: Duration = Duration::from_secs(10);
115const GC_GRACE: Duration = Duration::from_secs(14 * 24 * 60 * 60);
116const STAGING_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
117
118impl Config {
119 pub fn from_env() -> Self {
120 let bind = std::env::var("LFSX_BIND")
121 .ok()
122 .and_then(|raw| raw.parse().ok())
123 .unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 8080)));
124
125 let storage_root = std::env::var("LFSX_STORAGE_ROOT")
126 .map(PathBuf::from)
127 .unwrap_or_else(|_| PathBuf::from("/var/lib/lfsx"));
128
129 let public_url = std::env::var("LFSX_PUBLIC_URL")
130 .ok()
131 .filter(|url| !url.is_empty())
132 .map(|url| url.trim_end_matches('/').to_owned());
133
134 Self {
135 bind,
136 storage_root,
137 public_url,
138 action_lifetime: 1800,
139 gc_grace: seconds("LFSX_GC_GRACE").unwrap_or(GC_GRACE),
140 staging_max_age: seconds("LFSX_STAGING_MAX_AGE").unwrap_or(STAGING_MAX_AGE),
141 lock_max_age: seconds("LFSX_LOCK_MAX_AGE"),
142 max_object_size: bytes("LFSX_MAX_OBJECT_SIZE"),
143 repo_quota: bytes("LFSX_REPO_QUOTA"),
144 compression: compression(),
145 encryption_key_file: std::env::var("LFSX_ENCRYPTION_KEY_FILE")
146 .ok()
147 .filter(|path| !path.is_empty())
148 .map(PathBuf::from),
149 storage: Storage::from_env(),
150 auth: Auth::from_env(),
151 }
152 }
153
154 pub fn base_url(&self, headers: &HeaderMap) -> String {
155 if let Some(configured) = &self.public_url {
156 return configured.clone();
157 }
158
159 let scheme = headers
160 .get("x-forwarded-proto")
161 .and_then(|value| value.to_str().ok())
162 .and_then(|value| value.split(',').next())
163 .map(str::trim)
164 .filter(|scheme| !scheme.is_empty())
165 .unwrap_or("http");
166
167 let authority = headers
168 .get(header::HOST)
169 .and_then(|value| value.to_str().ok())
170 .map(str::trim)
171 .filter(|host| !host.is_empty())
172 .unwrap_or("localhost");
173
174 format!("{scheme}://{authority}")
175 }
176
177 pub fn object_url(&self, base: &str, ns: &Namespace, oid: &str) -> String {
178 format!("{base}/{ns}/objects/{oid}")
179 }
180
181 pub fn verify_url(&self, base: &str, ns: &Namespace) -> String {
182 format!("{base}/{ns}/objects/verify")
183 }
184
185 pub fn action(&self, href: String) -> Action {
186 Action {
187 href,
188 expires_in: self.action_lifetime,
189 }
190 }
191}
192
193impl Auth {
194 fn from_env() -> Self {
195 if std::env::var("LFSX_AUTH").as_deref() == Ok("disabled") {
196 tracing::warn!(
197 "LFSX_AUTH=disabled — every request is accepted, run this on a trusted network only"
198 );
199 return Self::Disabled;
200 }
201
202 let provider = match std::env::var("LFSX_AUTH").as_deref() {
203 Ok("gitlab") => Provider::Gitlab,
204 _ => Provider::Github,
205 };
206
207 let api_url = std::env::var(provider.api_url_variable())
208 .unwrap_or_else(|_| provider.default_api_url().to_owned())
209 .trim_end_matches('/')
210 .to_owned();
211
212 Self::Forge {
213 provider,
214 api_url,
215 cache_ttl: seconds("LFSX_AUTH_CACHE_TTL").unwrap_or(CACHE_TTL),
216 rejection_ttl: seconds("LFSX_AUTH_REJECTION_TTL").unwrap_or(REJECTION_TTL),
217 }
218 }
219}
220
221fn compression() -> Option<i32> {
230 match std::env::var("LFSX_COMPRESSION").ok()?.trim() {
231 "" | "none" | "off" => None,
232 "zstd" => Some(3),
233 other => match other
234 .strip_prefix("zstd:")
235 .and_then(|level| level.parse().ok())
236 {
237 Some(level @ 1..=19) => Some(level),
238 _ => {
239 tracing::warn!(
240 "LFSX_COMPRESSION={other} is not a codec this server knows — storing objects as they arrive"
241 );
242 None
243 }
244 },
245 }
246}
247
248fn bytes(variable: &str) -> Option<u64> {
249 let configured = std::env::var(variable).ok()?.trim().parse().ok()?;
250
251 if configured == 0 {
252 tracing::warn!("{variable}=0 would refuse every upload — ignoring it");
253 return None;
254 }
255
256 Some(configured)
257}
258
259fn seconds(variable: &str) -> Option<Duration> {
260 std::env::var(variable)
261 .ok()
262 .and_then(|raw| raw.parse().ok())
263 .map(Duration::from_secs)
264}