greentic-operator 0.4.43

Greentic operator CLI for local dev and demo orchestration.
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
//! Persist config and secrets from QA apply-answers output.
//!
//! After a provider's `apply-answers` op returns a config object, this module:
//! - Extracts secret fields (identified by `FormSpec.questions[].secret == true`)
//!   and writes them to the dev secrets store.
//! - Writes remaining (non-secret) fields to the provider config envelope.

use std::path::Path;

use anyhow::Result;
use greentic_secrets_lib::{
    ApplyOptions, DevStore, SecretFormat, SeedDoc, SeedEntry, SeedValue, apply_seed,
};
use qa_spec::FormSpec;
use serde_json::{Map as JsonMap, Value};

use crate::secrets_gate::canonical_secret_uri;
use crate::secrets_setup::resolve_env;

/// Extract secret fields from the QA config output and write them to the dev store.
///
/// Returns a list of secret keys that were persisted.
pub async fn persist_qa_secrets(
    store: &DevStore,
    env: &str,
    tenant: &str,
    team: Option<&str>,
    provider_id: &str,
    config: &Value,
    form_spec: &FormSpec,
) -> Result<Vec<String>> {
    // Collect all question IDs — WASM components read both secret and non-secret
    // config values via the secrets API, so we must persist everything.
    let all_question_ids: Vec<&str> = form_spec.questions.iter().map(|q| q.id.as_str()).collect();

    if all_question_ids.is_empty() {
        return Ok(vec![]);
    }

    let Some(config_map) = config.as_object() else {
        return Ok(vec![]);
    };

    let mut entries = Vec::new();
    let mut saved_keys = Vec::new();

    for &key in &all_question_ids {
        if let Some(value) = config_map.get(key) {
            let text = match value {
                Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            if text.is_empty() || text == "null" {
                continue;
            }
            let uri = canonical_secret_uri(env, tenant, team, provider_id, key);
            entries.push(SeedEntry {
                uri,
                format: SecretFormat::Text,
                value: SeedValue::Text { text },
                description: Some(format!("from QA setup for {provider_id}")),
            });
            saved_keys.push(key.to_string());
        }
    }

    if entries.is_empty() {
        return Ok(vec![]);
    }

    let report = apply_seed(store, &SeedDoc { entries }, ApplyOptions::default()).await;

    if !report.failed.is_empty() {
        return Err(anyhow::anyhow!(
            "failed to persist {} secret(s): {:?}",
            report.failed.len(),
            report.failed
        ));
    }

    Ok(saved_keys)
}

/// Write non-secret config fields to the provider config envelope.
///
/// Filters out secret fields (identified by the FormSpec) before writing.
pub fn persist_qa_config(
    providers_root: &Path,
    provider_id: &str,
    config: &Value,
    pack_path: &Path,
    form_spec: &FormSpec,
    backup: bool,
) -> Result<()> {
    let secret_ids: Vec<&str> = form_spec
        .questions
        .iter()
        .filter(|q| q.secret)
        .map(|q| q.id.as_str())
        .collect();

    let filtered_config = if secret_ids.is_empty() {
        config.clone()
    } else {
        filter_secrets(config, &secret_ids)
    };

    crate::provider_config_envelope::write_provider_config_envelope(
        providers_root,
        provider_id,
        "qa-setup",
        &filtered_config,
        pack_path,
        backup,
    )?;

    Ok(())
}

/// Remove secret fields from a config object.
fn filter_secrets(config: &Value, secret_ids: &[&str]) -> Value {
    let Some(map) = config.as_object() else {
        return config.clone();
    };
    let filtered: JsonMap<String, Value> = map
        .iter()
        .filter(|(key, _)| !secret_ids.contains(&key.as_str()))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    Value::Object(filtered)
}

/// Persist all config values as secrets without requiring a FormSpec.
///
/// This is used by `demo start --setup-input` where the QA form spec may not
/// be available but WASM components still read config values via the secrets API.
///
/// Also reads the pack's `secret-requirements.json` (if a `pack_path` is
/// provided) and seeds aliases so that WASM components that look up secrets by
/// their canonical requirement key (e.g. `WEBEX_BOT_TOKEN` → `webex_bot_token`)
/// can find the value even though the answers file uses a shorter key
/// (e.g. `bot_token`).
pub async fn persist_all_config_as_secrets(
    bundle_root: &Path,
    env: &str,
    tenant: &str,
    team: Option<&str>,
    provider_id: &str,
    config: &Value,
    pack_path: Option<&Path>,
) -> Result<Vec<String>> {
    let Some(config_map) = config.as_object() else {
        return Ok(vec![]);
    };
    if config_map.is_empty() {
        return Ok(vec![]);
    }

    let store_path = crate::dev_store_path::ensure_path(bundle_root)?;
    let store = DevStore::with_path(&store_path).map_err(|err| {
        anyhow::anyhow!(
            "failed to open dev secrets store {}: {err}",
            store_path.display()
        )
    })?;

    let mut entries = Vec::new();
    let mut saved_keys = Vec::new();

    for (key, value) in config_map {
        let text = match value {
            Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        if text.is_empty() || text == "null" {
            continue;
        }
        let uri = canonical_secret_uri(env, tenant, team, provider_id, key);
        entries.push(SeedEntry {
            uri,
            format: SecretFormat::Text,
            value: SeedValue::Text { text },
            description: Some(format!("from setup-input for {provider_id}")),
        });
        saved_keys.push(key.to_string());
    }

    // Seed aliases from secret-requirements.json so WASM components can find
    // secrets by their canonical requirement key (e.g. WEBEX_BOT_TOKEN →
    // webex_bot_token) even when the answers file uses a shorter key (bot_token).
    if let Some(pp) = pack_path {
        seed_secret_requirement_aliases(
            &mut entries,
            config_map,
            env,
            tenant,
            team,
            provider_id,
            pp,
        );
    }

    if entries.is_empty() {
        return Ok(vec![]);
    }

    let report = apply_seed(&store, &SeedDoc { entries }, ApplyOptions::default()).await;

    if !report.failed.is_empty() {
        return Err(anyhow::anyhow!(
            "failed to persist {} secret(s): {:?}",
            report.failed.len(),
            report.failed
        ));
    }

    Ok(saved_keys)
}

/// Read `assets/secret-requirements.json` from a pack and seed alias entries
/// for any requirement key that differs from the answers key after
/// canonicalization.
fn seed_secret_requirement_aliases(
    entries: &mut Vec<SeedEntry>,
    config_map: &JsonMap<String, Value>,
    env: &str,
    tenant: &str,
    team: Option<&str>,
    provider_id: &str,
    pack_path: &Path,
) {
    let reqs = match read_secret_requirements(pack_path) {
        Ok(r) => r,
        Err(_) => return,
    };
    let normalize = crate::secret_name::canonical_secret_name;
    let existing_keys: std::collections::HashSet<String> = entries
        .iter()
        .filter_map(|e| e.uri.rsplit('/').next().map(String::from))
        .collect();

    for req in &reqs {
        let canonical_req_key = normalize(&req.key);
        if existing_keys.contains(&canonical_req_key) {
            continue;
        }
        // Try to find a matching value in config_map by checking if the
        // requirement key ends with the config key (e.g. WEBEX_BOT_TOKEN
        // matches bot_token, SLACK_BOT_TOKEN matches bot_token).
        let matched_value = config_map.iter().find_map(|(cfg_key, cfg_val)| {
            let norm_cfg = normalize(cfg_key);
            if canonical_req_key.ends_with(&norm_cfg) {
                let text = match cfg_val {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                if text.is_empty() || text == "null" {
                    None
                } else {
                    Some(text)
                }
            } else {
                None
            }
        });
        if let Some(text) = matched_value {
            let uri = canonical_secret_uri(env, tenant, team, provider_id, &canonical_req_key);
            entries.push(SeedEntry {
                uri,
                format: SecretFormat::Text,
                value: SeedValue::Text { text },
                description: Some(format!("alias from {} for {provider_id}", req.key)),
            });
        }
    }
}

/// Minimal representation of a secret-requirements.json entry.
#[derive(serde::Deserialize)]
struct SecretRequirement {
    key: String,
}

fn read_secret_requirements(pack_path: &Path) -> Result<Vec<SecretRequirement>> {
    let file = std::fs::File::open(pack_path)?;
    let mut archive = zip::ZipArchive::new(file)?;
    let entry = archive.by_name("assets/secret-requirements.json")?;
    let reqs: Vec<SecretRequirement> = serde_json::from_reader(entry)?;
    Ok(reqs)
}

/// Convenience function to persist both secrets and config from QA results.
///
/// Creates a `DevStore` from the bundle root and persists both.
#[allow(clippy::too_many_arguments)]
pub async fn persist_qa_results(
    bundle_root: &Path,
    providers_root: &Path,
    tenant: &str,
    team: Option<&str>,
    provider_id: &str,
    config: &Value,
    pack_path: &Path,
    form_spec: &FormSpec,
    backup: bool,
) -> Result<(Vec<String>, bool)> {
    let env = resolve_env(None);
    let store_path = crate::dev_store_path::ensure_path(bundle_root)?;
    let store = DevStore::with_path(&store_path).map_err(|err| {
        anyhow::anyhow!(
            "failed to open dev secrets store {}: {err}",
            store_path.display()
        )
    })?;

    let saved_secrets =
        persist_qa_secrets(&store, &env, tenant, team, provider_id, config, form_spec).await?;

    let config_written = if config.as_object().is_some_and(|m| !m.is_empty()) {
        persist_qa_config(
            providers_root,
            provider_id,
            config,
            pack_path,
            form_spec,
            backup,
        )?;
        true
    } else {
        false
    };

    Ok((saved_secrets, config_written))
}

/// OAuth authorization stub.
///
/// Prints the authorization URL and returns `None`. This is a placeholder for
/// future integration with `greentic-oauth` for providers that require OAuth
/// (e.g., Teams, Slack with OAuth scopes).
pub fn oauth_authorize_stub(provider_id: &str, auth_url: Option<&str>) -> Option<String> {
    if let Some(url) = auth_url {
        println!("[oauth] Authorize {provider_id} at: {url}");
        println!("[oauth] After authorizing, re-run setup to complete configuration.");
    } else {
        println!("[oauth] Provider {provider_id} requires OAuth authorization.");
        println!("[oauth] OAuth integration is not yet implemented.");
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use qa_spec::{QuestionSpec, QuestionType};
    use serde_json::json;

    fn make_form_spec(questions: Vec<QuestionSpec>) -> FormSpec {
        FormSpec {
            id: "test".into(),
            title: "Test".into(),
            version: "1.0.0".into(),
            description: None,
            presentation: None,
            progress_policy: None,
            secrets_policy: None,
            store: vec![],
            validations: vec![],
            includes: vec![],
            questions,
        }
    }

    fn question(id: &str, secret: bool) -> QuestionSpec {
        QuestionSpec {
            id: id.into(),
            kind: QuestionType::String,
            title: id.into(),
            title_i18n: None,
            description: None,
            description_i18n: None,
            required: false,
            choices: None,
            default_value: None,
            secret,
            visible_if: None,
            constraint: None,
            list: None,
            computed: None,
            policy: Default::default(),
            computed_overridable: false,
        }
    }

    #[test]
    fn filters_out_secret_fields() {
        let config = json!({
            "enabled": true,
            "bot_token": "secret123",
            "public_url": "https://example.com"
        });
        let secret_ids = vec!["bot_token"];
        let filtered = filter_secrets(&config, &secret_ids);
        assert!(filtered.get("enabled").is_some());
        assert!(filtered.get("public_url").is_some());
        assert!(filtered.get("bot_token").is_none());
    }

    #[test]
    fn no_secrets_returns_full_config() {
        let config = json!({"enabled": true, "url": "https://example.com"});
        let filtered = filter_secrets(&config, &[]);
        assert_eq!(filtered, config);
    }

    #[test]
    fn identifies_secret_questions() {
        let spec = make_form_spec(vec![
            question("enabled", false),
            question("bot_token", true),
            question("api_secret", true),
            question("url", false),
        ]);
        let secret_ids: Vec<&str> = spec
            .questions
            .iter()
            .filter(|q| q.secret)
            .map(|q| q.id.as_str())
            .collect();
        assert_eq!(secret_ids, vec!["bot_token", "api_secret"]);
    }
}