greentic-setup 0.4.28

End-to-end bundle setup engine for the Greentic platform — pack discovery, QA-driven configuration, secrets persistence, and bundle lifecycle management
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
//! Tenant config synchronization for webchat-gui OAuth settings.
//!
//! After setup persists OAuth answers to secrets, this module updates the
//! static tenant config JSON (`assets/webchat-gui/config/tenants/<tenant>.json`)
//! to enable/disable OAuth providers and set client IDs. This ensures the
//! webchat-gui runtime serves the correct auth config without manual editing.

use std::path::Path;

use anyhow::{Context, Result};
use serde_json::{Map, Value};

use crate::platform_setup::load_effective_static_routes_defaults;

/// Well-known OIDC provider definitions.
struct OidcProviderDef {
    id_suffix: &'static str,
    label: &'static str,
    answer_enable_key: &'static str,
    answer_client_id_key: &'static str,
    authorization_url: &'static str,
    scope: &'static str,
}

const OIDC_PROVIDERS: &[OidcProviderDef] = &[
    OidcProviderDef {
        id_suffix: "google",
        label: "Sign in with Google",
        answer_enable_key: "oauth_enable_google",
        answer_client_id_key: "oauth_google_client_id",
        authorization_url: "https://accounts.google.com/o/oauth2/v2/auth",
        scope: "openid profile email",
    },
    OidcProviderDef {
        id_suffix: "microsoft",
        label: "Sign in with Microsoft",
        answer_enable_key: "oauth_enable_microsoft",
        answer_client_id_key: "oauth_microsoft_client_id",
        authorization_url: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        scope: "openid profile email",
    },
    OidcProviderDef {
        id_suffix: "github",
        label: "Sign in with GitHub",
        answer_enable_key: "oauth_enable_github",
        answer_client_id_key: "oauth_github_client_id",
        authorization_url: "https://github.com/login/oauth/authorize",
        scope: "read:user user:email",
    },
];

/// Synchronize webchat-gui OAuth answers to the tenant config JSON.
///
/// Only runs for `messaging-webchat-gui` providers. Updates the tenant config
/// at `<bundle>/assets/webchat-gui/config/tenants/<tenant>.json`.
pub fn sync_oauth_to_tenant_config(
    bundle_path: &Path,
    tenant: &str,
    provider_id: &str,
    answers: &Value,
) -> Result<bool> {
    // Only apply to webchat-gui providers
    if !provider_id.contains("webchat-gui") {
        return Ok(false);
    }

    let answers_obj = match answers.as_object() {
        Some(m) => m,
        None => return Ok(false),
    };

    // Check if OAuth is configured in answers
    let oauth_enabled = answers_obj
        .get("oauth_enabled")
        .and_then(|v| v.as_bool().or_else(|| v.as_str().map(|s| s == "true")))
        .unwrap_or(false);

    // Find tenant config file
    let config_path = bundle_path
        .join("assets/webchat-gui/config/tenants")
        .join(format!("{tenant}.json"));

    if !config_path.exists() {
        // Try default.json as fallback
        let default_path = bundle_path.join("assets/webchat-gui/config/tenants/default.json");
        if default_path.exists() {
            return update_tenant_config(
                &default_path,
                tenant,
                oauth_enabled,
                answers_obj,
                resolve_public_base_url(bundle_path, tenant, answers_obj)?,
            );
        }
        return Ok(false);
    }

    update_tenant_config(
        &config_path,
        tenant,
        oauth_enabled,
        answers_obj,
        resolve_public_base_url(bundle_path, tenant, answers_obj)?,
    )
}

fn update_tenant_config(
    config_path: &Path,
    tenant: &str,
    oauth_enabled: bool,
    answers: &Map<String, Value>,
    public_base_url: Option<String>,
) -> Result<bool> {
    let raw = std::fs::read_to_string(config_path)
        .with_context(|| format!("read tenant config {}", config_path.display()))?;

    let mut config: Value = serde_json::from_str(&raw).context("parse tenant config as JSON")?;

    let auth = config.as_object_mut().and_then(|m| {
        m.entry("auth")
            .or_insert_with(|| Value::Object(Map::new()))
            .as_object_mut()
    });

    let Some(auth) = auth else {
        return Ok(false);
    };

    let providers = auth
        .entry("providers")
        .or_insert_with(|| Value::Array(vec![]));

    let Some(providers_arr) = providers.as_array_mut() else {
        return Ok(false);
    };

    let mut changed = false;

    for def in OIDC_PROVIDERS {
        let enabled = oauth_enabled
            && answers
                .get(def.answer_enable_key)
                .and_then(|v| v.as_bool().or_else(|| v.as_str().map(|s| s == "true")))
                .unwrap_or(false);

        let client_id = answers
            .get(def.answer_client_id_key)
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();

        let provider_id = format!("{tenant}-{}", def.id_suffix);
        let redirect_uri = public_base_url.as_deref().map(|public_base_url| {
            format!(
                "{}/v1/web/webchat/{}/",
                public_base_url.trim_end_matches('/'),
                tenant,
            )
        });

        // Find existing provider entry — match by exact ID or by suffix (e.g. "google", "microsoft")
        if let Some(existing) = providers_arr.iter_mut().find(|p| {
            let id = p.get("id").and_then(Value::as_str).unwrap_or("");
            id == provider_id || id == def.id_suffix
        }) {
            if let Some(obj) = existing.as_object_mut() {
                obj.insert("enabled".to_string(), Value::Bool(enabled));
                if !client_id.is_empty() {
                    obj.insert("clientId".to_string(), Value::String(client_id));
                }
                if let Some(redirect_uri) = redirect_uri.as_ref() {
                    obj.insert(
                        "redirectUri".to_string(),
                        Value::String(redirect_uri.clone()),
                    );
                }
                changed = true;
            }
        } else if enabled {
            // Add new provider entry
            let mut entry = Map::new();
            entry.insert("id".to_string(), Value::String(provider_id));
            entry.insert("label".to_string(), Value::String(def.label.to_string()));
            entry.insert("type".to_string(), Value::String("oidc".to_string()));
            entry.insert("enabled".to_string(), Value::Bool(true));
            entry.insert(
                "authorizationUrl".to_string(),
                Value::String(def.authorization_url.to_string()),
            );
            if !client_id.is_empty() {
                entry.insert("clientId".to_string(), Value::String(client_id));
            }
            if let Some(redirect_uri) = redirect_uri.as_ref() {
                entry.insert(
                    "redirectUri".to_string(),
                    Value::String(redirect_uri.clone()),
                );
            }
            entry.insert("scope".to_string(), Value::String(def.scope.to_string()));
            entry.insert(
                "responseType".to_string(),
                Value::String("code".to_string()),
            );
            providers_arr.push(Value::Object(entry));
            changed = true;
        }
    }

    // Handle custom OIDC provider
    let custom_enabled = oauth_enabled
        && answers
            .get("oauth_enable_custom")
            .and_then(|v| v.as_bool().or_else(|| v.as_str().map(|s| s == "true")))
            .unwrap_or(false);

    if custom_enabled {
        let custom_id = format!("{tenant}-custom-oidc");
        let label = answers
            .get("oauth_custom_label")
            .and_then(Value::as_str)
            .unwrap_or("SSO Login")
            .to_string();
        let auth_url = answers
            .get("oauth_custom_auth_url")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let client_id = answers
            .get("oauth_custom_client_id")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let scopes = answers
            .get("oauth_custom_scopes")
            .and_then(Value::as_str)
            .unwrap_or("openid profile email")
            .to_string();
        let redirect_uri = public_base_url.as_deref().map(|public_base_url| {
            format!(
                "{}/v1/web/webchat/{}/",
                public_base_url.trim_end_matches('/'),
                tenant,
            )
        });

        if let Some(existing) = providers_arr
            .iter_mut()
            .find(|p| p.get("id").and_then(Value::as_str) == Some(&custom_id))
        {
            if let Some(obj) = existing.as_object_mut() {
                obj.insert("enabled".to_string(), Value::Bool(true));
                obj.insert("label".to_string(), Value::String(label));
                if !auth_url.is_empty() {
                    obj.insert("authorizationUrl".to_string(), Value::String(auth_url));
                }
                if !client_id.is_empty() {
                    obj.insert("clientId".to_string(), Value::String(client_id));
                }
                if let Some(redirect_uri) = redirect_uri.as_ref() {
                    obj.insert(
                        "redirectUri".to_string(),
                        Value::String(redirect_uri.clone()),
                    );
                }
                obj.insert("scope".to_string(), Value::String(scopes));
                changed = true;
            }
        } else {
            let mut entry = Map::new();
            entry.insert("id".to_string(), Value::String(custom_id));
            entry.insert("label".to_string(), Value::String(label));
            entry.insert("type".to_string(), Value::String("oidc".to_string()));
            entry.insert("enabled".to_string(), Value::Bool(true));
            if !auth_url.is_empty() {
                entry.insert("authorizationUrl".to_string(), Value::String(auth_url));
            }
            if !client_id.is_empty() {
                entry.insert("clientId".to_string(), Value::String(client_id));
            }
            if let Some(redirect_uri) = redirect_uri.as_ref() {
                entry.insert(
                    "redirectUri".to_string(),
                    Value::String(redirect_uri.clone()),
                );
            }
            entry.insert("scope".to_string(), Value::String(scopes));
            entry.insert(
                "responseType".to_string(),
                Value::String("code".to_string()),
            );
            providers_arr.push(Value::Object(entry));
            changed = true;
        }
    }

    if changed {
        let output = serde_json::to_string_pretty(&config)?;
        std::fs::write(config_path, output)
            .with_context(|| format!("write tenant config {}", config_path.display()))?;
    }

    Ok(changed)
}

fn resolve_public_base_url(
    bundle_path: &Path,
    tenant: &str,
    answers: &Map<String, Value>,
) -> Result<Option<String>> {
    if let Some(value) = answers
        .get("public_base_url")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .filter(|value| !is_placeholder_public_base_url(value))
    {
        return Ok(Some(value.to_string()));
    }

    let from_policy = load_effective_static_routes_defaults(bundle_path, tenant, Some("default"))?
        .and_then(|policy| policy.public_base_url)
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .filter(|value| !is_placeholder_public_base_url(value));

    Ok(from_policy)
}

fn is_placeholder_public_base_url(value: &str) -> bool {
    let normalized = value.trim().trim_end_matches('/').to_ascii_lowercase();
    normalized.is_empty()
        || normalized.contains("example.com")
        || normalized.contains("localhost")
        || normalized.contains("127.0.0.1")
}

#[cfg(test)]
mod tests {
    use super::{is_placeholder_public_base_url, resolve_public_base_url, update_tenant_config};
    use serde_json::{Map, Value, json};

    #[test]
    fn resolve_public_base_url_ignores_placeholder_answer() {
        let temp = tempfile::tempdir().unwrap();
        let answers = json!({
            "public_base_url": "https://example.com"
        });
        let resolved =
            resolve_public_base_url(temp.path(), "demo", answers.as_object().unwrap()).unwrap();
        assert!(resolved.is_none());
    }

    #[test]
    fn resolve_public_base_url_prefers_non_placeholder_answer() {
        let temp = tempfile::tempdir().unwrap();
        let answers = json!({
            "public_base_url": "https://demo.example.net"
        });
        let resolved =
            resolve_public_base_url(temp.path(), "demo", answers.as_object().unwrap()).unwrap();
        assert_eq!(resolved.as_deref(), Some("https://demo.example.net"));
    }

    #[test]
    fn update_tenant_config_preserves_existing_redirect_when_public_base_url_missing() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join("demo.json");
        std::fs::write(
            &config_path,
            serde_json::to_string_pretty(&json!({
                "auth": {
                    "providers": [
                        {
                            "id": "demo-google",
                            "enabled": true,
                            "redirectUri": "https://existing.example.net/v1/web/webchat/demo/"
                        }
                    ]
                }
            }))
            .unwrap(),
        )
        .unwrap();

        let mut answers = Map::new();
        answers.insert("oauth_enabled".into(), Value::Bool(true));
        answers.insert("oauth_enable_google".into(), Value::Bool(true));
        answers.insert(
            "oauth_google_client_id".into(),
            Value::String("client-id".into()),
        );

        update_tenant_config(&config_path, "demo", true, &answers, None).unwrap();

        let updated: Value =
            serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
        assert_eq!(
            updated["auth"]["providers"][0]["redirectUri"].as_str(),
            Some("https://existing.example.net/v1/web/webchat/demo/")
        );
    }

    #[test]
    fn placeholder_detection_catches_local_and_example_urls() {
        assert!(is_placeholder_public_base_url("https://example.com"));
        assert!(is_placeholder_public_base_url("http://localhost:8080"));
        assert!(is_placeholder_public_base_url("http://127.0.0.1:8080"));
        assert!(!is_placeholder_public_base_url("https://demo.example.net"));
    }
}