mockforge-http 0.3.116

HTTP/REST protocol support for MockForge
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
//! Consent screen handlers
//!
//! This module provides endpoints for OAuth2 consent screens with
//! permissions/scopes toggles and risk simulation integration.

use axum::{
    extract::{Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, Json},
};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;

use crate::auth::risk_engine::{RiskAction, RiskEngine};
use crate::handlers::oauth2_server::OAuth2ServerState;

/// Consent request parameters
#[derive(Debug, Deserialize)]
pub struct ConsentRequest {
    /// Client ID
    pub client_id: String,
    /// Scopes (space-separated)
    pub scope: Option<String>,
    /// State parameter
    pub state: Option<String>,
    /// Authorization code (if consent already given)
    pub code: Option<String>,
    /// Redirect URI for the OAuth2 flow
    pub redirect_uri: Option<String>,
}

/// Consent decision request
#[derive(Debug, Deserialize)]
pub struct ConsentDecisionRequest {
    /// Client ID
    pub client_id: String,
    /// State parameter
    pub state: Option<String>,
    /// Whether consent was approved
    pub approved: bool,
    /// Approved scopes
    pub scopes: Vec<String>,
    /// Redirect URI for the OAuth2 flow
    pub redirect_uri: Option<String>,
}

/// Consent screen state
#[derive(Clone)]
pub struct ConsentState {
    /// OAuth2 server state
    pub oauth2_state: OAuth2ServerState,
    /// Risk engine
    pub risk_engine: Arc<RiskEngine>,
}

/// Get consent screen
pub async fn get_consent_screen(
    State(state): State<ConsentState>,
    headers: HeaderMap,
    Query(params): Query<ConsentRequest>,
) -> Result<Html<String>, StatusCode> {
    // Extract risk factors from request context
    let mut risk_factors: HashMap<String, f64> = HashMap::new();

    // IP-based risk: unknown IPs get a baseline factor
    if let Some(ip) = headers
        .get("x-forwarded-for")
        .or_else(|| headers.get("x-real-ip"))
        .and_then(|h| h.to_str().ok())
    {
        // Loopback/private IPs are lower risk
        let ip_trimmed = ip.split(',').next().unwrap_or(ip).trim();
        let ip_risk = if ip_trimmed.starts_with("127.")
            || ip_trimmed == "::1"
            || ip_trimmed.starts_with("10.")
            || ip_trimmed.starts_with("192.168.")
        {
            0.1
        } else {
            0.3
        };
        risk_factors.insert("ip_risk".to_string(), ip_risk);
    }

    // User-agent risk: missing or unusual user agents are higher risk
    if let Some(ua) = headers.get("user-agent").and_then(|h| h.to_str().ok()) {
        let ua_risk = if ua.contains("bot") || ua.contains("curl") || ua.contains("wget") {
            0.5
        } else {
            0.1
        };
        risk_factors.insert("user_agent_risk".to_string(), ua_risk);
    } else {
        risk_factors.insert("user_agent_risk".to_string(), 0.6);
    }

    let risk_assessment = state.risk_engine.assess_risk("user-default", &risk_factors).await;

    // If risk is too high, block or require additional verification
    if risk_assessment.recommended_action == RiskAction::Block {
        return Ok(Html(blocked_login_html()));
    }

    // Parse scopes
    let scopes = params
        .scope
        .as_ref()
        .map(|s| s.split(' ').map(|s| s.to_string()).collect::<Vec<_>>())
        .unwrap_or_else(Vec::new);

    // Generate consent screen HTML
    let html = generate_consent_screen_html(
        &params.client_id,
        &scopes,
        params.state.as_deref(),
        params.redirect_uri.as_deref(),
    );
    Ok(Html(html))
}

/// Submit consent decision
pub async fn submit_consent(
    State(state): State<ConsentState>,
    Json(request): Json<ConsentDecisionRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    if !request.approved {
        return Ok(Json(serde_json::json!({
            "approved": false,
            "message": "Consent denied"
        })));
    }

    // Generate authorization code and store it in OAuth2 state
    let code = uuid::Uuid::new_v4().to_string();
    let expires_at = chrono::Utc::now().timestamp() + 600; // 10 minute expiry

    let code_info = crate::handlers::oauth2_server::AuthorizationCodeInfo {
        client_id: request.client_id.clone(),
        redirect_uri: request.redirect_uri.clone().unwrap_or_default(),
        scopes: request.scopes.clone(),
        user_id: "consent-user".to_string(),
        state: request.state.clone(),
        expires_at,
        tenant_context: None,
    };

    // Store the authorization code
    {
        let mut auth_codes = state.oauth2_state.auth_codes.write().await;
        auth_codes.insert(code.clone(), code_info);
    }

    Ok(Json(serde_json::json!({
        "approved": true,
        "scopes": request.scopes,
        "code": code,
        "message": "Consent approved"
    })))
}

/// Generate consent screen HTML
fn generate_consent_screen_html(
    client_id: &str,
    scopes: &[String],
    state: Option<&str>,
    redirect_uri: Option<&str>,
) -> String {
    let scope_items = scopes
        .iter()
        .map(|scope| {
            let description = get_scope_description(scope);
            format!(
                r#"
                <div class="scope-item">
                    <label class="scope-toggle">
                        <input type="checkbox" name="scope" value="{}" checked>
                        <span class="scope-name">{}</span>
                    </label>
                    <p class="scope-description">{}</p>
                </div>
                "#,
                scope, scope, description
            )
        })
        .collect::<String>();

    let state_param = state
        .map(|s| format!(r#"<input type="hidden" name="state" value="{}">"#, s))
        .unwrap_or_default();

    let redirect_uri_param = redirect_uri
        .map(|u| format!(r#"<input type="hidden" name="redirect_uri" value="{}">"#, u))
        .unwrap_or_default();

    format!(
        r#"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Authorize Application - MockForge</title>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }}
        .consent-container {{
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 500px;
            width: 100%;
            padding: 40px;
            animation: slideUp 0.3s ease-out;
        }}
        @keyframes slideUp {{
            from {{
                opacity: 0;
                transform: translateY(20px);
            }}
            to {{
                opacity: 1;
                transform: translateY(0);
            }}
        }}
        .app-icon {{
            width: 64px;
            height: 64px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            margin: 0 auto 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            color: white;
        }}
        h1 {{
            font-size: 24px;
            font-weight: 600;
            text-align: center;
            margin-bottom: 8px;
            color: #1a1a1a;
        }}
        .client-id {{
            text-align: center;
            color: #666;
            font-size: 14px;
            margin-bottom: 32px;
        }}
        .permissions-title {{
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #1a1a1a;
        }}
        .scope-item {{
            padding: 16px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            margin-bottom: 12px;
            transition: all 0.2s;
        }}
        .scope-item:hover {{
            border-color: #667eea;
            background: #f8f9ff;
        }}
        .scope-toggle {{
            display: flex;
            align-items: center;
            cursor: pointer;
            margin-bottom: 8px;
        }}
        .scope-toggle input[type="checkbox"] {{
            width: 20px;
            height: 20px;
            margin-right: 12px;
            cursor: pointer;
            accent-color: #667eea;
        }}
        .scope-name {{
            font-weight: 500;
            color: #1a1a1a;
        }}
        .scope-description {{
            font-size: 13px;
            color: #666;
            margin-left: 32px;
            line-height: 1.5;
        }}
        .buttons {{
            display: flex;
            gap: 12px;
            margin-top: 32px;
        }}
        button {{
            flex: 1;
            padding: 14px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }}
        .btn-approve {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }}
        .btn-approve:hover {{
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }}
        .btn-deny {{
            background: #f5f5f5;
            color: #666;
        }}
        .btn-deny:hover {{
            background: #e5e5e5;
        }}
        .privacy-link {{
            text-align: center;
            margin-top: 24px;
            font-size: 13px;
            color: #666;
        }}
        .privacy-link a {{
            color: #667eea;
            text-decoration: none;
        }}
        .privacy-link a:hover {{
            text-decoration: underline;
        }}
    </style>
</head>
<body>
    <div class="consent-container">
        <div class="app-icon">🔐</div>
        <h1>Authorize Application</h1>
        <p class="client-id">{}</p>

        <p class="permissions-title">This application is requesting the following permissions:</p>

        <form id="consent-form" method="POST" action="/consent/decision">
            <input type="hidden" name="client_id" value="{}">
            {}
            {}
            <div class="scopes">
                {}
            </div>

            <div class="buttons">
                <button type="submit" class="btn-approve" name="approved" value="true">
                    Approve
                </button>
                <button type="button" class="btn-deny" onclick="denyConsent()">
                    Deny
                </button>
            </div>
        </form>

        <div class="privacy-link">
            By approving, you agree to our <a href="/privacy">Privacy Policy</a> and <a href="/terms">Terms of Service</a>.
        </div>
    </div>

    <script>
        function denyConsent() {{
            document.getElementById('consent-form').innerHTML += '<input type="hidden" name="approved" value="false">';
            document.getElementById('consent-form').submit();
        }}
    </script>
</body>
</html>
        "#,
        client_id, client_id, state_param, redirect_uri_param, scope_items
    )
}

/// Get scope description
fn get_scope_description(scope: &str) -> &str {
    match scope {
        "openid" => "Access your basic profile information",
        "profile" => "Access your profile information including name and picture",
        "email" => "Access your email address",
        "address" => "Access your address information",
        "phone" => "Access your phone number",
        "offline_access" => "Access your information while you're offline",
        _ => "Access to this permission",
    }
}

/// Generate blocked login HTML
fn blocked_login_html() -> String {
    r#"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Blocked - MockForge</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .blocked-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 400px;
            width: 100%;
            padding: 40px;
            text-align: center;
        }
        .icon {
            font-size: 64px;
            margin-bottom: 24px;
        }
        h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #1a1a1a;
        }
        p {
            color: #666;
            line-height: 1.6;
            margin-bottom: 24px;
        }
    </style>
</head>
<body>
    <div class="blocked-container">
        <div class="icon">🚫</div>
        <h1>Login Blocked</h1>
        <p>Your login attempt has been blocked due to security concerns. Please contact support if you believe this is an error.</p>
    </div>
</body>
</html>
    "#.to_string()
}

/// Create consent router
pub fn consent_router(state: ConsentState) -> axum::Router {
    use axum::routing::{get, post};

    axum::Router::new()
        .route("/consent", get(get_consent_screen))
        .route("/consent/decision", post(submit_consent))
        .with_state(state)
}