teaql-tool-core 0.1.2

Core types and error definitions for the TeaQL Tool ecosystem.
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
use std::collections::{HashMap, HashSet};

use crate::audit::{AuditConfig, AuditLevel, Module};

// ─── Whitelist ────────────────────────────────────────────────

/// The complete, fixed set of allowed TEAQL_ environment variable names.
/// Any TEAQL_ prefixed env var not in this list causes immediate process exit.
const ALLOWED_ENV_VARS: &[&str] = &[
    "TEAQL_AUDIT",
    "TEAQL_SQL",
    "TEAQL_SQL_TABLES",
    "TEAQL_TOOL",
    "TEAQL_TOOL_FOCUS",
    "TEAQL_SINK",
    "TEAQL_SCHEMA",
];

/// Allowed values for level-type env vars. Prefixed with underscore
/// to avoid collision with user-defined entity/table names.
const ALLOWED_LEVELS: &[&str] = &["_silent", "_summary", "_full"];

/// Allowed values for TEAQL_SINK.
const ALLOWED_SINKS: &[&str] = &["_stdout", "_file", "_both"];

/// Allowed values for TEAQL_SCHEMA.
const ALLOWED_SCHEMA_MODES: &[&str] = &["_verify", "_dryrun", "_execute"];

/// All valid module names for TEAQL_TOOL_FOCUS.
const ALLOWED_MODULES: &[(&str, Module)] = &[
    ("http", Module::Http),
    ("file", Module::File),
    ("cmd", Module::Cmd),
    ("email", Module::Email),
    ("kv", Module::Kv),
    ("crypto", Module::Crypto),
    ("jwt", Module::Jwt),
    ("time", Module::Time),
    ("id", Module::Id),
    ("text", Module::Text),
    ("decimal", Module::Decimal),
    ("money", Module::Money),
    ("json", Module::Json),
    ("regex", Module::Regex),
    ("codec", Module::Codec),
    ("list", Module::List),
    ("map", Module::Map),
    ("diff", Module::Diff),
    ("url", Module::Url),
    ("validate", Module::Validate),
    ("color", Module::Color),
    ("unit", Module::Unit),
    ("daterange", Module::DateRange),
    ("desensitize", Module::Desensitize),
    ("filter", Module::Filter),
    ("tree", Module::Tree),
    ("system", Module::System),
];

// ─── Output sink ──────────────────────────────────────────────

/// Where audit output is written. Controlled by TEAQL_SINK.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditSink {
    Stdout,
    File,
    Both,
}

impl Default for AuditSink {
    fn default() -> Self {
        AuditSink::Both
    }
}

/// Controls schema migration behavior at startup. Controlled by TEAQL_SCHEMA.
/// Default is `Verify` — the safest option for production.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchemaMode {
    /// Check that the database schema matches the model.
    /// If there is any mismatch, print the details and exit immediately.
    /// This is the DEFAULT — no env var needed for the safest behavior.
    Verify,

    /// Print the SQL statements that would be executed to bring the
    /// schema in sync, but do NOT execute them. For DBA review.
    DryRun,

    /// Actually execute schema changes (CREATE TABLE, ALTER TABLE ADD COLUMN,
    /// CREATE INDEX, seed data). Use in development and CI only.
    Execute,
}

impl Default for SchemaMode {
    fn default() -> Self {
        SchemaMode::Verify
    }
}

// ─── Env config result ────────────────────────────────────────

/// The fully resolved configuration parsed from environment variables.
/// Constructed by `AuditConfig::from_env()` or `AuditConfig::from_env_with_tables()`.
#[derive(Debug, Clone)]
pub struct EnvAuditConfig {
    /// Core audit config with module levels.
    pub config: AuditConfig,
    /// Global entity audit level (from TEAQL_AUDIT).
    pub entity_level: AuditLevel,
    /// Global SQL log level (from TEAQL_SQL).
    pub sql_level: AuditLevel,
    /// SQL table include filter (from TEAQL_SQL_TABLES). None = all tables.
    pub sql_tables: Option<HashSet<String>>,
    /// Output sink (from TEAQL_SINK).
    pub sink: AuditSink,
    /// Schema migration mode (from TEAQL_SCHEMA). Default: Verify.
    pub schema_mode: SchemaMode,
}

impl EnvAuditConfig {
    /// Check if SQL logging is active for a given table name.
    pub fn sql_active_for(&self, table: &str) -> bool {
        if self.sql_level == AuditLevel::Silent {
            return false;
        }
        match &self.sql_tables {
            Some(tables) => tables.contains(table),
            None => true, // No filter = all tables
        }
    }
}

// ─── Parsing ──────────────────────────────────────────────────

fn parse_level(value: &str, var_name: &str) -> AuditLevel {
    match value {
        "_silent" => AuditLevel::Silent,
        "_summary" => AuditLevel::Summary,
        "_full" => AuditLevel::Full,
        other => {
            eprintln!(
                "\nFATAL: Invalid value \"{}\" for environment variable \"{}\"\n\
                 Allowed values: {}\n\n\
                 Application refused to start.\n",
                other,
                var_name,
                ALLOWED_LEVELS.join(", "),
            );
            std::process::exit(1);
        }
    }
}

fn parse_sink(value: &str) -> AuditSink {
    match value {
        "_stdout" => AuditSink::Stdout,
        "_file" => AuditSink::File,
        "_both" => AuditSink::Both,
        other => {
            eprintln!(
                "\nFATAL: Invalid value \"{}\" for environment variable \"TEAQL_SINK\"\n\
                 Allowed values: {}\n\n\
                 Application refused to start.\n",
                other,
                ALLOWED_SINKS.join(", "),
            );
            std::process::exit(1);
        }
    }
}

fn parse_schema_mode(value: &str) -> SchemaMode {
    match value {
        "_verify" => SchemaMode::Verify,
        "_dryrun" => SchemaMode::DryRun,
        "_execute" => SchemaMode::Execute,
        other => {
            eprintln!(
                "\nFATAL: Invalid value \"{}\" for environment variable \"TEAQL_SCHEMA\"\n\
                 Allowed values: {}\n\n\
                 Application refused to start.\n",
                other,
                ALLOWED_SCHEMA_MODES.join(", "),
            );
            std::process::exit(1);
        }
    }
}

fn parse_module_list(value: &str) -> Vec<Module> {
    let module_map: HashMap<&str, Module> = ALLOWED_MODULES.iter().copied().collect();
    let available: Vec<&str> = ALLOWED_MODULES.iter().map(|(name, _)| *name).collect();

    value
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(|name| {
            *module_map.get(name).unwrap_or_else(|| {
                eprintln!(
                    "\nFATAL: Unknown module \"{}\" in TEAQL_TOOL_FOCUS\n\
                     Available modules: {}\n\n\
                     Application refused to start.\n",
                    name,
                    available.join(", "),
                );
                std::process::exit(1);
            })
        })
        .collect()
}

fn parse_table_list(value: &str, known_tables: &[&str]) -> HashSet<String> {
    let known_set: HashSet<&str> = known_tables.iter().copied().collect();
    value
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(|name| {
            if !known_set.contains(name) {
                eprintln!(
                    "\nFATAL: Unknown table \"{}\" in TEAQL_SQL_TABLES\n\
                     Available tables: {}\n\n\
                     Application refused to start.\n",
                    name,
                    known_tables.join(", "),
                );
                std::process::exit(1);
            }
            name.to_string()
        })
        .collect()
}

// ─── Whitelist enforcement ────────────────────────────────────

/// The set of TEAQL_ prefixes that belong to the audit config namespace.
/// Any env var starting with one of these prefixes must exactly match
/// an entry in ALLOWED_ENV_VARS, or the process exits.
const AUDIT_PREFIXES: &[&str] = &[
    "TEAQL_AUDIT",
    "TEAQL_SQL",
    "TEAQL_TOOL",
    "TEAQL_SINK",
    "TEAQL_SCHEMA",
];

/// Scan environment variables in the audit namespace.
/// If any matches an audit prefix but is not in the exact whitelist,
/// print an error and exit immediately.
/// Non-audit TEAQL_ vars (e.g. TEAQL_ENDPOINT_PREFIX) are ignored.
fn enforce_env_whitelist() {
    let allowed: HashSet<&str> = ALLOWED_ENV_VARS.iter().copied().collect();

    for (key, _) in std::env::vars() {
        let in_audit_namespace = AUDIT_PREFIXES.iter().any(|prefix| key.starts_with(prefix));
        if in_audit_namespace && !allowed.contains(key.as_str()) {
            // Try to suggest a close match
            let suggestion = ALLOWED_ENV_VARS
                .iter()
                .min_by_key(|v| levenshtein(&key, v))
                .unwrap();

            eprintln!(
                "\nFATAL: Unknown environment variable \"{}\"\n\
                 Did you mean \"{}\"?\n\n\
                 Allowed TEAQL audit variables:\n  {}\n\n\
                 Application refused to start.\n",
                key,
                suggestion,
                ALLOWED_ENV_VARS.join(", "),
            );
            std::process::exit(1);
        }
    }
}

/// Simple Levenshtein distance for typo suggestion.
fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let (m, n) = (a.len(), b.len());
    let mut dp = vec![vec![0usize; n + 1]; m + 1];
    for i in 0..=m {
        dp[i][0] = i;
    }
    for j in 0..=n {
        dp[0][j] = j;
    }
    for i in 1..=m {
        for j in 1..=n {
            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
            dp[i][j] = (dp[i - 1][j] + 1)
                .min(dp[i][j - 1] + 1)
                .min(dp[i - 1][j - 1] + cost);
        }
    }
    dp[m][n]
}

// ─── Public API ───────────────────────────────────────────────

/// Build an `EnvAuditConfig` from environment variables.
///
/// `known_tables` is the list of valid table names for this project,
/// typically provided by the generated code. Used to validate
/// TEAQL_SQL_TABLES values.
///
/// This function:
/// 1. Scans ALL env vars — panics if any unknown TEAQL_ var is found.
/// 2. Parses the 6 allowed env vars into a typed config.
/// 3. Validates all values against their respective whitelists.
///
/// If no TEAQL_ env vars are set, returns production defaults.
pub fn audit_config_from_env(known_tables: &[&str]) -> EnvAuditConfig {
    // Step 1: Reject unknown TEAQL_ env vars
    enforce_env_whitelist();

    // Step 2: Parse each env var (use defaults if not set)
    let entity_level = std::env::var("TEAQL_AUDIT")
        .map(|v| parse_level(&v, "TEAQL_AUDIT"))
        .unwrap_or(AuditLevel::Full);

    let sql_level = std::env::var("TEAQL_SQL")
        .map(|v| parse_level(&v, "TEAQL_SQL"))
        .unwrap_or(AuditLevel::Silent);

    let sql_tables: Option<HashSet<String>> = std::env::var("TEAQL_SQL_TABLES")
        .ok()
        .map(|v| parse_table_list(&v, known_tables));

    let tool_level = std::env::var("TEAQL_TOOL")
        .map(|v| parse_level(&v, "TEAQL_TOOL"))
        .unwrap_or(AuditLevel::Silent);

    let tool_focus: Option<Vec<Module>> = std::env::var("TEAQL_TOOL_FOCUS")
        .ok()
        .map(|v| parse_module_list(&v));

    let sink = std::env::var("TEAQL_SINK")
        .map(|v| parse_sink(&v))
        .unwrap_or(AuditSink::Both);

    let schema_mode = std::env::var("TEAQL_SCHEMA")
        .map(|v| parse_schema_mode(&v))
        .unwrap_or(SchemaMode::Verify);

    // Step 3: Build the AuditConfig
    let config = match &tool_focus {
        Some(focused) => {
            // Focus mode: listed modules get _full, rest get tool_level
            let mut cfg = AuditConfig::new(tool_level, tool_level);
            for m in focused {
                cfg = cfg.enable(*m, AuditLevel::Full);
            }
            cfg
        }
        None => {
            // No focus: all modules use tool_level
            AuditConfig::new(tool_level, tool_level)
        }
    };

    EnvAuditConfig {
        config,
        entity_level,
        sql_level,
        sql_tables,
        sink,
        schema_mode,
    }
}

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

    #[test]
    fn test_levenshtein() {
        assert_eq!(levenshtein("TEAQL_SQL", "TEAQL_SQL"), 0);
        assert_eq!(levenshtein("TEAQL_SQLL", "TEAQL_SQL"), 1);
        assert_eq!(levenshtein("TEAQL_AUDIT", "TEAQL_SQL"), 5);
    }

    #[test]
    fn test_parse_level() {
        assert_eq!(parse_level("_silent", "TEST"), AuditLevel::Silent);
        assert_eq!(parse_level("_summary", "TEST"), AuditLevel::Summary);
        assert_eq!(parse_level("_full", "TEST"), AuditLevel::Full);
    }

    #[test]
    fn test_parse_sink() {
        assert_eq!(parse_sink("_stdout"), AuditSink::Stdout);
        assert_eq!(parse_sink("_file"), AuditSink::File);
        assert_eq!(parse_sink("_both"), AuditSink::Both);
    }

    #[test]
    fn test_parse_schema_mode() {
        assert_eq!(parse_schema_mode("_verify"), SchemaMode::Verify);
        assert_eq!(parse_schema_mode("_dryrun"), SchemaMode::DryRun);
        assert_eq!(parse_schema_mode("_execute"), SchemaMode::Execute);
        assert_eq!(SchemaMode::default(), SchemaMode::Verify);
    }

    #[test]
    fn test_parse_module_list() {
        let modules = parse_module_list("http,money,crypto");
        assert_eq!(modules.len(), 3);
        assert_eq!(modules[0], Module::Http);
        assert_eq!(modules[1], Module::Money);
        assert_eq!(modules[2], Module::Crypto);
    }

    #[test]
    fn test_parse_table_list() {
        let tables = parse_table_list("task,task_status", &["task", "task_status", "task_execution_log"]);
        assert_eq!(tables.len(), 2);
        assert!(tables.contains("task"));
        assert!(tables.contains("task_status"));
    }

    #[test]
    fn test_sql_active_for() {
        let cfg = EnvAuditConfig {
            config: AuditConfig::production(),
            entity_level: AuditLevel::Full,
            sql_level: AuditLevel::Full,
            sql_tables: Some(["task".to_string()].into_iter().collect()),
            sink: AuditSink::Both,
            schema_mode: SchemaMode::Verify,
        };
        assert!(cfg.sql_active_for("task"));
        assert!(!cfg.sql_active_for("task_status"));

        // No filter = all tables active
        let cfg_all = EnvAuditConfig {
            config: AuditConfig::production(),
            entity_level: AuditLevel::Full,
            sql_level: AuditLevel::Full,
            sql_tables: None,
            sink: AuditSink::Both,
            schema_mode: SchemaMode::Verify,
        };
        assert!(cfg_all.sql_active_for("task"));
        assert!(cfg_all.sql_active_for("anything"));

        // Silent level = nothing active
        let cfg_silent = EnvAuditConfig {
            config: AuditConfig::production(),
            entity_level: AuditLevel::Full,
            sql_level: AuditLevel::Silent,
            sql_tables: None,
            sink: AuditSink::Both,
            schema_mode: SchemaMode::Verify,
        };
        assert!(!cfg_silent.sql_active_for("task"));
    }
}