noetl-server 2.58.0

NoETL Control Plane - Async Rust server for workflow 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
//! Credential API handlers.
//!
//! Endpoints for managing encrypted credentials.

use axum::{
    Json,
    extract::{Path, Query, State},
    http::StatusCode,
};
use serde::Deserialize;

use crate::crypto::{SealedEnvelope, sealed_seal};
use crate::db::models::{CredentialCreateRequest, CredentialListResponse, CredentialResponse};
use crate::error::{AppError, AppResult};
use crate::services::{CredentialService, RuntimeService};

/// Query parameters for listing credentials.
#[derive(Debug, Deserialize, Default)]
pub struct ListCredentialsQuery {
    /// Filter by credential type
    #[serde(rename = "type")]
    pub credential_type: Option<String>,

    /// Free-text search
    pub q: Option<String>,
}

/// Query parameters for getting a credential.
#[derive(Debug, Deserialize, Default)]
pub struct GetCredentialQuery {
    /// Include decrypted data in response
    #[serde(default)]
    pub include_data: bool,

    /// Execution ID (for audit logging)
    pub execution_id: Option<i64>,

    /// Parent execution ID (for audit logging)
    pub parent_execution_id: Option<i64>,
}

/// Create or update a credential.
///
/// `POST /api/credentials`
///
/// # Request Body
///
/// ```json
/// {
///   "name": "my-database-creds",
///   "type": "postgres",
///   "data": {
///     "username": "admin",
///     "password": "secret123",
///     "host": "db.example.com"
///   },
///   "meta": {"environment": "production"},
///   "tags": ["database", "production"],
///   "description": "Production database credentials"
/// }
/// ```
///
/// # Response
///
/// ```json
/// {
///   "id": "123456789",
///   "name": "my-database-creds",
///   "type": "postgres",
///   "created_at": "2025-01-01T00:00:00Z",
///   "updated_at": "2025-01-01T00:00:00Z"
/// }
/// ```
pub async fn create_or_update(
    service: State<CredentialService>,
    request: Json<CredentialCreateRequest>,
) -> AppResult<(StatusCode, Json<CredentialResponse>)> {
    let started_at = std::time::Instant::now();
    let result = create_or_update_inner(service, request).await;
    let status_label = if result.is_ok() { "ok" } else { "error" };
    crate::metrics::record_write_request(
        crate::metrics::endpoint::CREDENTIALS_UPSERT,
        status_label,
        started_at.elapsed().as_secs_f64(),
    );
    result
}

async fn create_or_update_inner(
    State(service): State<CredentialService>,
    Json(request): Json<CredentialCreateRequest>,
) -> AppResult<(StatusCode, Json<CredentialResponse>)> {
    let response = service.create_or_update(request).await?;
    Ok((StatusCode::OK, Json(response)))
}

/// List credentials with optional filtering.
///
/// `GET /api/credentials`
///
/// # Query Parameters
///
/// - `type`: Filter by credential type
/// - `q`: Free-text search on name and description
///
/// # Response
///
/// ```json
/// {
///   "items": [...],
///   "filter": {"type": "postgres", "q": "production"}
/// }
/// ```
pub async fn list(
    State(service): State<CredentialService>,
    Query(query): Query<ListCredentialsQuery>,
) -> AppResult<Json<CredentialListResponse>> {
    let response = service
        .list(query.credential_type.as_deref(), query.q.as_deref())
        .await?;
    Ok(Json(response))
}

/// Get a credential by ID or name.
///
/// `GET /api/credentials/{identifier}`
///
/// # Path Parameters
///
/// - `identifier`: Credential ID (numeric) or name (string)
///
/// # Query Parameters
///
/// - `include_data`: If true, includes decrypted credential data
///
/// # Response
///
/// ```json
/// {
///   "id": "123456789",
///   "name": "my-database-creds",
///   "type": "postgres",
///   "data": {...},  // only if include_data=true
///   "created_at": "2025-01-01T00:00:00Z"
/// }
/// ```
pub async fn get(
    State(service): State<CredentialService>,
    Path(identifier): Path<String>,
    Query(query): Query<GetCredentialQuery>,
) -> AppResult<Json<CredentialResponse>> {
    let response = service
        .get(&identifier, query.include_data, query.execution_id)
        .await?;
    Ok(Json(response))
}

/// Delete a credential.
///
/// `DELETE /api/credentials/{identifier}`
///
/// # Path Parameters
///
/// - `identifier`: Credential ID (numeric) or name (string)
///
/// # Response
///
/// ```json
/// {
///   "message": "Credential deleted successfully",
///   "id": "123456789"
/// }
/// ```
pub async fn delete(
    State(service): State<CredentialService>,
    Path(identifier): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
    let id = service.delete(&identifier).await?;
    Ok(Json(serde_json::json!({
        "message": "Credential deleted successfully",
        "id": id
    })))
}

/// State extractor for the sealed-credential endpoint — bundles the two
/// services the handler needs (Secrets Wallet Phase 5b, noetl/ai-meta#61).
#[derive(Clone)]
pub struct SealedCredentialDeps {
    pub credentials: CredentialService,
    pub runtime: RuntimeService,
}

/// Query parameters for the sealed-credential endpoint.
#[derive(Debug, Deserialize, Default)]
pub struct GetSealedCredentialQuery {
    /// `name` of the worker_pool row in `noetl.runtime` whose registered
    /// public key the response is sealed to.
    pub worker_id: String,
    /// Forwarded to the underlying credential fetch — kept for audit
    /// correlation, NOT used as the seal recipient.
    pub execution_id: Option<i64>,
    /// Forwarded to the underlying credential fetch.
    pub parent_execution_id: Option<i64>,
}

/// Get a credential as a sealed payload addressed to a specific worker.
///
/// Secrets Wallet **Phase 5b** ([noetl/ai-meta#61]).  The credential payload
/// (the same JSON the plain `GET /api/credentials/{identifier}` returns with
/// `include_data=true`) is sealed with the X25519 public key the worker
/// registered with itself at startup.  The plaintext exists briefly inside
/// the server process at seal time; it never enters the response body, so an
/// operator with `kubectl exec` on the server pod sees only ciphertext.
///
/// `GET /api/credentials/{identifier}/sealed?worker_id=<name>`
///
/// The query MUST supply `worker_id` (the `name` of the `kind=worker_pool`
/// row in `noetl.runtime` that registered a sealing pubkey).  When the
/// worker exists but didn't register a key, returns `400 BadRequest`.
///
/// Response: a [`SealedEnvelope`] JSON (see `src/crypto/sealed.rs` for the
/// wire shape).  Phase 5c integrates the worker side (ephemeral X25519
/// keypair at startup + unseal + `zeroize` after the caller's tool dispatch).
///
/// [noetl/ai-meta#61]: https://github.com/noetl/ai-meta/issues/61
pub async fn get_sealed(
    State(deps): State<SealedCredentialDeps>,
    Path(identifier): Path<String>,
    Query(query): Query<GetSealedCredentialQuery>,
) -> AppResult<Json<SealedEnvelope>> {
    let span = tracing::info_span!(
        "credential.seal",
        worker_id = %query.worker_id,
        identifier = %identifier,
        execution_id = query.execution_id,
    );
    let _guard = span.enter();

    // Look up the worker's sealing pubkey first; this is the cheapest reject
    // and avoids decrypting + serialising the credential for a worker that
    // can't unseal it.
    let pubkey_bytes = match deps.runtime.get_worker_public_key(&query.worker_id).await {
        Ok(Some(b)) => b,
        Ok(None) => {
            crate::metrics::record_credential_seal("no_pubkey");
            return Err(AppError::BadRequest(format!(
                "worker '{}' did not register a sealing pubkey (worker_public_key \
                 missing from the noetl.runtime row, or the worker_pool row \
                 doesn't exist)",
                query.worker_id
            )));
        }
        Err(e) => {
            crate::metrics::record_credential_seal("worker_not_found");
            return Err(e);
        }
    };
    let pubkey = x25519_dalek::PublicKey::from(pubkey_bytes);

    // Fetch the credential payload (with include_data=true — the whole point
    // of sealing is to deliver the resolved secret).
    //
    // Phase 6e — when the local fetch fails with a residency violation AND a
    // cross-region broker is configured for the credential's home region,
    // forward the request to the broker instead of bubbling the violation
    // up.  The broker resolves locally, seals to THIS worker's pubkey, and
    // returns the envelope directly.  Cleartext stays in the credential's
    // home region.
    let credential = match deps
        .credentials
        .get(&identifier, true, query.execution_id)
        .await
    {
        Ok(c) => c,
        Err(AppError::ResidencyViolation {
            credential,
            entry_region,
            server_region,
        }) => {
            // Look up a broker for the entry's region.  When none is
            // configured, propagate the violation per Phase-6c fail-closed
            // semantics.
            let registry = crate::secrets::broker::registry();
            let Some(broker_url) = registry.broker_for(&entry_region) else {
                crate::metrics::record_credential_seal("residency_violation");
                return Err(AppError::ResidencyViolation {
                    credential,
                    entry_region,
                    server_region,
                });
            };
            tracing::info!(
                worker_id = %query.worker_id,
                credential = %credential,
                entry_region = %entry_region,
                broker_url = %broker_url,
                "credential.cross_region.fallback"
            );
            // Forward to the broker.  Wrap the seal in our own handler so
            // we can record cross-region duration.
            let started = std::time::Instant::now();
            let client = match crate::secrets::broker::BrokerClient::new() {
                Ok(c) => c,
                Err(e) => {
                    crate::metrics::record_cross_region_broker_call(&entry_region, "unreachable");
                    return Err(e);
                }
            };
            let body = crate::secrets::broker::CrossRegionResolveRequest {
                alias: identifier.clone(),
                worker_public_key_b64: {
                    use base64::Engine as _;
                    base64::engine::general_purpose::STANDARD.encode(pubkey_bytes)
                },
                worker_id: query.worker_id.clone(),
                execution_id: query.execution_id,
                parent_execution_id: query.parent_execution_id,
                expected_entry_region: entry_region.clone(),
                requesting_region: server_region.clone(),
            };
            let envelope = match client.resolve(broker_url, &body).await {
                Ok(e) => e,
                Err(e) => {
                    crate::metrics::record_cross_region_broker_call_duration(
                        &entry_region,
                        started.elapsed().as_secs_f64(),
                    );
                    crate::metrics::record_cross_region_broker_call(&entry_region, "unreachable");
                    return Err(e);
                }
            };
            crate::metrics::record_cross_region_broker_call_duration(
                &entry_region,
                started.elapsed().as_secs_f64(),
            );
            crate::metrics::record_cross_region_broker_call(&entry_region, "ok");
            crate::metrics::record_credential_seal("ok_via_broker");
            return Ok(Json(envelope));
        }
        Err(e) => {
            crate::metrics::record_credential_seal("credential_error");
            return Err(e);
        }
    };
    let plaintext = serde_json::to_vec(&credential).map_err(|e| {
        crate::metrics::record_credential_seal("seal_error");
        AppError::Internal(format!("sealed get: serialize credential: {e}"))
    })?;

    let envelope = sealed_seal(&pubkey, &plaintext).inspect_err(|_| {
        crate::metrics::record_credential_seal("seal_error");
    })?;
    crate::metrics::record_credential_seal("ok");
    Ok(Json(envelope))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::sealed_open;
    use x25519_dalek::{PublicKey, StaticSecret};

    /// End-to-end primitive contract: sealing a serialized credential JSON
    /// and opening it on the worker side round-trips losslessly via the
    /// sealed_seal / sealed_open primitives the handler uses.  Locks the
    /// shape `get_sealed` produces against drift in either crypto-side
    /// constant.
    #[test]
    fn sealed_credential_round_trips_via_primitives() {
        let recipient_sk = StaticSecret::random_from_rng(rand_core::OsRng);
        let recipient_pk = PublicKey::from(&recipient_sk);

        let credential = serde_json::json!({
            "id": "1234567890",
            "name": "duffel-token",
            "type": "bearer",
            "data": { "token": "sk-test-AbCdEf123" }
        });
        let plaintext = serde_json::to_vec(&credential).unwrap();

        let envelope = sealed_seal(&recipient_pk, &plaintext).unwrap();
        let opened = sealed_open(&recipient_sk, &envelope).unwrap();
        let opened_json: serde_json::Value = serde_json::from_slice(&opened).unwrap();

        assert_eq!(opened_json, credential);
    }

    /// Tampered envelope is rejected — the AEAD auth tag catches any flipped
    /// byte in the sealed-credential ciphertext (same guarantee Phase 5a's
    /// `sealed::tests` exercise, here pinned at the handler-payload layer).
    #[test]
    fn tampered_sealed_credential_is_rejected() {
        use base64::{Engine as _, engine::general_purpose::STANDARD as B64};

        let recipient_sk = StaticSecret::random_from_rng(rand_core::OsRng);
        let recipient_pk = PublicKey::from(&recipient_sk);
        let plaintext = br#"{"id":"1","name":"x","type":"bearer","data":{"token":"t"}}"#;
        let mut envelope = sealed_seal(&recipient_pk, plaintext).unwrap();

        let mut ct = B64.decode(&envelope.ciphertext).unwrap();
        ct[0] ^= 0x01;
        envelope.ciphertext = B64.encode(&ct);

        let err = sealed_open(&recipient_sk, &envelope).unwrap_err();
        assert!(format!("{err:?}").contains("AEAD verify/decrypt"));
    }
}