kaccy-api 0.2.0

REST API and WebSocket server for Kaccy Protocol - comprehensive backend service
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
//! Integration tests for Kaccy API
//!
//! These tests verify end-to-end functionality of the API endpoints.
//! Note: These tests require a running database and Bitcoin node.

#[cfg(test)]
mod integration_tests {
    use serde_json::json;

    /// Test helper to build API base URL
    fn api_url(path: &str) -> String {
        format!("http://localhost:3000{}", path)
    }

    /// Test data structures
    #[derive(Debug, serde::Deserialize)]
    struct AuthResponse {
        token: String,
        user: serde_json::Value,
    }

    #[allow(dead_code)]
    #[derive(Debug, serde::Deserialize)]
    struct ErrorResponse {
        error: String,
        message: String,
    }

    /// Helper to create test user credentials
    fn test_credentials(suffix: &str) -> (String, String, String) {
        (
            format!("test{}@example.com", suffix),
            "SecureTestPass123!".to_string(),
            format!("testuser{}", suffix),
        )
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_user_registration_flow() {
        let client = reqwest::Client::new();
        let (email, password, username) = test_credentials("_reg");

        // Register a new user
        let response = client
            .post(api_url("/api/auth/register"))
            .json(&json!({
                "email": email,
                "password": password,
                "username": username
            }))
            .send()
            .await
            .expect("Failed to send registration request");

        assert_eq!(response.status(), 200);

        let auth_response: AuthResponse = response.json().await.expect("Failed to parse response");
        assert!(!auth_response.token.is_empty());
        assert_eq!(auth_response.user["username"], username);
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_duplicate_email_registration() {
        let client = reqwest::Client::new();
        let (email, password, username) = test_credentials("_dup");

        // First registration should succeed
        let _ = client
            .post(api_url("/api/auth/register"))
            .json(&json!({
                "email": email,
                "password": password,
                "username": username
            }))
            .send()
            .await;

        // Second registration with same email should fail
        let response = client
            .post(api_url("/api/auth/register"))
            .json(&json!({
                "email": email,
                "password": password,
                "username": format!("{}_2", username)
            }))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 400);
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_login_flow() {
        let client = reqwest::Client::new();
        let (email, password, username) = test_credentials("_login");

        // Register user first
        let _ = client
            .post(api_url("/api/auth/register"))
            .json(&json!({
                "email": email,
                "password": password,
                "username": username
            }))
            .send()
            .await;

        // Then login
        let response = client
            .post(api_url("/api/auth/login"))
            .json(&json!({
                "email": email,
                "password": password
            }))
            .send()
            .await
            .expect("Failed to send login request");

        assert_eq!(response.status(), 200);

        let auth_response: AuthResponse = response.json().await.expect("Failed to parse response");
        assert!(!auth_response.token.is_empty());
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_invalid_login() {
        let client = reqwest::Client::new();

        let response = client
            .post(api_url("/api/auth/login"))
            .json(&json!({
                "email": "nonexistent@example.com",
                "password": "wrongpassword"
            }))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 401);
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_protected_endpoint_without_auth() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/api/users/me"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 401);
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_protected_endpoint_with_auth() {
        let client = reqwest::Client::new();
        let (email, password, username) = test_credentials("_protected");

        // Register and get token
        let auth_response: AuthResponse = client
            .post(api_url("/api/auth/register"))
            .json(&json!({
                "email": email,
                "password": password,
                "username": username
            }))
            .send()
            .await
            .expect("Failed to register")
            .json()
            .await
            .expect("Failed to parse");

        // Access protected endpoint
        let response = client
            .get(api_url("/api/users/me"))
            .header("Authorization", format!("Bearer {}", auth_response.token))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let user: serde_json::Value = response.json().await.expect("Failed to parse");
        assert_eq!(user["email"], email);
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_token_listing() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/api/tokens"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let data: serde_json::Value = response.json().await.expect("Failed to parse");
        assert!(data["tokens"].is_array());
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_pagination() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/api/tokens?page=1&per_page=10"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let data: serde_json::Value = response.json().await.expect("Failed to parse");
        assert_eq!(data["page"], 1);
        assert_eq!(data["per_page"], 10);
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_health_check() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/health"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let data: serde_json::Value = response.json().await.expect("Failed to parse");
        assert_eq!(data["status"], "healthy");
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_detailed_health_check() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/health/detailed"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let data: serde_json::Value = response.json().await.expect("Failed to parse");
        assert!(data["database"].is_string());
        assert!(data["db_latency_ms"].is_number());
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_profile_update() {
        let client = reqwest::Client::new();
        let (email, password, username) = test_credentials("_profile");

        // Register user
        let auth_response: AuthResponse = client
            .post(api_url("/api/auth/register"))
            .json(&json!({
                "email": email,
                "password": password,
                "username": username
            }))
            .send()
            .await
            .expect("Failed to register")
            .json()
            .await
            .expect("Failed to parse");

        // Update profile
        let response = client
            .put(api_url("/api/users/me"))
            .header("Authorization", format!("Bearer {}", auth_response.token))
            .json(&json!({
                "display_name": "Test User",
                "bio": "This is a test bio"
            }))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let user: serde_json::Value = response.json().await.expect("Failed to parse");
        assert_eq!(user["display_name"], "Test User");
        assert_eq!(user["bio"], "This is a test bio");
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_rate_limiting() {
        let client = reqwest::Client::new();

        // Make many requests quickly
        for i in 0..150 {
            let response = client
                .get(api_url("/health"))
                .send()
                .await
                .expect("Failed to send request");

            if i < 100 {
                // Should succeed for first 100 requests
                assert_eq!(response.status(), 200, "Request {} should succeed", i);
            } else {
                // Should be rate limited after 100
                if response.status() == 429 {
                    // Rate limit kicked in
                    return;
                }
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_cors_headers() {
        let client = reqwest::Client::new();

        let response = client
            .request(reqwest::Method::OPTIONS, api_url("/api/tokens"))
            .header("Origin", "http://localhost:3001")
            .header("Access-Control-Request-Method", "GET")
            .send()
            .await
            .expect("Failed to send request");

        // Check CORS headers are present
        assert!(
            response
                .headers()
                .contains_key("access-control-allow-origin")
        );
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_request_id_header() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/health"))
            .send()
            .await
            .expect("Failed to send request");

        // Check that request ID header is present
        assert!(response.headers().contains_key("x-request-id"));
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_code_examples_endpoint() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/api/docs/examples"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let examples: Vec<serde_json::Value> = response.json().await.expect("Failed to parse");
        assert!(!examples.is_empty());
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_specific_example_endpoint() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/api/docs/examples/register"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let example: serde_json::Value = response.json().await.expect("Failed to parse");
        assert_eq!(example["operation"], "register");
        assert!(example["examples"].is_array());
    }

    #[tokio::test]
    #[ignore] // Requires running server
    async fn test_postman_collection_endpoint() {
        let client = reqwest::Client::new();

        let response = client
            .get(api_url("/api/docs/postman"))
            .send()
            .await
            .expect("Failed to send request");

        assert_eq!(response.status(), 200);

        let collection: serde_json::Value = response.json().await.expect("Failed to parse");
        assert!(collection["info"].is_object());
        assert!(collection["item"].is_array());
    }
}