zebflow 0.6.1

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
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
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
//! Project credential management service.

use std::collections::HashSet;
use std::sync::Arc;

use serde_json::Value;

use crate::platform::adapters::data::DataAdapter;
use crate::platform::error::PlatformError;
use crate::platform::model::{
    ProjectCredential, ProjectCredentialListItem, SecureRequestVariableDefinition,
    UpsertProjectCredentialRequest, now_ts, slug_segment,
};

/// Project-scoped credentials stored in the metadata catalog.
pub struct CredentialService {
    data: Arc<dyn DataAdapter>,
    http_client: reqwest::Client,
    /// Prevents concurrent token refresh for the same credential.
    refreshing: tokio::sync::Mutex<HashSet<String>>,
}

impl CredentialService {
    /// Creates the credential service.
    pub fn new(data: Arc<dyn DataAdapter>, http_client: reqwest::Client) -> Self {
        Self {
            data,
            http_client,
            refreshing: tokio::sync::Mutex::new(HashSet::new()),
        }
    }

    /// Lists safe project credential summaries.
    pub fn list_project_credentials(
        &self,
        owner: &str,
        project: &str,
    ) -> Result<Vec<ProjectCredentialListItem>, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        self.ensure_project_exists(&owner, &project)?;
        let mut items = self
            .data
            .list_project_credentials(&owner, &project)?
            .into_iter()
            .map(|credential| {
                let auth_roles = credential
                    .secret
                    .get("auth_roles")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(ToString::to_string))
                            .collect()
                    })
                    .unwrap_or_default();
                let secure_request_vars = if credential.kind == "secure_request" {
                    extract_secure_request_vars(&credential.secret)
                } else {
                    Vec::new()
                };
                let oauth2_status = if credential.kind == "oauth2" {
                    derive_oauth2_status(&credential.secret)
                } else {
                    String::new()
                };
                ProjectCredentialListItem {
                    credential_id: credential.credential_id,
                    title: credential.title,
                    kind: credential.kind,
                    has_secret: !credential.secret.is_null(),
                    notes: credential.notes,
                    auth_roles,
                    secure_request_vars,
                    oauth2_status,
                    created_at: credential.created_at,
                    updated_at: credential.updated_at,
                }
            })
            .collect::<Vec<_>>();
        items.sort_by(|a, b| a.credential_id.cmp(&b.credential_id));
        Ok(items)
    }

    /// Resolves one full credential payload for runtime use.
    pub fn get_project_credential(
        &self,
        owner: &str,
        project: &str,
        credential_id: &str,
    ) -> Result<Option<ProjectCredential>, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        let credential_id = slug_segment(credential_id);
        self.ensure_project_exists(&owner, &project)?;
        if credential_id.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_CREDENTIAL_INVALID",
                "credential id must not be empty",
            ));
        }
        self.data
            .get_project_credential(&owner, &project, &credential_id)
    }

    /// Creates or updates one credential.
    pub fn upsert_project_credential(
        &self,
        owner: &str,
        project: &str,
        req: &UpsertProjectCredentialRequest,
    ) -> Result<ProjectCredential, PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        self.ensure_project_exists(&owner, &project)?;

        let credential_id = slug_segment(&req.credential_id);
        if credential_id.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_CREDENTIAL_INVALID",
                "credential id must not be empty",
            ));
        }
        let kind = slug_segment(&req.kind);
        if kind.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_CREDENTIAL_INVALID",
                "credential kind must not be empty",
            ));
        }

        let now = now_ts();
        let existing = self
            .data
            .get_project_credential(&owner, &project, &credential_id)?;
        let created_at = existing.as_ref().map(|row| row.created_at).unwrap_or(now);
        let credential = ProjectCredential {
            owner: owner.clone(),
            project: project.clone(),
            credential_id: credential_id.clone(),
            title: if req.title.trim().is_empty() {
                credential_id.replace('-', " ")
            } else {
                req.title.trim().to_string()
            },
            kind,
            secret: req.secret.clone(),
            notes: req.notes.trim().to_string(),
            created_at,
            updated_at: now,
        };
        self.data.put_project_credential(&credential)?;
        Ok(credential)
    }

    /// Deletes one credential.
    pub fn delete_project_credential(
        &self,
        owner: &str,
        project: &str,
        credential_id: &str,
    ) -> Result<(), PlatformError> {
        let owner = slug_segment(owner);
        let project = slug_segment(project);
        let credential_id = slug_segment(credential_id);
        self.ensure_project_exists(&owner, &project)?;
        if credential_id.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_CREDENTIAL_INVALID",
                "credential id must not be empty",
            ));
        }
        self.data
            .delete_project_credential(&owner, &project, &credential_id)
    }

    // ── OAuth2 token management ─────────────────────────────────────────────

    /// Exchanges an OAuth2 authorization code for tokens and stores them in the credential.
    pub async fn exchange_oauth2_code(
        &self,
        owner: &str,
        project: &str,
        credential_id: &str,
        code: &str,
        redirect_uri: &str,
    ) -> Result<(), PlatformError> {
        let credential = self
            .get_project_credential(owner, project, credential_id)?
            .ok_or_else(|| {
                PlatformError::new("PLATFORM_CREDENTIAL_MISSING", "credential not found")
            })?;
        if credential.kind != "oauth2" {
            return Err(PlatformError::new(
                "PLATFORM_CREDENTIAL_INVALID",
                "credential is not oauth2",
            ));
        }
        let secret = &credential.secret;
        let client_id = secret_str(secret, "client_id")?;
        let client_secret = secret_str(secret, "client_secret")?;
        let token_url = secret_str(secret, "token_url")?;

        let resp = self
            .http_client
            .post(&token_url)
            .form(&[
                ("grant_type", "authorization_code"),
                ("code", code),
                ("redirect_uri", redirect_uri),
                ("client_id", &client_id),
                ("client_secret", &client_secret),
            ])
            .send()
            .await
            .map_err(|e| {
                PlatformError::new(
                    "PLATFORM_OAUTH2_EXCHANGE",
                    format!("token request failed: {e}"),
                )
            })?;

        let status = resp.status();
        let body: Value = resp.json().await.map_err(|e| {
            PlatformError::new(
                "PLATFORM_OAUTH2_EXCHANGE",
                format!("failed to parse token response: {e}"),
            )
        })?;

        if !status.is_success() {
            let err_desc = body
                .get("error_description")
                .or_else(|| body.get("error"))
                .and_then(Value::as_str)
                .unwrap_or("unknown error");
            return Err(PlatformError::new(
                "PLATFORM_OAUTH2_EXCHANGE",
                format!("token exchange failed ({status}): {err_desc}"),
            ));
        }

        let access_token = body
            .get("access_token")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let refresh_token = body
            .get("refresh_token")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let expires_in = body
            .get("expires_in")
            .and_then(Value::as_i64)
            .unwrap_or(3600);
        let token_type = body
            .get("token_type")
            .and_then(Value::as_str)
            .unwrap_or("Bearer");

        let mut updated_secret = credential.secret.clone();
        if let Value::Object(map) = &mut updated_secret {
            map.insert(
                "access_token".to_string(),
                Value::String(access_token.to_string()),
            );
            if !refresh_token.is_empty() {
                map.insert(
                    "refresh_token".to_string(),
                    Value::String(refresh_token.to_string()),
                );
            }
            map.insert(
                "expires_at".to_string(),
                Value::Number((now_ts() + expires_in - 60).into()),
            );
            map.insert(
                "token_type".to_string(),
                Value::String(token_type.to_string()),
            );
        }

        let updated = ProjectCredential {
            secret: updated_secret,
            updated_at: now_ts(),
            ..credential
        };
        self.data.put_project_credential(&updated)?;
        Ok(())
    }

    /// Refreshes an OAuth2 access token using the stored refresh_token.
    /// Returns the new access_token.
    pub async fn refresh_oauth2_token(
        &self,
        owner: &str,
        project: &str,
        credential_id: &str,
    ) -> Result<String, PlatformError> {
        let key = format!("{owner}/{project}/{credential_id}");

        // Dedup: if already refreshing, wait then re-read
        {
            let mut lock = self.refreshing.lock().await;
            if lock.contains(&key) {
                drop(lock);
                // Another task is refreshing — wait briefly, then read updated credential
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                let cred = self
                    .get_project_credential(owner, project, credential_id)?
                    .ok_or_else(|| {
                        PlatformError::new("PLATFORM_CREDENTIAL_MISSING", "credential not found")
                    })?;
                return Ok(cred
                    .secret
                    .get("access_token")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string());
            }
            lock.insert(key.clone());
        }

        let result = self
            .do_refresh_oauth2_token(owner, project, credential_id)
            .await;

        // Always remove from refreshing set
        {
            let mut lock = self.refreshing.lock().await;
            lock.remove(&key);
        }

        result
    }

    async fn do_refresh_oauth2_token(
        &self,
        owner: &str,
        project: &str,
        credential_id: &str,
    ) -> Result<String, PlatformError> {
        let credential = self
            .get_project_credential(owner, project, credential_id)?
            .ok_or_else(|| {
                PlatformError::new("PLATFORM_CREDENTIAL_MISSING", "credential not found")
            })?;
        let secret = &credential.secret;
        let client_id = secret_str(secret, "client_id")?;
        let client_secret = secret_str(secret, "client_secret")?;
        let token_url = secret_str(secret, "token_url")?;
        let refresh_token = secret_str(secret, "refresh_token")?;

        if refresh_token.is_empty() {
            return Err(PlatformError::new(
                "PLATFORM_OAUTH2_REFRESH",
                "no refresh_token stored — credential needs re-authorization",
            ));
        }

        let resp = self
            .http_client
            .post(&token_url)
            .form(&[
                ("grant_type", "refresh_token"),
                ("refresh_token", &refresh_token),
                ("client_id", &client_id),
                ("client_secret", &client_secret),
            ])
            .send()
            .await
            .map_err(|e| {
                PlatformError::new(
                    "PLATFORM_OAUTH2_REFRESH",
                    format!("refresh request failed: {e}"),
                )
            })?;

        let status = resp.status();
        let body: Value = resp.json().await.map_err(|e| {
            PlatformError::new(
                "PLATFORM_OAUTH2_REFRESH",
                format!("failed to parse refresh response: {e}"),
            )
        })?;

        if !status.is_success() {
            let err_desc = body
                .get("error_description")
                .or_else(|| body.get("error"))
                .and_then(Value::as_str)
                .unwrap_or("unknown error");
            return Err(PlatformError::new(
                "PLATFORM_OAUTH2_REFRESH",
                format!("token refresh failed ({status}): {err_desc}"),
            ));
        }

        let new_access_token = body
            .get("access_token")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let new_refresh_token = body
            .get("refresh_token")
            .and_then(Value::as_str)
            .map(ToString::to_string);
        let expires_in = body
            .get("expires_in")
            .and_then(Value::as_i64)
            .unwrap_or(3600);

        let mut updated_secret = credential.secret.clone();
        if let Value::Object(map) = &mut updated_secret {
            map.insert(
                "access_token".to_string(),
                Value::String(new_access_token.clone()),
            );
            if let Some(rt) = new_refresh_token {
                if !rt.is_empty() {
                    map.insert("refresh_token".to_string(), Value::String(rt));
                }
            }
            map.insert(
                "expires_at".to_string(),
                Value::Number((now_ts() + expires_in - 60).into()),
            );
        }

        let updated = ProjectCredential {
            secret: updated_secret,
            updated_at: now_ts(),
            ..credential
        };
        self.data.put_project_credential(&updated)?;
        Ok(new_access_token)
    }

    /// Returns a valid OAuth2 access token, refreshing first if expired.
    pub async fn get_valid_oauth2_token(
        &self,
        owner: &str,
        project: &str,
        credential_id: &str,
    ) -> Result<String, PlatformError> {
        let credential = self
            .get_project_credential(owner, project, credential_id)?
            .ok_or_else(|| {
                PlatformError::new("PLATFORM_CREDENTIAL_MISSING", "credential not found")
            })?;
        let secret = &credential.secret;
        let expires_at = secret
            .get("expires_at")
            .and_then(Value::as_i64)
            .unwrap_or(0);
        let now = now_ts();

        if expires_at > now + 60 {
            // Token still valid (with 60s buffer)
            Ok(secret
                .get("access_token")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string())
        } else {
            self.refresh_oauth2_token(owner, project, credential_id)
                .await
        }
    }

    fn ensure_project_exists(&self, owner: &str, project: &str) -> Result<(), PlatformError> {
        if self.data.get_project(owner, project)?.is_some() {
            return Ok(());
        }
        Err(PlatformError::new(
            "PLATFORM_PROJECT_MISSING",
            format!("project '{owner}/{project}' not found"),
        ))
    }
}

/// Helper to extract a string field from a secret JSON object.
fn secret_str(secret: &Value, key: &str) -> Result<String, PlatformError> {
    Ok(secret
        .get(key)
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string())
}

fn derive_oauth2_status(secret: &Value) -> String {
    let has_refresh = secret
        .get("refresh_token")
        .and_then(Value::as_str)
        .map(|s| !s.is_empty())
        .unwrap_or(false);
    if !has_refresh {
        return "not_configured".to_string();
    }
    let expires_at = secret
        .get("expires_at")
        .and_then(Value::as_i64)
        .unwrap_or(0);
    let now = now_ts();
    if expires_at > 0 && expires_at < now {
        "expired".to_string()
    } else {
        "authorized".to_string()
    }
}

fn extract_secure_request_vars(secret: &Value) -> Vec<SecureRequestVariableDefinition> {
    let Some(items) = secret.get("variables").and_then(Value::as_array) else {
        return Vec::new();
    };
    items
        .iter()
        .filter_map(|item| {
            let name = item
                .get("name")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .trim()
                .to_string();
            if name.is_empty() {
                return None;
            }
            Some(SecureRequestVariableDefinition {
                name: name.clone(),
                label: item
                    .get("label")
                    .and_then(Value::as_str)
                    .unwrap_or(&name)
                    .trim()
                    .to_string(),
                value_type: item
                    .get("value_type")
                    .or_else(|| item.get("type"))
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .trim()
                    .to_string(),
                required: item
                    .get("required")
                    .and_then(Value::as_bool)
                    .unwrap_or(false),
                default_expr: item
                    .get("default_expr")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .trim()
                    .to_string(),
                description: item
                    .get("description")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .trim()
                    .to_string(),
            })
        })
        .collect()
}