1
//! Slice B: per-user JWT signing keys, end to end against real Postgres.
2
//!
3
//! Verifies the security-critical properties of the cutover: a user's token
4
//! signed with their own private key verifies against their public key, and a
5
//! token is REJECTED when checked against a different user's key (forgery /
6
//! cross-user isolation). Mirrors the web layer's mint → verify path using the
7
//! same `server::auth_keys` lookups and PEM wire form.
8
//!
9
//! Run via:
10
//!   DATABASE_URL=postgres://… cargo test -p tests-integration --features db
11

            
12
#![cfg(feature = "db")]
13

            
14
use base64::{Engine as _, engine::general_purpose::STANDARD};
15
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
16
use serde::{Deserialize, Serialize};
17
use sqlx::postgres::PgPoolOptions;
18
use tests_integration::tenant_guard::TestTenant;
19

            
20
#[derive(Serialize, Deserialize)]
21
struct Claims {
22
    sub: String,
23
    exp: i64,
24
}
25

            
26
5
fn decode_b64_pem(b64: &str) -> Vec<u8> {
27
5
    STANDARD.decode(b64).expect("base64 pem")
28
5
}
29

            
30
2
fn sign(private_pem_b64: &str, sub: &str) -> String {
31
2
    let pem = decode_b64_pem(private_pem_b64);
32
2
    let claims = Claims {
33
2
        sub: sub.to_string(),
34
2
        exp: 9_999_999_999,
35
2
    };
36
2
    encode(
37
2
        &Header::new(Algorithm::RS256),
38
2
        &claims,
39
2
        &EncodingKey::from_rsa_pem(&pem).expect("encoding key"),
40
2
    )
41
2
    .expect("sign")
42
2
}
43

            
44
3
fn verifies_against(public_pem_b64: &str, token: &str) -> bool {
45
3
    let pem = decode_b64_pem(public_pem_b64);
46
3
    let key = match DecodingKey::from_rsa_pem(&pem) {
47
3
        Ok(k) => k,
48
        Err(_) => return false,
49
    };
50
3
    decode::<Claims>(token, &key, &Validation::new(Algorithm::RS256)).is_ok()
51
3
}
52

            
53
// One `#[tokio::test]` so the process-static admin pool keeps a stable lifetime
54
// across scenarios (see the provisioning test for the rationale).
55
#[tokio::test]
56
1
async fn per_user_signing_keys_end_to_end() -> anyhow::Result<()> {
57
1
    sign_verify_and_reject_cross_user().await?;
58
1
    stored_key_round_trips_through_lookup().await?;
59
2
    Ok(())
60
1
}
61

            
62
/// A token verifies against its own signer's public key and is REJECTED against
63
/// a different user's key (cross-user isolation / forgery guarantee).
64
1
async fn sign_verify_and_reject_cross_user() -> anyhow::Result<()> {
65
1
    let user_a = server::auth_keys::generate().await?;
66
1
    let user_b = server::auth_keys::generate().await?;
67

            
68
1
    let token_a = sign(&user_a.private_pem_b64, "user-a");
69

            
70
1
    assert!(
71
1
        verifies_against(&user_a.public_pem_b64, &token_a),
72
        "token must verify against its own signer's public key"
73
    );
74
1
    assert!(
75
1
        !verifies_against(&user_b.public_pem_b64, &token_a),
76
        "token must NOT verify against a different user's public key"
77
    );
78
1
    Ok(())
79
1
}
80

            
81
/// Provision a real per-user DB, store a generated private key, read it back via
82
/// the same lookup the mint path uses, and prove a token it signs verifies
83
/// against the public half.
84
1
async fn stored_key_round_trips_through_lookup() -> anyhow::Result<()> {
85
1
    let user_id = uuid::Uuid::new_v4();
86
1
    let _tenant = TestTenant::tenant(user_id, format!("nomi_user_{}", user_id.simple()));
87
1
    let keypair = server::auth_keys::generate().await?;
88

            
89
1
    let dsn = server::provision::create_user_database(user_id).await?;
90
1
    server::provision::store_user_private_key(&dsn, &keypair.private_pem_b64).await?;
91

            
92
    // private_key_for routes through userpool, which resolves the per-user DB
93
    // from the global users.db_name — so the user must exist in the directory.
94
1
    let admin_url = std::env::var("DATABASE_URL")?;
95
1
    let directory = PgPoolOptions::new()
96
1
        .max_connections(1)
97
1
        .connect(&admin_url)
98
1
        .await?;
99
1
    sqlx::query(
100
1
        // `verified` defaults FALSE, and this row is routed through the real
101
1
        // tenant pool, which refuses a disabled account.
102
1
        "INSERT INTO users (id, user_name, email, user_password, database_name, jwt_public_key, verified) \
103
1
         VALUES ($1, 'authkey-test', $2, 'x', $3, $4, TRUE)",
104
1
    )
105
1
    .bind(user_id)
106
1
    .bind(format!("authkey-{user_id}@example.test"))
107
1
    .bind(&dsn)
108
1
    .bind(&keypair.public_pem_b64)
109
1
    .execute(&directory)
110
1
    .await?;
111

            
112
1
    let fetched_private = server::auth_keys::private_key_for(user_id).await?;
113
1
    assert_eq!(fetched_private, keypair.private_pem_b64);
114

            
115
1
    let fetched_public = server::auth_keys::public_key_for(user_id)
116
1
        .await?
117
1
        .expect("identity");
118
1
    assert_eq!(fetched_public.public_key, keypair.public_pem_b64);
119
1
    assert!(fetched_public.verified);
120

            
121
1
    let token = sign(&fetched_private, &user_id.to_string());
122
1
    assert!(verifies_against(&keypair.public_pem_b64, &token));
123

            
124
1
    directory.close().await;
125
1
    Ok(())
126
1
}