newton-core 0.4.17

newton protocol core sdk
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
use super::{ApiPermission, DatabaseManager};
use alloy::primitives::Address;
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use sqlx::{postgres::PgRow, Row};
use std::collections::HashSet;
use tracing::{error, info};
use uuid::Uuid;

/// Render a bearer string for log output without leaking the secret.
///
/// Bearers reach this layer in plaintext — the gateway compares against the
/// raw value at request time and the provisioning CLI mints them in cleartext
/// for one-time delivery. Centralized log sinks (CloudWatch, Datadog) MUST NOT
/// see the full token because a leaked log line then permanently grants the
/// permissions the key carries. Show only the structural prefix and length so
/// operators can correlate redacted log lines back to a specific key without
/// the token surfacing in scrollback or aggregated traces.
pub fn redact_bearer(key: &str) -> String {
    let prefix_len = key.find('_').map(|p| p + 1).unwrap_or(0).min(key.len());
    let prefix = &key[..prefix_len];
    format!("{prefix}*** ({}c)", key.len())
}

/// Database model for API keys with additional metadata.
///
/// `Debug` is implemented manually so the cleartext `api_key` field is never
/// serialized into log records via `?record`-style formatting. Auto-deriving
/// `Debug` would expose the bearer at every span field that captures this
/// type by reference.
#[derive(Clone)]
pub struct ApiKeyRecord {
    /// Unique identifier for this API key
    pub id: Uuid,
    /// User ID associated with this API key
    pub user_id: Uuid,
    /// Ethereum wallet address associated with this user
    pub address: Address,
    /// API key string (bearer token)
    pub api_key: String,
    /// Human-readable name for the API key
    pub name: String,
    /// Set of permissions granted to this key
    pub permissions: HashSet<ApiPermission>,
    /// Optional rate limit override (requests per minute)
    pub rate_limit: Option<u32>,
    /// Timestamp when the key was created
    pub created_at: DateTime<Utc>,
    /// Timestamp when the key was last updated
    pub updated_at: DateTime<Utc>,
    /// Whether the key is currently active
    pub is_active: bool,
    /// Optional expiration timestamp
    pub expires_at: Option<DateTime<Utc>>,
    /// Optional description of the key's purpose
    pub description: Option<String>,
}

impl std::fmt::Debug for ApiKeyRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ApiKeyRecord")
            .field("id", &self.id)
            .field("user_id", &self.user_id)
            .field("address", &self.address)
            .field("api_key", &redact_bearer(&self.api_key))
            .field("name", &self.name)
            .field("permissions", &self.permissions)
            .field("rate_limit", &self.rate_limit)
            .field("created_at", &self.created_at)
            .field("updated_at", &self.updated_at)
            .field("is_active", &self.is_active)
            .field("expires_at", &self.expires_at)
            .field("description", &self.description)
            .finish()
    }
}

impl ApiKeyRecord {
    /// Checks if the API key is currently valid
    pub fn is_valid(&self) -> bool {
        if !self.is_active {
            return false;
        }

        if let Some(expires_at) = self.expires_at {
            if expires_at < Utc::now() {
                return false;
            }
        }

        true
    }

    /// Checks if the API key has the specified permission
    pub fn has_permission(&self, permission: &ApiPermission) -> bool {
        self.permissions.iter().any(|p| p.implies(permission))
    }
}

/// Repository for API key CRUD operations
#[derive(Debug, Clone)]
pub struct ApiKeyRepository {
    db: DatabaseManager,
}

/// Parameters for updating an existing API key record.
#[derive(Debug, Default)]
pub struct ApiKeyUpdate {
    /// Optional new name for the API key.
    pub name: Option<String>,
    /// Optional new set of permissions.
    pub permissions: Option<HashSet<ApiPermission>>,
    /// Optional new rate limit.
    pub rate_limit: Option<Option<u32>>,
    /// Optional updated active flag.
    pub is_active: Option<bool>,
    /// Optional updated description.
    pub description: Option<Option<String>>,
    /// Optional updated expiration timestamp.
    pub expires_at: Option<Option<DateTime<Utc>>>,
}

impl ApiKeyRepository {
    /// Creates a new API key repository
    pub fn new(db: DatabaseManager) -> Self {
        Self { db }
    }

    /// Retrieves an API key by its key string
    ///
    /// # Arguments
    ///
    /// * `key` - The API key string
    ///
    /// # Returns
    ///
    /// Returns the API key record if found
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails
    pub async fn get_by_key(&self, key: &str) -> sqlx::Result<Option<ApiKeyRecord>> {
        let row = sqlx::query(
            r#"
            SELECT id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
                   is_active, expires_at, description
            FROM api_keys
            WHERE api_key = $1
            "#,
        )
        .bind(key)
        .fetch_optional(self.db.pool())
        .await?;

        Ok(row.map(Self::row_to_record))
    }

    /// Retrieves all active API keys
    ///
    /// # Returns
    ///
    /// Returns a vector of all active API key records
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails
    pub async fn get_all_active(&self) -> sqlx::Result<Vec<ApiKeyRecord>> {
        let rows = sqlx::query(
            r#"
            SELECT id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
                   is_active, expires_at, description
            FROM api_keys
            WHERE is_active = true
            ORDER BY created_at DESC
            "#,
        )
        .fetch_all(self.db.pool())
        .await?;

        Ok(rows.into_iter().map(Self::row_to_record).collect())
    }

    /// Creates a new API key
    ///
    /// # Arguments
    ///
    /// * `key` - The API key string
    /// * `name` - Human-readable name for the key
    /// * `permissions` - Set of permissions to grant
    /// * `rate_limit` - Optional rate limit (requests per minute)
    /// * `description` - Optional description
    /// * `expires_at` - Optional expiration timestamp
    /// * `user_id` - UUID of the user who owns this API key
    ///
    /// # Returns
    ///
    /// Returns the created API key record
    ///
    /// # Errors
    ///
    /// Returns an error if the database insert fails
    #[allow(clippy::too_many_arguments)]
    pub async fn create(
        &self,
        user_id: Uuid,
        address: Address,
        api_key: String,
        name: String,
        permissions: HashSet<ApiPermission>,
        rate_limit: Option<u32>,
        description: Option<String>,
        expires_at: Option<DateTime<Utc>>,
    ) -> sqlx::Result<ApiKeyRecord> {
        let permissions_json = Self::permissions_to_json(&permissions);

        let row = sqlx::query(
            r#"
            INSERT INTO api_keys (user_id, address, api_key, name, permissions, rate_limit, description, expires_at)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            RETURNING id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
                      is_active, expires_at, description
            "#,
        )
        .bind(user_id)
        .bind(address.as_slice())
        .bind(&api_key)
        .bind(&name)
        .bind(permissions_json)
        .bind(rate_limit.map(|r| r as i32))
        .bind(description)
        .bind(expires_at)
        .fetch_one(self.db.pool())
        .await?;

        info!(
            "Created new API key: name={name} bearer={} address={address}",
            redact_bearer(&api_key)
        );
        Ok(Self::row_to_record(row))
    }

    /// Atomically rotates an active API key: deactivates the old row and
    /// inserts a new row carrying the same identity tuple `(user_id, address,
    /// permissions)` plus the supplied new bearer / name. Both writes execute
    /// inside a single PostgreSQL transaction, so concurrent rotations of the
    /// same bearer can only succeed once — the second caller's deactivate
    /// finds `is_active = false` and the entire transaction rolls back.
    ///
    /// Returns the newly-issued [`ApiKeyRecord`]. The old bearer is no longer
    /// active in the same DB visibility unit; the gateway's `AdminRevalidator`
    /// re-reads from the database on every Admin bypass and rejects cached
    /// Admin records whose live row is now inactive, and the non-Admin cache
    /// eviction follows the gateway's normal 5-minute refresh cycle.
    ///
    /// # Errors
    ///
    /// - `RowNotFound` if `old_api_key` does not match an active row.
    /// - Other sqlx errors propagate from the transaction.
    pub async fn rotate(&self, old_api_key: &str, new_api_key: String, new_name: String) -> sqlx::Result<ApiKeyRecord> {
        let mut tx = self.db.pool().begin().await?;

        // Deactivate the old row gated on `is_active = true`. If two callers
        // race with the same bearer, only one observes a row to deactivate;
        // the other gets RowNotFound and rolls back without ever inserting a
        // duplicate replacement.
        let old_row = sqlx::query(
            r#"
            UPDATE api_keys
               SET is_active = false, updated_at = NOW()
             WHERE api_key = $1 AND is_active = true
            RETURNING id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
                      is_active, expires_at, description
            "#,
        )
        .bind(old_api_key)
        .fetch_one(&mut *tx)
        .await?;

        let old = Self::row_to_record(old_row);

        let permissions_json = Self::permissions_to_json(&old.permissions);
        let new_row = sqlx::query(
            r#"
            INSERT INTO api_keys (user_id, address, api_key, name, permissions, rate_limit, description, expires_at)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            RETURNING id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
                      is_active, expires_at, description
            "#,
        )
        .bind(old.user_id)
        .bind(old.address.as_slice())
        .bind(&new_api_key)
        .bind(&new_name)
        .bind(permissions_json)
        .bind(old.rate_limit.map(|r| r as i32))
        .bind(old.description.clone())
        // The new bearer inherits the source row's `expires_at` verbatim
        // via `.bind(old.expires_at)` below. Rotation is a same-permission,
        // different-secret operation; silently dropping `expires_at = None`
        // would let a soon-to-expire key gain indefinite validity through a
        // routine rotate. Operators who want to extend access must explicitly
        // revoke + create a new key, the same path used for the initial
        // issuance — never a side effect of rotate.
        .bind::<Option<DateTime<Utc>>>(old.expires_at)
        .fetch_one(&mut *tx)
        .await?;

        tx.commit().await?;

        info!(
            "Rotated API key: old_id={} old_bearer={} new_bearer={} address={}",
            old.id,
            redact_bearer(old_api_key),
            redact_bearer(&new_api_key),
            old.address
        );
        Ok(Self::row_to_record(new_row))
    }

    /// Updates an existing API key
    ///
    /// # Arguments
    ///
    /// * `key` - The API key string
    /// * `name` - Optional new name
    /// * `permissions` - Optional new permissions set
    /// * `rate_limit` - Optional new rate limit
    /// * `is_active` - Optional new active status
    /// * `description` - Optional new description
    /// * `expires_at` - Optional new expiration timestamp
    ///
    /// # Returns
    ///
    /// Returns the updated API key record
    ///
    /// # Errors
    ///
    /// Returns an error if the database update fails or key not found
    pub async fn update(&self, key: &str, update: ApiKeyUpdate) -> sqlx::Result<ApiKeyRecord> {
        // Build dynamic update query
        let mut query = String::from("UPDATE api_keys SET updated_at = NOW()");
        let mut param_count = 1;

        if update.name.is_some() {
            param_count += 1;
            query.push_str(&format!(", name = ${}", param_count));
        }
        if update.permissions.is_some() {
            param_count += 1;
            query.push_str(&format!(", permissions = ${}", param_count));
        }
        if update.rate_limit.is_some() {
            param_count += 1;
            query.push_str(&format!(", rate_limit = ${}", param_count));
        }
        if update.is_active.is_some() {
            param_count += 1;
            query.push_str(&format!(", is_active = ${}", param_count));
        }
        if update.description.is_some() {
            param_count += 1;
            query.push_str(&format!(", description = ${}", param_count));
        }
        if update.expires_at.is_some() {
            param_count += 1;
            query.push_str(&format!(", expires_at = ${}", param_count));
        }

        query.push_str(
            " WHERE api_key = $1 RETURNING id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at, is_active, expires_at, description",
        );

        let mut q = sqlx::query(&query).bind(key);

        if let Some(n) = update.name {
            q = q.bind(n);
        }
        if let Some(p) = update.permissions {
            q = q.bind(Self::permissions_to_json(&p));
        }
        if let Some(r) = update.rate_limit {
            q = q.bind(r.map(|v| v as i32));
        }
        if let Some(a) = update.is_active {
            q = q.bind(a);
        }
        if let Some(d) = update.description {
            q = q.bind(d);
        }
        if let Some(e) = update.expires_at {
            q = q.bind(e);
        }

        let row = q.fetch_one(self.db.pool()).await?;

        info!("Updated API key: bearer={}", redact_bearer(key));
        Ok(Self::row_to_record(row))
    }

    /// Deletes an API key
    ///
    /// # Arguments
    ///
    /// * `key` - The API key string to delete
    ///
    /// # Returns
    ///
    /// Returns true if the key was deleted, false if not found
    ///
    /// # Errors
    ///
    /// Returns an error if the database delete fails
    pub async fn delete(&self, key: &str) -> sqlx::Result<bool> {
        let result = sqlx::query("DELETE FROM api_keys WHERE api_key = $1")
            .bind(key)
            .execute(self.db.pool())
            .await?;

        let deleted = result.rows_affected() > 0;
        if deleted {
            info!("Deleted API key: bearer={}", redact_bearer(key));
        }
        Ok(deleted)
    }

    /// Deactivates an API key (soft delete)
    ///
    /// # Arguments
    ///
    /// * `key` - The API key string to deactivate
    ///
    /// # Returns
    ///
    /// Returns true if the key was deactivated
    ///
    /// # Errors
    ///
    /// Returns an error if the database update fails
    pub async fn deactivate(&self, key: &str) -> sqlx::Result<bool> {
        let result = sqlx::query("UPDATE api_keys SET is_active = false, updated_at = NOW() WHERE api_key = $1")
            .bind(key)
            .execute(self.db.pool())
            .await?;

        let deactivated = result.rows_affected() > 0;
        if deactivated {
            info!("Deactivated API key: bearer={}", redact_bearer(key));
        }
        Ok(deactivated)
    }

    /// Converts a database row to ApiKeyRecord
    fn row_to_record(row: PgRow) -> ApiKeyRecord {
        let permissions_json: JsonValue = row.get("permissions");
        let permissions = Self::json_to_permissions(&permissions_json);

        let address_bytes: Vec<u8> = row.get("address");
        let address = Address::from_slice(&address_bytes);

        ApiKeyRecord {
            id: row.get("id"),
            user_id: row.get("user_id"),
            address,
            api_key: row.get("api_key"),
            name: row.get("name"),
            permissions,
            rate_limit: row.get::<Option<i32>, _>("rate_limit").map(|r| r as u32),
            created_at: row.get("created_at"),
            updated_at: row.get("updated_at"),
            is_active: row.get("is_active"),
            expires_at: row.get("expires_at"),
            description: row.get("description"),
        }
    }

    /// Converts permissions HashSet to JSON array
    fn permissions_to_json(permissions: &HashSet<ApiPermission>) -> JsonValue {
        let perms: Vec<String> = permissions
            .iter()
            .filter_map(|p| serde_json::to_value(p).ok())
            .filter_map(|v| v.as_str().map(String::from))
            .collect();
        JsonValue::Array(perms.into_iter().map(JsonValue::String).collect())
    }

    /// Converts JSON array to permissions HashSet
    fn json_to_permissions(json: &JsonValue) -> HashSet<ApiPermission> {
        match json {
            JsonValue::Array(arr) => arr
                .iter()
                .filter_map(|v| v.as_str())
                .filter_map(|s| serde_json::from_value(JsonValue::String(s.to_string())).ok())
                .collect(),
            _ => {
                error!("Invalid permissions JSON format: {:?}", json);
                HashSet::new()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redact_keeps_prefix_drops_secret_body() {
        // The redaction format is "<prefix>*** (<len>c)". The full bearer
        // body must NOT appear anywhere in the redacted form, regardless
        // of how many random characters happen to match a prefix substring.
        let bearer = "nidx_abcdefghijklmnopqrstuvwxyz23456789";
        let redacted = redact_bearer(bearer);
        assert!(redacted.starts_with("nidx_***"), "missing prefix: {redacted:?}");
        assert!(redacted.contains(&format!("({}c)", bearer.len())));
        // Pull the unique random tail (everything after the prefix) and
        // assert it is not present in the redacted output.
        let tail = &bearer[5..];
        assert!(!redacted.contains(tail), "redaction leaked the tail: {redacted:?}");
    }

    #[test]
    fn redact_handles_legacy_no_prefix_keys() {
        // The legacy seed rows (`admin_key_CHANGE_ME_IN_PRODUCTION`,
        // `rpc_write_key_CHANGE_ME_IN_PRODUCTION`) split on the first '_'.
        // Verify those redact to a stable prefix without leaking the secret.
        let bearer = "admin_key_CHANGE_ME_IN_PRODUCTION";
        let redacted = redact_bearer(bearer);
        assert!(redacted.starts_with("admin_***"), "got {redacted:?}");
        assert!(!redacted.contains("CHANGE_ME"), "legacy key body leaked: {redacted:?}");
    }

    #[test]
    fn redact_handles_no_underscore_keys() {
        // A bearer with no underscore at all should redact to "*** (Nc)" —
        // no prefix to keep, just length attribution.
        let bearer = "rawopaquetokenwithoutprefix";
        let redacted = redact_bearer(bearer);
        assert!(redacted.starts_with("***"), "got {redacted:?}");
        assert!(!redacted.contains("rawopaque"), "raw body leaked: {redacted:?}");
    }

    #[test]
    fn redact_handles_empty_bearer() {
        // Defensive: redaction on an empty string must not panic. An empty
        // bearer is structurally invalid but reaches this layer in error
        // paths (e.g., logging on attempted lookup of an empty key string).
        let redacted = redact_bearer("");
        assert_eq!(redacted, "*** (0c)");
    }
}