forked from SubStream-Protocol/SubStream-Protocol-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsep10Integration.test.js
More file actions
485 lines (402 loc) · 15.8 KB
/
sep10Integration.test.js
File metadata and controls
485 lines (402 loc) · 15.8 KB
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
475
476
477
478
479
480
481
482
483
484
485
const request = require("supertest");
const app = require("./index");
const StellarSdk = require("@stellar/stellar-sdk");
describe("SEP-10 Complete Integration Tests", () => {
let testKeypair;
let testPublicKey;
let authToken;
let challengeXDR;
beforeAll(() => {
// Generate test keypair for testing
testKeypair = StellarSdk.Keypair.random();
testPublicKey = testKeypair.publicKey();
});
describe("Acceptance Criteria 1: Secure Authentication Without Passwords", () => {
it("should allow users to authenticate using only Stellar public key", async () => {
// Step 1: Generate challenge with just public key
const challengeResponse = await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
expect(challengeResponse.body.success).toBe(true);
expect(challengeResponse.body.challenge).toBeDefined();
expect(challengeResponse.body.nonce).toBeDefined();
expect(challengeResponse.body.expiresAt).toBeDefined();
// Verify no username/password/email was required
expect(challengeResponse.body).not.toHaveProperty('username');
expect(challengeResponse.body).not.toHaveProperty('password');
expect(challengeResponse.body).not.toHaveProperty('email');
challengeXDR = challengeResponse.body.challenge;
});
it("should issue JWT token after wallet signature verification", async () => {
// This test simulates the wallet signing process
// In a real scenario, the wallet would sign the challenge
// For testing purposes, we'll create a valid signature
const transaction = StellarSdk.TransactionBuilder.fromXDR(
challengeXDR,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
// Sign with the test keypair (simulating wallet signature)
transaction.sign(testKeypair);
const signedChallengeXDR = transaction.toXDR();
// Verify and get token
const verifyResponse = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: signedChallengeXDR,
})
.expect(200);
expect(verifyResponse.body.success).toBe(true);
expect(verifyResponse.body.token).toBeDefined();
expect(verifyResponse.body.user.publicKey).toBe(testPublicKey.toLowerCase());
expect(verifyResponse.body.user.type).toBe('stellar');
expect(verifyResponse.body.user.tier).toBeDefined();
authToken = verifyResponse.body.token;
// Verify JWT contains public key as subject claim
const jwt = require('jsonwebtoken');
const decoded = jwt.decode(authToken);
expect(decoded.publicKey).toBe(testPublicKey.toLowerCase());
expect(decoded.type).toBe('stellar');
});
});
describe("Acceptance Criteria 2: SEP-10 Specification Compliance", () => {
it("should generate SEP-10 compliant challenge transactions", async () => {
const response = await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
const transaction = StellarSdk.TransactionBuilder.fromXDR(
response.body.challenge,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
// SEP-10 Requirements Verification
expect(transaction.operations.length).toBe(1);
expect(transaction.operations[0].type).toBe("manageData");
expect(transaction.operations[0].source).toBe(testPublicKey);
// Operation name must follow <domain> auth format
const expectedName = `${process.env.DOMAIN || "substream-protocol.com"} auth`;
expect(transaction.operations[0].name).toBe(expectedName);
// Must have timebounds
expect(transaction.timebounds).toBeDefined();
expect(transaction.timebounds.minTime).toBeGreaterThan(0);
expect(transaction.timebounds.maxTime).toBeGreaterThan(transaction.timebounds.minTime);
// Timebounds should be reasonable (5 minutes standard)
const timeDiff = transaction.timebounds.maxTime - transaction.timebounds.minTime;
expect(timeDiff).toBeLessThanOrEqual(300); // 5 minutes
});
it("should verify wallet signature against original challenge", async () => {
// Generate fresh challenge
const challengeResponse = await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
const transaction = StellarSdk.TransactionBuilder.fromXDR(
challengeResponse.body.challenge,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
// Sign with correct keypair
transaction.sign(testKeypair);
const signedChallengeXDR = transaction.toXDR();
const verifyResponse = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: signedChallengeXDR,
})
.expect(200);
expect(verifyResponse.body.success).toBe(true);
// Test with wrong signature (different keypair)
const wrongKeypair = StellarSdk.Keypair.random();
const wrongTransaction = StellarSdk.TransactionBuilder.fromXDR(
challengeResponse.body.challenge,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
wrongTransaction.sign(wrongKeypair);
const wrongSignedXDR = wrongTransaction.toXDR();
const wrongVerifyResponse = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: wrongSignedXDR,
})
.expect(400);
expect(wrongVerifyResponse.body.success).toBe(false);
expect(wrongVerifyResponse.body.error).toContain('Invalid signature');
});
it("should prevent nonce reuse and enforce expiration", async () => {
// Generate challenge
const challengeResponse = await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
const transaction = StellarSdk.TransactionBuilder.fromXDR(
challengeResponse.body.challenge,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
transaction.sign(testKeypair);
const signedChallengeXDR = transaction.toXDR();
// First verification should succeed
const firstVerify = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: signedChallengeXDR,
})
.expect(200);
expect(firstVerify.body.success).toBe(true);
// Second verification with same challenge should fail
const secondVerify = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: signedChallengeXDR,
})
.expect(400);
expect(secondVerify.body.success).toBe(false);
expect(secondVerify.body.error).toContain('already used');
});
});
describe("Acceptance Criteria 3: Protected Route Security", () => {
it("should deny access to protected routes without authentication", async () => {
// Test various protected routes
const protectedRoutes = [
'/content',
'/storage/health',
'/analytics/view-event',
'/posts'
];
for (const route of protectedRoutes) {
const response = await request(app)
.get(route)
.expect(401);
expect(response.body.success).toBe(false);
expect(response.body.error).toContain('Access token required');
}
});
it("should allow access to protected routes with valid Stellar JWT", async () => {
// Ensure we have a valid token
if (!authToken) {
const challengeResponse = await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
const transaction = StellarSdk.TransactionBuilder.fromXDR(
challengeResponse.body.challenge,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
transaction.sign(testKeypair);
const signedChallengeXDR = transaction.toXDR();
const verifyResponse = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: signedChallengeXDR,
})
.expect(200);
authToken = verifyResponse.body.token;
}
// Test access to protected routes
const response = await request(app)
.get('/content')
.set('Authorization', `Bearer ${authToken}`)
.expect(200);
expect(response.body.success).toBe(true);
});
it("should reject invalid JWT tokens", async () => {
const invalidTokens = [
'invalid.token.format',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.invalid.signature',
'completely-invalid-token'
];
for (const token of invalidTokens) {
const response = await request(app)
.get('/content')
.set('Authorization', `Bearer ${token}`)
.expect(403);
expect(response.body.success).toBe(false);
expect(response.body.error).toContain('Invalid or expired token');
}
});
it("should reject tokens for wrong authentication type", async () => {
// Create a fake Ethereum-style token
const jwt = require('jsonwebtoken');
const fakeEthToken = jwt.sign(
{
address: testPublicKey.toLowerCase(),
tier: 'bronze',
type: 'ethereum' // Wrong type for Stellar auth
},
process.env.JWT_SECRET || 'test-secret',
{ expiresIn: '1h' }
);
// Try to access Stellar-specific endpoint
const response = await request(app)
.get('/auth/stellar/session')
.set('Authorization', `Bearer ${fakeEthToken}`)
.expect(403);
expect(response.body.success).toBe(false);
expect(response.body.error).toContain('Invalid token type');
});
});
describe("Additional Security Features", () => {
it("should handle session management correctly", async () => {
if (!authToken) {
// Create a new token for this test
const challengeResponse = await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
const transaction = StellarSdk.TransactionBuilder.fromXDR(
challengeResponse.body.challenge,
process.env.STELLAR_NETWORK_PASSPHRASE || "Test SDF Network ; September 2015"
);
transaction.sign(testKeypair);
const signedChallengeXDR = transaction.toXDR();
const verifyResponse = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: signedChallengeXDR,
})
.expect(200);
authToken = verifyResponse.body.token;
}
// Get session info
const sessionResponse = await request(app)
.get('/auth/stellar/session')
.set('Authorization', `Bearer ${authToken}`)
.expect(200);
expect(sessionResponse.body.success).toBe(true);
expect(sessionResponse.body.session.publicKey).toBe(testPublicKey.toLowerCase());
// Logout
const logoutResponse = await request(app)
.post('/auth/stellar/logout')
.set('Authorization', `Bearer ${authToken}`)
.expect(200);
expect(logoutResponse.body.success).toBe(true);
// Token should be invalid after logout
const sessionAfterLogout = await request(app)
.get('/auth/stellar/session')
.set('Authorization', `Bearer ${authToken}`)
.expect(403);
expect(sessionAfterLogout.body.success).toBe(false);
});
it("should enforce rate limiting on authentication endpoints", async () => {
// Test rate limiting by making multiple rapid requests
const promises = [];
for (let i = 0; i < 10; i++) {
promises.push(
request(app)
.get("/auth/challenge")
.query({ publicKey: StellarSdk.Keypair.random().publicKey() })
);
}
const responses = await Promise.all(promises);
// At least some requests should succeed
const successCount = responses.filter(r => r.status === 200).length;
expect(successCount).toBeGreaterThan(0);
// Some might be rate limited (429) depending on configuration
const rateLimitedCount = responses.filter(r => r.status === 429).length;
// This is optional behavior, so we don't enforce it strictly
});
});
describe("Error Handling and Edge Cases", () => {
it("should handle invalid public keys gracefully", async () => {
const invalidKeys = [
'invalid-key',
'G123', // Too short
'G' + 'A'.repeat(56), // Invalid format
'',
null,
undefined
];
for (const key of invalidKeys) {
const response = await request(app)
.get("/auth/challenge")
.query({ publicKey: key })
.expect(400);
expect(response.body.success).toBe(false);
expect(response.body.error).toContain('Stellar public key required');
}
});
it("should handle malformed XDR gracefully", async () => {
const malformedXDRs = [
'invalid-xdr',
'AAAAAA==',
'',
null,
undefined
];
for (const xdr of malformedXDRs) {
const response = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey,
challengeXDR: xdr
})
.expect(400);
expect(response.body.success).toBe(false);
}
});
it("should handle missing required fields", async () => {
// Missing publicKey
const response1 = await request(app)
.post("/auth/verify")
.send({
challengeXDR: 'some-xdr'
})
.expect(400);
expect(response1.body.error).toContain('Missing required fields');
// Missing challengeXDR
const response2 = await request(app)
.post("/auth/verify")
.send({
publicKey: testPublicKey
})
.expect(400);
expect(response2.body.error).toContain('Missing required fields');
// Missing both
const response3 = await request(app)
.post("/auth/verify")
.send({})
.expect(400);
expect(response3.body.error).toContain('Missing required fields');
});
});
describe("Performance and Scalability", () => {
it("should handle concurrent authentication requests", async () => {
const concurrentRequests = 20;
const promises = [];
for (let i = 0; i < concurrentRequests; i++) {
const keypair = StellarSdk.Keypair.random();
promises.push(
request(app)
.get("/auth/challenge")
.query({ publicKey: keypair.publicKey() })
);
}
const responses = await Promise.all(promises);
// All requests should succeed
const successCount = responses.filter(r => r.status === 200).length;
expect(successCount).toBe(concurrentRequests);
// All responses should have valid challenge structure
responses.forEach(response => {
expect(response.body.success).toBe(true);
expect(response.body.challenge).toBeDefined();
expect(response.body.nonce).toBeDefined();
expect(response.body.expiresAt).toBeDefined();
});
});
it("should have reasonable response times", async () => {
const startTime = Date.now();
await request(app)
.get("/auth/challenge")
.query({ publicKey: testPublicKey })
.expect(200);
const responseTime = Date.now() - startTime;
// Should respond within reasonable time (less than 1 second)
expect(responseTime).toBeLessThan(1000);
});
});
});