Skip to main content

max / makenotwork

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