forked from ServiceStack/ServiceStack
/
StatelessAuthTests.cs
574 lines (488 loc) · 19.5 KB
/
StatelessAuthTests.cs
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Amazon.DynamoDBv2;
using NUnit.Framework;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Aws.DynamoDb;
using ServiceStack.Configuration;
using ServiceStack.Data;
using ServiceStack.Logging;
using ServiceStack.OrmLite;
using ServiceStack.Redis;
using ServiceStack.Text;
namespace RazorRockstars.Console.Files
{
public class CustomUserSession : AuthUserSession
{
public int Counter { get; set; }
}
[Route("/secured")]
public class Secured : IReturn<SecuredResponse>
{
public string Name { get; set; }
}
public class SecuredResponse
{
public string Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
[Authenticate]
public class SecureService : IService
{
public object Any(Secured request)
{
return new SecuredResponse { Result = request.Name };
}
}
public class JsonHttpClientStatelessAuthTests : StatelessAuthTests
{
protected override IServiceClient GetClientWithUserPassword(bool alwaysSend = false)
{
return new JsonHttpClient(ListeningOn)
{
UserName = Username,
Password = Password,
AlwaysSendBasicAuthHeader = alwaysSend,
};
}
protected override IServiceClient GetClientWithApiKey()
{
return new JsonHttpClient(ListeningOn)
{
Credentials = new NetworkCredential(ApiKey.Id, ""),
};
}
protected override IServiceClient GetClientWithApiKeyBearerToken()
{
return new JsonHttpClient(ListeningOn)
{
BearerToken = ApiKey.Id,
};
}
protected override IServiceClient GetClient()
{
return new JsonHttpClient(ListeningOn);
}
}
public class DynamoDbAuthRepoStatelessAuthTests : StatelessAuthTests
{
public static AmazonDynamoDBClient CreateDynamoDBClient()
{
var dynamoClient = new AmazonDynamoDBClient("keyId", "key", new AmazonDynamoDBConfig
{
ServiceURL = ConfigUtils.GetAppSetting("DynamoDbUrl", "http://localhost:8000"),
});
return dynamoClient;
}
protected override ServiceStackHost CreateAppHost()
{
var pocoDynamo = new PocoDynamo(CreateDynamoDBClient());
pocoDynamo.DeleteAllTables(TimeSpan.FromMinutes(1));
return new AppHost
{
EnableAuth = true,
Use = container => container.Register<IAuthRepository>(c => new DynamoDbAuthRepository(pocoDynamo))
};
}
}
public class MemoryAuthRepoStatelessAuthTests : StatelessAuthTests
{
protected override ServiceStackHost CreateAppHost()
{
return new AppHost
{
EnableAuth = true,
Use = container => container.Register<IAuthRepository>(c => new InMemoryAuthRepository())
};
}
}
public class RedisAuthRepoStatelessAuthTests : StatelessAuthTests
{
protected override ServiceStackHost CreateAppHost()
{
var redisManager = new RedisManagerPool();
using (var redis = redisManager.GetClient())
{
redis.FlushAll();
}
return new AppHost
{
EnableAuth = true,
Use = container => container.Register<IAuthRepository>(c => new RedisAuthRepository(redisManager))
};
}
}
public class StatelessAuthTests
{
public const string ListeningOn = "http://localhost:2337/";
protected readonly ServiceStackHost appHost;
protected ApiKey ApiKey;
private IManageApiKeys apiRepo;
private ApiKeyAuthProvider apiProvider;
private string userId;
protected virtual ServiceStackHost CreateAppHost()
{
return new AppHost
{
EnableAuth = true,
Use = container => container.Register<IAuthRepository>(c =>
new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()))
};
}
public StatelessAuthTests()
{
//LogManager.LogFactory = new ConsoleLogFactory();
appHost = CreateAppHost()
.Init()
.Start("http://*:2337/");
var client = GetClient();
var response = client.Post(new Register
{
UserName = "user",
Password = "p@55word",
Email = "as@if{0}.com",
DisplayName = "DisplayName",
FirstName = "FirstName",
LastName = "LastName",
});
userId = response.UserId;
apiRepo = (IManageApiKeys)appHost.Resolve<IAuthRepository>();
ApiKey = apiRepo.GetUserApiKeys(userId).First(x => x.Environment == "test");
apiProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
appHost.Dispose();
}
[Ignore("Debug Run")]
[Test]
public void RunFor10Mins()
{
Process.Start(ListeningOn);
Thread.Sleep(TimeSpan.FromMinutes(10));
}
public const string Username = "user";
public const string Password = "p@55word";
protected virtual IServiceClient GetClientWithUserPassword(bool alwaysSend = false)
{
return new JsonServiceClient(ListeningOn)
{
UserName = Username,
Password = Password,
AlwaysSendBasicAuthHeader = alwaysSend,
};
}
protected virtual IServiceClient GetClientWithApiKey()
{
return new JsonServiceClient(ListeningOn)
{
Credentials = new NetworkCredential(ApiKey.Id, ""),
};
}
protected virtual IServiceClient GetClientWithApiKeyBearerToken()
{
return new JsonServiceClient(ListeningOn)
{
BearerToken = ApiKey.Id,
};
}
protected virtual IServiceClient GetClient()
{
return new JsonServiceClient(ListeningOn);
}
[Test]
public void Does_create_multiple_ApiKeys()
{
var apiKeys = apiRepo.GetUserApiKeys(userId);
Assert.That(apiKeys.Count, Is.EqualTo(
apiProvider.Environments.Length * apiProvider.KeyTypes.Length));
Assert.That(apiKeys.All(x => x.UserAuthId != null));
Assert.That(apiKeys.All(x => x.Environment != null));
Assert.That(apiKeys.All(x => x.KeyType != null));
Assert.That(apiKeys.All(x => x.CreatedDate != default(DateTime)));
Assert.That(apiKeys.All(x => x.CancelledDate == null));
Assert.That(apiKeys.All(x => x.ExpiryDate == null));
foreach (var apiKey in apiKeys)
{
var byId = apiRepo.GetApiKey(apiKey.Id);
Assert.That(byId.Id, Is.EqualTo(apiKey.Id));
}
}
[Test]
public void Regenerating_AuthKeys_invalidates_existing_Keys_and_enables_new_keys()
{
var client = new JsonServiceClient(ListeningOn) {
Credentials = new NetworkCredential(ApiKey.Id, ""),
};
var apiKeyResponse = client.Get(new GetApiKeys { Environment = "live" });
apiKeyResponse.PrintDump();
var oldApiKey = apiKeyResponse.Results[0].Key;
client = new JsonServiceClient(ListeningOn) {
BearerToken = oldApiKey,
};
//Key IsValid
var request = new Secured { Name = "test" };
var response = client.Send(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var regenResponse = client.Send(new RegenrateApiKeys { Environment = "live" });
try
{
//Key is no longer valid
apiKeyResponse = client.Get(new GetApiKeys { Environment = "live" });
Assert.Fail("Should throw");
}
catch (WebServiceException ex)
{
Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.Forbidden));
}
//Change to new Valid Key
client.BearerToken = regenResponse.Results[0].Key;
apiKeyResponse = client.Get(new GetApiKeys { Environment = "live" });
Assert.That(regenResponse.Results.Map(x => x.Key), Is.EquivalentTo(
apiKeyResponse.Results.Map(x => x.Key)));
}
[Test]
public void Doesnt_allow_using_expired_keys()
{
var client = new JsonServiceClient(ListeningOn)
{
Credentials = new NetworkCredential(ApiKey.Id, ""),
};
var authResponse = client.Get(new Authenticate());
var apiKeys = apiRepo.GetUserApiKeys(authResponse.UserId)
.Where(x => x.Environment == "live")
.ToList();
var oldApiKey = apiKeys[0].Id;
client = new JsonServiceClient(ListeningOn) {
BearerToken = oldApiKey,
};
//Key IsValid
var request = new Secured { Name = "test" };
var response = client.Send(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
apiKeys[0].ExpiryDate = DateTime.UtcNow.AddMinutes(-1);
apiRepo.StoreAll(new[]{ apiKeys[0] });
try
{
//Key is no longer valid
client.Get(new GetApiKeys { Environment = "live" });
Assert.Fail("Should throw");
}
catch (WebServiceException ex)
{
Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.Forbidden));
}
client = new JsonServiceClient(ListeningOn) {
Credentials = new NetworkCredential(ApiKey.Id, ""),
};
var regenResponse = client.Send(new RegenrateApiKeys { Environment = "live" });
//Change to new Valid Key
client.BearerToken = regenResponse.Results[0].Key;
var apiKeyResponse = client.Get(new GetApiKeys { Environment = "live" });
Assert.That(regenResponse.Results.Map(x => x.Key), Is.EquivalentTo(
apiKeyResponse.Results.Map(x => x.Key)));
}
[Test]
public void Authenticating_once_with_BasicAuth_does_not_establish_auth_session()
{
var client = GetClientWithUserPassword(alwaysSend: true);
var request = new Secured { Name = "test" };
var response = client.Send<SecuredResponse>(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var newClient = GetClient();
newClient.SetSessionId(client.GetSessionId());
try
{
response = newClient.Send<SecuredResponse>(request);
Assert.Fail("Should throw");
}
catch (WebServiceException webEx)
{
Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
}
}
[Test]
public void Authenticating_once_with_ApiKeyAuth_does_not_establish_auth_session()
{
var client = GetClientWithApiKey();
var request = new Secured { Name = "test" };
var response = client.Send(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var newClient = GetClient();
newClient.SetSessionId(client.GetSessionId());
try
{
response = newClient.Send<SecuredResponse>(request);
Assert.Fail("Should throw");
}
catch (WebServiceException webEx)
{
Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
}
}
[Test]
public async Task Authenticating_once_with_ApiKeyAuth_does_not_establish_auth_session_Async()
{
var client = GetClientWithApiKey();
var request = new Secured { Name = "test" };
var response = await client.SendAsync<SecuredResponse>(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var newClient = GetClient();
newClient.SetSessionId(client.GetSessionId());
try
{
response = await newClient.SendAsync<SecuredResponse>(request);
Assert.Fail("Should throw");
}
catch (WebServiceException webEx)
{
Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
}
}
[Test]
public void Authenticating_once_with_ApiKeyAuth_BearerToken_does_not_establish_auth_session()
{
var client = GetClientWithApiKeyBearerToken();
var request = new Secured { Name = "test" };
var response = client.Send<SecuredResponse>(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var newClient = GetClient();
newClient.SetSessionId(client.GetSessionId());
try
{
response = newClient.Send<SecuredResponse>(request);
Assert.Fail("Should throw");
}
catch (WebServiceException webEx)
{
Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
}
}
[Test]
public async Task Authenticating_once_with_ApiKeyAuth_BearerToken_does_not_establish_auth_session_Async()
{
var client = GetClientWithApiKeyBearerToken();
var request = new Secured { Name = "test" };
var response = await client.SendAsync<SecuredResponse>(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var newClient = GetClient();
newClient.SetSessionId(client.GetSessionId());
try
{
response = await newClient.SendAsync<SecuredResponse>(request);
Assert.Fail("Should throw");
}
catch (WebServiceException webEx)
{
Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
}
}
[Test]
public void Authenticating_once_with_CredentialsAuth_does_establish_auth_session()
{
var client = GetClient();
try
{
client.Send(new Authenticate());
Assert.Fail("Should throw");
}
catch (WebServiceException ex)
{
Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
}
client.Post(new Authenticate
{
provider = "credentials",
UserName = Username,
Password = Password,
});
client.Send(new Authenticate());
var request = new Secured { Name = "test" };
var response = client.Send<SecuredResponse>(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
var newClient = GetClient();
newClient.SetSessionId(client.GetSessionId());
response = newClient.Send<SecuredResponse>(request);
Assert.That(response.Result, Is.EqualTo(request.Name));
}
[Test]
public void Can_not_access_Secured_Pages_without_Authentication()
{
Assert.That(ListeningOn.CombineWith("/secured").GetStringFromUrl(),
Is.StringContaining("<!--page:Login.cshtml-->"));
Assert.That(ListeningOn.CombineWith("/SecuredPage").GetStringFromUrl(),
Is.StringContaining("<!--page:Login.cshtml-->"));
}
[Test]
public void Can_access_Secured_Pages_with_BasicAuth()
{
Assert.That(ListeningOn.CombineWith("/secured").GetStringFromUrl(
requestFilter: req => req.AddBasicAuth(Username, Password)),
Is.StringContaining("<!--view:Secured.cshtml-->"));
Assert.That(ListeningOn.CombineWith("/SecuredPage").GetStringFromUrl(
requestFilter: req => req.AddBasicAuth(Username, Password)),
Is.StringContaining("<!--page:SecuredPage.cshtml-->"));
}
[Test]
public void Can_access_Secured_Pages_with_ApiKeyAuth()
{
Assert.That(ListeningOn.CombineWith("/secured").GetStringFromUrl(
requestFilter: req => req.AddApiKeyAuth(ApiKey.Id)),
Is.StringContaining("<!--view:Secured.cshtml-->"));
Assert.That(ListeningOn.CombineWith("/SecuredPage").GetStringFromUrl(
requestFilter: req => req.AddApiKeyAuth(ApiKey.Id)),
Is.StringContaining("<!--page:SecuredPage.cshtml-->"));
}
[Test]
public async Task Can_access_Secured_Pages_with_ApiKeyAuth_async()
{
Assert.That(await ListeningOn.CombineWith("/secured").GetStringFromUrlAsync(
requestFilter: req => req.AddApiKeyAuth(ApiKey.Id)),
Is.StringContaining("<!--view:Secured.cshtml-->"));
Assert.That(await ListeningOn.CombineWith("/SecuredPage").GetStringFromUrlAsync(
requestFilter: req => req.AddApiKeyAuth(ApiKey.Id)),
Is.StringContaining("<!--page:SecuredPage.cshtml-->"));
}
[Test]
public void Can_access_Secured_Pages_with_ApiKeyAuth_BearerToken()
{
Assert.That(ListeningOn.CombineWith("/secured").GetStringFromUrl(
requestFilter: req => req.AddBearerToken(ApiKey.Id)),
Is.StringContaining("<!--view:Secured.cshtml-->"));
Assert.That(ListeningOn.CombineWith("/SecuredPage").GetStringFromUrl(
requestFilter: req => req.AddBearerToken(ApiKey.Id)),
Is.StringContaining("<!--page:SecuredPage.cshtml-->"));
}
[Test]
public async Task Can_access_Secured_Pages_with_ApiKeyAuth_BearerToken_Async()
{
Assert.That(await ListeningOn.CombineWith("/secured").GetStringFromUrlAsync(
requestFilter: req => req.AddBearerToken(ApiKey.Id)),
Is.StringContaining("<!--view:Secured.cshtml-->"));
Assert.That(await ListeningOn.CombineWith("/SecuredPage").GetStringFromUrlAsync(
requestFilter: req => req.AddBearerToken(ApiKey.Id)),
Is.StringContaining("<!--page:SecuredPage.cshtml-->"));
}
[Test]
public void Can_access_Secured_Pages_with_CredentialsAuth()
{
var client = GetClient();
client.Post(new Authenticate
{
provider = "credentials",
UserName = Username,
Password = Password,
});
Assert.That(client.Get<string>("/secured?format=html"),
Is.StringContaining("<!--view:Secured.cshtml-->"));
Assert.That(client.Get<string>("/SecuredPage?format=html"),
Is.StringContaining("<!--page:SecuredPage.cshtml-->"));
}
}
}