-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathDPoPTokenEndpointTests.cs
More file actions
557 lines (473 loc) · 20.9 KB
/
DPoPTokenEndpointTests.cs
File metadata and controls
557 lines (473 loc) · 20.9 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
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
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.
using System.Net;
using Duende.IdentityModel;
using Duende.IdentityModel.Client;
using Duende.IdentityServer;
using Duende.IdentityServer.Configuration;
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
using IntegrationTests.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace IntegrationTests.Endpoints.Token;
public class DPoPTokenEndpointTests : DPoPEndpointTestBase
{
protected const string Category = "DPoP Token endpoint";
private ClientCredentialsTokenRequest CreateClientCredentialsTokenRequest(
string proofToken = null, bool omitDPoPProof = false)
{
var request = new ClientCredentialsTokenRequest()
{
Address = IdentityServerPipeline.TokenEndpoint,
ClientId = "client1",
ClientSecret = "secret",
Scope = "scope1",
};
if (!omitDPoPProof)
{
proofToken ??= CreateDPoPProofToken();
request.Headers.Add("DPoP", proofToken);
}
return request;
}
private RefreshTokenRequest CreateRefreshTokenRequest(
TokenResponse codeResponse, string clientId = "client1", bool omitDPoPProof = false)
{
var rtRequest = new RefreshTokenRequest
{
Address = IdentityServerPipeline.TokenEndpoint,
ClientId = clientId,
ClientSecret = "secret",
RefreshToken = codeResponse.RefreshToken
};
if (!omitDPoPProof)
{
rtRequest.Headers.Add("DPoP", CreateDPoPProofToken());
}
return rtRequest;
}
[Fact]
[Trait("Category", Category)]
public async Task valid_dpop_request_should_return_bound_access_token()
{
var request = CreateClientCredentialsTokenRequest();
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeFalse();
response.TokenType.ShouldBe("DPoP");
var jkt = GetJKTFromAccessToken(response);
jkt.ShouldBe(JKT);
}
[Fact]
[Trait("Category", Category)]
public async Task valid_dpop_request_with_unusual_but_valid_proof_token_should_return_bound_access_token()
{
// The point here is to have an array in the payload, to exercise
// the json serialization
Payload.Add("key_ops", new string[] { "sign", "verify" });
var request = CreateClientCredentialsTokenRequest();
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeFalse();
response.TokenType.ShouldBe("DPoP");
var jkt = GetJKTFromAccessToken(response);
jkt.ShouldBe(JKT);
}
[Fact]
[Trait("Category", Category)]
public async Task dpop_proof_token_too_long_should_fail()
{
Payload.Add("foo", new string('x', 3000));
var request = CreateClientCredentialsTokenRequest();
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task replayed_dpop_token_should_fail()
{
// Shared proof used throughout
var dpopToken = CreateDPoPProofToken();
// Initial request succeeds
var firstRequest = CreateClientCredentialsTokenRequest(dpopToken);
var firstResponse = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(firstRequest);
firstResponse.IsError.ShouldBeFalse();
firstResponse.TokenType.ShouldBe("DPoP");
var jkt = GetJKTFromAccessToken(firstResponse);
jkt.ShouldBe(JKT);
// Second request fails
var secondRequest = CreateClientCredentialsTokenRequest(dpopToken);
secondRequest.Headers.Add("DPoP", dpopToken);
var secondResponse = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(secondRequest);
secondResponse.IsError.ShouldBeTrue();
}
[Fact]
[Trait("Category", Category)]
public async Task invalid_dpop_request_should_fail()
{
var request = CreateClientCredentialsTokenRequest(proofToken: "malformed");
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeTrue();
response.Error.ShouldBe("invalid_dpop_proof");
}
[Fact]
[Trait("Category", Category)]
public async Task missing_dpop_token_when_required_should_fail()
{
ConfidentialClient.RequireDPoP = true;
var request = CreateClientCredentialsTokenRequest(omitDPoPProof: true);
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeTrue();
response.Error.ShouldBe("invalid_request");
}
[Fact]
[Trait("Category", Category)]
public async Task multiple_dpop_tokens_should_fail()
{
var request = CreateClientCredentialsTokenRequest(omitDPoPProof: true);
var dpopToken = CreateDPoPProofToken();
request.Headers.Add("DPoP", dpopToken);
request.Headers.Add("DPoP", dpopToken);
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeTrue();
response.Error.ShouldBe("invalid_request");
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task valid_dpop_request_should_return_bound_refresh_token(ParMode parMode)
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
var rtRequest = CreateRefreshTokenRequest(codeResponse);
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.ShouldHaveDPoPThumbprint(JKT);
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task confidential_client_dpop_proof_should_be_required_on_renewal(ParMode parMode)
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
var rtRequest = CreateRefreshTokenRequest(codeResponse, omitDPoPProof: true);
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.IsError.ShouldBeTrue();
rtResponse.Error.ShouldBe("invalid_request");
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task public_client_dpop_proof_should_be_required_on_renewal(ParMode parMode)
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(clientId: "client2", parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
var rtRequest = CreateRefreshTokenRequest(codeResponse, clientId: "client2", omitDPoPProof: true);
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.IsError.ShouldBeTrue();
rtResponse.Error.ShouldBe("invalid_request");
}
[Theory]
[InlineData(ParMode.Unused)]
[InlineData(ParMode.NoBinding)]
[Trait("Category", Category)]
public async Task dpop_should_not_be_able_to_start_on_renewal(ParMode parMode)
{
// Initial code flow doesn't use dpop
var codeRequest = await CreateAuthCodeTokenRequestAsync(omitDPoPProofAtTokenEndpoint: true, parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.IsError.ShouldBeFalse();
// Subsequent refresh token request tries to use dpop
var rtRequest = CreateRefreshTokenRequest(codeResponse, omitDPoPProof: false);
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.IsError.ShouldBeTrue();
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task confidential_client_should_be_able_to_use_different_dpop_key_for_refresh_token_request(ParMode parMode)
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
CreateNewRSAKey();
var rtRequest = CreateRefreshTokenRequest(codeResponse);
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.ShouldHaveDPoPThumbprint(JKT);
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task public_client_should_not_be_able_to_use_different_dpop_key_for_refresh_token_request(ParMode parMode)
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(clientId: "client2", parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
CreateNewRSAKey();
var rtRequest = CreateRefreshTokenRequest(codeResponse, clientId: "client2");
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.IsError.ShouldBeTrue();
rtResponse.Error.ShouldBe("invalid_dpop_proof");
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task public_client_using_same_dpop_key_for_refresh_token_request_should_succeed(ParMode parMode)
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(clientId: "client2", parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
var firstRefreshRequest = CreateRefreshTokenRequest(codeResponse, clientId: "client2");
var firstRefreshResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(firstRefreshRequest);
firstRefreshResponse.ShouldHaveDPoPThumbprint(JKT);
var secondRefreshRequest = CreateRefreshTokenRequest(codeResponse, clientId: "client2");
var secondRefreshResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(secondRefreshRequest);
secondRefreshResponse.ShouldHaveDPoPThumbprint(JKT);
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task missing_proof_token_when_required_on_refresh_token_request_should_fail(ParMode parMode)
{
ConfidentialClient.RequireDPoP = true;
var codeRequest = await CreateAuthCodeTokenRequestAsync(parMode: parMode);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
var rtRequest = CreateRefreshTokenRequest(codeResponse, omitDPoPProof: true);
var rtResponse = await Pipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest);
rtResponse.IsError.ShouldBeTrue();
rtResponse.Error.ShouldBe("invalid_request");
}
[Theory]
[InlineData(AccessTokenType.Reference)]
[InlineData(AccessTokenType.Jwt)]
[Trait("Category", Category)]
public async Task valid_dpop_request_at_introspection_should_return_binding_information(AccessTokenType accessTokenType)
{
ConfidentialClient.AccessTokenType = accessTokenType;
var codeRequest = await CreateAuthCodeTokenRequestAsync();
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
var introspectionRequest = new TokenIntrospectionRequest
{
Address = IdentityServerPipeline.IntrospectionEndpoint,
ClientId = "api1",
ClientSecret = "secret",
Token = codeResponse.AccessToken,
};
var introspectionResponse = await Pipeline.BackChannelClient.IntrospectTokenAsync(introspectionRequest);
introspectionResponse.IsError.ShouldBeFalse();
GetJKTFromCnfClaim(introspectionResponse.Claims).ShouldBe(JKT);
}
[Fact]
[Trait("Category", Category)]
public async Task matching_dpop_key_thumbprint_on_authorize_endpoint_and_token_endpoint_should_succeed()
{
var codeRequest = await CreateAuthCodeTokenRequestAsync(dpopJkt: JKT);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.ShouldHaveDPoPThumbprint(JKT);
}
[Fact]
[Trait("Category", Category)]
public async Task dpop_key_thumbprint_too_long_should_fail()
{
var url = Pipeline.CreateAuthorizeUrl(
clientId: "client1",
responseType: "code",
responseMode: "query",
scope: "openid scope1 offline_access",
redirectUri: "https://client1/callback",
extra: new
{
dpop_jkt = new string('x', 101)
});
await Pipeline.BrowserClient.GetAsync(url);
Pipeline.ErrorWasCalled.ShouldBeTrue();
}
[Theory]
[InlineData(ParMode.Unused)]
[InlineData(ParMode.DpopJktParameter)]
[InlineData(ParMode.DpopHeader)]
[InlineData(ParMode.Both)]
[Trait("Category", Category)]
public async Task mismatched_dpop_key_thumbprint_on_authorize_endpoint_and_token_endpoint_should_fail(ParMode parMode)
{
var oldJkt = JKT;
var oldProof = CreateDPoPProofToken(htu: IdentityServerPipeline.ParEndpoint);
CreateNewRSAKey();
JKT.ShouldNotBe(oldJkt);
var codeRequest = await CreateAuthCodeTokenRequestAsync(parMode: parMode, dpopJkt: oldJkt, dpopProof: oldProof);
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.IsError.ShouldBeTrue();
codeResponse.Error.ShouldBe("invalid_dpop_proof");
}
[Theory]
[ClassData(typeof(ParModes))]
[Trait("Category", Category)]
public async Task server_issued_nonce_should_be_emitted(ParMode parMode)
{
var expectedNonce = "nonce";
Pipeline.OnPostConfigureServices += services =>
{
services.AddSingleton<MockDPoPProofValidator>();
services.AddSingleton<IDPoPProofValidator>(sp =>
{
var mockValidator = sp.GetRequiredService<MockDPoPProofValidator>();
mockValidator.ServerIssuedNonce = expectedNonce;
return mockValidator;
});
};
Pipeline.Initialize();
var codeRequest = await CreateAuthCodeTokenRequestAsync(parMode: parMode, expectedDpopNonce: expectedNonce);
if (parMode is ParMode.DpopHeader or ParMode.Both)
{
return;
}
var codeResponse = await Pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest);
codeResponse.IsError.ShouldBeTrue();
codeResponse.Error.ShouldBe(OidcConstants.TokenErrors.UseDPoPNonce);
codeResponse.DPoPNonce.ShouldBe(expectedNonce);
}
[Fact]
[Trait("Category", Category)]
public async Task token_request_when_using_mtls_for_client_authentication_should_succeed()
{
var clientId = "mtls_client";
var clientCert = TestCert.Load();
var client = new Client
{
ClientId = clientId,
ClientSecrets =
{
new Secret
{
Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint,
Value = clientCert.Thumbprint
}
},
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "scope1" },
RequireDPoP = true
};
Pipeline.Clients.Add(client);
Pipeline.Initialize();
Pipeline.SetClientCertificate(clientCert);
var tokenClient = Pipeline.GetMtlsClient();
tokenClient.DefaultRequestHeaders.Add("DPoP", CreateDPoPProofToken(htu: IdentityServerPipeline.TokenMtlsEndpoint));
var formParams = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "scope", "scope1" }
};
var form = new FormUrlEncodedContent(formParams);
var response = await tokenClient.PostAsync(IdentityServerPipeline.TokenMtlsEndpoint, form);
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var json = await response.Content.ReadAsStringAsync();
json.ShouldContain("access_token");
json.ShouldContain("\"token_type\":\"DPoP\"");
}
internal class MockDPoPProofValidator : DefaultDPoPProofValidator
{
public MockDPoPProofValidator(IdentityServerOptions options, IReplayCache replayCache, IClock clock, Microsoft.AspNetCore.DataProtection.IDataProtectionProvider dataProtectionProvider, ILogger<DefaultDPoPProofValidator> logger) : base(options, replayCache, clock, dataProtectionProvider, logger)
{
}
public string ServerIssuedNonce { get; set; }
protected override async Task ValidateFreshnessAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result)
{
if (ServerIssuedNonce.IsPresent())
{
result.ServerIssuedNonce = ServerIssuedNonce;
result.IsError = true;
result.Error = OidcConstants.TokenErrors.UseDPoPNonce;
return;
}
await base.ValidateFreshnessAsync(context, result);
}
}
public enum KeyType { RSA, EC }
[Theory]
[InlineData("RS256", KeyType.RSA)]
[InlineData("RS384", KeyType.RSA)]
[InlineData("RS512", KeyType.RSA)]
[InlineData("PS256", KeyType.RSA)]
[InlineData("PS384", KeyType.RSA)]
[InlineData("PS512", KeyType.RSA)]
[InlineData("ES256", KeyType.EC)]
[InlineData("ES384", KeyType.EC)]
[InlineData("ES512", KeyType.EC)]
[Trait("Category", Category)]
public async Task all_supported_signing_algorithms_should_work(string alg, KeyType keyType)
{
if (keyType == KeyType.RSA)
{
CreateNewRSAKey();
}
else
{
CreateNewECKey();
}
var proofToken = CreateDPoPProofToken(alg);
var request = CreateClientCredentialsTokenRequest(proofToken);
var response = await Pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request);
response.IsError.ShouldBeFalse();
response.TokenType.ShouldBe("DPoP");
var jkt = GetJKTFromAccessToken(response);
jkt.ShouldBe(JKT);
}
[Fact]
[Trait("Category", Category)]
public async Task mtls_and_dpop_request_should_succeed()
{
var clientId = "mtls_dpop_client";
var clientCert = TestCert.Load();
// Add a client that requires mTLS and supports DPoP
var client = new Client
{
ClientId = clientId,
ClientSecrets =
{
new Secret
{
Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint,
Value = clientCert.Thumbprint
}
},
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "scope1" },
RequireDPoP = true
};
Pipeline.Clients.Add(client);
Pipeline.Initialize();
// Set the client certificate in the pipeline
Pipeline.SetClientCertificate(clientCert);
var tokenClient = Pipeline.GetMtlsClient();
var formParams = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "scope", "scope1" }
};
var form = new FormUrlEncodedContent(formParams);
tokenClient.DefaultRequestHeaders.Add("DPoP", CreateDPoPProofToken(htu: IdentityServerPipeline.TokenMtlsEndpoint));
var response = await tokenClient.PostAsync(IdentityServerPipeline.TokenMtlsEndpoint, form);
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var json = await response.Content.ReadAsStringAsync();
json.ShouldContain("access_token");
json.ShouldContain("\"token_type\":\"DPoP\"");
}
}
public class ParModes : TheoryData<ParMode>
{
public ParModes()
{
Add(ParMode.Unused);
Add(ParMode.NoBinding);
Add(ParMode.DpopHeader);
Add(ParMode.DpopJktParameter);
Add(ParMode.Both);
}
}