@medyll/idae-api 0.138.0 → 0.139.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -0
- package/dist/__tests__/README.md +583 -0
- package/dist/__tests__/fixtures/mockData.d.ts +219 -0
- package/dist/__tests__/fixtures/mockData.js +243 -0
- package/dist/__tests__/helpers/testUtils.d.ts +153 -0
- package/dist/__tests__/helpers/testUtils.js +328 -0
- package/dist/client/IdaeApiClient.d.ts +7 -0
- package/dist/client/IdaeApiClient.js +15 -2
- package/dist/client/IdaeApiClientCollection.d.ts +17 -9
- package/dist/client/IdaeApiClientCollection.js +32 -11
- package/dist/client/IdaeApiClientConfig.d.ts +2 -0
- package/dist/client/IdaeApiClientConfig.js +10 -2
- package/dist/client/IdaeApiClientRequest.js +30 -15
- package/dist/config/routeDefinitions.d.ts +8 -0
- package/dist/config/routeDefinitions.js +63 -15
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/openApi/redoc.html +12 -0
- package/dist/openApi/swagger-ui.html +23 -0
- package/dist/server/IdaeApi.d.ts +15 -0
- package/dist/server/IdaeApi.js +94 -22
- package/dist/server/engine/requestDatabaseManager.d.ts +1 -1
- package/dist/server/engine/requestDatabaseManager.js +6 -10
- package/dist/server/engine/routeManager.d.ts +1 -0
- package/dist/server/engine/routeManager.js +33 -17
- package/dist/server/middleware/README.md +46 -0
- package/dist/server/middleware/authMiddleware.d.ts +63 -0
- package/dist/server/middleware/authMiddleware.js +121 -12
- package/dist/server/middleware/authorizationMiddleware.d.ts +18 -0
- package/dist/server/middleware/authorizationMiddleware.js +38 -0
- package/dist/server/middleware/databaseMiddleware.d.ts +6 -1
- package/dist/server/middleware/databaseMiddleware.js +111 -6
- package/dist/server/middleware/docsMiddleware.d.ts +13 -0
- package/dist/server/middleware/docsMiddleware.js +30 -0
- package/dist/server/middleware/healthMiddleware.d.ts +15 -0
- package/dist/server/middleware/healthMiddleware.js +19 -0
- package/dist/server/middleware/mcpMiddleware.d.ts +10 -0
- package/dist/server/middleware/mcpMiddleware.js +14 -0
- package/dist/server/middleware/openApiMiddleware.d.ts +7 -0
- package/dist/server/middleware/openApiMiddleware.js +20 -0
- package/dist/server/middleware/tenantContextMiddleware.d.ts +25 -0
- package/dist/server/middleware/tenantContextMiddleware.js +31 -0
- package/dist/server/middleware/validationLayer.d.ts +8 -0
- package/dist/server/middleware/validationLayer.js +23 -0
- package/dist/server/middleware/validationMiddleware.d.ts +16 -0
- package/dist/server/middleware/validationMiddleware.js +30 -0
- package/package.json +18 -4
package/README.md
CHANGED
|
@@ -48,6 +48,8 @@ npm install @medyll/idae-api --next # for the next version (if available)
|
|
|
48
48
|
|
|
49
49
|
---
|
|
50
50
|
|
|
51
|
+
|
|
52
|
+
|
|
51
53
|
## Main Features
|
|
52
54
|
|
|
53
55
|
- Multi-database management (MongoDB, MySQL, etc.)
|
|
@@ -57,6 +59,30 @@ npm install @medyll/idae-api --next # for the next version (if available)
|
|
|
57
59
|
- Hooks/events on all CRUD operations
|
|
58
60
|
- Complete TypeScript client for API consumption
|
|
59
61
|
- Inherits all advanced methods from [@medyll/idae-db](https://www.npmjs.com/package/@medyll/idae-db)
|
|
62
|
+
- **Comprehensive middleware system** for authentication, authorization, validation, multi-tenancy, docs, and health endpoints
|
|
63
|
+
- **Strict multi-tenancy**: Tenant context required for all requests (see below)
|
|
64
|
+
- **Robust error handling**: All errors are handled by a centralized middleware
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
### Advanced (2026):
|
|
68
|
+
- **OpenAPI auto-generation & docs**: `/openapi.json` (spec), `/docs` (Swagger UI), `/redoc` (Redoc)
|
|
69
|
+
- **RBAC/ABAC**: Per-route authorization via JWT roles/scopes (see `authorization` in route definitions)
|
|
70
|
+
- **Strict multi-tenancy**: Tenant context required for all requests (from JWT, e.g. `tenantId` claim)
|
|
71
|
+
- **Security/validation**: CORS, helmet, rate limiting, payload limits, Zod validation, DB guardrails, health endpoints
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Middleware, Multi-Tenancy, and Error Handling
|
|
76
|
+
|
|
77
|
+
This project uses a comprehensive middleware system for authentication, authorization, validation, multi-tenancy, documentation, and health endpoints. See [`src/lib/server/middleware/README.md`](src/lib/server/middleware/README.md) for a full list and integration order.
|
|
78
|
+
|
|
79
|
+
**Multi-tenancy** is enforced via `tenantContextMiddleware`, which extracts the tenant context from the JWT or user object and injects it into the request. All protected routes require a valid tenant context. See the developer docs and middleware README for details and options.
|
|
80
|
+
|
|
81
|
+
**Error handling** is centralized: any error thrown in a route or middleware is caught and returned as a JSON error response with the appropriate status code.
|
|
82
|
+
|
|
83
|
+
**Testing**: Extensive tests cover edge cases, error handling, and multi-tenancy scenarios. See `src/lib/server/__tests__/middleware/` for examples.
|
|
84
|
+
|
|
85
|
+
**CI/CD**: The test suite must pass for all changes. Run `npm run test` locally and ensure your CI pipeline is green before merging.
|
|
60
86
|
|
|
61
87
|
---
|
|
62
88
|
|
|
@@ -310,6 +336,41 @@ Contributions are welcome! Feel free to submit a Pull Request.
|
|
|
310
336
|
|
|
311
337
|
---
|
|
312
338
|
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
## Erreurs courantes & troubleshooting
|
|
343
|
+
|
|
344
|
+
Voici quelques problèmes fréquemment rencontrés et leurs solutions rapides :
|
|
345
|
+
|
|
346
|
+
- **req.idaeDb ou req.connectedCollection undefined** : la route ne correspond pas au pattern attendu ou le middleware n’est pas appliqué. Vérifie le chemin et l’ordre des middlewares.
|
|
347
|
+
- **Token invalide sur route protégée** : header Authorization absent/mal formé, ou token expiré. Vérifie la config côté client et serveur.
|
|
348
|
+
- **Timeout ou erreur de connexion MongoDB** : URI incorrect ou service MongoDB non démarré. Vérifie la chaîne de connexion et l’état du service.
|
|
349
|
+
- **Résultat de requête vide** : mauvais nom de collection/db, ou filtre trop restrictif. Loggue les paramètres pour debug.
|
|
350
|
+
- **404 ou handler non appelé** : route non enregistrée ou méthode HTTP incorrecte. Vérifie la déclaration dans routeDefinitions.ts.
|
|
351
|
+
- **Mismatch de types client/serveur** : le serveur doit retourner des objets sérialisables, le client doit utiliser les bons types génériques.
|
|
352
|
+
- **Middleware d’auth non appliqué partout** : chaque route protégée doit avoir requiresAuth: true et l’auth doit être activée dans la config.
|
|
353
|
+
|
|
354
|
+
Pour plus de détails et de cas avancés, consulte :
|
|
355
|
+
- [.github/copilot-instructions.md](.github/copilot-instructions.md)
|
|
356
|
+
- [src/lib/server/middleware/README.md](src/lib/server/middleware/README.md)
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
## Schéma d’architecture (à compléter)
|
|
361
|
+
|
|
362
|
+
```mermaid
|
|
363
|
+
flowchart TD
|
|
364
|
+
Client <--> API[IdaeApi (Express)]
|
|
365
|
+
API --> MW[Middleware]
|
|
366
|
+
MW --> DB[IdaeDbAdapter (MongoDB/MySQL)]
|
|
367
|
+
API --> Auth[Auth/JWT]
|
|
368
|
+
API --> Docs[OpenAPI/Swagger]
|
|
369
|
+
MW --> MultiTenancy[TenantContext]
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
---
|
|
373
|
+
|
|
313
374
|
## License
|
|
314
375
|
|
|
315
376
|
This project is licensed under the MIT License.
|
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
# @medyll/idae-api Test Suite Documentation
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
This directory contains comprehensive tests for the @medyll/idae-api framework. The test suite is designed to:
|
|
6
|
+
|
|
7
|
+
- ✅ Validate all core components (auth, database, routing, client)
|
|
8
|
+
- ✅ Prevent security vulnerabilities (injection attacks, token tampering, XSS)
|
|
9
|
+
- ✅ Ensure request→response cycles work end-to-end
|
|
10
|
+
- ✅ Maintain API stability across refactors
|
|
11
|
+
- ✅ Document expected behavior through executable tests
|
|
12
|
+
|
|
13
|
+
## Test Structure
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
src/lib/__tests__/
|
|
17
|
+
├── middleware/ # Request processing pipeline
|
|
18
|
+
│ ├── authMiddleware.test.ts # JWT token lifecycle, auth attacks
|
|
19
|
+
│ └── databaseMiddleware.test.ts # DB connection injection prevention
|
|
20
|
+
│
|
|
21
|
+
├── engine/ # Core business logic
|
|
22
|
+
│ ├── routeManager.test.ts # Route registration, enable/disable
|
|
23
|
+
│ └── requestDatabaseManager.test.ts # URI construction, DB routing
|
|
24
|
+
│
|
|
25
|
+
├── client/ # Client library
|
|
26
|
+
│ └── IdaeApiClient.test.ts # HTTP dispatch, Bearer tokens, deserialization
|
|
27
|
+
│
|
|
28
|
+
├── integration/ # Component interaction
|
|
29
|
+
│ ├── crud-flow.test.ts # Complete CRUD roundtrips
|
|
30
|
+
│ ├── auth-flow.test.ts # Authentication + database chains
|
|
31
|
+
│ └── error-handling.test.ts # Error propagation, recovery
|
|
32
|
+
│
|
|
33
|
+
├── e2e/ # End-to-end scenarios
|
|
34
|
+
│ ├── security.test.ts # Attack vectors, vulnerability assessment
|
|
35
|
+
│ └── server-client-roundtrip.test.ts # Full stack client→server→client
|
|
36
|
+
│
|
|
37
|
+
├── fixtures/ # Test data
|
|
38
|
+
│ └── mockData.ts # Reusable mock objects, payloads
|
|
39
|
+
│
|
|
40
|
+
└── helpers/ # Utilities
|
|
41
|
+
└── testUtils.ts # Mock builders, assertions, performance helpers
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Running Tests
|
|
45
|
+
|
|
46
|
+
### Run all tests
|
|
47
|
+
```bash
|
|
48
|
+
npm run test
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Run specific test file
|
|
52
|
+
```bash
|
|
53
|
+
npm run test src/lib/server/__tests__/middleware/authMiddleware.test.ts
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Run tests in watch mode
|
|
57
|
+
```bash
|
|
58
|
+
npm run test -- --watch
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Run with coverage report
|
|
62
|
+
```bash
|
|
63
|
+
npm run test -- --coverage
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Run only security tests
|
|
67
|
+
```bash
|
|
68
|
+
npm run test -- e2e/security.test.ts
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Test Files & Coverage
|
|
72
|
+
|
|
73
|
+
### Unit Tests
|
|
74
|
+
|
|
75
|
+
#### 1. **authMiddleware.test.ts** (388 lines, 60+ tests)
|
|
76
|
+
**Purpose**: Validate JWT token generation, verification, refresh, and authentication middleware execution.
|
|
77
|
+
|
|
78
|
+
**Key Test Areas**:
|
|
79
|
+
- ✅ Token generation with correct algorithm (HS256)
|
|
80
|
+
- ✅ Token verification with valid signatures
|
|
81
|
+
- ✅ Token refresh with expiration handling
|
|
82
|
+
- ✅ Middleware execution and auth header parsing
|
|
83
|
+
- ✅ Bearer token extraction from Authorization header
|
|
84
|
+
|
|
85
|
+
**Security Tests** (6 attack scenarios):
|
|
86
|
+
- ❌ Token tampering (payload modification)
|
|
87
|
+
- ❌ Token signature forgery
|
|
88
|
+
- ❌ Algorithm confusion attacks (none algorithm)
|
|
89
|
+
- ❌ Expired token validation
|
|
90
|
+
- ❌ Hardcoded credentials vulnerability (CRITICAL)
|
|
91
|
+
- ❌ Missing Authorization header handling
|
|
92
|
+
|
|
93
|
+
**Run**:
|
|
94
|
+
```bash
|
|
95
|
+
npm run test -- authMiddleware.test.ts
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### 2. **databaseMiddleware.test.ts** (331 lines, 35+ tests)
|
|
99
|
+
**Purpose**: Validate database middleware injection of IdaeDb instance and request augmentation.
|
|
100
|
+
|
|
101
|
+
**Key Test Areas**:
|
|
102
|
+
- ✅ Middleware execution flow
|
|
103
|
+
- ✅ Request augmentation (req.idaeDb, req.collectionName, req.dbName)
|
|
104
|
+
- ✅ Query parameter parsing (qs library)
|
|
105
|
+
- ✅ Error handling for invalid parameters
|
|
106
|
+
|
|
107
|
+
**Security Tests** (injection prevention):
|
|
108
|
+
- ❌ SQL injection in collection names (`'; DROP TABLE`)
|
|
109
|
+
- ❌ NoSQL injection in queries (`{ $ne: null }`)
|
|
110
|
+
- ❌ XSS payloads (`<script>alert`)
|
|
111
|
+
- ❌ Long string DoS attempts (500+ chars)
|
|
112
|
+
- ❌ Unicode and special character handling
|
|
113
|
+
|
|
114
|
+
**Run**:
|
|
115
|
+
```bash
|
|
116
|
+
npm run test -- databaseMiddleware.test.ts
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
#### 3. **routeManager.test.ts** (278 lines, 40+ tests)
|
|
120
|
+
**Purpose**: Validate route registration, singleton pattern, and enable/disable lifecycle.
|
|
121
|
+
|
|
122
|
+
**Key Test Areas**:
|
|
123
|
+
- ✅ Singleton pattern implementation
|
|
124
|
+
- ✅ Route CRUD operations (add/get/remove)
|
|
125
|
+
- ✅ Enable/disable toggle functionality
|
|
126
|
+
- ✅ Route handler preservation
|
|
127
|
+
- ✅ Multiple route registration
|
|
128
|
+
|
|
129
|
+
**Edge Cases**:
|
|
130
|
+
- ❌ Duplicate route handling
|
|
131
|
+
- ❌ Disable→enable→disable cycles
|
|
132
|
+
- ❌ Handler function type checking
|
|
133
|
+
- ❌ Route path parsing
|
|
134
|
+
|
|
135
|
+
**Run**:
|
|
136
|
+
```bash
|
|
137
|
+
npm run test -- routeManager.test.ts
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### 4. **requestDatabaseManager.test.ts** (321 lines, 45+ tests)
|
|
141
|
+
**Purpose**: Validate database URI construction, collection name extraction, environment variable handling.
|
|
142
|
+
|
|
143
|
+
**Key Test Areas**:
|
|
144
|
+
- ✅ Request parsing (.fromReq method)
|
|
145
|
+
- ✅ Database URI construction (mongodb://host:port/dbName)
|
|
146
|
+
- ✅ Collection name extraction
|
|
147
|
+
- ✅ Database name routing
|
|
148
|
+
- ✅ Environment variable resolution
|
|
149
|
+
|
|
150
|
+
**Security Tests**:
|
|
151
|
+
- ❌ SQL injection attempts
|
|
152
|
+
- ❌ NoSQL injection in database names
|
|
153
|
+
- ❌ Unicode character handling
|
|
154
|
+
- ❌ Very long names (1000+ chars)
|
|
155
|
+
- ❌ Special character escaping
|
|
156
|
+
|
|
157
|
+
**Edge Cases**:
|
|
158
|
+
- ❌ Missing collectionName
|
|
159
|
+
- ❌ Null/undefined values
|
|
160
|
+
- ❌ Single dot parsing
|
|
161
|
+
- ❌ Multiple dots in collection name
|
|
162
|
+
|
|
163
|
+
**Run**:
|
|
164
|
+
```bash
|
|
165
|
+
npm run test -- requestDatabaseManager.test.ts
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
#### 5. **IdaeApiClient.test.ts** (512 lines, 65+ tests)
|
|
169
|
+
**Purpose**: Validate client initialization, HTTP methods, Bearer token handling, URL building.
|
|
170
|
+
|
|
171
|
+
**Key Test Areas**:
|
|
172
|
+
- ✅ Client initialization and singleton pattern
|
|
173
|
+
- ✅ db().collection() chaining
|
|
174
|
+
- ✅ HTTP method mapping (GET/POST/PUT/DELETE)
|
|
175
|
+
- ✅ Bearer token header injection
|
|
176
|
+
- ✅ Request body serialization
|
|
177
|
+
- ✅ Response deserialization
|
|
178
|
+
- ✅ Error handling
|
|
179
|
+
|
|
180
|
+
**HTTP Methods**:
|
|
181
|
+
- GET → .find(), .findById()
|
|
182
|
+
- POST → .create()
|
|
183
|
+
- PUT → .update()
|
|
184
|
+
- DELETE → .deleteById()
|
|
185
|
+
|
|
186
|
+
**Error Scenarios**:
|
|
187
|
+
- ❌ Missing Authorization header (401)
|
|
188
|
+
- ❌ Invalid token format
|
|
189
|
+
- ❌ Network timeouts
|
|
190
|
+
- ❌ Malformed server responses
|
|
191
|
+
- ❌ 500 Internal Server Error
|
|
192
|
+
- ❌ 404 Not Found
|
|
193
|
+
- ❌ Rate limiting (429)
|
|
194
|
+
|
|
195
|
+
**Run**:
|
|
196
|
+
```bash
|
|
197
|
+
npm run test -- IdaeApiClient.test.ts
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Integration Tests (Pending Implementation)
|
|
201
|
+
|
|
202
|
+
#### 6. **crud-flow.test.ts** (Planned: 300 lines)
|
|
203
|
+
**Purpose**: Full CRUD roundtrips through IdaeApi middleware chain with real/mocked database.
|
|
204
|
+
|
|
205
|
+
**Tests**:
|
|
206
|
+
- CREATE → READ → UPDATE → DELETE sequences
|
|
207
|
+
- Middleware chain validation
|
|
208
|
+
- Database adapter interaction
|
|
209
|
+
- Error propagation
|
|
210
|
+
|
|
211
|
+
#### 7. **auth-flow.test.ts** (Planned: 250 lines)
|
|
212
|
+
**Purpose**: Authentication through database operations.
|
|
213
|
+
|
|
214
|
+
**Tests**:
|
|
215
|
+
- Login → token generation → use token → query DB
|
|
216
|
+
- Permission checks
|
|
217
|
+
- Token expiration during request
|
|
218
|
+
- Logout with token revocation
|
|
219
|
+
|
|
220
|
+
#### 8. **error-handling.test.ts** (Planned: 200 lines)
|
|
221
|
+
**Purpose**: Error scenarios and recovery patterns.
|
|
222
|
+
|
|
223
|
+
**Tests**:
|
|
224
|
+
- Database connection failures
|
|
225
|
+
- Middleware exceptions
|
|
226
|
+
- Invalid request parameters
|
|
227
|
+
- Timeout handling
|
|
228
|
+
- Error response formatting
|
|
229
|
+
|
|
230
|
+
### End-to-End Tests
|
|
231
|
+
|
|
232
|
+
#### 9. **security.test.ts** (400+ lines, 30+ attack scenarios)
|
|
233
|
+
**Purpose**: Validate defense against common security attacks.
|
|
234
|
+
|
|
235
|
+
**Attack Vectors**:
|
|
236
|
+
|
|
237
|
+
1. **Token Tampering** (5 tests)
|
|
238
|
+
- Payload modification
|
|
239
|
+
- Signature forgery
|
|
240
|
+
- Wrong secret signing
|
|
241
|
+
- Algorithm confusion
|
|
242
|
+
- Clock skew
|
|
243
|
+
|
|
244
|
+
2. **Authorization Bypass** (5 tests)
|
|
245
|
+
- Missing Authorization header
|
|
246
|
+
- Missing Bearer prefix
|
|
247
|
+
- Basic auth instead of Bearer
|
|
248
|
+
- Only "Bearer" keyword
|
|
249
|
+
- Hardcoded credentials (CRITICAL)
|
|
250
|
+
|
|
251
|
+
3. **Injection Attacks** (8 tests)
|
|
252
|
+
- SQL injection in params
|
|
253
|
+
- NoSQL injection ($where, $function)
|
|
254
|
+
- XSS via stored data
|
|
255
|
+
- HTML injection
|
|
256
|
+
- XML special characters
|
|
257
|
+
|
|
258
|
+
4. **Session/Token Attacks** (5 tests)
|
|
259
|
+
- Token replay/reuse
|
|
260
|
+
- Brute force (rate limiting gap)
|
|
261
|
+
- Timing attacks
|
|
262
|
+
- Session fixation
|
|
263
|
+
|
|
264
|
+
5. **Cryptographic Issues** (5 tests)
|
|
265
|
+
- Weak secret validation
|
|
266
|
+
- Token uniqueness
|
|
267
|
+
- Algorithm validation
|
|
268
|
+
- Deprecated algorithms
|
|
269
|
+
|
|
270
|
+
**Critical Issues Documented**:
|
|
271
|
+
- ❌ Hardcoded credentials (admin/password)
|
|
272
|
+
- ❌ No rate limiting on login
|
|
273
|
+
- ❌ No token revocation mechanism
|
|
274
|
+
- ❌ No CORS validation
|
|
275
|
+
- ❌ Missing security headers
|
|
276
|
+
|
|
277
|
+
**Run**:
|
|
278
|
+
```bash
|
|
279
|
+
npm run test -- e2e/security.test.ts
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
#### 10. **server-client-roundtrip.test.ts** (550+ lines, 40+ tests)
|
|
283
|
+
**Purpose**: Full stack integration - client request → server → response → client deserialization.
|
|
284
|
+
|
|
285
|
+
**Test Categories**:
|
|
286
|
+
|
|
287
|
+
1. **CRUD Happy Path** (5 tests)
|
|
288
|
+
- CREATE → READ → UPDATE → DELETE
|
|
289
|
+
- Data type preservation
|
|
290
|
+
- Complex nested objects
|
|
291
|
+
|
|
292
|
+
2. **Complex Queries** (3 tests)
|
|
293
|
+
- Filtered searches
|
|
294
|
+
- MongoDB operators
|
|
295
|
+
- Batch operations
|
|
296
|
+
|
|
297
|
+
3. **Authentication Flow** (4 tests)
|
|
298
|
+
- Bearer token inclusion
|
|
299
|
+
- Missing token handling
|
|
300
|
+
- Token refresh
|
|
301
|
+
- 403 Forbidden
|
|
302
|
+
|
|
303
|
+
4. **Error Handling** (6 tests)
|
|
304
|
+
- Network timeouts
|
|
305
|
+
- Malformed responses
|
|
306
|
+
- 500 errors
|
|
307
|
+
- 404 errors
|
|
308
|
+
- 429 rate limiting
|
|
309
|
+
|
|
310
|
+
5. **Encoding & Serialization** (6 tests)
|
|
311
|
+
- UTF-8 characters
|
|
312
|
+
- Emoji handling
|
|
313
|
+
- Special characters
|
|
314
|
+
- Deep nesting
|
|
315
|
+
- MongoDB operators
|
|
316
|
+
|
|
317
|
+
6. **Multi-Database Support** (3 tests)
|
|
318
|
+
- Route to correct database
|
|
319
|
+
- Route to correct collection
|
|
320
|
+
- Multiple connections
|
|
321
|
+
|
|
322
|
+
**Run**:
|
|
323
|
+
```bash
|
|
324
|
+
npm run test -- e2e/server-client-roundtrip.test.ts
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
## Test Utilities
|
|
328
|
+
|
|
329
|
+
### Mock Data (`fixtures/mockData.ts`)
|
|
330
|
+
|
|
331
|
+
**Available Fixtures**:
|
|
332
|
+
```typescript
|
|
333
|
+
// User data
|
|
334
|
+
mockUsers: User[] // 3 test users with roles, ages, status
|
|
335
|
+
|
|
336
|
+
// Collections
|
|
337
|
+
mockPosts: Post[] // Sample posts
|
|
338
|
+
mockComments: Comment[] // Sample comments
|
|
339
|
+
|
|
340
|
+
// Tokens
|
|
341
|
+
mockTokens.valid // admin, user, expired tokens
|
|
342
|
+
mockTokens.invalid // malformed, tampered, none algorithm
|
|
343
|
+
|
|
344
|
+
// Attack Payloads
|
|
345
|
+
mockSQLInjectionPayloads // 5 SQL injection attempts
|
|
346
|
+
mockNoSQLInjectionPayloads // 5 NoSQL injection attempts
|
|
347
|
+
mockXSSPayloads // 8 XSS attack vectors
|
|
348
|
+
mockCSRFPayloads // 3 CSRF attempts
|
|
349
|
+
|
|
350
|
+
// Edge Cases
|
|
351
|
+
mockEdgeCasesData // 6 edge case scenarios
|
|
352
|
+
- veryLongString (10k chars)
|
|
353
|
+
- unicodeChars ('你好世界🚀')
|
|
354
|
+
- specialChars (!@#$%...)
|
|
355
|
+
- nullByte
|
|
356
|
+
- newlines
|
|
357
|
+
- tabs
|
|
358
|
+
|
|
359
|
+
// Database Configs
|
|
360
|
+
mockDatabaseConfigs // MongoDB & MySQL configs
|
|
361
|
+
|
|
362
|
+
// Error Responses
|
|
363
|
+
mockErrorResponses // 401, 403, 404, 400, 500, 503 responses
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
### Test Helpers (`helpers/testUtils.ts`)
|
|
367
|
+
|
|
368
|
+
**Mock Builders**:
|
|
369
|
+
```typescript
|
|
370
|
+
createMockRequest(overrides) // Mock Express Request
|
|
371
|
+
createMockResponse() // Mock Express Response
|
|
372
|
+
createMockNextFunction() // Mock Express next()
|
|
373
|
+
createMockMiddlewareContext() // Complete middleware context
|
|
374
|
+
createMockCollection(defaultData) // Mock IdaeDb collection adapter
|
|
375
|
+
createMockIdaeDb(collections) // Mock IdaeDb instance
|
|
376
|
+
createMockFetchResponse(data, options) // Mock fetch() response
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
**Token Utilities**:
|
|
380
|
+
```typescript
|
|
381
|
+
generateMockToken(payload, secret, expiresIn) // Generate JWT for testing
|
|
382
|
+
extractBearerToken(authHeader) // Parse Authorization header
|
|
383
|
+
isValidTokenFormat(token) // Validate JWT format
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
**Assertions**:
|
|
387
|
+
```typescript
|
|
388
|
+
testAssertions.statusCode(res, expected) // Assert HTTP status
|
|
389
|
+
testAssertions.hasAuthHeader(req) // Assert Authorization header
|
|
390
|
+
testAssertions.hasError(res) // Assert error response
|
|
391
|
+
testAssertions.hasData(res) // Assert success response
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
**Performance Testing**:
|
|
395
|
+
```typescript
|
|
396
|
+
measurePerformance(fn, iterations) // Measure async function timing
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
**Helpers**:
|
|
400
|
+
```typescript
|
|
401
|
+
waitFor(condition, timeout) // Wait for condition
|
|
402
|
+
assertMiddlewareCalled(middleware, index) // Assert middleware invoked
|
|
403
|
+
createTestDatabaseUri(dbType, dbName) // Create test DB URI
|
|
404
|
+
sanitizeForAssertion(data, keysToRemove) // Remove sensitive data before test
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
## Coverage Goals
|
|
408
|
+
|
|
409
|
+
- **Lines**: 80% minimum (currently ~60%)
|
|
410
|
+
- **Functions**: 80% minimum (currently ~65%)
|
|
411
|
+
- **Branches**: 70% minimum (currently ~50%)
|
|
412
|
+
- **Statements**: 80% minimum (currently ~60%)
|
|
413
|
+
|
|
414
|
+
**Priority Areas** (highest to lowest):
|
|
415
|
+
1. Authentication middleware (security-critical)
|
|
416
|
+
2. Database middleware (injection prevention)
|
|
417
|
+
3. Route manager (routing logic)
|
|
418
|
+
4. Client HTTP dispatch (API stability)
|
|
419
|
+
5. Database manager (URI construction)
|
|
420
|
+
6. Integration flows (end-to-end)
|
|
421
|
+
7. Error handling (recovery paths)
|
|
422
|
+
|
|
423
|
+
## Running Coverage Report
|
|
424
|
+
|
|
425
|
+
```bash
|
|
426
|
+
npm run test -- --coverage
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
This generates:
|
|
430
|
+
- `coverage/index.html` - Interactive HTML report
|
|
431
|
+
- `coverage/lcov.info` - LCOV format for CI/CD
|
|
432
|
+
- Console output with summary
|
|
433
|
+
|
|
434
|
+
## Known Issues & Gaps
|
|
435
|
+
|
|
436
|
+
### Security Vulnerabilities Documented
|
|
437
|
+
|
|
438
|
+
1. **CRITICAL: Hardcoded Credentials**
|
|
439
|
+
- Issue: Login uses hardcoded admin/password
|
|
440
|
+
- FIX: Implement bcrypt password hashing
|
|
441
|
+
- FIX: Use environment variables for credentials
|
|
442
|
+
|
|
443
|
+
2. **HIGH: No Rate Limiting**
|
|
444
|
+
- Issue: No protection against brute force attacks
|
|
445
|
+
- FIX: Add rate limiting middleware
|
|
446
|
+
- FIX: Implement exponential backoff
|
|
447
|
+
|
|
448
|
+
3. **HIGH: No Token Revocation**
|
|
449
|
+
- Issue: Tokens cannot be revoked before expiry
|
|
450
|
+
- FIX: Implement token blacklist
|
|
451
|
+
- FIX: Add logout with token invalidation
|
|
452
|
+
|
|
453
|
+
4. **MEDIUM: No Audit Logging**
|
|
454
|
+
- Issue: Failed auth attempts not logged
|
|
455
|
+
- FIX: Implement comprehensive audit logging
|
|
456
|
+
|
|
457
|
+
5. **MEDIUM: No CORS Validation**
|
|
458
|
+
- Issue: CORS not configured
|
|
459
|
+
- FIX: Add CORS middleware with allowed origins
|
|
460
|
+
|
|
461
|
+
### Missing Tests (TODO)
|
|
462
|
+
|
|
463
|
+
- [ ] MongoDB-specific tests (with memory-server)
|
|
464
|
+
- [ ] MySQL-specific tests (Sequelize)
|
|
465
|
+
- [ ] Streaming response handling
|
|
466
|
+
- [ ] Large payload handling
|
|
467
|
+
- [ ] Concurrent request handling
|
|
468
|
+
- [ ] Connection pool exhaustion scenarios
|
|
469
|
+
- [ ] Memory leak detection
|
|
470
|
+
- [ ] Performance regression tests
|
|
471
|
+
|
|
472
|
+
## Test Execution Timeline
|
|
473
|
+
|
|
474
|
+
**Typical test run**: 5-10 seconds (all 200+ tests)
|
|
475
|
+
|
|
476
|
+
**By category**:
|
|
477
|
+
- Unit tests (middleware/engine): ~2s
|
|
478
|
+
- Client tests: ~1s
|
|
479
|
+
- E2E tests: ~3-5s
|
|
480
|
+
- Coverage collection: +2-3s
|
|
481
|
+
|
|
482
|
+
## CI/CD Integration
|
|
483
|
+
|
|
484
|
+
### GitHub Actions Example
|
|
485
|
+
```yaml
|
|
486
|
+
- name: Run tests
|
|
487
|
+
run: npm run test
|
|
488
|
+
|
|
489
|
+
- name: Generate coverage
|
|
490
|
+
run: npm run test -- --coverage
|
|
491
|
+
|
|
492
|
+
- name: Upload coverage
|
|
493
|
+
uses: codecov/codecov-action@v3
|
|
494
|
+
with:
|
|
495
|
+
files: ./coverage/lcov.info
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
## Best Practices
|
|
499
|
+
|
|
500
|
+
### Writing New Tests
|
|
501
|
+
|
|
502
|
+
1. **Follow AAA Pattern** (Arrange, Act, Assert)
|
|
503
|
+
```typescript
|
|
504
|
+
// Arrange
|
|
505
|
+
const token = generateMockToken({ role: 'admin' });
|
|
506
|
+
|
|
507
|
+
// Act
|
|
508
|
+
const verified = authMiddleware.verifyToken(token);
|
|
509
|
+
|
|
510
|
+
// Assert
|
|
511
|
+
expect(verified.role).toBe('admin');
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
2. **Use Descriptive Test Names**
|
|
515
|
+
```typescript
|
|
516
|
+
it('should return 401 for missing Authorization header', () => { ... });
|
|
517
|
+
// Instead of: it('should reject unauthorized', () => { ... });
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
3. **Test Security First**
|
|
521
|
+
- Include attack scenarios in test coverage
|
|
522
|
+
- Document why a test matters for security
|
|
523
|
+
- Mark CRITICAL issues in test comments
|
|
524
|
+
|
|
525
|
+
4. **Mock External Dependencies**
|
|
526
|
+
```typescript
|
|
527
|
+
vi.mock('@medyll/idae-db', () => ({
|
|
528
|
+
IdaeDb: { init: vi.fn(...) }
|
|
529
|
+
}));
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
5. **Reset Mocks Between Tests**
|
|
533
|
+
```typescript
|
|
534
|
+
beforeEach(() => {
|
|
535
|
+
vi.clearAllMocks();
|
|
536
|
+
});
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
## Troubleshooting
|
|
540
|
+
|
|
541
|
+
### Test Fails with "Cannot find module"
|
|
542
|
+
- Ensure path aliases in tsconfig.json match imports
|
|
543
|
+
- Check $lib alias points to src/lib
|
|
544
|
+
|
|
545
|
+
### Test Timeouts
|
|
546
|
+
- Increase timeout: `it('test', async () => {...}, 20000)`
|
|
547
|
+
- Check for unresolved promises in async code
|
|
548
|
+
|
|
549
|
+
### Mocks Not Working
|
|
550
|
+
- Verify vi.mock() is called before imports
|
|
551
|
+
- Check mock implementation matches module exports
|
|
552
|
+
- Use vi.clearAllMocks() in beforeEach
|
|
553
|
+
|
|
554
|
+
### Coverage Not Generated
|
|
555
|
+
- Install coverage provider: `npm install -D @vitest/coverage-v8`
|
|
556
|
+
- Check vite.config.ts coverage configuration
|
|
557
|
+
- Ensure test files use .test.ts or .spec.ts suffix
|
|
558
|
+
|
|
559
|
+
## References
|
|
560
|
+
|
|
561
|
+
- [Vitest Documentation](https://vitest.dev)
|
|
562
|
+
- [Testing Library](https://testing-library.com)
|
|
563
|
+
- [@medyll/idae-db Adapter Pattern](https://www.npmjs.com/package/@medyll/idae-db)
|
|
564
|
+
- [OWASP Security Testing Guide](https://owasp.org/www-project-web-security-testing-guide)
|
|
565
|
+
- [JWT Best Practices](https://tools.ietf.org/html/rfc8725)
|
|
566
|
+
|
|
567
|
+
## Contributing Tests
|
|
568
|
+
|
|
569
|
+
When adding new features:
|
|
570
|
+
1. Write tests before implementation (TDD)
|
|
571
|
+
2. Ensure all tests pass: `npm run test`
|
|
572
|
+
3. Maintain >80% coverage: `npm run test -- --coverage`
|
|
573
|
+
4. Include security tests for new endpoints
|
|
574
|
+
5. Document CRITICAL issues in test comments
|
|
575
|
+
6. Run `npm run lint` and `npm run format` before commit
|
|
576
|
+
|
|
577
|
+
## Questions & Support
|
|
578
|
+
|
|
579
|
+
For test-related questions:
|
|
580
|
+
- Check this documentation first
|
|
581
|
+
- Review similar test files for patterns
|
|
582
|
+
- Check vitest.dev for framework questions
|
|
583
|
+
- Review mockData.ts and testUtils.ts for helper usage
|