sirr-server 1.0.50

Sirr server library — axum HTTP server with redb storage and ChaCha20Poly1305 encryption
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
//! Online license validation against SirrLock.
//!
//! Cached with background revalidation so `create_secret` is never blocked
//! on HTTP after startup. A 72-hour grace period allows operation if
//! SirrLock is temporarily unreachable.

use std::sync::Arc;
use std::time::{Duration, Instant};

use serde::Deserialize;
use tokio::sync::RwLock;
use tracing::{info, warn};

use crate::store::audit::AuditEvent;
use crate::store::Store;

const ACTION_LICENSE_VALIDATE: &str = "license.validate";

/// JSON response from `GET /api/validate?key=...`.
#[derive(Debug, Deserialize)]
pub struct ValidationResponse {
    pub valid: bool,
    pub plan: Option<String>,
    pub limit: Option<u64>,
    pub reason: Option<String>,
}

/// Locally cached validation result.
#[derive(Debug, Clone)]
struct CachedValidation {
    valid: bool,
    plan: Option<String>,
    limit: Option<u64>,
    checked_at: Instant,
    /// Last time a *successful* (valid=true) response was received.
    last_success_at: Option<Instant>,
}

/// Online license validator with HTTP cache + grace period.
#[derive(Clone)]
pub struct OnlineValidator {
    client: reqwest::Client,
    license_key: String,
    validation_url: String,
    cache: Arc<RwLock<Option<CachedValidation>>>,
    cache_ttl: Duration,
    grace_period: Duration,
}

impl OnlineValidator {
    pub fn new(
        license_key: String,
        validation_url: String,
        cache_ttl_secs: u64,
        grace_period_secs: u64,
    ) -> Self {
        let tls_insecure = std::env::var("SIRR_TLS_INSECURE")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);

        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(5))
            .danger_accept_invalid_certs(tls_insecure)
            .build()
            .expect("build reqwest client");

        Self {
            client,
            license_key,
            validation_url,
            cache: Arc::new(RwLock::new(None)),
            cache_ttl: Duration::from_secs(cache_ttl_secs),
            grace_period: Duration::from_secs(grace_period_secs),
        }
    }

    /// Call the SirrLock validation endpoint.
    async fn validate_remote(&self) -> Result<ValidationResponse, reqwest::Error> {
        let url = format!("{}?key={}", self.validation_url, self.license_key);
        self.client.get(&url).send().await?.json().await
    }

    /// Run at server startup. Awaits the first validation; if unreachable, warns
    /// but allows the server to start (backward compatibility).
    pub async fn validate_startup(&self, store: &Store) -> bool {
        match self.validate_remote().await {
            Ok(resp) => {
                let valid = resp.valid;
                let now = Instant::now();

                let cached = CachedValidation {
                    valid,
                    plan: resp.plan.clone(),
                    limit: resp.limit,
                    checked_at: now,
                    last_success_at: if valid { Some(now) } else { None },
                };
                *self.cache.write().await = Some(cached);

                let detail = if valid {
                    format!("startup;plan={}", resp.plan.as_deref().unwrap_or("unknown"))
                } else {
                    format!(
                        "startup;denied;reason={}",
                        resp.reason.as_deref().unwrap_or("unknown")
                    )
                };

                let _ = store.record_audit(AuditEvent::new(
                    ACTION_LICENSE_VALIDATE,
                    None,
                    "server".into(),
                    valid,
                    Some(detail),
                    None,
                    None,
                ));

                if valid {
                    info!(
                        plan = resp.plan.as_deref().unwrap_or("unknown"),
                        "license validated online"
                    );
                } else {
                    warn!(
                        reason = resp.reason.as_deref().unwrap_or("unknown"),
                        "license rejected by SirrLock"
                    );
                }
                valid
            }
            Err(e) => {
                warn!(error = %e, "SirrLock unreachable at startup — allowing degraded mode");
                let _ = store.record_audit(AuditEvent::new(
                    ACTION_LICENSE_VALIDATE,
                    None,
                    "server".into(),
                    true,
                    Some(format!("startup;unreachable;error={e}")),
                    None,
                    None,
                ));
                // Seed cache with a "valid but unchecked" entry so grace period begins.
                let now = Instant::now();
                *self.cache.write().await = Some(CachedValidation {
                    valid: true,
                    plan: None,
                    limit: None,
                    checked_at: now,
                    last_success_at: Some(now),
                });
                true
            }
        }
    }

    /// Non-blocking check used by `create_secret`. Returns `true` if the
    /// license is currently considered valid.
    ///
    /// - Fresh cache (< cache_ttl) → use cached result
    /// - Stale cache → spawn background revalidation, use cached result
    /// - Grace period expired (> 72h since last success) → deny
    pub async fn is_valid(&self, store: &Store) -> bool {
        let cache = self.cache.read().await.clone();

        match cache {
            Some(c) => {
                let age = c.checked_at.elapsed();

                if age < self.cache_ttl {
                    // Fresh — use as-is.
                    return c.valid;
                }

                // Stale — spawn background revalidation.
                self.spawn_revalidate(store.clone());

                // Check grace period: if we've had a success within the grace window, allow.
                if let Some(last_ok) = c.last_success_at {
                    if last_ok.elapsed() < self.grace_period {
                        return true;
                    }
                }

                // Grace period expired — use last known result (which may be false).
                c.valid
            }
            None => {
                // No cache at all — shouldn't happen after startup, but deny to be safe.
                false
            }
        }
    }

    /// Spawn a background task to revalidate and update the cache.
    fn spawn_revalidate(&self, store: Store) {
        let this = self.clone();
        tokio::spawn(async move {
            match this.validate_remote().await {
                Ok(resp) => {
                    let valid = resp.valid;
                    let now = Instant::now();
                    let mut guard = this.cache.write().await;
                    let prev_success = guard.as_ref().and_then(|c| c.last_success_at);

                    *guard = Some(CachedValidation {
                        valid,
                        plan: resp.plan.clone(),
                        limit: resp.limit,
                        checked_at: now,
                        last_success_at: if valid { Some(now) } else { prev_success },
                    });

                    let detail = if valid {
                        format!(
                            "revalidate;plan={}",
                            resp.plan.as_deref().unwrap_or("unknown")
                        )
                    } else {
                        format!(
                            "revalidate;denied;reason={}",
                            resp.reason.as_deref().unwrap_or("unknown")
                        )
                    };

                    let _ = store.record_audit(AuditEvent::new(
                        ACTION_LICENSE_VALIDATE,
                        None,
                        "server".into(),
                        valid,
                        Some(detail),
                        None,
                        None,
                    ));
                }
                Err(e) => {
                    warn!(error = %e, "background license revalidation failed");
                    // Update checked_at so we don't spam revalidation on every request.
                    let mut guard = this.cache.write().await;
                    if let Some(ref mut c) = *guard {
                        c.checked_at = Instant::now();
                    }

                    let _ = store.record_audit(AuditEvent::new(
                        ACTION_LICENSE_VALIDATE,
                        None,
                        "server".into(),
                        false,
                        Some(format!("revalidate;unreachable;error={e}")),
                        None,
                        None,
                    ));
                }
            }
        });
    }

    /// Return the cached plan name, if available.
    pub async fn cached_plan(&self) -> Option<String> {
        self.cache
            .read()
            .await
            .as_ref()
            .and_then(|c| c.plan.clone())
    }

    /// Return the cached secret limit, if available.
    pub async fn cached_limit(&self) -> Option<u64> {
        self.cache.read().await.as_ref().and_then(|c| c.limit)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::audit::AuditQuery;
    use tempfile::tempdir;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn make_store() -> (Store, tempfile::TempDir) {
        let key = crate::store::crypto::generate_key();
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let store = Store::open(&db_path, key).unwrap();
        (store, dir)
    }

    #[tokio::test]
    async fn valid_license_caches_result() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/validate"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "valid": true,
                "plan": "pro",
                "limit": null
            })))
            .mount(&mock)
            .await;

        let (store, _dir) = make_store();
        let v = OnlineValidator::new(
            "sirr_lic_test".into(),
            format!("{}/api/validate", mock.uri()),
            3600,
            259200, // 72h
        );

        let result = v.validate_startup(&store).await;
        assert!(result);
        assert_eq!(v.cached_plan().await, Some("pro".into()));

        // Should use cache (no HTTP call).
        assert!(v.is_valid(&store).await);

        // Audit log should have the startup event.
        let events = store
            .list_audit(&AuditQuery {
                since: None,
                until: None,
                action: Some("license.validate".into()),
                key: None,
                limit: 100,
                org_id: None,
            })
            .unwrap();
        assert!(!events.is_empty());
        assert!(events[0].success);
    }

    #[tokio::test]
    async fn invalid_license_denied() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/validate"))
            .respond_with(ResponseTemplate::new(402).set_body_json(serde_json::json!({
                "valid": false,
                "reason": "expired"
            })))
            .mount(&mock)
            .await;

        let (store, _dir) = make_store();
        let v = OnlineValidator::new(
            "sirr_lic_test".into(),
            format!("{}/api/validate", mock.uri()),
            3600,
            259200,
        );

        let result = v.validate_startup(&store).await;
        assert!(!result);
        assert!(!v.is_valid(&store).await);
    }

    #[tokio::test]
    async fn unreachable_allows_degraded_mode() {
        // Use a URL that will definitely fail.
        let (store, _dir) = make_store();
        let v = OnlineValidator::new(
            "sirr_lic_test".into(),
            "http://127.0.0.1:1/api/validate".into(),
            3600,
            259200,
        );

        // Startup should succeed (degraded mode).
        let result = v.validate_startup(&store).await;
        assert!(result);

        // Cache should be seeded — is_valid should return true (within grace period).
        assert!(v.is_valid(&store).await);
    }

    #[tokio::test]
    async fn stale_cache_triggers_revalidation() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/validate"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "valid": true,
                "plan": "pro",
                "limit": null
            })))
            .expect(2..) // startup + revalidation
            .mount(&mock)
            .await;

        let (store, _dir) = make_store();
        // Cache TTL of 0 means immediately stale.
        let v = OnlineValidator::new(
            "sirr_lic_test".into(),
            format!("{}/api/validate", mock.uri()),
            0, // immediately stale
            259200,
        );

        v.validate_startup(&store).await;

        // This should trigger background revalidation due to stale cache,
        // but still return true (grace period).
        assert!(v.is_valid(&store).await);

        // Give background task time to complete.
        tokio::time::sleep(Duration::from_millis(200)).await;
    }
}