athena_rs 3.11.0

Hyper performant polyglot Database driver
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! IP control policy data layer for API keys.
//!
//! Covers per-key whitelist/blacklist CIDR entries, the seen-IP aggregation
//! used by virgin-mode learning, and the global overrides that take
//! precedence over per-key rules.

use std::net::IpAddr;

use chrono::{DateTime, Utc};
use ipnetwork::IpNetwork;
use serde::Serialize;
use sqlx::postgres::{PgPool, PgRow};
use sqlx::{Postgres, Row, Transaction};

/// Single IP or CIDR rule stored against an API key or global scope.
#[derive(Debug, Clone, Serialize)]
pub struct IpRule {
    pub id: String,
    pub addr: String,
    pub label: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// Full per-key IP policy snapshot used on the auth hot path.
#[derive(Debug, Clone, Serialize)]
pub struct ApiKeyIpPolicy {
    pub api_key_id: i64,
    pub virgin_mode: bool,
    pub virgin_resolved: bool,
    pub virgin_resolved_at: Option<DateTime<Utc>>,
    pub virgin_until_n_requests: i32,
    pub virgin_request_count: i32,
    pub max_whitelist_ips: i32,
    pub whitelist: Vec<IpRule>,
    pub blacklist: Vec<IpRule>,
}

/// Observed IP counter row for a given API key.
#[derive(Debug, Clone, Serialize)]
pub struct SeenIpRecord {
    pub id: String,
    pub addr: String,
    pub first_seen_at: DateTime<Utc>,
    pub last_seen_at: DateTime<Utc>,
    pub hit_count: i64,
    pub locked_in: bool,
}

/// Outcome of recording an observed IP during virgin learning.
#[derive(Debug, Clone)]
pub struct SeenIpUpdate {
    pub distinct_ip_count: i64,
    pub hit_count_for_ip: i64,
    pub was_new: bool,
}

fn map_ip_rule(row: &PgRow, id_column: &str) -> Result<IpRule, sqlx::Error> {
    let id: uuid::Uuid = row.try_get(id_column)?;
    let addr: IpNetwork = row.try_get("addr")?;
    Ok(IpRule {
        id: id.to_string(),
        addr: addr.to_string(),
        label: row.try_get("label")?,
        created_at: row.try_get("created_at")?,
    })
}

/// Loads the per-key IP policy including virgin-mode counters and both
/// whitelist and blacklist entries in as few round-trips as possible.
pub async fn load_api_key_ip_policy(
    pool: &PgPool,
    api_key_id: i64,
) -> Result<Option<ApiKeyIpPolicy>, sqlx::Error> {
    let key_row: Option<PgRow> = sqlx::query(
        r#"
        SELECT
            id,
            virgin_mode,
            virgin_resolved,
            virgin_resolved_at,
            virgin_until_n_requests,
            virgin_request_count,
            max_whitelist_ips
        FROM api_keys
        WHERE id = $1
        "#,
    )
    .bind(api_key_id)
    .fetch_optional(pool)
    .await?;

    let Some(key_row) = key_row else {
        return Ok(None);
    };

    let whitelist_rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT api_key_ip_whitelist_id AS id, addr, label, created_at
        FROM api_key_ip_whitelist
        WHERE api_key_id = $1
        ORDER BY created_at
        "#,
    )
    .bind(api_key_id)
    .fetch_all(pool)
    .await?;

    let blacklist_rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT api_key_ip_blacklist_id AS id, addr, label, created_at
        FROM api_key_ip_blacklist
        WHERE api_key_id = $1
        ORDER BY created_at
        "#,
    )
    .bind(api_key_id)
    .fetch_all(pool)
    .await?;

    let whitelist: Vec<IpRule> = whitelist_rows
        .iter()
        .map(|row| map_ip_rule(row, "id"))
        .collect::<Result<_, _>>()?;
    let blacklist: Vec<IpRule> = blacklist_rows
        .iter()
        .map(|row| map_ip_rule(row, "id"))
        .collect::<Result<_, _>>()?;

    Ok(Some(ApiKeyIpPolicy {
        api_key_id: key_row.try_get("id")?,
        virgin_mode: key_row.try_get("virgin_mode")?,
        virgin_resolved: key_row.try_get("virgin_resolved")?,
        virgin_resolved_at: key_row.try_get("virgin_resolved_at")?,
        virgin_until_n_requests: key_row.try_get("virgin_until_n_requests")?,
        virgin_request_count: key_row.try_get("virgin_request_count")?,
        max_whitelist_ips: key_row.try_get("max_whitelist_ips")?,
        whitelist,
        blacklist,
    }))
}

/// Loads the global whitelist and blacklist rules relevant to a client.
///
/// Rules with `client_name IS NULL` apply to every client.
pub async fn load_global_ip_rules(
    pool: &PgPool,
    client_name: Option<&str>,
) -> Result<(Vec<IpRule>, Vec<IpRule>), sqlx::Error> {
    let whitelist_rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT api_key_ip_global_whitelist_id AS id, addr, label, created_at
        FROM api_key_ip_global_whitelist
        WHERE client_name IS NULL OR client_name = $1
        ORDER BY created_at
        "#,
    )
    .bind(client_name)
    .fetch_all(pool)
    .await?;

    let blacklist_rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT api_key_ip_global_blacklist_id AS id, addr, label, created_at
        FROM api_key_ip_global_blacklist
        WHERE client_name IS NULL OR client_name = $1
        ORDER BY created_at
        "#,
    )
    .bind(client_name)
    .fetch_all(pool)
    .await?;

    let whitelist: Vec<IpRule> = whitelist_rows
        .iter()
        .map(|row| map_ip_rule(row, "id"))
        .collect::<Result<_, _>>()?;
    let blacklist: Vec<IpRule> = blacklist_rows
        .iter()
        .map(|row| map_ip_rule(row, "id"))
        .collect::<Result<_, _>>()?;

    Ok((whitelist, blacklist))
}

/// Upserts a seen IP for the given key, incrementing hit counters and
/// returning the post-write distinct IP count used to decide virgin lock-in.
pub async fn record_seen_ip(
    pool: &PgPool,
    api_key_id: i64,
    ip: IpAddr,
) -> Result<SeenIpUpdate, sqlx::Error> {
    let addr: IpNetwork = IpNetwork::from(ip);
    let mut tx: Transaction<'_, Postgres> = pool.begin().await?;

    let row: PgRow = sqlx::query(
        r#"
        INSERT INTO api_key_ip_seen (api_key_id, addr, ipv4_address, first_seen_at, last_seen_at, hit_count)
        VALUES ($1, $2, $3, now(), now(), 1)
        ON CONFLICT (api_key_id, addr)
        DO UPDATE SET
            ipv4_address = COALESCE(api_key_ip_seen.ipv4_address, EXCLUDED.ipv4_address),
            last_seen_at = now(),
            hit_count = api_key_ip_seen.hit_count + 1
        RETURNING hit_count, (xmax = 0) AS was_new
        "#,
    )
    .bind(api_key_id)
    .bind(addr)
    .bind(ip.to_string())
    .fetch_one(&mut *tx)
    .await?;

    let hit_count_for_ip: i64 = row.try_get("hit_count")?;
    let was_new: bool = row.try_get("was_new")?;

    let distinct_ip_count: i64 = sqlx::query_scalar(
        r#"
        SELECT COUNT(*)::bigint
        FROM api_key_ip_seen
        WHERE api_key_id = $1
        "#,
    )
    .bind(api_key_id)
    .fetch_one(&mut *tx)
    .await?;

    tx.commit().await?;

    Ok(SeenIpUpdate {
        distinct_ip_count,
        hit_count_for_ip,
        was_new,
    })
}

/// Returns the updated virgin request counter. Used as part of the virgin
/// lock-in decision whenever a successful auth comes in for an unresolved key.
pub async fn increment_virgin_request_count(
    pool: &PgPool,
    api_key_id: i64,
) -> Result<i32, sqlx::Error> {
    let row: PgRow = sqlx::query(
        r#"
        UPDATE api_keys
        SET
            virgin_request_count = virgin_request_count + 1,
            updated_at = now()
        WHERE id = $1
        RETURNING virgin_request_count
        "#,
    )
    .bind(api_key_id)
    .fetch_one(pool)
    .await?;

    row.try_get("virgin_request_count")
}

/// Copies up to `max_take` of the earliest-seen IPs into the whitelist.
/// When `max_take` is `None` or `Some(0)`, every seen IP is promoted.
pub async fn promote_seen_ips_to_whitelist(
    pool: &PgPool,
    api_key_id: i64,
    max_take: Option<i32>,
) -> Result<i64, sqlx::Error> {
    let limit: Option<i32> = max_take.filter(|value| *value > 0);
    let row: PgRow = sqlx::query(
        r#"
        WITH candidates AS (
            SELECT addr
            FROM api_key_ip_seen
            WHERE api_key_id = $1
            ORDER BY first_seen_at
            LIMIT COALESCE($2, 2147483647)
        ),
        inserted AS (
            INSERT INTO api_key_ip_whitelist (api_key_id, addr, label)
            SELECT $1, addr::cidr, 'virgin_learned'
            FROM candidates
            ON CONFLICT (api_key_id, addr) DO NOTHING
            RETURNING 1
        )
        SELECT COUNT(*)::bigint AS promoted FROM inserted
        "#,
    )
    .bind(api_key_id)
    .bind(limit)
    .fetch_one(pool)
    .await?;

    row.try_get("promoted")
}

/// Marks the key as virgin-resolved and locks in the matching seen-IP rows.
pub async fn mark_virgin_resolved(pool: &PgPool, api_key_id: i64) -> Result<(), sqlx::Error> {
    let mut tx: Transaction<'_, Postgres> = pool.begin().await?;

    sqlx::query(
        r#"
        UPDATE api_keys
        SET
            virgin_resolved = true,
            virgin_resolved_at = COALESCE(virgin_resolved_at, now()),
            updated_at = now()
        WHERE id = $1
        "#,
    )
    .bind(api_key_id)
    .execute(&mut *tx)
    .await?;

    sqlx::query(
        r#"
        UPDATE api_key_ip_seen
        SET locked_in = true
        WHERE api_key_id = $1
        "#,
    )
    .bind(api_key_id)
    .execute(&mut *tx)
    .await?;

    tx.commit().await
}

/// Clears virgin-resolved state and optionally truncates seen-IP history so
/// the key restarts learning on next auth.
pub async fn reset_virgin_state(
    pool: &PgPool,
    api_key_id: i64,
    clear_seen: bool,
) -> Result<(), sqlx::Error> {
    let mut tx: Transaction<'_, Postgres> = pool.begin().await?;

    sqlx::query(
        r#"
        UPDATE api_keys
        SET
            virgin_resolved = false,
            virgin_resolved_at = NULL,
            virgin_request_count = 0,
            updated_at = now()
        WHERE id = $1
        "#,
    )
    .bind(api_key_id)
    .execute(&mut *tx)
    .await?;

    if clear_seen {
        sqlx::query(
            r#"
            DELETE FROM api_key_ip_seen
            WHERE api_key_id = $1
            "#,
        )
        .bind(api_key_id)
        .execute(&mut *tx)
        .await?;
    } else {
        sqlx::query(
            r#"
            UPDATE api_key_ip_seen
            SET locked_in = false
            WHERE api_key_id = $1
            "#,
        )
        .bind(api_key_id)
        .execute(&mut *tx)
        .await?;
    }

    tx.commit().await
}

/// Lists seen-IP rows for admin UI inspection.
pub async fn list_seen_ips(
    pool: &PgPool,
    api_key_id: i64,
    limit: i32,
    offset: i32,
) -> Result<Vec<SeenIpRecord>, sqlx::Error> {
    let limit: i32 = limit.clamp(1, 1000);
    let offset: i32 = offset.max(0);
    let rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT api_key_ip_seen_id AS id, addr, first_seen_at, last_seen_at, hit_count, locked_in
        FROM api_key_ip_seen
        WHERE api_key_id = $1
        ORDER BY last_seen_at DESC
        LIMIT $2 OFFSET $3
        "#,
    )
    .bind(api_key_id)
    .bind(limit)
    .bind(offset)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|row| {
            let id: uuid::Uuid = row.try_get("id")?;
            let addr: IpNetwork = row.try_get("addr")?;
            Ok(SeenIpRecord {
                id: id.to_string(),
                addr: addr.to_string(),
                first_seen_at: row.try_get("first_seen_at")?,
                last_seen_at: row.try_get("last_seen_at")?,
                hit_count: row.try_get("hit_count")?,
                locked_in: row.try_get("locked_in")?,
            })
        })
        .collect()
}

/// Inserts a batch of rules. Duplicates (same `api_key_id`+`addr`) are ignored.
pub async fn upsert_whitelist_entries(
    pool: &PgPool,
    api_key_id: i64,
    addrs: &[IpNetwork],
    label: Option<&str>,
) -> Result<i64, sqlx::Error> {
    insert_ip_entries(pool, "api_key_ip_whitelist", api_key_id, addrs, label).await
}

pub async fn upsert_blacklist_entries(
    pool: &PgPool,
    api_key_id: i64,
    addrs: &[IpNetwork],
    label: Option<&str>,
) -> Result<i64, sqlx::Error> {
    insert_ip_entries(pool, "api_key_ip_blacklist", api_key_id, addrs, label).await
}

pub async fn delete_whitelist_entries(
    pool: &PgPool,
    api_key_id: i64,
    addrs: &[IpNetwork],
) -> Result<i64, sqlx::Error> {
    delete_ip_entries(pool, "api_key_ip_whitelist", api_key_id, addrs).await
}

pub async fn delete_blacklist_entries(
    pool: &PgPool,
    api_key_id: i64,
    addrs: &[IpNetwork],
) -> Result<i64, sqlx::Error> {
    delete_ip_entries(pool, "api_key_ip_blacklist", api_key_id, addrs).await
}

async fn insert_ip_entries(
    pool: &PgPool,
    table: &str,
    api_key_id: i64,
    addrs: &[IpNetwork],
    label: Option<&str>,
) -> Result<i64, sqlx::Error> {
    if addrs.is_empty() {
        return Ok(0);
    }

    // `table` is picked from the fixed allow-list above; interpolation is safe.
    let sql: String = format!(
        r#"
        INSERT INTO {table} (api_key_id, addr, label)
        SELECT $1, addr, $3
        FROM UNNEST($2::cidr[]) AS t(addr)
        ON CONFLICT (api_key_id, addr) DO NOTHING
        "#,
    );

    let result = sqlx::query(&sql)
        .bind(api_key_id)
        .bind(addrs)
        .bind(label)
        .execute(pool)
        .await?;

    Ok(result.rows_affected() as i64)
}

async fn delete_ip_entries(
    pool: &PgPool,
    table: &str,
    api_key_id: i64,
    addrs: &[IpNetwork],
) -> Result<i64, sqlx::Error> {
    if addrs.is_empty() {
        return Ok(0);
    }

    let sql: String = format!(
        r#"
        DELETE FROM {table}
        WHERE api_key_id = $1
          AND addr = ANY($2::cidr[])
        "#,
    );

    let result = sqlx::query(&sql)
        .bind(api_key_id)
        .bind(addrs)
        .execute(pool)
        .await?;

    Ok(result.rows_affected() as i64)
}

/// Scope identifier for global IP list entries.
#[derive(Debug, Clone, Serialize)]
pub struct GlobalIpRule {
    pub id: String,
    pub addr: String,
    pub client_name: Option<String>,
    pub label: Option<String>,
    pub created_at: DateTime<Utc>,
}

pub async fn list_global_whitelist(pool: &PgPool) -> Result<Vec<GlobalIpRule>, sqlx::Error> {
    list_global_rules(pool, "api_key_ip_global_whitelist").await
}

pub async fn list_global_blacklist(pool: &PgPool) -> Result<Vec<GlobalIpRule>, sqlx::Error> {
    list_global_rules(pool, "api_key_ip_global_blacklist").await
}

async fn list_global_rules(pool: &PgPool, table: &str) -> Result<Vec<GlobalIpRule>, sqlx::Error> {
    let id_column = format!("{}_id", table);
    let sql: String = format!(
        r#"
        SELECT {id_column} AS id, addr, client_name, label, created_at
        FROM {table}
        ORDER BY created_at
        "#,
    );

    let rows: Vec<PgRow> = sqlx::query(&sql).fetch_all(pool).await?;
    rows.into_iter()
        .map(|row| {
            let id: uuid::Uuid = row.try_get("id")?;
            let addr: IpNetwork = row.try_get("addr")?;
            Ok(GlobalIpRule {
                id: id.to_string(),
                addr: addr.to_string(),
                client_name: row.try_get("client_name")?,
                label: row.try_get("label")?,
                created_at: row.try_get("created_at")?,
            })
        })
        .collect()
}

pub async fn insert_global_whitelist_entry(
    pool: &PgPool,
    addr: IpNetwork,
    client_name: Option<&str>,
    label: Option<&str>,
) -> Result<GlobalIpRule, sqlx::Error> {
    insert_global_entry(
        pool,
        "api_key_ip_global_whitelist",
        addr,
        client_name,
        label,
    )
    .await
}

pub async fn insert_global_blacklist_entry(
    pool: &PgPool,
    addr: IpNetwork,
    client_name: Option<&str>,
    label: Option<&str>,
) -> Result<GlobalIpRule, sqlx::Error> {
    insert_global_entry(
        pool,
        "api_key_ip_global_blacklist",
        addr,
        client_name,
        label,
    )
    .await
}

async fn insert_global_entry(
    pool: &PgPool,
    table: &str,
    addr: IpNetwork,
    client_name: Option<&str>,
    label: Option<&str>,
) -> Result<GlobalIpRule, sqlx::Error> {
    let id_column = format!("{}_id", table);
    let sql: String = format!(
        r#"
        INSERT INTO {table} (addr, client_name, label)
        VALUES ($1, $2, $3)
        ON CONFLICT (addr, client_name)
        DO UPDATE SET label = EXCLUDED.label
        RETURNING {id_column} AS id, addr, client_name, label, created_at
        "#,
    );

    let row: PgRow = sqlx::query(&sql)
        .bind(addr)
        .bind(client_name)
        .bind(label)
        .fetch_one(pool)
        .await?;

    let id: uuid::Uuid = row.try_get("id")?;
    let stored_addr: IpNetwork = row.try_get("addr")?;
    Ok(GlobalIpRule {
        id: id.to_string(),
        addr: stored_addr.to_string(),
        client_name: row.try_get("client_name")?,
        label: row.try_get("label")?,
        created_at: row.try_get("created_at")?,
    })
}

pub async fn delete_global_whitelist_entry(
    pool: &PgPool,
    addr: IpNetwork,
    client_name: Option<&str>,
) -> Result<bool, sqlx::Error> {
    delete_global_entry(pool, "api_key_ip_global_whitelist", addr, client_name).await
}

pub async fn delete_global_blacklist_entry(
    pool: &PgPool,
    addr: IpNetwork,
    client_name: Option<&str>,
) -> Result<bool, sqlx::Error> {
    delete_global_entry(pool, "api_key_ip_global_blacklist", addr, client_name).await
}

async fn delete_global_entry(
    pool: &PgPool,
    table: &str,
    addr: IpNetwork,
    client_name: Option<&str>,
) -> Result<bool, sqlx::Error> {
    let sql: String = format!(
        r#"
        DELETE FROM {table}
        WHERE addr = $1
          AND ((client_name IS NULL AND $2::text IS NULL) OR client_name = $2)
        "#,
    );

    let result = sqlx::query(&sql)
        .bind(addr)
        .bind(client_name)
        .execute(pool)
        .await?;

    Ok(result.rows_affected() > 0)
}

/// Convenience: returns `true` if any rule in `rules` contains `ip`.
pub fn ip_matches_any(rules: &[IpRule], ip: IpAddr) -> bool {
    rules
        .iter()
        .any(|rule| match rule.addr.parse::<IpNetwork>() {
            Ok(network) => network.contains(ip),
            Err(_) => false,
        })
}