solid-pod-rs-idp 0.4.0-alpha.2

Solid-OIDC identity provider (authorization-code + DPoP-bound tokens, JWKS, credentials, dynamic client registration) — Rust port of JavaScriptSolidServer/src/idp
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
//! `/idp/credentials` — email+password login flow (row 79).
//!
//! JSS parity: `src/idp/credentials.js:28-150`. The JSS endpoint
//! accepts `email`+`password` (or `username`+`password`), optionally
//! binds to a DPoP proof, and returns an access-token JSON body.
//!
//! Rate-limiting is bolted on via the core crate's `RateLimiter`
//! trait, keyed by `(route="idp_credentials", subject=IP)`. The
//! default policy shipped by core is 60/min which is too generous
//! for brute-force protection; this module accepts a caller-supplied
//! limiter so consumers can plug in `LruRateLimiter::with_policy`
//! with `("idp_credentials", 10, Duration::from_secs(60))` to match
//! JSS (`src/idp/index.js:255-265`).

use std::net::IpAddr;

use serde::{Deserialize, Serialize};
use thiserror::Error;

use solid_pod_rs::security::rate_limit::{
    RateLimitDecision, RateLimitKey, RateLimitSubject, RateLimiter,
};

use crate::jwks::Jwks;
use crate::tokens::{issue_access_token, AccessToken};
use crate::user_store::{User, UserStore};

/// Minimum password length enforced at registration time.
/// Mirrors JSS commit `1feead2` which rejects passwords shorter than
/// 8 characters.
pub const MIN_PASSWORD_LENGTH: usize = 8;

/// Rate-limit route name we share with the rest of the crate. JSS
/// mirrors this as `/idp/credentials` — we drop the path prefix and
/// use the canonical name so operator metrics don't need to strip.
pub const RATE_LIMIT_ROUTE: &str = "idp_credentials";

/// Errors surfaced by [`login`].
#[derive(Debug, Error)]
pub enum LoginError {
    /// Request is rate-limited. The JSS handler returns 429.
    #[error("rate limited, retry after {retry_after_secs}s")]
    RateLimited {
        /// Seconds the client should wait.
        retry_after_secs: u64,
    },

    /// Unknown user, wrong password, etc. JSS returns
    /// `{"error":"invalid_grant"}` with HTTP 401.
    #[error("invalid credentials")]
    InvalidGrant,

    /// Password does not meet the minimum length requirement.
    /// JSS commit `1feead2` enforces >= 8 characters.
    #[error("password must be at least {min_length} characters")]
    PasswordTooShort {
        /// The minimum length that was not met.
        min_length: usize,
    },

    /// Caller passed a malformed body.
    #[error("invalid request: {0}")]
    InvalidRequest(String),

    /// Store backend exploded.
    #[error("user store: {0}")]
    UserStore(String),

    /// Token signing failed.
    #[error("token issuance: {0}")]
    Token(String),
}

/// Response body matching JSS `src/idp/credentials.js:138-145`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialsResponse {
    /// Signed access token (JWT).
    pub access_token: String,
    /// `"DPoP"` when a valid proof was supplied, else `"Bearer"`.
    pub token_type: String,
    /// Lifetime in seconds.
    pub expires_in: u64,
    /// Authenticated WebID.
    pub webid: String,
    /// Internal account id.
    pub id: String,
}

/// Email+password login.
///
/// - `email` / `password` — user-supplied credentials. Email is
///   case-normalised before lookup (matches [`UserStore`] contract).
/// - `user_store` — source of truth for the account record.
/// - `jwks` — signing keys; the active key is used to sign the
///   returned access token.
/// - `issuer` — issuer URL (must match discovery's `issuer`).
/// - `dpop_jkt` — when the caller has already verified a DPoP proof
///   from the Authorization-adjacent `DPoP` header, pass the proof's
///   `jkt` here. The token is then marked DPoP-bound.
/// - `limiter` + `ip` — rate-limit subject. Callers who do not want
///   rate limits can pass a `NoopRateLimiter` (tests only).
/// - `ttl_secs` — access-token TTL. JSS defaults to 3600.
#[allow(clippy::too_many_arguments)]
pub async fn login(
    email: &str,
    password: &str,
    user_store: &dyn UserStore,
    jwks: &Jwks,
    issuer: &str,
    dpop_jkt: Option<&str>,
    limiter: &dyn RateLimiter,
    ip: IpAddr,
    now: u64,
    ttl_secs: u64,
) -> Result<CredentialsResponse, LoginError> {
    // --- rate-limit gate ----------------------------------------------------
    let key = RateLimitKey {
        route: RATE_LIMIT_ROUTE,
        subject: RateLimitSubject::Ip(ip),
    };
    match limiter.check(&key).await {
        RateLimitDecision::Allow => {}
        RateLimitDecision::Deny {
            retry_after_secs, ..
        } => return Err(LoginError::RateLimited { retry_after_secs }),
    }

    // --- input validation ---------------------------------------------------
    if email.is_empty() || password.is_empty() {
        return Err(LoginError::InvalidRequest(
            "email and password are required".into(),
        ));
    }

    // --- authentication -----------------------------------------------------
    let user: Option<User> = user_store
        .find_by_email(email)
        .await
        .map_err(|e| LoginError::UserStore(e.to_string()))?;

    let Some(user) = user else {
        return Err(LoginError::InvalidGrant);
    };

    let ok = user_store
        .verify_password(&user, password)
        .await
        .map_err(|e| LoginError::UserStore(e.to_string()))?;
    if !ok {
        return Err(LoginError::InvalidGrant);
    }

    // --- token issuance -----------------------------------------------------
    let key = jwks.active_key();
    let token: AccessToken = issue_access_token(
        &key,
        issuer,
        &user.webid,
        &user.id,
        "credentials_client", // Matches JSS line 121.
        "openid webid",
        dpop_jkt,
        now,
        ttl_secs,
    )
    .map_err(|e| LoginError::Token(e.to_string()))?;

    Ok(CredentialsResponse {
        access_token: token.jwt,
        token_type: if dpop_jkt.is_some() {
            "DPoP".into()
        } else {
            "Bearer".into()
        },
        expires_in: ttl_secs,
        webid: user.webid,
        id: user.id,
    })
}

/// Validate that a password meets the minimum length requirement.
///
/// Returns `Ok(())` when the password is at least [`MIN_PASSWORD_LENGTH`]
/// characters, or `Err(LoginError::PasswordTooShort)` otherwise. Empty
/// passwords are also rejected (they are shorter than 8 chars).
///
/// This is a standalone helper so both the credentials endpoint and
/// any registration flow can share the same policy.
pub fn validate_password_length(password: &str) -> Result<(), LoginError> {
    if password.len() < MIN_PASSWORD_LENGTH {
        return Err(LoginError::PasswordTooShort {
            min_length: MIN_PASSWORD_LENGTH,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;
    use std::time::Duration;

    use solid_pod_rs::security::rate_limit::LruRateLimiter;

    use crate::jwks::Jwks;
    use crate::user_store::InMemoryUserStore;

    fn ip() -> IpAddr {
        IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1))
    }

    fn seed() -> (InMemoryUserStore, Jwks, LruRateLimiter) {
        let store = InMemoryUserStore::new();
        store
            .insert_user(
                "acct-1",
                "alice@example.com",
                "https://alice.example/profile#me",
                Some("Alice".into()),
                "hunter2!",
            )
            .unwrap();
        let jwks = Jwks::generate_es256().unwrap();
        // JSS policy: 10 per minute.
        let limiter = LruRateLimiter::with_policy(vec![(
            RATE_LIMIT_ROUTE.to_string(),
            10,
            Duration::from_secs(60),
        )]);
        (store, jwks, limiter)
    }

    #[tokio::test]
    async fn login_succeeds_with_correct_password() {
        let (store, jwks, limiter) = seed();
        let resp = login(
            "alice@example.com",
            "hunter2!",
            &store,
            &jwks,
            "https://pod.example/",
            Some("JKT-OK"),
            &limiter,
            ip(),
            1_700_000_000,
            3600,
        )
        .await
        .unwrap();
        assert_eq!(resp.token_type, "DPoP");
        assert_eq!(resp.webid, "https://alice.example/profile#me");
        assert_eq!(resp.expires_in, 3600);
        assert!(resp.access_token.contains('.'));
    }

    #[tokio::test]
    async fn login_returns_bearer_when_no_dpop() {
        let (store, jwks, limiter) = seed();
        let resp = login(
            "alice@example.com",
            "hunter2!",
            &store,
            &jwks,
            "https://pod.example/",
            None,
            &limiter,
            ip(),
            1_700_000_000,
            3600,
        )
        .await
        .unwrap();
        assert_eq!(resp.token_type, "Bearer");
    }

    #[tokio::test]
    async fn login_rejects_wrong_password() {
        let (store, jwks, limiter) = seed();
        let err = login(
            "alice@example.com",
            "nope",
            &store,
            &jwks,
            "https://pod.example/",
            None,
            &limiter,
            ip(),
            1_700_000_000,
            3600,
        )
        .await
        .unwrap_err();
        assert!(matches!(err, LoginError::InvalidGrant));
    }

    #[tokio::test]
    async fn login_rejects_unknown_user() {
        let (store, jwks, limiter) = seed();
        let err = login(
            "nobody@example.com",
            "hunter2!",
            &store,
            &jwks,
            "https://pod.example/",
            None,
            &limiter,
            ip(),
            1_700_000_000,
            3600,
        )
        .await
        .unwrap_err();
        assert!(matches!(err, LoginError::InvalidGrant));
    }

    #[tokio::test]
    async fn login_rate_limited_after_ten_attempts() {
        let (store, jwks, limiter) = seed();
        for _ in 0..10 {
            // Deliberate wrong password — we're stress-testing the
            // limiter, not the happy path.
            let _ = login(
                "alice@example.com",
                "wrong",
                &store,
                &jwks,
                "https://pod.example/",
                None,
                &limiter,
                ip(),
                1_700_000_000,
                3600,
            )
            .await;
        }
        let err = login(
            "alice@example.com",
            "hunter2!",
            &store,
            &jwks,
            "https://pod.example/",
            None,
            &limiter,
            ip(),
            1_700_000_000,
            3600,
        )
        .await
        .unwrap_err();
        match err {
            LoginError::RateLimited { retry_after_secs } => {
                assert!(retry_after_secs >= 1);
            }
            other => panic!("expected RateLimited, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn login_rejects_blank_input() {
        let (store, jwks, limiter) = seed();
        let err = login(
            "",
            "",
            &store,
            &jwks,
            "https://pod.example/",
            None,
            &limiter,
            ip(),
            0,
            3600,
        )
        .await
        .unwrap_err();
        assert!(matches!(err, LoginError::InvalidRequest(_)));
    }

    // ---- password-length validation (JSS commit 1feead2) ----

    #[test]
    fn password_too_short_7_chars_rejected() {
        let err = validate_password_length("1234567").unwrap_err();
        match err {
            LoginError::PasswordTooShort { min_length } => {
                assert_eq!(min_length, 8);
            }
            other => panic!("expected PasswordTooShort, got {other:?}"),
        }
    }

    #[test]
    fn password_exactly_8_chars_accepted() {
        validate_password_length("12345678").unwrap();
    }

    #[test]
    fn password_longer_than_8_chars_accepted() {
        validate_password_length("a]9Kz!#mN@xP").unwrap();
    }

    #[test]
    fn empty_password_rejected() {
        let err = validate_password_length("").unwrap_err();
        match err {
            LoginError::PasswordTooShort { min_length } => {
                assert_eq!(min_length, 8);
            }
            other => panic!("expected PasswordTooShort, got {other:?}"),
        }
    }

    #[test]
    fn min_password_length_constant_is_8() {
        assert_eq!(MIN_PASSWORD_LENGTH, 8);
    }
}