postrust-proxy 0.5.1

Reverse proxy for Postrust with load balancing and automatic TLS certificates
Documentation
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Domain management service.
//!
//! High-level service for managing custom domains, routes, and upstreams.

use crate::error::{ProxyError, ProxyResult};
use crate::saas::db;
use crate::saas::types::*;
use crate::saas::verification::DomainVerificationService;
use rand::Rng;
use sqlx::PgPool;
use std::sync::Arc;
use uuid::Uuid;

/// Domain management service.
pub struct DomainManager {
    pool: PgPool,
    verification_service: Arc<DomainVerificationService>,
}

impl DomainManager {
    /// Create a new domain manager.
    pub fn new(pool: PgPool, verification_service: Arc<DomainVerificationService>) -> Self {
        Self {
            pool,
            verification_service,
        }
    }

    // =========================================================================
    // Domain Management
    // =========================================================================

    /// Create a new domain for a tenant.
    pub async fn create_domain(
        &self,
        tenant_id: Uuid,
        req: CreateDomainRequest,
    ) -> ProxyResult<DomainResponse> {
        // Validate domain format
        self.validate_domain_format(&req.domain)?;

        // Check tenant quota
        let (current, max) = db::check_domain_quota(&self.pool, tenant_id).await?;
        if current >= max as i64 {
            return Err(ProxyError::QuotaExceeded(format!(
                "Domain limit reached ({}/{})",
                current, max
            )));
        }

        // Check if domain already exists
        if db::domain_exists(&self.pool, &req.domain).await? {
            return Err(ProxyError::Conflict("Domain already registered".into()));
        }

        // Generate verification token
        let verification_token = generate_verification_token();

        // Create domain
        let domain =
            db::create_domain(&self.pool, tenant_id, req.clone(), &verification_token).await?;

        // Create verification challenge
        let expected_value = format!("postrust-verify={}", verification_token);
        let challenge_type = match req.verification_method {
            VerificationMethod::Dns => "dns",
            VerificationMethod::Http => "http",
        };
        db::create_verification_challenge(
            &self.pool,
            domain.id,
            challenge_type,
            &verification_token,
            &expected_value,
        )
        .await?;

        // Generate verification instructions
        let instructions = match domain.verification_method {
            VerificationMethod::Dns => {
                VerificationInstructions::dns(&domain.domain, &verification_token)
            }
            VerificationMethod::Http => {
                VerificationInstructions::http(&domain.domain, &verification_token)
            }
        };

        Ok(DomainResponse {
            domain,
            verification_instructions: instructions,
        })
    }

    /// Get a domain by ID for a tenant.
    pub async fn get_domain(
        &self,
        id: Uuid,
        tenant_id: Uuid,
    ) -> ProxyResult<Option<DomainResponse>> {
        let domain = db::get_domain_for_tenant(&self.pool, id, tenant_id).await?;

        Ok(domain.map(|d| {
            let instructions = match d.verification_method {
                VerificationMethod::Dns => {
                    VerificationInstructions::dns(&d.domain, &d.verification_token)
                }
                VerificationMethod::Http => {
                    VerificationInstructions::http(&d.domain, &d.verification_token)
                }
            };
            DomainResponse {
                domain: d,
                verification_instructions: instructions,
            }
        }))
    }

    /// List all domains for a tenant.
    pub async fn list_domains(&self, tenant_id: Uuid) -> ProxyResult<Vec<Domain>> {
        db::list_domains(&self.pool, tenant_id).await
    }

    /// Delete a domain.
    pub async fn delete_domain(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<bool> {
        db::delete_domain(&self.pool, id, tenant_id).await
    }

    /// Verify a domain.
    pub async fn verify_domain(
        &self,
        id: Uuid,
        tenant_id: Uuid,
    ) -> ProxyResult<VerificationResult> {
        let domain = db::get_domain_for_tenant(&self.pool, id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        // Record verification attempt
        db::record_verification_attempt(&self.pool, id).await?;

        // Perform verification based on method
        let result = match domain.verification_method {
            VerificationMethod::Dns => {
                self.verification_service
                    .verify_dns(&domain.domain, &domain.verification_token)
                    .await
            }
            VerificationMethod::Http => {
                self.verification_service
                    .verify_http(&domain.domain, &domain.verification_token)
                    .await
            }
        };

        match &result {
            VerificationResult::Verified => {
                // Update domain status
                db::update_verification_status(&self.pool, id, VerificationStatus::Verified)
                    .await?;

                // A domain asking for ACME is queued, not marked
                // `provisioning`.
                //
                // `pending` is the worker's inbox: `saas::ssl::run` claims
                // these rows, flips them to `provisioning` itself, and records
                // `active` or `failed` with a reason. Setting `provisioning`
                // here would claim work was under way before anything had
                // started, and would take the row out of the worker's own
                // claim query -- so it would sit mid-issuance for ever.
                if domain.ssl_provider == SslProvider::Acme {
                    tracing::info!(
                        domain = %domain.domain,
                        "queued for ACME certificate issuance"
                    );
                    db::update_ssl_status(&self.pool, id, SslStatus::Pending, None).await?;
                }

                tracing::info!(domain = %domain.domain, "Domain verified successfully");
            }
            VerificationResult::Failed { reason } => {
                tracing::warn!(domain = %domain.domain, reason = %reason, "Domain verification failed");
            }
            VerificationResult::Pending => {}
        }

        Ok(result)
    }

    /// Look up a live HTTP verification challenge by its token.
    ///
    /// Exposed so the well-known endpoint can answer challenges without
    /// reaching past this service for the pool. The caller must still check
    /// that the request arrived for the returned domain.
    pub async fn find_live_http_challenge(
        &self,
        token: &str,
    ) -> ProxyResult<Option<db::HttpChallenge>> {
        db::find_live_http_challenge(&self.pool, token).await
    }

    /// Apply a partial update to a domain.
    ///
    /// The domain name cannot be changed -- see [`UpdateDomainRequest`] for
    /// why -- so this only moves the verification method and the SSL provider.
    pub async fn update_domain(
        &self,
        id: Uuid,
        tenant_id: Uuid,
        req: UpdateDomainRequest,
    ) -> ProxyResult<Domain> {
        db::update_domain(
            &self.pool,
            id,
            tenant_id,
            req.verification_method.as_ref(),
            req.ssl_provider.as_ref(),
        )
        .await?
        .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))
    }

    /// Store a certificate an operator supplied, after checking it.
    ///
    /// The checks are the point. An unchecked upload gives a listener that
    /// accepts the certificate now and fails every handshake later: the key may
    /// not match the chain, the certificate may be expired, or it may be for
    /// another domain entirely. All three are refused here, with a message
    /// saying which.
    pub async fn upload_certificate(
        &self,
        id: Uuid,
        tenant_id: Uuid,
        cert_store: &crate::tls::CertificateStore,
        req: UploadCertificateRequest,
    ) -> ProxyResult<Domain> {
        let domain = db::get_domain_for_tenant(&self.pool, id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        let facts = crate::tls::validate_for_domain(
            &domain.domain,
            req.cert_pem.as_bytes(),
            req.key_pem.as_bytes(),
        )?;

        cert_store
            .save(crate::tls::Certificate {
                domain: domain.domain.clone(),
                cert_pem: req.cert_pem.into_bytes(),
                key_pem: req.key_pem.into_bytes(),
                expires_at: Some(facts.expires_at),
            })
            .await?;

        let updated = db::record_uploaded_certificate(&self.pool, id, tenant_id, facts.expires_at)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        tracing::info!(
            domain = %updated.domain,
            expires_at = %facts.expires_at,
            "stored an uploaded certificate"
        );
        Ok(updated)
    }

    /// Queue a verified ACME domain for certificate issuance.
    ///
    /// Sets state and returns; the work is done by the issuance worker. That is
    /// the whole endpoint, and deliberately so: an ACME order is several round
    /// trips to the CA plus a challenge the CA has to fetch back from us, and
    /// retrying under a rate limit is the normal failure mode. Doing it inline
    /// would hold the request open and let a client timeout orphan an order the
    /// CA had already started.
    ///
    /// Idempotent, and also the way to retry after a failure -- it clears the
    /// attempt count and the backoff.
    pub async fn queue_ssl_issuance(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<Domain> {
        db::queue_for_issuance(&self.pool, id, tenant_id)
            .await?
            .ok_or_else(|| {
                ProxyError::NotFound(
                    "No verified domain with ssl_provider = acme for this tenant".into(),
                )
            })
    }

    /// Enable a verified domain.
    pub async fn enable_domain(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<bool> {
        // First check if domain is verified
        let domain = db::get_domain_for_tenant(&self.pool, id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        if domain.verification_status != VerificationStatus::Verified {
            return Err(ProxyError::Validation(
                "Domain must be verified before enabling".into(),
            ));
        }

        db::enable_domain(&self.pool, id).await
    }

    /// Disable a domain.
    pub async fn disable_domain(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<bool> {
        // Verify ownership
        db::get_domain_for_tenant(&self.pool, id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        db::disable_domain(&self.pool, id).await
    }

    // =========================================================================
    // Route Management
    // =========================================================================

    /// Create a route for a domain.
    pub async fn create_route(
        &self,
        domain_id: Uuid,
        tenant_id: Uuid,
        req: CreateDomainRouteRequest,
    ) -> ProxyResult<DomainRoute> {
        // Verify domain belongs to tenant
        let _domain = db::get_domain_for_tenant(&self.pool, domain_id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        // Verify upstream belongs to tenant
        db::get_upstream_for_tenant(&self.pool, req.upstream_id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Upstream not found".into()))?;

        db::create_route(&self.pool, domain_id, tenant_id, req).await
    }

    /// Get a route by ID.
    pub async fn get_route(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<Option<DomainRoute>> {
        db::get_route_for_tenant(&self.pool, id, tenant_id).await
    }

    /// List routes for a domain.
    pub async fn list_routes_for_domain(
        &self,
        domain_id: Uuid,
        tenant_id: Uuid,
    ) -> ProxyResult<Vec<DomainRoute>> {
        // Verify domain belongs to tenant
        db::get_domain_for_tenant(&self.pool, domain_id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Domain not found".into()))?;

        db::list_routes_for_domain(&self.pool, domain_id, tenant_id).await
    }

    /// Update a route.
    pub async fn update_route(
        &self,
        id: Uuid,
        tenant_id: Uuid,
        req: UpdateDomainRouteRequest,
    ) -> ProxyResult<Option<DomainRoute>> {
        // If upstream_id is being updated, verify it belongs to tenant
        if let Some(upstream_id) = req.upstream_id {
            db::get_upstream_for_tenant(&self.pool, upstream_id, tenant_id)
                .await?
                .ok_or_else(|| ProxyError::NotFound("Upstream not found".into()))?;
        }

        db::update_route(&self.pool, id, tenant_id, req).await
    }

    /// Delete a route.
    pub async fn delete_route(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<bool> {
        db::delete_route(&self.pool, id, tenant_id).await
    }

    // =========================================================================
    // Upstream Management
    // =========================================================================

    /// Create an upstream for a tenant.
    pub async fn create_upstream(
        &self,
        tenant_id: Uuid,
        req: CreateUpstreamRequest,
    ) -> ProxyResult<DomainUpstream> {
        db::create_upstream(&self.pool, tenant_id, req).await
    }

    /// Get an upstream by ID.
    pub async fn get_upstream(
        &self,
        id: Uuid,
        tenant_id: Uuid,
    ) -> ProxyResult<Option<DomainUpstream>> {
        db::get_upstream_for_tenant(&self.pool, id, tenant_id).await
    }

    /// List upstreams for a tenant.
    pub async fn list_upstreams(&self, tenant_id: Uuid) -> ProxyResult<Vec<DomainUpstream>> {
        db::list_upstreams(&self.pool, tenant_id).await
    }

    /// Update an upstream.
    pub async fn update_upstream(
        &self,
        id: Uuid,
        tenant_id: Uuid,
        req: UpdateUpstreamRequest,
    ) -> ProxyResult<Option<DomainUpstream>> {
        db::update_upstream(&self.pool, id, tenant_id, req).await
    }

    /// Delete an upstream.
    pub async fn delete_upstream(&self, id: Uuid, tenant_id: Uuid) -> ProxyResult<bool> {
        db::delete_upstream(&self.pool, id, tenant_id).await
    }

    /// Add a backend to an upstream.
    pub async fn add_backend(
        &self,
        upstream_id: Uuid,
        tenant_id: Uuid,
        req: CreateBackendRequest,
    ) -> ProxyResult<DomainBackend> {
        // Verify upstream belongs to tenant
        db::get_upstream_for_tenant(&self.pool, upstream_id, tenant_id)
            .await?
            .ok_or_else(|| ProxyError::NotFound("Upstream not found".into()))?;

        db::create_backend(&self.pool, upstream_id, req).await
    }

    /// Remove a backend from an upstream.
    pub async fn remove_backend(
        &self,
        backend_id: Uuid,
        upstream_id: Uuid,
        tenant_id: Uuid,
    ) -> ProxyResult<bool> {
        db::delete_backend(&self.pool, backend_id, upstream_id, tenant_id).await
    }

    // =========================================================================
    // Tenant Management
    // =========================================================================

    /// Get tenant usage statistics.
    pub async fn get_tenant_usage(&self, tenant_id: Uuid) -> ProxyResult<TenantUsage> {
        db::get_tenant_usage(&self.pool, tenant_id).await
    }

    // =========================================================================
    // Validation Helpers
    // =========================================================================

    /// Validate domain format.
    fn validate_domain_format(&self, domain: &str) -> ProxyResult<()> {
        // Check length
        if domain.is_empty() || domain.len() > 253 {
            return Err(ProxyError::Validation("Invalid domain length".into()));
        }

        // Must have at least one dot
        if !domain.contains('.') {
            return Err(ProxyError::Validation(
                "Domain must have at least one dot".into(),
            ));
        }

        // Check each label
        for label in domain.split('.') {
            if label.is_empty() || label.len() > 63 {
                return Err(ProxyError::Validation("Invalid domain label length".into()));
            }

            // Check first and last characters
            let chars: Vec<char> = label.chars().collect();
            if chars.first().is_none_or(|c| !c.is_alphanumeric())
                || chars.last().is_none_or(|c| !c.is_alphanumeric())
            {
                return Err(ProxyError::Validation(
                    "Domain labels must start and end with alphanumeric characters".into(),
                ));
            }

            // Check all characters
            for c in label.chars() {
                if !c.is_alphanumeric() && c != '-' {
                    return Err(ProxyError::Validation(
                        "Domain labels can only contain alphanumeric characters and hyphens".into(),
                    ));
                }
            }
        }

        Ok(())
    }
}

/// Generate a secure verification token.
fn generate_verification_token() -> String {
    const CHARSET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    let mut rng = rand::rng();

    (0..32)
        .map(|_| {
            let idx = rng.random_range(0..CHARSET.len());
            CHARSET[idx] as char
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    // Note: `validate_domain_format` is exercised via integration tests that
    // build a real `DomainManager` (it needs a live pool). A previous unit test
    // here constructed the manager from `std::mem::zeroed()`, which is undefined
    // behavior and crashed on drop, so it was removed.

    #[test]
    fn test_generate_verification_token() {
        let token = generate_verification_token();
        assert_eq!(token.len(), 32);
        assert!(token.chars().all(|c| c.is_alphanumeric()));
    }
}