View Javadoc
1   package de.dlr.shepard.common.filters;
2   
3   import static org.junit.jupiter.api.Assertions.assertEquals;
4   import static org.junit.jupiter.api.Assertions.assertThrows;
5   import static org.mockito.ArgumentMatchers.any;
6   import static org.mockito.Mockito.never;
7   import static org.mockito.Mockito.verify;
8   import static org.mockito.Mockito.when;
9   
10  import de.dlr.shepard.BaseTestCase;
11  import de.dlr.shepard.auth.apikey.entities.ApiKey;
12  import de.dlr.shepard.auth.apikey.services.ApiKeyService;
13  import de.dlr.shepard.auth.security.ApiKeyLastSeenCache;
14  import de.dlr.shepard.auth.security.JwtPrincipal;
15  import de.dlr.shepard.auth.security.JwtSecurityContext;
16  import de.dlr.shepard.auth.security.RolesList;
17  import de.dlr.shepard.auth.users.entities.User;
18  import de.dlr.shepard.common.util.PkiHelper;
19  import io.jsonwebtoken.Jwts;
20  import io.quarkus.test.InjectMock;
21  import io.quarkus.test.component.QuarkusComponentTest;
22  import io.quarkus.test.component.TestConfigProperty;
23  import jakarta.inject.Inject;
24  import jakarta.ws.rs.container.ContainerRequestContext;
25  import jakarta.ws.rs.core.Response;
26  import jakarta.ws.rs.core.SecurityContext;
27  import jakarta.ws.rs.core.UriInfo;
28  import java.net.URI;
29  import java.net.URISyntaxException;
30  import java.security.KeyFactory;
31  import java.security.NoSuchAlgorithmException;
32  import java.security.PrivateKey;
33  import java.security.PublicKey;
34  import java.security.spec.InvalidKeySpecException;
35  import java.security.spec.PKCS8EncodedKeySpec;
36  import java.security.spec.X509EncodedKeySpec;
37  import java.util.Base64;
38  import java.util.Date;
39  import java.util.UUID;
40  import org.apache.commons.lang3.time.DateUtils;
41  import org.junit.jupiter.api.BeforeAll;
42  import org.junit.jupiter.api.BeforeEach;
43  import org.junit.jupiter.api.Test;
44  import org.mockito.ArgumentCaptor;
45  import org.mockito.Captor;
46  
47  @QuarkusComponentTest
48  @TestConfigProperty(
49    key = "oidc.public",
50    value = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiAxFyffvM0oiga3h2E7XpHtJvu1vTodrn9Y426FOv80YJcMwPkaI5tXY5hnLjgOwsVNSBv9wAhLL4bUfP+TVhdg4dijD2H/3FamheQaPmduimytzQjlHIIfFuZidH12ZyUrOWfDxiHiRFQ3Dd8dlS7MbIsWt/qBIg16ZZazTJTiaSyP/qH305x9iRjrtGRmvE2VMOdc5EhujFMJnQWWgwOnv2C9U9KIchkPCz+TAL4kKJ79BUi4b0+jxL5Cbgyt0bMo27Zx0zQjU7f0ynFIllqZ6new3Q8HYbr4AIkca4pMjfKWrTHkrQBL2cEXHLIHt86C17goKteToqDjphkwImwIDAQAB"
51  )
52  @TestConfigProperty(key = "oidc.role", value = "test_role")
53  public class JwtFilterTest extends BaseTestCase {
54  
55    private static PrivateKey privateKey;
56    private static PublicKey publicKey;
57  
58    @InjectMock
59    ContainerRequestContext context;
60  
61    @InjectMock
62    UriInfo uriInfo;
63  
64    @InjectMock
65    PkiHelper pkiHelper;
66  
67    @InjectMock
68    ApiKeyService apiKeyService;
69  
70    @InjectMock
71    ApiKeyLastSeenCache apiKeyLastSeenCache;
72  
73    @Inject
74    JwtFilter filter;
75  
76    @Captor
77    ArgumentCaptor<Response> responseCaptor;
78  
79    @Captor
80    ArgumentCaptor<SecurityContext> scCaptor;
81  
82    @BeforeAll
83    public static void createKeys() throws NoSuchAlgorithmException, InvalidKeySpecException {
84      var privateString =
85        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCIDEXJ9+8zSiKBreHYTteke0m+7W9Oh2uf1jjboU6/zRglwzA+Rojm1djmGcuOA7CxU1IG/3ACEsvhtR8/5NWF2Dh2KMPYf/cVqaF5Bo+Z26KbK3NCOUcgh8W5mJ0fXZnJSs5Z8PGIeJEVDcN3x2VLsxsixa3+oEiDXpllrNMlOJpLI/+offTnH2JGOu0ZGa8TZUw51zkSG6MUwmdBZaDA6e/YL1T0ohyGQ8LP5MAviQonv0FSLhvT6PEvkJuDK3RsyjbtnHTNCNTt/TKcUiWWpnqd7DdDwdhuvgAiRxrikyN8patMeStAEvZwRccsge3zoLXuCgq15OioOOmGTAibAgMBAAECggEABBqirFIPZDOzUMgnDPhr5ulVMy5EclEBfSPgOTfngT+1n8YAmZBVJumCjoZuro0L8n159v4TqexZPCjTlYDYtB3urhnStqA9muiwF0+MW27Vu+qWooPJ0oBmBZBGBSE0t27LRMlQ7/X7InB02hMoyhzQD7943TqGlXfwFrIc+H1uXN8MrB4boRX71/yEPT8hv8nWB0FLcgfwtl1l+81otJFveMO/RLStHUH3Auomb/Hh4u96H6S6lUZ8TJ6+8jh2LXmg/RpsqHIWhDbZaNQJE1YdySe3bijov3s/PISaE8pRec6l6KaYkUuFUa6RoGP1RnopsFuN+EeLRMXTRtxgEQKBgQDDB1YRjE7YAYUqeuohhMgx9Ms39zsJGrs6KHE4uWtJFR/Jo3Kq093ykGA+IO+DK/IhBXGzy53SIQ9J7WEONpMmaahY6/Bkhn2nRI9biNaPCovHeO+nIpwtIdTUQLg/d+om+jC2My0YLGk71A5TRkIBPBE9NirbITxibo6jwWWOwwKBgQCylI1fx6f1gdEAP0qM7/LVLrZU3Qx+Q9rPcGG2FI1gWYu69o3JBGpSXqKcAc9hxtFVBaOGpaj9sB8+fPfMXWAvM7c808eL0zOmDC6RlQs0N4XmpV/vUeurgkLQfgB4sfUXbVWHQNsAkvB64BVbbmWFEcHzaBMytb2whvU9hcExSQKBgQCDuSjAoWt/KUev8WTBTtWIKDY5jpopBA0AsuAF1/ZGXiYiImsIRiDZ+/mE/OnIRp46/1pUfWoSypFw9Qtgdivc/e/eXzz2KIAlwYCx6jJAWnceOuhiklW5heghk7Td6TgVK1ZLOTVz5ksNRaSHSiS6gL+EAFnhtwj50oI0yCK30QKBgF7k028HADhUYEQaXbogs1AW/2p+/+mEkxxR4opHx4xgaQDTjSo5P2o/wXbW+2VAqfHdCjU9iFwuH5wr+d1N7ROIDqGzA8FIXJSquoA/y/FWY7/ZNu5MAMhlcq2plwSLw+pL/fveOcHHUyRoONEaC7Y3ZnG6ZyE2M/M+88hab/uJAoGARSSJgG3rRz8hcfQEfopo3rzdeAMY0ws+fXlHp6u51PP+238rB0Y+/b/NeHzwwuqeIxqVTcbd5E8Va7KESPuuzfIQtKbGuVwFpZzWHmROt312AoxeSwRDpOQibpfBAF59D40+SCl6N64whiVoEgJvOQGYB6BIcunIhSpLSD2YId4=";
86      var publicString =
87        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiAxFyffvM0oiga3h2E7XpHtJvu1vTodrn9Y426FOv80YJcMwPkaI5tXY5hnLjgOwsVNSBv9wAhLL4bUfP+TVhdg4dijD2H/3FamheQaPmduimytzQjlHIIfFuZidH12ZyUrOWfDxiHiRFQ3Dd8dlS7MbIsWt/qBIg16ZZazTJTiaSyP/qH305x9iRjrtGRmvE2VMOdc5EhujFMJnQWWgwOnv2C9U9KIchkPCz+TAL4kKJ79BUi4b0+jxL5Cbgyt0bMo27Zx0zQjU7f0ynFIllqZ6new3Q8HYbr4AIkca4pMjfKWrTHkrQBL2cEXHLIHt86C17goKteToqDjphkwImwIDAQAB";
88      var keyFactory = KeyFactory.getInstance("RSA");
89  
90      byte[] privateDecoded = Base64.getDecoder().decode(privateString);
91      PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateDecoded);
92      privateKey = keyFactory.generatePrivate(privateSpec);
93  
94      byte[] publicDecoded = Base64.getDecoder().decode(publicString);
95      X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(publicDecoded);
96      publicKey = keyFactory.generatePublic(publicSpec);
97    }
98  
99    @BeforeEach
100   public void setUpKeys() throws IllegalAccessException {
101     when(pkiHelper.getPublicKey()).thenReturn(publicKey);
102   }
103 
104   @BeforeEach
105   public void setUpUriInfo() throws URISyntaxException {
106     URI uri = new URI("http://localhost:8080/shepard/api/projects");
107     URI baseUri = new URI("http://localhost:8080/shepard/api");
108     String relativePath = "/projects";
109     when(uriInfo.getPath()).thenReturn(relativePath);
110     when(uriInfo.getAbsolutePath()).thenReturn(uri);
111     when(uriInfo.getBaseUri()).thenReturn(baseUri);
112     when(context.getUriInfo()).thenReturn(uriInfo);
113     when(context.getMethod()).thenReturn("GET");
114   }
115 
116   @Test
117   public void testFilterCORS() throws URISyntaxException {
118     when(context.getMethod()).thenReturn("OPTIONS");
119     filter.filter(context);
120     verify(context, never()).abortWith(any());
121   }
122 
123   @Test
124   public void testFilterPublic_publicRoute() throws URISyntaxException {
125     when(uriInfo.getPath()).thenReturn("/versionz");
126     filter.filter(context);
127     verify(context, never()).abortWith(any());
128   }
129 
130   @Test
131   public void testFilterPublic_privateRoute() throws URISyntaxException {
132     when(uriInfo.getPath()).thenReturn("/versionsz");
133     filter.filter(context);
134     verify(context).abortWith(any());
135   }
136 
137   @Test
138   public void testFilterNoHeader() throws URISyntaxException {
139     when(context.getHeaderString("Authorization")).thenReturn(null);
140     filter.filter(context);
141     verify(context).abortWith(responseCaptor.capture());
142     assertEquals(401, responseCaptor.getValue().getStatus());
143   }
144 
145   @Test
146   public void testFilterWrongHeader() {
147     when(context.getHeaderString("Authorization")).thenReturn("sehr falsch");
148     filter.filter(context);
149     verify(context).abortWith(responseCaptor.capture());
150     assertEquals(401, responseCaptor.getValue().getStatus());
151   }
152 
153   @Test
154   public void testFilterTokenExpired() throws InvalidKeySpecException, NoSuchAlgorithmException {
155     Date now = DateUtils.addMinutes(new Date(), -10);
156     Date future = DateUtils.addMinutes(new Date(), -5);
157 
158     String jws = Jwts.builder()
159       .setSubject("Bob")
160       .setAudience("account")
161       .setExpiration(future)
162       .setNotBefore(now)
163       .setIssuedAt(new Date())
164       .setId(UUID.randomUUID().toString())
165       .claim("azp", "testcase")
166       .claim("name", "MyName")
167       .claim("preferred_username", "MyUserName")
168       .claim("given_name", "MyFirstName")
169       .claim("family_name", "MyLastName")
170       .claim("email", "MyEMail")
171       .claim("realm_access", new RolesList(new String[] { "test_role" }))
172       .signWith(privateKey)
173       .compact();
174 
175     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
176     filter.filter(context);
177     verify(context).abortWith(responseCaptor.capture());
178     assertEquals(401, responseCaptor.getValue().getStatus());
179   }
180 
181   @Test
182   public void testFilterMissingSubject() throws InvalidKeySpecException, NoSuchAlgorithmException {
183     Date now = new Date();
184     Date future = DateUtils.addMinutes(now, 5);
185     UUID keyId = UUID.randomUUID();
186 
187     String jws = Jwts.builder()
188       .setAudience("account")
189       .setExpiration(future)
190       .setNotBefore(now)
191       .setIssuedAt(new Date())
192       .setId(keyId.toString())
193       .claim("azp", "testcase")
194       .claim("name", "MyName")
195       .claim("preferred_username", "MyUserName")
196       .claim("given_name", "MyFirstName")
197       .claim("family_name", "MyLastName")
198       .claim("email", "MyEMail")
199       .claim("realm_access", new RolesList(new String[] { "test_role" }))
200       .signWith(privateKey)
201       .compact();
202 
203     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
204     filter.filter(context);
205     verify(context).abortWith(responseCaptor.capture());
206     assertEquals(401, responseCaptor.getValue().getStatus());
207   }
208 
209   @Test
210   public void testFilterEmptySubject() throws InvalidKeySpecException, NoSuchAlgorithmException {
211     Date now = new Date();
212     Date future = DateUtils.addMinutes(now, 5);
213     UUID keyId = UUID.randomUUID();
214 
215     String jws = Jwts.builder()
216       .setAudience("account")
217       .setExpiration(future)
218       .setNotBefore(now)
219       .setIssuedAt(new Date())
220       .setId(keyId.toString())
221       .claim("azp", "testcase")
222       .claim("name", "MyName")
223       .claim("preferred_username", "MyUserName")
224       .claim("given_name", "MyFirstName")
225       .claim("family_name", "MyLastName")
226       .claim("email", "MyEMail")
227       .claim("realm_access", new RolesList(new String[] { "test_role" }))
228       .claim("sub", "")
229       .signWith(privateKey)
230       .compact();
231 
232     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
233     filter.filter(context);
234     verify(context).abortWith(responseCaptor.capture());
235     assertEquals(401, responseCaptor.getValue().getStatus());
236   }
237 
238   @Test
239   public void testFilterMissingRole() throws InvalidKeySpecException, NoSuchAlgorithmException {
240     Date now = new Date();
241     Date future = DateUtils.addMinutes(now, 5);
242     UUID keyId = UUID.randomUUID();
243 
244     String jws = Jwts.builder()
245       .setSubject("Bob")
246       .setAudience("account")
247       .setExpiration(future)
248       .setNotBefore(now)
249       .setIssuedAt(new Date())
250       .setId(keyId.toString())
251       .claim("azp", "testcase")
252       .claim("name", "MyName")
253       .claim("preferred_username", "MyUserName")
254       .claim("given_name", "MyFirstName")
255       .claim("family_name", "MyLastName")
256       .claim("email", "MyEMail")
257       .signWith(privateKey)
258       .compact();
259 
260     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
261     filter.filter(context);
262     verify(context).abortWith(responseCaptor.capture());
263     assertEquals(401, responseCaptor.getValue().getStatus());
264   }
265 
266   @Test
267   public void testFilterWrongRole() throws InvalidKeySpecException, NoSuchAlgorithmException {
268     Date now = new Date();
269     Date future = DateUtils.addMinutes(now, 5);
270     UUID keyId = UUID.randomUUID();
271 
272     String jws = Jwts.builder()
273       .setSubject("Bob")
274       .setAudience("account")
275       .setExpiration(future)
276       .setNotBefore(now)
277       .setIssuedAt(new Date())
278       .setId(keyId.toString())
279       .claim("azp", "testcase")
280       .claim("name", "MyName")
281       .claim("preferred_username", "MyUserName")
282       .claim("given_name", "MyFirstName")
283       .claim("family_name", "MyLastName")
284       .claim("email", "MyEMail")
285       .claim("realm_access", new RolesList(new String[] { "wrong_role" }))
286       .signWith(privateKey)
287       .compact();
288 
289     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
290     filter.filter(context);
291     verify(context).abortWith(responseCaptor.capture());
292     assertEquals(401, responseCaptor.getValue().getStatus());
293   }
294 
295   @Test
296   @TestConfigProperty(key = "oidc.role", value = "")
297   public void testFilterNoRoleConfigured()
298     throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalAccessException {
299     Date now = new Date();
300     Date future = DateUtils.addMinutes(now, 5);
301     UUID keyId = UUID.randomUUID();
302 
303     String jws = Jwts.builder()
304       .setSubject("Bob")
305       .setAudience("account")
306       .setExpiration(future)
307       .setNotBefore(now)
308       .setIssuedAt(new Date())
309       .setId(keyId.toString())
310       .claim("azp", "testcase")
311       .claim("name", "MyName")
312       .claim("preferred_username", "MyUserName")
313       .claim("given_name", "MyFirstName")
314       .claim("family_name", "MyLastName")
315       .claim("email", "MyEMail")
316       .claim("realm_access", new RolesList(new String[] { "another_role" }))
317       .signWith(privateKey)
318       .compact();
319 
320     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
321     filter.filter(context);
322     verify(context, never()).abortWith(any());
323   }
324 
325   @Test
326   public void testFilterSucessful() throws InvalidKeySpecException, NoSuchAlgorithmException {
327     Date now = new Date();
328     Date future = DateUtils.addMinutes(now, 5);
329     UUID keyId = UUID.randomUUID();
330 
331     String jws = Jwts.builder()
332       .setSubject("Bob")
333       .setAudience("account")
334       .setExpiration(future)
335       .setNotBefore(now)
336       .setIssuedAt(new Date())
337       .setId(keyId.toString())
338       .claim("azp", "testcase")
339       .claim("name", "MyName")
340       .claim("preferred_username", "MyUserName")
341       .claim("given_name", "MyFirstName")
342       .claim("family_name", "MyLastName")
343       .claim("email", "MyEMail")
344       .claim("realm_access", new RolesList(new String[] { "test_role" }))
345       .signWith(privateKey)
346       .compact();
347 
348     JwtPrincipal principal = new JwtPrincipal("account", "testcase", "Bob", keyId.toString(), new String[0]);
349     JwtSecurityContext securityContext = new JwtSecurityContext(context.getSecurityContext(), principal);
350 
351     when(context.getHeaderString("Authorization")).thenReturn("Bearer " + jws);
352     filter.filter(context);
353     verify(context, never()).abortWith(any());
354     verify(context).setSecurityContext(scCaptor.capture());
355     assertEquals(securityContext.getUserPrincipal(), scCaptor.getValue().getUserPrincipal());
356   }
357 
358   @Test
359   public void testFilterSucessfulApiKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
360     Date now = new Date();
361     UUID uid = UUID.randomUUID();
362 
363     String jws = Jwts.builder()
364       .setSubject("MyUserName")
365       .setNotBefore(now)
366       .setIssuedAt(new Date())
367       .setId(uid.toString())
368       .signWith(privateKey)
369       .compact();
370 
371     User user = new User("MyUserName");
372 
373     ApiKey apiKey = new ApiKey(uid);
374     apiKey.setName("MyApiKey");
375     apiKey.setJws(jws);
376     apiKey.setBelongsTo(user);
377 
378     JwtPrincipal principal = new JwtPrincipal("MyUserName", uid.toString());
379     JwtSecurityContext securityContext = new JwtSecurityContext(context.getSecurityContext(), principal);
380 
381     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
382     when(apiKeyService.getApiKey(uid)).thenReturn(apiKey);
383 
384     filter.filter(context);
385     verify(context, never()).abortWith(any());
386     verify(context).setSecurityContext(scCaptor.capture());
387     verify(apiKeyLastSeenCache).cacheKey(uid.toString());
388     assertEquals(securityContext.getUserPrincipal(), scCaptor.getValue().getUserPrincipal());
389   }
390 
391   @Test
392   public void testFilterMissingSubjectApiKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
393     Date now = new Date();
394     UUID uid = UUID.randomUUID();
395 
396     String jws = Jwts.builder()
397       .setNotBefore(now)
398       .setIssuedAt(new Date())
399       .setId(uid.toString())
400       .signWith(privateKey)
401       .compact();
402 
403     User user = new User("MyUserName");
404 
405     ApiKey apiKey = new ApiKey(uid);
406     apiKey.setName("MyApiKey");
407     apiKey.setJws(jws);
408     apiKey.setBelongsTo(user);
409 
410     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
411     when(apiKeyService.getApiKey(user.getUsername(), uid)).thenReturn(apiKey);
412 
413     filter.filter(context);
414     verify(context).abortWith(responseCaptor.capture());
415     assertEquals(401, responseCaptor.getValue().getStatus());
416   }
417 
418   @Test
419   public void testFilterEmptySubjectApiKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
420     Date now = new Date();
421     UUID uid = UUID.randomUUID();
422 
423     String jws = Jwts.builder()
424       .setNotBefore(now)
425       .setIssuedAt(new Date())
426       .setId(uid.toString())
427       .claim("sub", "")
428       .signWith(privateKey)
429       .compact();
430 
431     User user = new User("MyUserName");
432 
433     ApiKey apiKey = new ApiKey(uid);
434     apiKey.setName("MyApiKey");
435     apiKey.setJws(jws);
436     apiKey.setBelongsTo(user);
437 
438     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
439     when(apiKeyService.getApiKey(user.getUsername(), uid)).thenReturn(apiKey);
440 
441     filter.filter(context);
442     verify(context).abortWith(responseCaptor.capture());
443     assertEquals(401, responseCaptor.getValue().getStatus());
444   }
445 
446   @Test
447   public void testFilterNotYetValidApiKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
448     Date future = DateUtils.addMinutes(new Date(), 5);
449     UUID uid = UUID.randomUUID();
450 
451     String jws = Jwts.builder()
452       .setSubject("MyUserName")
453       .setNotBefore(future)
454       .setIssuedAt(new Date())
455       .setId(uid.toString())
456       .signWith(privateKey)
457       .compact();
458 
459     User user = new User("MyUserName");
460 
461     ApiKey apiKey = new ApiKey(uid);
462     apiKey.setName("MyApiKey");
463     apiKey.setJws(jws);
464     apiKey.setBelongsTo(user);
465 
466     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
467     when(apiKeyService.getApiKey(user.getUsername(), uid)).thenReturn(apiKey);
468 
469     filter.filter(context);
470     verify(context).abortWith(responseCaptor.capture());
471     assertEquals(401, responseCaptor.getValue().getStatus());
472   }
473 
474   @Test
475   public void testFilterNotFoundInDBApiKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
476     Date now = new Date();
477     UUID uid = UUID.randomUUID();
478 
479     String jws = Jwts.builder()
480       .setSubject("MyUserName")
481       .setNotBefore(now)
482       .setIssuedAt(new Date())
483       .setId(uid.toString())
484       .signWith(privateKey)
485       .compact();
486 
487     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
488     when(apiKeyService.getApiKey(uid)).thenThrow(IllegalArgumentException.class);
489     when(apiKeyService.getApiKey("MyUserName", uid)).thenThrow(IllegalArgumentException.class);
490 
491     assertThrows(IllegalArgumentException.class, () -> filter.filter(context));
492   }
493 
494   @Test
495   public void testFilterWrongFoundInDBApiKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
496     Date now = new Date();
497     UUID uid = UUID.randomUUID();
498 
499     String jws = Jwts.builder()
500       .setSubject("MyUserName")
501       .setNotBefore(now)
502       .setIssuedAt(new Date())
503       .setId(uid.toString())
504       .signWith(privateKey)
505       .compact();
506 
507     User user = new User("MyUserName");
508 
509     ApiKey apiKey = new ApiKey(uid);
510     apiKey.setName("MyApiKey");
511     apiKey.setJws("Wrong");
512     apiKey.setBelongsTo(user);
513 
514     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
515     when(apiKeyService.getApiKey(uid)).thenThrow(IllegalArgumentException.class);
516     when(apiKeyService.getApiKey(user.getUsername(), uid)).thenReturn(apiKey);
517 
518     assertThrows(IllegalArgumentException.class, () -> filter.filter(context));
519   }
520 
521   @Test
522   public void testFilterGracePeriod() throws InvalidKeySpecException, NoSuchAlgorithmException {
523     Date now = new Date();
524     UUID uid = UUID.randomUUID();
525 
526     String jws = Jwts.builder()
527       .setSubject("MyUserName")
528       .setNotBefore(now)
529       .setIssuedAt(new Date())
530       .setId(uid.toString())
531       .signWith(privateKey)
532       .compact();
533 
534     JwtPrincipal principal = new JwtPrincipal("MyUserName", uid.toString());
535     JwtSecurityContext securityContext = new JwtSecurityContext(context.getSecurityContext(), principal);
536 
537     when(context.getHeaderString("X-API-KEY")).thenReturn(jws);
538     when(apiKeyLastSeenCache.isKeyCached(uid.toString())).thenReturn(true);
539 
540     filter.filter(context);
541     verify(context, never()).abortWith(any());
542     verify(context).setSecurityContext(scCaptor.capture());
543     verify(apiKeyService, never()).getApiKey("MyUserName", uid);
544     assertEquals(securityContext.getUserPrincipal(), scCaptor.getValue().getUserPrincipal());
545   }
546 }