velesdb-cli 1.12.0

Interactive CLI and REPL for VelesDB with VelesQL support
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
//! License management module for VelesDB CLI
//!
//! Provides commands to activate, verify, and display license information.
//! Uses Ed25519 cryptographic signatures for validation.
//!
//! This module uses the SAME cryptographic algorithms as velesdb-premium
//! to ensure compatibility with licenses generated by GetAppSuite.

use anyhow::{Context, Result};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use colored::Colorize;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// License tier enumeration (must match velesdb-premium)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LicenseTier {
    Professional,
    Team,
    Enterprise,
}

impl std::fmt::Display for LicenseTier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LicenseTier::Professional => write!(f, "Professional"),
            LicenseTier::Team => write!(f, "Team"),
            LicenseTier::Enterprise => write!(f, "Enterprise"),
        }
    }
}

/// Premium feature flags (must match velesdb-premium).
///
/// Only features that require a commercial license belong here.
/// Features available in the open-source core (Hybrid Search, Advanced Filtering,
/// GPU Acceleration) were removed in #390 since they ship ungated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum PremiumFeature {
    EncryptionAtRest,
    Snapshots,
    MultiTenancy,
    RBAC,
    SSO,
    AuditLogging,
}

impl std::fmt::Display for PremiumFeature {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PremiumFeature::EncryptionAtRest => write!(f, "Encryption at Rest"),
            PremiumFeature::Snapshots => write!(f, "Snapshots & Backups"),
            PremiumFeature::MultiTenancy => write!(f, "Multi-Tenancy"),
            PremiumFeature::RBAC => write!(f, "RBAC"),
            PremiumFeature::SSO => write!(f, "SSO"),
            PremiumFeature::AuditLogging => write!(f, "Audit Logging"),
        }
    }
}

/// Decoded license information (must match velesdb-premium)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseInfo {
    /// License key
    pub key: String,
    /// License tier
    pub tier: LicenseTier,
    /// Organization name
    pub organization: String,
    /// Expiration timestamp (Unix epoch)
    pub expires_at: u64,
    /// Maximum number of instances (-1 = unlimited)
    pub max_instances: i32,
    /// Enabled premium features.
    ///
    /// Uses a lenient deserializer that silently skips unknown variants
    /// (e.g. `"HybridSearch"` from legacy license payloads).
    #[serde(deserialize_with = "deserialize_features_lenient")]
    pub features: Vec<PremiumFeature>,
}

/// Deserializes a `Vec<PremiumFeature>` while silently skipping unknown variants.
///
/// Legacy license payloads signed by GetAppSuite may contain variants that were
/// removed in #390 (`HybridSearch`, `AdvancedFiltering`, `GpuAcceleration`).
/// Rather than rejecting the entire payload, we filter out unrecognized strings.
fn deserialize_features_lenient<'de, D>(
    deserializer: D,
) -> std::result::Result<Vec<PremiumFeature>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw: Vec<serde_json::Value> = Vec::deserialize(deserializer)?;
    Ok(raw
        .into_iter()
        .filter_map(|v| serde_json::from_value::<PremiumFeature>(v).ok())
        .collect())
}

impl LicenseInfo {
    /// Checks if the license has expired
    pub fn is_expired(&self) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        now > self.expires_at
    }

    /// Checks if a feature is enabled
    #[allow(dead_code)] // Reason: public API for license validation (used in tests, consumed by velesdb-premium)
    pub fn has_feature(&self, feature: PremiumFeature) -> bool {
        self.features.contains(&feature)
    }

    /// Format expiration date as human-readable string
    pub fn expires_at_formatted(&self) -> String {
        use chrono::{DateTime, Utc};
        #[allow(clippy::cast_possible_wrap)]
        let timestamp = self.expires_at as i64;
        DateTime::<Utc>::from_timestamp(timestamp, 0).map_or_else(
            || "Unknown".to_string(),
            |dt| dt.format("%Y-%m-%d").to_string(),
        )
    }
}

/// Signed license format: `<base64_payload>.<base64_signature>`
#[derive(Debug, Clone)]
pub struct SignedLicense {
    /// The license payload (JSON encoded LicenseInfo)
    pub payload: Vec<u8>,
    /// The Ed25519 signature of the payload
    pub signature: Signature,
}

impl SignedLicense {
    /// Parses a signed license from the standard format
    /// Format: base64(payload).base64(signature)
    pub fn parse(license_string: &str) -> Result<Self> {
        let parts: Vec<&str> = license_string.split('.').collect();
        if parts.len() != 2 {
            anyhow::bail!("Invalid license format. Expected: <payload>.<signature>");
        }

        let payload = BASE64
            .decode(parts[0])
            .context("Failed to decode license payload (invalid base64)")?;

        let sig_bytes = BASE64
            .decode(parts[1])
            .context("Failed to decode license signature (invalid base64)")?;

        let sig_array: [u8; 64] = sig_bytes
            .try_into()
            .map_err(|_| anyhow::anyhow!("Invalid signature length (expected 64 bytes)"))?;

        let signature = Signature::from_bytes(&sig_array);

        Ok(Self { payload, signature })
    }

    /// Verifies the signature using a public key
    pub fn verify_with_key(&self, public_key_b64: &str) -> Result<()> {
        let key_bytes = BASE64
            .decode(public_key_b64)
            .context("Failed to decode public key (invalid base64)")?;

        // Handle both raw 32-byte keys and DER-encoded keys
        let raw_key = if key_bytes.len() == 32 {
            key_bytes
        } else if key_bytes.len() == 44 && key_bytes.starts_with(&[0x30, 0x2a]) {
            key_bytes[12..].to_vec()
        } else {
            anyhow::bail!("Invalid public key length (expected 32 or 44 bytes)");
        };

        let key_array: [u8; 32] = raw_key
            .try_into()
            .map_err(|_| anyhow::anyhow!("Invalid public key format"))?;

        let verifying_key =
            VerifyingKey::from_bytes(&key_array).context("Failed to create verifying key")?;

        verifying_key
            .verify(&self.payload, &self.signature)
            .map_err(|_| anyhow::anyhow!("Invalid signature - license may have been tampered with"))
    }

    /// Extracts the license info from the verified payload
    pub fn extract_info(&self) -> Result<LicenseInfo> {
        serde_json::from_slice(&self.payload)
            .context("Failed to parse license payload (invalid JSON)")
    }
}

/// Validates a signed license and returns the license info if valid
pub fn validate_license(license_string: &str, public_key_b64: &str) -> Result<LicenseInfo> {
    let signed = SignedLicense::parse(license_string)?;
    signed.verify_with_key(public_key_b64)?;
    let info = signed.extract_info()?;

    if info.is_expired() {
        anyhow::bail!("License has expired on {}", info.expires_at_formatted());
    }

    Ok(info)
}

/// Get the license config file path (~/.velesdb/license)
pub fn get_license_config_path() -> Result<PathBuf> {
    let home = dirs::home_dir().context("Could not determine home directory")?;
    let config_dir = home.join(".velesdb");
    fs::create_dir_all(&config_dir).context("Failed to create .velesdb config directory")?;
    Ok(config_dir.join("license"))
}

/// Save license key to config file
pub fn save_license_key(license_key: &str) -> Result<()> {
    let path = get_license_config_path()?;
    fs::write(&path, license_key)
        .with_context(|| format!("Failed to write license to {}", path.display()))?;
    Ok(())
}

/// Load license key from config file
pub fn load_license_key() -> Result<String> {
    let path = get_license_config_path()?;
    fs::read_to_string(&path)
        .with_context(|| format!("Failed to read license from {}", path.display()))
}

/// Display license information in a formatted way
pub fn display_license_info(info: &LicenseInfo) {
    println!("\n{}", "License Information".green().bold());
    println!("{}", "=".repeat(60).green());
    println!("  {} {}", "Key:".cyan(), info.key);
    println!("  {} {}", "Organization:".cyan(), info.organization.bold());
    println!("  {} {}", "Tier:".cyan(), info.tier.to_string().yellow());
    println!(
        "  {} {}",
        "Max Instances:".cyan(),
        if info.max_instances == -1 {
            "Unlimited".to_string()
        } else {
            info.max_instances.to_string()
        }
    );
    println!("  {} {}", "Expires:".cyan(), info.expires_at_formatted());

    if info.is_expired() {
        println!("  {} {}", "Status:".cyan(), "EXPIRED".red().bold());
    } else {
        println!("  {} {}", "Status:".cyan(), "VALID".green().bold());
    }

    println!("\n{}", "Enabled Features:".cyan().bold());
    for feature in &info.features {
        println!("  {} {}", "✓".green(), feature);
    }
    println!();
}

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

    #[test]
    fn test_license_tier_display() {
        assert_eq!(LicenseTier::Professional.to_string(), "Professional");
        assert_eq!(LicenseTier::Team.to_string(), "Team");
        assert_eq!(LicenseTier::Enterprise.to_string(), "Enterprise");
    }

    #[test]
    fn test_license_info_has_feature() {
        let info = LicenseInfo {
            key: "TEST-KEY".to_string(),
            tier: LicenseTier::Professional,
            organization: "Test Corp".to_string(),
            expires_at: u64::MAX,
            max_instances: 1,
            features: vec![PremiumFeature::Snapshots],
        };

        assert!(info.has_feature(PremiumFeature::Snapshots));
        assert!(!info.has_feature(PremiumFeature::MultiTenancy));
    }

    #[test]
    fn test_premium_feature_enum_only_contains_true_premium_variants() {
        // After #390: HybridSearch, AdvancedFiltering, GpuAcceleration are free
        // in open-source core and must NOT be in the PremiumFeature enum.
        // The remaining 6 variants are genuinely premium.
        let all_premium = [
            PremiumFeature::EncryptionAtRest,
            PremiumFeature::Snapshots,
            PremiumFeature::MultiTenancy,
            PremiumFeature::RBAC,
            PremiumFeature::SSO,
            PremiumFeature::AuditLogging,
        ];

        // Verify Display works for each remaining variant
        for feature in &all_premium {
            let display = feature.to_string();
            assert!(
                !display.is_empty(),
                "Display must be non-empty for {feature:?}"
            );
        }
    }

    #[test]
    fn test_premium_feature_display_values() {
        assert_eq!(
            PremiumFeature::EncryptionAtRest.to_string(),
            "Encryption at Rest"
        );
        assert_eq!(PremiumFeature::Snapshots.to_string(), "Snapshots & Backups");
        assert_eq!(PremiumFeature::MultiTenancy.to_string(), "Multi-Tenancy");
        assert_eq!(PremiumFeature::RBAC.to_string(), "RBAC");
        assert_eq!(PremiumFeature::SSO.to_string(), "SSO");
        assert_eq!(PremiumFeature::AuditLogging.to_string(), "Audit Logging");
    }

    #[test]
    fn test_premium_feature_serde_roundtrip() {
        let features = vec![
            PremiumFeature::EncryptionAtRest,
            PremiumFeature::Snapshots,
            PremiumFeature::RBAC,
        ];
        let json = serde_json::to_string(&features).unwrap();
        let deserialized: Vec<PremiumFeature> = serde_json::from_str(&json).unwrap();
        assert_eq!(features, deserialized);
    }

    #[test]
    fn test_legacy_license_with_removed_features_deserializes() {
        // Existing license payloads signed by GetAppSuite may contain
        // "HybridSearch", "AdvancedFiltering", or "GpuAcceleration".
        // These must be silently ignored (the features are now free).
        let legacy_json = r#"{
            "key": "LEGACY-KEY",
            "tier": "Professional",
            "organization": "Legacy Corp",
            "expires_at": 9999999999,
            "max_instances": 5,
            "features": ["HybridSearch", "Snapshots", "AdvancedFiltering", "GpuAcceleration", "RBAC"]
        }"#;
        let info: LicenseInfo = serde_json::from_str(legacy_json).unwrap();
        assert_eq!(
            info.features.len(),
            2,
            "Only Snapshots and RBAC are true premium"
        );
        assert!(info.has_feature(PremiumFeature::Snapshots));
        assert!(info.has_feature(PremiumFeature::RBAC));
    }

    #[test]
    fn test_license_info_is_expired() {
        let expired = LicenseInfo {
            key: "TEST-KEY".to_string(),
            tier: LicenseTier::Professional,
            organization: "Test Corp".to_string(),
            expires_at: 1_000_000, // Very old timestamp
            max_instances: 1,
            features: vec![],
        };

        assert!(expired.is_expired());

        let valid = LicenseInfo {
            key: "TEST-KEY".to_string(),
            tier: LicenseTier::Professional,
            organization: "Test Corp".to_string(),
            expires_at: u64::MAX,
            max_instances: 1,
            features: vec![],
        };

        assert!(!valid.is_expired());
    }

    #[test]
    fn test_signed_license_parse_invalid_format() {
        let result = SignedLicense::parse("invalid-format");
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid license format"));
    }

    #[test]
    fn test_signed_license_parse_invalid_base64() {
        let result = SignedLicense::parse("not-base64.also-not-base64");
        assert!(result.is_err());
    }
}