earl 0.5.2

AI-safe CLI for AI agents
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use std::collections::HashSet;
#[cfg(feature = "bash")]
use std::path::{Component, Path};

use anyhow::{Result, bail};

use super::environments::validate_env_name;
#[cfg(feature = "bash")]
use super::schema::BashOperationTemplate;
#[cfg(feature = "graphql")]
use super::schema::GraphqlOperationTemplate;
#[cfg(feature = "grpc")]
use super::schema::GrpcOperationTemplate;
#[cfg(feature = "http")]
use super::schema::HttpOperationTemplate;
#[cfg(feature = "sql")]
use super::schema::SqlOperationTemplate;
#[allow(unused_imports)]
use super::schema::{
    ApiKeyLocation, AuthTemplate, BodyTemplate, CommandTemplate, MultipartPartTemplate,
    OperationTemplate, ParamSpec, TemplateFile, TransportTemplate,
};

pub fn validate_template_file(file: &TemplateFile) -> Result<()> {
    if file.version != 1 {
        bail!(
            "unsupported template version {} for provider {}",
            file.version,
            file.provider
        );
    }
    if file.provider.trim().is_empty() {
        bail!("template provider must not be empty");
    }
    if file.commands.is_empty() {
        bail!("provider {} defines no commands", file.provider);
    }

    // Build set of defined environment names for cross-reference checks
    let defined_env_names: std::collections::HashSet<String> = file
        .environments
        .as_ref()
        .map(|e| e.environments.keys().cloned().collect())
        .unwrap_or_default();

    if let Some(envs) = &file.environments {
        // environments.default must reference a defined environment
        if let Some(default_name) = &envs.default {
            validate_env_name(default_name).map_err(|e| {
                anyhow::anyhow!("provider `{}` environments.default: {e}", file.provider)
            })?;
            if !envs.environments.contains_key(default_name.as_str()) {
                bail!(
                    "provider `{}` environments.default is `{default_name}` but that environment is not defined; \
                     available: {}",
                    file.provider,
                    envs.environments
                        .keys()
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(", ")
                );
            }
        }
        // Validate format of all declared environment names
        for env_key in envs.environments.keys() {
            validate_env_name(env_key).map_err(|e| {
                anyhow::anyhow!(
                    "provider `{}` environments block contains invalid name `{env_key}`: {e}",
                    file.provider
                )
            })?;
        }
        // All secrets referenced in vars values must be declared in environments.secrets
        let declared_secrets: std::collections::HashSet<&str> =
            envs.secrets.iter().map(String::as_str).collect();
        for (env_name, vars) in &envs.environments {
            for (var_name, value) in vars {
                for secret_ref in extract_secret_refs(value) {
                    if !declared_secrets.contains(secret_ref) {
                        bail!(
                            "provider `{}` environments.{env_name}.{var_name} references secret \
                             `{secret_ref}` which is not declared in environments.secrets",
                            file.provider
                        );
                    }
                }
            }
        }
    }

    for (name, cmd) in &file.commands {
        for (env_name, override_) in &cmd.environment_overrides {
            // Environment override names must follow the same format rules as CLI --env values
            validate_env_name(env_name).map_err(|e| {
                anyhow::anyhow!(
                    "command `{name}` has invalid environment override name `{env_name}`: {e}"
                )
            })?;
            // Per-command environment names must be defined in the provider environments block
            // when one exists. When there is no provider-level environments block the cross-
            // reference check is skipped: per-command overrides are valid without a global
            // block (they activate via `--env <name>` and `vars.*` will be empty). Template
            // authors relying only on operation overrides without vars injection may omit the
            // global block intentionally.
            if !defined_env_names.is_empty() && !defined_env_names.contains(env_name) {
                bail!(
                    "command `{name}` has environment override for `{env_name}` \
                     which is not defined in the provider environments block; \
                     defined: {}",
                    defined_env_names
                        .iter()
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(", ")
                );
            }
            // Protocol switching requires annotation
            if override_.operation.protocol() != cmd.operation.protocol()
                && !cmd.annotations.allow_environment_protocol_switching
            {
                bail!(
                    "command `{name}` environment `{env_name}` switches protocol \
                     from {:?} to {:?}; add `annotations {{ allow_environment_protocol_switching = true }}` \
                     to opt in",
                    cmd.operation.protocol(),
                    override_.operation.protocol()
                );
            }
            // Validate the override operation itself
            validate_operation(name, &override_.operation, &cmd.annotations.secrets)?;
            // Validate override result if provided
            if let Some(result) = &override_.result
                && result.output.trim().is_empty()
            {
                bail!("command `{name}` environment override `{env_name}` has empty result.output");
            }
        }
        validate_command(name, cmd)?;
    }

    Ok(())
}

/// Extracts `secrets.X.Y` references from Jinja `{{ secrets.X.Y }}` expressions.
fn extract_secret_refs(value: &str) -> Vec<&str> {
    let mut refs = Vec::new();
    let mut remaining = value;
    while let Some(start) = remaining.find("{{") {
        remaining = &remaining[start + 2..];
        let end = match remaining.find("}}") {
            Some(e) => e,
            None => break,
        };
        let expr = remaining[..end].trim();
        if let Some(key) = expr.strip_prefix("secrets.") {
            // Take everything up to the first whitespace or pipe
            let key = key
                .split(|c: char| c.is_whitespace() || c == '|')
                .next()
                .unwrap_or(key);
            let key = key.trim_end_matches('.');
            refs.push(key);
        }
        remaining = &remaining[end + 2..];
    }
    refs
}

fn validate_command(command_name: &str, cmd: &CommandTemplate) -> Result<()> {
    if cmd.title.trim().is_empty() {
        bail!("command {command_name} has empty title");
    }

    if cmd.summary.trim().is_empty() {
        bail!("command {command_name} has empty summary");
    }

    if cmd.description.trim().is_empty() {
        bail!("command {command_name} has empty description");
    }

    validate_operation(command_name, &cmd.operation, &cmd.annotations.secrets)?;

    if cmd.result.output.trim().is_empty() {
        bail!("command {command_name} has empty result.output");
    }

    validate_params(command_name, &cmd.params)?;
    validate_template_args(command_name, cmd)?;

    Ok(())
}

fn validate_params(command_name: &str, params: &[ParamSpec]) -> Result<()> {
    let mut seen = HashSet::new();
    for param in params {
        if param.name.trim().is_empty() {
            bail!("command {command_name} has parameter with empty name");
        }
        if !seen.insert(&param.name) {
            bail!(
                "command {command_name} has duplicate parameter `{}`",
                param.name
            );
        }
    }
    Ok(())
}

fn validate_operation(
    command_name: &str,
    operation: &OperationTemplate,
    allowed_secrets: &[String],
) -> Result<()> {
    #[allow(unreachable_patterns)]
    match operation {
        #[cfg(feature = "http")]
        OperationTemplate::Http(op) => validate_http_operation(command_name, op, allowed_secrets),
        #[cfg(feature = "graphql")]
        OperationTemplate::Graphql(op) => {
            validate_graphql_operation(command_name, op, allowed_secrets)
        }
        #[cfg(feature = "grpc")]
        OperationTemplate::Grpc(op) => validate_grpc_operation(command_name, op, allowed_secrets),
        #[cfg(feature = "bash")]
        OperationTemplate::Bash(op) => validate_bash_operation(command_name, op),
        #[cfg(feature = "sql")]
        OperationTemplate::Sql(op) => validate_sql_operation(command_name, op, allowed_secrets),
        #[cfg(feature = "browser")]
        OperationTemplate::Browser(_) => Ok(()),
        _ => bail!("unsupported protocol (feature not enabled)"),
    }
}

#[cfg(feature = "http")]
fn validate_http_operation(
    command_name: &str,
    operation: &HttpOperationTemplate,
    allowed_secrets: &[String],
) -> Result<()> {
    if operation.url.trim().is_empty() {
        bail!("command {command_name} has empty operation.url");
    }
    if operation.method.trim().is_empty() {
        bail!("command {command_name} has empty operation.method");
    }

    if let Some(auth) = &operation.auth {
        validate_auth(command_name, auth, allowed_secrets)?;
    }
    if let Some(body) = &operation.body {
        validate_body(command_name, body)?;
    }
    validate_transport(command_name, operation.transport.as_ref())?;

    Ok(())
}

#[cfg(feature = "graphql")]
fn validate_graphql_operation(
    command_name: &str,
    operation: &GraphqlOperationTemplate,
    allowed_secrets: &[String],
) -> Result<()> {
    if operation.url.trim().is_empty() {
        bail!("command {command_name} has empty operation.url");
    }
    if operation.graphql.query.trim().is_empty() {
        bail!("command {command_name} has empty operation.graphql.query");
    }
    if !operation.method.trim().is_empty() && !operation.method.eq_ignore_ascii_case("POST") {
        bail!("command {command_name} graphql operation.method must be POST when provided");
    }

    if let Some(auth) = &operation.auth {
        validate_auth(command_name, auth, allowed_secrets)?;
    }
    validate_transport(command_name, operation.transport.as_ref())?;

    Ok(())
}

#[cfg(feature = "grpc")]
fn validate_grpc_operation(
    command_name: &str,
    operation: &GrpcOperationTemplate,
    allowed_secrets: &[String],
) -> Result<()> {
    if operation.url.trim().is_empty() {
        bail!("command {command_name} has empty operation.url");
    }
    if operation.grpc.service.trim().is_empty() {
        bail!("command {command_name} has empty operation.grpc.service");
    }
    if operation.grpc.method.trim().is_empty() {
        bail!("command {command_name} has empty operation.grpc.method");
    }
    if let Some(path) = &operation.grpc.descriptor_set_file
        && path.trim().is_empty()
    {
        bail!("command {command_name} operation.grpc.descriptor_set_file must not be empty");
    }
    if let Some(body) = &operation.grpc.body
        && !body.is_object()
        && !body.is_array()
    {
        bail!(
            "command {command_name} operation.grpc.body must be a JSON object (unary/server-streaming) or array (client-streaming)"
        );
    }

    if let Some(auth) = &operation.auth {
        if let AuthTemplate::ApiKey { location, .. } = auth
            && !matches!(location, ApiKeyLocation::Header)
        {
            bail!("command {command_name} grpc auth api_key location must be `header`");
        }
        validate_auth(command_name, auth, allowed_secrets)?;
    }
    if let Some(transport) = operation.transport.as_ref() {
        if transport.proxy_profile.is_some() {
            bail!("command {command_name} grpc transport.proxy_profile is not supported");
        }
        if transport
            .tls
            .as_ref()
            .and_then(|tls| tls.min_version.as_ref())
            .is_some()
        {
            bail!("command {command_name} grpc transport.tls.min_version is not supported");
        }
    }
    validate_transport(command_name, operation.transport.as_ref())?;

    Ok(())
}

fn validate_auth(
    command_name: &str,
    auth: &AuthTemplate,
    allowed_secrets: &[String],
) -> Result<()> {
    let ensure_secret = |secret: &String| -> Result<()> {
        if !allowed_secrets.iter().any(|s| s == secret) {
            bail!(
                "command {command_name} auth secret `{secret}` is not declared in annotations.secrets"
            );
        }
        Ok(())
    };

    match auth {
        AuthTemplate::None => {}
        AuthTemplate::ApiKey { secret, .. } => ensure_secret(secret)?,
        AuthTemplate::Bearer { secret } => ensure_secret(secret)?,
        AuthTemplate::Basic {
            password_secret, ..
        } => ensure_secret(password_secret)?,
        AuthTemplate::OAuth2Profile { .. } => {}
    }

    Ok(())
}

fn validate_body(command_name: &str, body: &BodyTemplate) -> Result<()> {
    match body {
        BodyTemplate::Multipart { parts } => {
            if parts.is_empty() {
                bail!("command {command_name} multipart body must include at least one part");
            }
            for part in parts {
                validate_part(command_name, part)?;
            }
        }
        BodyTemplate::FileStream { path, .. } => {
            if path.trim().is_empty() {
                bail!("command {command_name} file_stream body path must not be empty");
            }
        }
        _ => {}
    }
    Ok(())
}

fn validate_part(command_name: &str, part: &MultipartPartTemplate) -> Result<()> {
    let mut count = 0;
    if part.value.is_some() {
        count += 1;
    }
    if part.bytes_base64.is_some() {
        count += 1;
    }
    if part.file_path.is_some() {
        count += 1;
    }
    if count != 1 {
        bail!(
            "command {command_name} multipart part `{}` must specify exactly one of value, bytes_base64, file_path",
            part.name
        );
    }
    Ok(())
}

fn validate_transport(command_name: &str, transport: Option<&TransportTemplate>) -> Result<()> {
    let Some(transport) = transport else {
        return Ok(());
    };

    if let Some(timeout_ms) = transport.timeout_ms
        && timeout_ms == 0
    {
        bail!("command {command_name} transport.timeout_ms must be greater than 0");
    }

    if let Some(max_response_bytes) = transport.max_response_bytes
        && max_response_bytes == 0
    {
        bail!("command {command_name} transport.max_response_bytes must be greater than 0");
    }

    if let Some(proxy_profile) = transport.proxy_profile.as_ref()
        && proxy_profile.trim().is_empty()
    {
        bail!("command {command_name} transport.proxy_profile must not be empty");
    }

    if let Some(tls) = transport.tls.as_ref()
        && let Some(min_version) = tls.min_version.as_ref()
    {
        let min_version = min_version.trim();
        if !min_version.is_empty() && !matches!(min_version, "1.0" | "1.1" | "1.2" | "1.3") {
            bail!(
                "command {command_name} has unsupported transport.tls.min_version `{min_version}`"
            );
        }
    }

    Ok(())
}

// ── Bash validation ──────────────────────────────────────

#[cfg(feature = "bash")]
fn validate_bash_operation(command_name: &str, operation: &BashOperationTemplate) -> Result<()> {
    if operation.bash.script.trim().is_empty() {
        bail!("command {command_name} has empty operation.bash.script");
    }

    if let Some(sandbox) = &operation.bash.sandbox
        && let Some(writable_paths) = &sandbox.writable_paths
    {
        for path in writable_paths {
            if path.starts_with('/') || path.starts_with('\\') {
                bail!(
                    "command {command_name} operation.bash.sandbox.writable_paths contains absolute path `{path}`"
                );
            }
            if Path::new(path)
                .components()
                .any(|c| matches!(c, Component::ParentDir))
            {
                bail!(
                    "command {command_name} operation.bash.sandbox.writable_paths contains `..` in path `{path}`"
                );
            }
        }
    }

    validate_transport(command_name, operation.transport.as_ref())
}

// ── Template args validation ──────────────────────────────────────────────────

/// Check that every `args.IDENT` reference in a command's template strings
/// corresponds to a declared parameter. Catches typos at load time.
fn validate_template_args(command_name: &str, cmd: &CommandTemplate) -> Result<()> {
    let declared: HashSet<&str> = cmd.params.iter().map(|p| p.name.as_str()).collect();

    let mut strings: Vec<String> = Vec::new();
    collect_operation_strings(&cmd.operation, &mut strings);
    strings.push(cmd.result.output.clone());
    for env_override in cmd.environment_overrides.values() {
        collect_operation_strings(&env_override.operation, &mut strings);
        if let Some(result) = &env_override.result {
            strings.push(result.output.clone());
        }
    }

    for s in &strings {
        for arg_ref in extract_args_refs(s) {
            if !declared.contains(arg_ref) {
                bail!(
                    "command {command_name} references undeclared param `args.{arg_ref}` in template"
                );
            }
        }
    }

    Ok(())
}

/// Extract all `IDENT` names following `args.` in a template string.
///
/// Known limitations (text scan, not a Jinja AST parse):
/// - False positives: `result.args.foo` or `env.args.key` match `args.foo`/`args.key`
///   because the scanner uses a plain substring match on `"args."`.
/// - False negatives: references inside Jinja comments (`{# args.x #}`) are
///   matched as if live; subscript-style `args["foo"]` access is invisible.
/// - Map keys in query/header/body objects are not scanned (only values are).
///
/// Good enough for catching typos in the common case.
fn extract_args_refs(s: &str) -> Vec<&str> {
    let mut refs = Vec::new();
    let mut remaining = s;
    while let Some(pos) = remaining.find("args.") {
        let after = &remaining[pos + 5..];
        let end = after
            .find(|c: char| !c.is_alphanumeric() && c != '_')
            .unwrap_or(after.len());
        if end > 0 {
            refs.push(&after[..end]);
        }
        // Advance past "args." plus the identifier chars consumed, or past the
        // non-identifier character that immediately followed "args." Use the
        // character's actual byte length to stay on valid UTF-8 boundaries.
        let skip = if end > 0 {
            end
        } else {
            after.chars().next().map(|c| c.len_utf8()).unwrap_or(0)
        };
        remaining = &remaining[pos + 5 + skip..];
    }
    refs
}

/// Recursively collect all string leaves from a JSON value.
fn collect_value_strings(value: &serde_json::Value, out: &mut Vec<String>) {
    match value {
        serde_json::Value::String(s) => out.push(s.clone()),
        serde_json::Value::Array(arr) => arr.iter().for_each(|v| collect_value_strings(v, out)),
        serde_json::Value::Object(obj) => obj.values().for_each(|v| collect_value_strings(v, out)),
        _ => {}
    }
}

/// Collect all template strings from a command's operation.
#[allow(unused_variables)]
fn collect_operation_strings(operation: &OperationTemplate, out: &mut Vec<String>) {
    match operation {
        #[cfg(feature = "http")]
        OperationTemplate::Http(op) => {
            out.push(op.url.clone());
            if let Some(p) = &op.path {
                out.push(p.clone());
            }
            if let Some(q) = &op.query {
                q.values().for_each(|v| collect_value_strings(v, out));
            }
            if let Some(h) = &op.headers {
                h.values().for_each(|v| collect_value_strings(v, out));
            }
            if let Some(c) = &op.cookies {
                c.values().for_each(|v| collect_value_strings(v, out));
            }
            if let Some(body) = &op.body {
                collect_body_strings(body, out);
            }
        }
        #[cfg(feature = "graphql")]
        OperationTemplate::Graphql(op) => {
            out.push(op.url.clone());
            if let Some(p) = &op.path {
                out.push(p.clone());
            }
            if let Some(q) = &op.query {
                q.values().for_each(|v| collect_value_strings(v, out));
            }
            if let Some(h) = &op.headers {
                h.values().for_each(|v| collect_value_strings(v, out));
            }
            if let Some(c) = &op.cookies {
                c.values().for_each(|v| collect_value_strings(v, out));
            }
            out.push(op.graphql.query.clone());
            if let Some(op_name) = &op.graphql.operation_name {
                out.push(op_name.clone());
            }
            if let Some(vars) = &op.graphql.variables {
                collect_value_strings(vars, out);
            }
        }
        #[cfg(feature = "grpc")]
        OperationTemplate::Grpc(op) => {
            out.push(op.url.clone());
            if let Some(h) = &op.headers {
                h.values().for_each(|v| collect_value_strings(v, out));
            }
            out.push(op.grpc.service.clone());
            out.push(op.grpc.method.clone());
            if let Some(body) = &op.grpc.body {
                collect_value_strings(body, out);
            }
            if let Some(dsf) = &op.grpc.descriptor_set_file {
                out.push(dsf.clone());
            }
        }
        #[cfg(feature = "bash")]
        OperationTemplate::Bash(op) => {
            out.push(op.bash.script.clone());
            if let Some(env) = &op.bash.env {
                env.values().for_each(|v| collect_value_strings(v, out));
            }
            if let Some(cwd) = &op.bash.cwd {
                out.push(cwd.clone());
            }
        }
        #[cfg(feature = "sql")]
        OperationTemplate::Sql(op) => {
            // sql.query is validated to not contain Jinja — skip it
            if let Some(params) = &op.sql.params {
                params.iter().for_each(|v| collect_value_strings(v, out));
            }
        }
        #[allow(unreachable_patterns)]
        _ => {}
    }
}

fn collect_body_strings(body: &BodyTemplate, out: &mut Vec<String>) {
    match body {
        BodyTemplate::None => {}
        BodyTemplate::Json { value } => collect_value_strings(value, out),
        BodyTemplate::FormUrlencoded { fields } => {
            fields.values().for_each(|v| collect_value_strings(v, out));
        }
        BodyTemplate::Multipart { parts } => {
            for part in parts {
                // Note: part.name (non-optional) is not scanned — multipart
                // part names are static identifiers in practice ("file", etc.)
                // and unlikely to contain args.* references.
                if let Some(v) = &part.value {
                    out.push(v.clone());
                }
                if let Some(v) = &part.bytes_base64 {
                    out.push(v.clone());
                }
                if let Some(v) = &part.file_path {
                    out.push(v.clone());
                }
                if let Some(v) = &part.filename {
                    out.push(v.clone());
                }
            }
        }
        BodyTemplate::RawText { value, .. } => out.push(value.clone()),
        BodyTemplate::RawBytesBase64 { value, .. } => out.push(value.clone()),
        BodyTemplate::FileStream { path, .. } => out.push(path.clone()),
    }
}

// ── SQL validation ───────────────────────────────────────

#[cfg(feature = "sql")]
fn validate_sql_operation(
    command_name: &str,
    operation: &SqlOperationTemplate,
    allowed_secrets: &[String],
) -> Result<()> {
    if operation.sql.query.trim().is_empty() {
        bail!("command {command_name} has empty operation.sql.query");
    }

    if operation.sql.query.contains("{{") || operation.sql.query.contains("}}") {
        bail!(
            "command {command_name} operation.sql.query must not contain Jinja2 template expressions"
        );
    }

    if operation.sql.connection_secret.trim().is_empty() {
        bail!("command {command_name} has empty operation.sql.connection_secret");
    }

    if !allowed_secrets
        .iter()
        .any(|s| s == &operation.sql.connection_secret)
    {
        bail!(
            "command {command_name} operation.sql.connection_secret `{}` is not declared in annotations.secrets",
            operation.sql.connection_secret
        );
    }

    validate_transport(command_name, operation.transport.as_ref())
}