-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathApiKeyControllerTestIT.java
More file actions
403 lines (368 loc) · 16.1 KB
/
ApiKeyControllerTestIT.java
File metadata and controls
403 lines (368 loc) · 16.1 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
package cwms.cda.api.auth;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
import cwms.cda.ApiServlet;
import cwms.cda.api.DataApiTestIT;
import cwms.cda.data.dao.AuthDao;
import cwms.cda.data.dto.Location;
import cwms.cda.data.dto.auth.ApiKey;
import cwms.cda.formatters.Formats;
import cwms.cda.formatters.json.JsonV1;
import fixtures.TestAccounts;
import fixtures.TestAccounts.KeyUser;
import fixtures.users.UserSpecSource;
import fixtures.users.annotation.AuthType;
import io.javalin.http.HttpCode;
import io.restassured.filter.log.LogDetail;
import io.restassured.specification.RequestSpecification;
import static cwms.cda.data.dao.JsonRatingUtilsTest.loadResourceAsString;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
/**
* Forced order is used here to allow better error reporting
* but to let all the tests run and make sure
*/
@Tag("integration")
@TestMethodOrder(OrderAnnotation.class)
@TestInstance(Lifecycle.PER_CLASS)
public class ApiKeyControllerTestIT extends DataApiTestIT {
private final String KEY_NAME = "TestKey1";
private final String EXPIRED_KEY_NAME = "TestKey2-Expired";
private static final List<ApiKey> realKeys = new ArrayList<>();
private static final List<ApiKey> firstReturnedKeys = new ArrayList<>();
// Create API key, no expiration
@Order(1)
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_creation_no_expiration(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec) {
final ApiKey key = new ApiKey(theUser.getName(),KEY_NAME);
ApiKey returnedKey =
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.contentType("application/json")
.body(key)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.CREATED.getStatus()))
.body("user-id",is(key.getUserId().toUpperCase()))
.body("key-name",is(key.getKeyName()))
.body("api-key.size()",is(256))
.body("created",not(equalTo(null)))
.body("expires",is(equalTo(null)))
.extract().as(ApiKey.class);
realKeys.add(returnedKey);
}
// Create API key with expiration
@Order(2)
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_creation_with_expiration(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec) {
final String keyName = "TestKey1-Expires";
final ApiKey key = new ApiKey(theUser.getName(),keyName,null,null,ZonedDateTime.now());
final ApiKey expiredKey = new ApiKey(key.getUserId(),EXPIRED_KEY_NAME,null,null,ZonedDateTime.now().minusMinutes(1L));
ApiKey returnedKey =
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.contentType("application/json")
.body(key)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.CREATED.getStatus()))
.body("user-id",is(key.getUserId().toUpperCase()))
.body("key-name",is(key.getKeyName()))
.body("api-key.size()",is(256))
.body("created",not(equalTo(null)))
.body("expires",not(equalTo(null)))
.extract().as(ApiKey.class);
realKeys.add(returnedKey);
returnedKey =
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.contentType("application/json")
.body(expiredKey)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.CREATED.getStatus()))
.body("user-id",is(expiredKey.getUserId().toUpperCase()))
.body("key-name",is(expiredKey.getKeyName()))
.body("api-key.size()",is(256))
.body("created",not(equalTo(null)))
.body("expires",not(equalTo(null)))
.extract().as(ApiKey.class);
realKeys.add(returnedKey);
final String bodyWithSpecificExpiresFormat = "{\"user-id\": \"" + theUser.getName() + "\",\"key-name\": \"foo\",\"api-key\": \"string\",\"expires\": \"2023-09-23T14:20:00.908Z\"}";
returnedKey =
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.contentType("application/json")
.body(bodyWithSpecificExpiresFormat)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.CREATED.getStatus()))
.body("user-id",is(expiredKey.getUserId().toUpperCase()))
.body("key-name",is("foo"))
.body("api-key.size()",is(256))
.body("created",not(equalTo(null)))
.body("expires",not(equalTo(null)))
.extract().as(ApiKey.class);
realKeys.add(returnedKey);
}
@Order(3)
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_creation_not_other_user(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec) {
final String keyName = "TestKey1-Expires";
// This doesn't need to be a user in the database, the check is done before it gets there
final ApiKey key = new ApiKey("Bob",keyName,null,null,ZonedDateTime.now());
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.contentType("application/json")
.body(key)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.UNAUTHORIZED.getStatus()))
.body("message",is(AuthDao.ONLY_OWN_KEY_MESSAGE));
}
// List API keys
@Order(4)
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_listing(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec) {
List<ApiKey> keys =
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.accept(Formats.JSON)
.when()
.get("/auth/keys/")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.OK.getStatus()))
.extract()
.body()
.jsonPath()
.getList(".", ApiKey.class);
assertFalse(keys.isEmpty(), "No keys were returned.");
firstReturnedKeys.addAll(keys);
/** There may be other keys so we just scan for the keys we know about */
for(ApiKey createdKey: realKeys) {
assertContainsKey(createdKey,keys);
}
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.accept(Formats.JSON)
.when()
.get("/auth/keys/{key-name}",KEY_NAME)
.then()
.statusCode(HttpCode.OK.getStatus());
}
// use api key
@Test
@Order(5)
public void test_key_usage() throws Exception {
createLocation("ApiKey-Test Location",true,"SPK");
String json = loadResourceAsString("cwms/cda/api/location_create_spk.json");
Location location = new Location.Builder(Formats.parseContent(Formats.parseHeader(Formats.JSON, Location.class),
json, Location.class))
.withOfficeId("SPK")
.withName(getClass().getSimpleName())
.build();
String serializedLocation = JsonV1.buildObjectMapper().writeValueAsString(location);
final KeyUser user = KeyUser.SPK_NORMAL;
// create location
given()
.log().ifValidationFails(LogDetail.ALL,true)
.accept(Formats.JSON)
.contentType(Formats.JSON)
.body(serializedLocation)
.header("Authorization", user.toHeaderValue())
.when()
.redirects().follow(true)
.redirects().max(3)
.post("/locations")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.assertThat()
.statusCode(is(HttpCode.CREATED.getStatus()));
final ApiKey expiredKey = realKeys.stream()
.filter(k -> k.getKeyName().equals(EXPIRED_KEY_NAME))
.findFirst()
.orElseThrow(() -> new Exception("expired key not in real keys list."));
final Location updateLocation = new Location.Builder(location)
.withCountyName("Sacramento")
.build();
final String serializedUpdateLocation = JsonV1.buildObjectMapper().writeValueAsString(updateLocation);
// fail to use expired key
given()
.log().ifValidationFails(LogDetail.ALL,true)
.accept(Formats.JSON)
.contentType(Formats.JSON)
.body(serializedUpdateLocation)
.header("Authorization", "apikey " + expiredKey.getApiKey())
.when()
.redirects().follow(true)
.redirects().max(3)
.put("/locations/{location-id}",updateLocation.getName())
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.assertThat()
// SHOULD be UNAUTHORIZED, test not correctly active, need to review after merging latest
// test changes.
.statusCode(is(HttpCode.NOT_FOUND.getStatus()));
// fail to use no existent key
given()
.log().ifValidationFails(LogDetail.ALL,true)
.accept(Formats.JSON)
.contentType(Formats.JSON)
.body(serializedUpdateLocation)
.header("Authorization", "apikey This_Key_doesn't_exist")
.when()
.redirects().follow(true)
.redirects().max(3)
.put("/locations/{location-id}",updateLocation.getName())
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.assertThat()
// Same note as above
.statusCode(is(HttpCode.UNAUTHORIZED.getStatus()));
}
@Order(6)
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_cannot_create_new_key(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec) {
final String keyName = "KeyFromKey";
// This doesn't need to be a user in the database, the check is done before it gets there
final ApiKey key = new ApiKey(theUser.getName(),keyName,null,null,ZonedDateTime.now());
given()
.log().ifValidationFails(LogDetail.ALL,true)
.header("Authorization", "apikey " + realKeys.get(0).getApiKey())
.contentType("application/json")
.body(key)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.FORBIDDEN.getStatus()))
.body("message",is("Missing roles {Role{name='" + ApiServlet.CAC_USER + "'}}"));
}
// delete api keys
// List API keys
@Order(7)
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_delete_key(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec) {
for(ApiKey key: realKeys) {
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.accept(Formats.JSON)
.when()
.delete("/auth/keys/{key-name}",key.getKeyName())
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.NO_CONTENT.getStatus()));
// try to retrieve the key
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.accept(Formats.JSON)
.when()
.get("/auth/keys/{key-name}",key.getKeyName())
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.NOT_FOUND.getStatus()));
}
List<ApiKey> keys =
given()
.log().ifValidationFails(LogDetail.ALL,true)
.spec(authSpec)
.accept(Formats.JSON)
.when()
.get("/auth/keys/")
.then()
.log().ifValidationFails(LogDetail.ALL,true)
.statusCode(is(HttpCode.OK.getStatus()))
.extract()
.body()
.jsonPath()
.getList(".", ApiKey.class);
assertTrue(keys.size() < firstReturnedKeys.size(), "Keys were not deleted.");
}
@ParameterizedTest
@ArgumentsSource(UserSpecSource.class)
@AuthType(user = TestAccounts.KeyUser.SPK_NORMAL)
void test_api_key_length_limit(String authType, TestAccounts.KeyUser theUser, RequestSpecification authSpec)
{
final ApiKey key = new ApiKey(theUser.getName(),
RandomStringUtils.randomAlphabetic(70));
given()
.log().ifValidationFails(LogDetail.ALL, true)
.spec(authSpec)
.contentType("application/json")
.body(key)
.when()
.post("/auth/keys")
.then()
.log().ifValidationFails(LogDetail.ALL, true)
.assertThat()
.statusCode(is(HttpServletResponse.SC_BAD_REQUEST))
.body("message", containsString("One or more provided values exceeds the maximum length for the parameter. "
+ "The field KEY_NAME with provided length of 70 has a maximum length of 64 characters."));
}
private void assertContainsKey(ApiKey expectedKey, List<ApiKey> returnedSet) {
for (ApiKey expected: returnedSet) {
if ( expected.getKeyName().equals(expectedKey.getKeyName())
&& expected.getUserId().equals(expectedKey.getUserId())
// Don't compare the ApiKey itself, it's not returned
&& expected.getCreated().equals(expectedKey.getCreated())
) {
ZonedDateTime expectedKeyExpires = expectedKey.getExpires();
ZonedDateTime expectedExpires = expected.getExpires();
if (expectedKeyExpires == null && expectedExpires == null) {
return;
} else if((expectedKeyExpires != null && expectedExpires != null)
&& expectedExpires.isEqual(expectedKeyExpires)) {
return;
}
}
}
fail("Expected key (" + expectedKey.toString() + ") was not found in the returned set of keys.");
}
}