Skip to main content

max / makenotwork

13.5 KB · 424 lines History Blame Raw
1 //! Custom domain management API endpoints.
2
3 use axum::{
4 extract::{Path, Query, State},
5 response::IntoResponse,
6 Form, Json,
7 };
8 use serde::Deserialize;
9 use serde_json::json;
10
11 use crate::{
12 auth::AuthUser,
13 db::{self, CustomDomainId},
14 error::{AppError, Result},
15 AppState,
16 };
17
18 #[derive(Deserialize)]
19 pub(super) struct AddDomainRequest {
20 domain: String,
21 }
22
23
24 /// POST /api/domains: add a custom domain.
25 #[tracing::instrument(skip_all, name = "api::domains::add")]
26 pub(super) async fn add_domain(
27 State(state): State<AppState>,
28 AuthUser(session_user): AuthUser,
29 Form(req): Form<AddDomainRequest>,
30 ) -> Result<impl IntoResponse> {
31 session_user.check_not_sandbox()?;
32 let domain = normalize_domain(&req.domain)?;
33 validate_domain(&domain)?;
34
35 let verification_token = generate_verification_token();
36
37 let _row =
38 db::custom_domains::create_custom_domain(&state.db, session_user.id, &domain, &verification_token)
39 .await?;
40
41 let instructions = format!(
42 "Add two DNS records, then click Verify: a CNAME <code>{0}</code> &rarr; <code>connect.makenot.work</code> (set DNS-only / unproxied), and a TXT <code>_mnw-verify.{0}</code> with value <code>{1}</code>.",
43 domain, verification_token
44 );
45
46 Ok(axum::response::Html(format!(
47 "<p class=\"success\">{}</p>",
48 instructions
49 )))
50 }
51
52 #[derive(Deserialize)]
53 pub(super) struct VerifyDomainRequest {
54 domain_id: CustomDomainId,
55 }
56
57 /// POST /api/domains/verify: trigger DNS verification.
58 #[tracing::instrument(skip_all, name = "api::domains::verify")]
59 pub(super) async fn verify_domain(
60 State(state): State<AppState>,
61 AuthUser(session_user): AuthUser,
62 Form(req): Form<VerifyDomainRequest>,
63 ) -> Result<impl IntoResponse> {
64 session_user.check_not_sandbox()?;
65 let cd = db::custom_domains::get_custom_domain_by_user(&state.db, session_user.id)
66 .await?
67 .ok_or(AppError::NotFound)?;
68
69 if cd.id != req.domain_id {
70 return Err(AppError::NotFound);
71 }
72
73 if cd.verified {
74 return Ok(axum::response::Html("<p class=\"success\">Domain already verified.</p>".to_string()));
75 }
76
77 // Query DNS via Cloudflare DNS-over-HTTPS
78 let lookup_name = format!("_mnw-verify.{}", cd.domain);
79 let txt_records = dns_lookup_txt(&lookup_name).await?;
80
81 let matched = txt_records
82 .iter()
83 .any(|txt| txt.trim() == cd.verification_token);
84
85 if !matched {
86 return Ok(axum::response::Html(format!(
87 "<p class=\"error\">TXT record not found. Add <code>_mnw-verify.{}</code> TXT <code>{}</code> and try again.</p>",
88 cd.domain, cd.verification_token
89 )));
90 }
91
92 // Mark verified in DB and update cache
93 db::custom_domains::mark_domain_verified(&state.db, cd.id).await?;
94 state
95 .domain_cache
96 .insert(cd.domain.clone(), session_user.id);
97
98 Ok(axum::response::Html("<p class=\"success\">Domain verified successfully. Reload to see changes.</p>".to_string()))
99 }
100
101 /// DELETE /api/domains/{id}: remove a custom domain.
102 #[tracing::instrument(skip_all, name = "api::domains::remove")]
103 pub(super) async fn remove_domain(
104 State(state): State<AppState>,
105 AuthUser(session_user): AuthUser,
106 Path(id): Path<CustomDomainId>,
107 ) -> Result<impl IntoResponse> {
108 session_user.check_not_sandbox()?;
109 // Fetch first so we can remove from cache
110 let cd = db::custom_domains::get_custom_domain_by_user(&state.db, session_user.id)
111 .await?
112 .ok_or(AppError::NotFound)?;
113
114 if cd.id != id {
115 return Err(AppError::NotFound);
116 }
117
118 db::custom_domains::delete_custom_domain(&state.db, id, session_user.id).await?;
119
120 // Remove from cache
121 state.domain_cache.remove(&cd.domain);
122
123 Ok(axum::http::StatusCode::NO_CONTENT)
124 }
125
126 /// GET /api/domains: get current user's custom domain.
127 #[tracing::instrument(skip_all, name = "api::domains::get")]
128 pub(super) async fn get_domain(
129 State(state): State<AppState>,
130 AuthUser(session_user): AuthUser,
131 ) -> Result<impl IntoResponse> {
132 let cd = db::custom_domains::get_custom_domain_by_user(&state.db, session_user.id).await?;
133
134 match cd {
135 Some(d) => {
136 let instructions = if d.verified {
137 String::new()
138 } else {
139 format!(
140 "Point {0} at connect.makenot.work (CNAME, DNS-only) and add a TXT _mnw-verify.{0} with value {1}, then verify.",
141 d.domain, d.verification_token
142 )
143 };
144 Ok(Json(json!({
145 "id": d.id,
146 "domain": d.domain,
147 "verified": d.verified,
148 "verification_token": d.verification_token,
149 "instructions": instructions,
150 "verified_at": d.verified_at,
151 })))
152 }
153 None => Ok(Json(json!(null))),
154 }
155 }
156
157 #[derive(Deserialize)]
158 pub(super) struct CaddyAskQuery {
159 domain: String,
160 }
161
162 /// GET /api/domains/caddy-ask: Caddy on-demand TLS check.
163 ///
164 /// Unauthenticated (called by Caddy, not users). Returns 200 if the domain
165 /// is verified, 404 if not. Caddy treats anything outside the 2xx range as
166 /// "do not issue."
167 ///
168 /// Abuse model: every request reaches MNW from Caddy's IP, so per-IP rate
169 /// limiting can't distinguish a legitimate visitor from an attacker probing
170 /// thousands of bogus hostnames. Defenses here are content-based:
171 /// 1. Reject syntactically-invalid hostnames before touching the DB.
172 /// 2. Bound concurrent cache-miss DB lookups via `caddy_ask_semaphore`;
173 /// at capacity, return 503 so Caddy backs off and the pool stays free.
174 #[tracing::instrument(skip_all, name = "api::domains::caddy_ask")]
175 pub(super) async fn caddy_ask(
176 State(state): State<AppState>,
177 Query(q): Query<CaddyAskQuery>,
178 ) -> impl IntoResponse {
179 use metrics::{counter, gauge};
180 let domain = q.domain.to_lowercase();
181
182 // Cheap structural reject: hostnames with no dot, spaces, control chars,
183 // or absurd length can't be verified domains. Skipping the DB on these
184 // shuts down the easiest flood vector.
185 if domain.is_empty()
186 || domain.len() > 253
187 || !domain.contains('.')
188 || domain.contains(|c: char| c.is_whitespace() || c.is_control())
189 {
190 counter!("caddy_ask_total", "outcome" => "rejected_invalid").increment(1);
191 return axum::http::StatusCode::NOT_FOUND;
192 }
193
194 // Fast path: cache hit, no DB, no semaphore.
195 if state.domain_cache.contains_key(&domain) {
196 counter!("caddy_ask_total", "outcome" => "cache_hit").increment(1);
197 return axum::http::StatusCode::OK;
198 }
199
200 // Slow path: cap concurrent DB lookups. `try_acquire` is non-blocking;
201 // hitting the cap means we're already under pressure and want Caddy to
202 // retry rather than queue.
203 let Ok(_permit) = state.caddy_ask_semaphore.try_acquire() else {
204 tracing::warn!(domain = %domain, "caddy-ask: cache-miss concurrency cap reached");
205 counter!("caddy_ask_total", "outcome" => "rejected_at_cap").increment(1);
206 return axum::http::StatusCode::SERVICE_UNAVAILABLE;
207 };
208
209 match db::custom_domains::get_verified_domain(&state.db, &domain).await {
210 Ok(Some(d)) => {
211 state.domain_cache.insert(d.domain, d.user_id);
212 // Update cache-size gauge after the insert so it reflects current state.
213 gauge!("domain_cache_entries").set(state.domain_cache.len() as f64);
214 counter!("caddy_ask_total", "outcome" => "miss_found").increment(1);
215 axum::http::StatusCode::OK
216 }
217 _ => {
218 counter!("caddy_ask_total", "outcome" => "miss_notfound").increment(1);
219 axum::http::StatusCode::NOT_FOUND
220 }
221 }
222 }
223
224 // ── Helpers ──
225
226 /// Normalize a domain: lowercase, strip protocol, strip trailing slash/path.
227 fn normalize_domain(input: &str) -> Result<String> {
228 let mut domain = input.trim().to_lowercase();
229
230 // Strip protocol if present
231 if let Some(rest) = domain.strip_prefix("https://") {
232 domain = rest.to_string();
233 } else if let Some(rest) = domain.strip_prefix("http://") {
234 domain = rest.to_string();
235 }
236
237 // Strip path
238 if let Some(pos) = domain.find('/') {
239 domain.truncate(pos);
240 }
241
242 // Strip port
243 if let Some(pos) = domain.find(':') {
244 domain.truncate(pos);
245 }
246
247 if domain.is_empty() {
248 return Err(AppError::validation("Domain cannot be empty.".to_string()));
249 }
250
251 Ok(domain)
252 }
253
254 /// Basic domain validation: must have at least one dot, no spaces, reasonable length.
255 fn validate_domain(domain: &str) -> Result<()> {
256 if domain.len() > 253 {
257 return Err(AppError::validation(
258 "Domain name is too long.".to_string(),
259 ));
260 }
261
262 if !domain.contains('.') {
263 return Err(AppError::validation(
264 "Domain must include a TLD (e.g. example.com).".to_string(),
265 ));
266 }
267
268 if domain.contains(' ') || domain.contains('\t') {
269 return Err(AppError::validation(
270 "Domain cannot contain spaces.".to_string(),
271 ));
272 }
273
274 // Block MNW domains
275 if domain == "makenot.work"
276 || domain.ends_with(".makenot.work")
277 || domain == "makenotwork.com"
278 || domain.ends_with(".makenotwork.com")
279 {
280 return Err(AppError::validation(
281 "Cannot use a makenot.work domain.".to_string(),
282 ));
283 }
284
285 // Check labels
286 for label in domain.split('.') {
287 if label.is_empty() || label.len() > 63 {
288 return Err(AppError::validation(
289 "Each domain label must be 1-63 characters.".to_string(),
290 ));
291 }
292 if !label
293 .chars()
294 .all(|c| c.is_ascii_alphanumeric() || c == '-')
295 {
296 return Err(AppError::validation(
297 "Domain labels can only contain letters, numbers, and hyphens.".to_string(),
298 ));
299 }
300 if label.starts_with('-') || label.ends_with('-') {
301 return Err(AppError::validation(
302 "Domain labels cannot start or end with a hyphen.".to_string(),
303 ));
304 }
305 }
306
307 Ok(())
308 }
309
310 /// Generate a random verification token.
311 fn generate_verification_token() -> String {
312 let mut bytes = [0u8; 16];
313 rand::RngCore::fill_bytes(&mut rand::rng(), &mut bytes);
314 format!("mnw-verify-{}", hex::encode(bytes))
315 }
316
317 /// Query TXT records via Cloudflare DNS-over-HTTPS.
318 async fn dns_lookup_txt(name: &str) -> Result<Vec<String>> {
319 let client = reqwest::Client::new();
320 let resp = client
321 .get("https://cloudflare-dns.com/dns-query")
322 .query(&[("name", name), ("type", "TXT")])
323 .header("Accept", "application/dns-json")
324 .timeout(std::time::Duration::from_secs(10))
325 .send()
326 .await
327 .map_err(|e| {
328 tracing::warn!(error = ?e, name = %name, "DNS lookup failed");
329 AppError::BadRequest("DNS lookup failed. Please try again.".to_string())
330 })?;
331
332 if !resp.status().is_success() {
333 return Err(AppError::BadRequest(
334 "DNS lookup failed. Please try again.".to_string(),
335 ));
336 }
337
338 let body: serde_json::Value = resp.json().await.map_err(|e| {
339 tracing::warn!(error = ?e, "Failed to parse DNS response");
340 AppError::BadRequest("DNS lookup failed. Please try again.".to_string())
341 })?;
342
343 // Parse Cloudflare DNS-over-HTTPS JSON response
344 let mut records = Vec::new();
345 if let Some(answers) = body["Answer"].as_array() {
346 for answer in answers {
347 if answer["type"].as_u64() == Some(16) {
348 // TXT record type = 16
349 if let Some(data) = answer["data"].as_str() {
350 // Remove surrounding quotes from TXT record data
351 let cleaned = data.trim_matches('"');
352 records.push(cleaned.to_string());
353 }
354 }
355 }
356 }
357
358 Ok(records)
359 }
360
361 #[cfg(test)]
362 mod tests {
363 use super::*;
364
365 #[test]
366 fn normalize_strips_protocol() {
367 assert_eq!(normalize_domain("https://example.com").unwrap(), "example.com");
368 assert_eq!(normalize_domain("http://example.com").unwrap(), "example.com");
369 }
370
371 #[test]
372 fn normalize_strips_path_and_port() {
373 assert_eq!(normalize_domain("example.com/path").unwrap(), "example.com");
374 assert_eq!(normalize_domain("example.com:443").unwrap(), "example.com");
375 }
376
377 #[test]
378 fn normalize_lowercases() {
379 assert_eq!(normalize_domain("EXAMPLE.COM").unwrap(), "example.com");
380 }
381
382 #[test]
383 fn normalize_empty_errors() {
384 assert!(normalize_domain("").is_err());
385 }
386
387 #[test]
388 fn validate_valid_domains() {
389 assert!(validate_domain("example.com").is_ok());
390 assert!(validate_domain("sub.example.com").is_ok());
391 assert!(validate_domain("my-site.co.uk").is_ok());
392 }
393
394 #[test]
395 fn validate_no_tld() {
396 assert!(validate_domain("localhost").is_err());
397 }
398
399 #[test]
400 fn validate_mnw_blocked() {
401 assert!(validate_domain("makenot.work").is_err());
402 assert!(validate_domain("sub.makenot.work").is_err());
403 assert!(validate_domain("makenotwork.com").is_err());
404 }
405
406 #[test]
407 fn validate_spaces() {
408 assert!(validate_domain("exam ple.com").is_err());
409 }
410
411 #[test]
412 fn validate_hyphen_edges() {
413 assert!(validate_domain("-example.com").is_err());
414 assert!(validate_domain("example-.com").is_err());
415 }
416
417 #[test]
418 fn verification_token_format() {
419 let token = generate_verification_token();
420 assert!(token.starts_with("mnw-verify-"));
421 assert_eq!(token.len(), "mnw-verify-".len() + 32);
422 }
423 }
424