forked from elastic/elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenIdConnectRealmTests.java
550 lines (514 loc) · 31 KB
/
OpenIdConnectRealmTests.java
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.security.authc.oidc;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.oauth2.sdk.id.State;
import com.nimbusds.openid.connect.sdk.Nonce;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.license.MockLicenseState;
import org.elasticsearch.rest.RestUtils;
import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectLogoutResponse;
import org.elasticsearch.xpack.core.security.action.oidc.OpenIdConnectPrepareAuthenticationResponse;
import org.elasticsearch.xpack.core.security.authc.AuthenticationResult;
import org.elasticsearch.xpack.core.security.authc.Realm;
import org.elasticsearch.xpack.core.security.authc.RealmConfig;
import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings;
import org.elasticsearch.xpack.core.security.authc.support.DelegatedAuthorizationSettings;
import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper;
import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.xpack.security.authc.support.MockLookupRealm;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.mockito.stubbing.Answer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static java.time.Instant.now;
import static org.elasticsearch.test.ActionListenerUtils.anyActionListener;
import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey;
import static org.elasticsearch.xpack.security.authc.oidc.OpenIdConnectRealm.CONTEXT_TOKEN_DATA;
import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class OpenIdConnectRealmTests extends OpenIdConnectTestCase {
private Settings globalSettings;
private Environment env;
private ThreadContext threadContext;
@Before
public void setupEnv() {
globalSettings = Settings.builder().put("path.home", createTempDir()).build();
env = TestEnvironment.newEnvironment(globalSettings);
threadContext = new ThreadContext(globalSettings);
}
public void testAuthentication() throws Exception {
final UserRoleMapper roleMapper = mock(UserRoleMapper.class);
final String principal = randomAlphaOfLength(12);
AtomicReference<UserRoleMapper.UserData> userData = new AtomicReference<>();
doAnswer(getAnswer(userData)).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener());
final boolean notPopulateMetadata = randomBoolean();
final String authenticatingRealm = randomBoolean() ? REALM_NAME : null;
AuthenticationResult result = authenticateWithOidc(principal, roleMapper, notPopulateMetadata, false, authenticatingRealm, null);
assertThat(result, notNullValue());
assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.SUCCESS));
assertThat(result.getUser().principal(), equalTo(principal));
assertThat(result.getUser().email(), equalTo("cbarton@shield.gov"));
assertThat(result.getUser().fullName(), equalTo("Clinton Barton"));
assertThat(result.getUser().roles(), arrayContainingInAnyOrder("kibana_user", "role1"));
if (notPopulateMetadata) {
assertThat(result.getUser().metadata(), anEmptyMap());
} else {
assertThat(result.getUser().metadata().get("oidc(iss)"), equalTo("https://op.company.org"));
assertThat(result.getUser().metadata().get("oidc(name)"), equalTo("Clinton Barton"));
final Object groups = result.getUser().metadata().get("oidc(groups)");
assertThat(groups, notNullValue());
assertThat(groups, instanceOf(Collection.class));
assertThat((Collection<?>) groups, contains("group1", "group2", "groups3"));
}
}
public void testClaimPropertyMapping() throws Exception {
final UserRoleMapper roleMapper = mock(UserRoleMapper.class);
final String principal = randomAlphaOfLength(12);
AtomicReference<UserRoleMapper.UserData> userData = new AtomicReference<>();
doAnswer(getAnswer(userData)).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener());
Map<String, Object> claimsWithObject = org.elasticsearch.core.Map.of(
"groups",
org.elasticsearch.core.List.of(
org.elasticsearch.core.Map.of("key1", org.elasticsearch.core.List.of("value1", "value2")),
org.elasticsearch.core.Map.of("key2", org.elasticsearch.core.List.of("value1", "value2"))
)
);
Map<String, Object> claimsWithNumber = org.elasticsearch.core.Map.of("groups", org.elasticsearch.core.List.of(2, "value2"));
Exception e = expectThrows(
Exception.class,
() -> authenticateWithOidc(principal, roleMapper, false, false, REALM_NAME, claimsWithObject)
);
Exception e2 = expectThrows(
Exception.class,
() -> authenticateWithOidc(principal, roleMapper, false, false, REALM_NAME, claimsWithNumber)
);
assertThat(e.getCause().getMessage(), containsString("expects a claim with String or a String Array value"));
assertThat(e2.getCause().getMessage(), containsString("expects a claim with String or a String Array value"));
}
public void testClaimMetadataMapping() throws Exception {
final UserRoleMapper roleMapper = mock(UserRoleMapper.class);
final String principal = randomAlphaOfLength(12);
AtomicReference<UserRoleMapper.UserData> userData = new AtomicReference<>();
doAnswer(getAnswer(userData)).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener());
Map<String, Object> claims = org.elasticsearch.core.Map.of(
"string",
"String",
"number",
232,
"boolean",
true,
"string_array",
org.elasticsearch.core.List.of("one", "two", "three"),
"number_array",
org.elasticsearch.core.List.of(1, 2, 3),
"boolean_array",
org.elasticsearch.core.List.of(true, false, true),
"object",
org.elasticsearch.core.Map.of("key", org.elasticsearch.core.List.of("value1", "value2")),
"object_array",
org.elasticsearch.core.List.of(
org.elasticsearch.core.Map.of("key1", org.elasticsearch.core.List.of("value1", "value2")),
org.elasticsearch.core.Map.of("key2", org.elasticsearch.core.List.of("value1", "value2"))
)
);
AuthenticationResult result = authenticateWithOidc(principal, roleMapper, false, false, REALM_NAME, claims);
assertThat(result, notNullValue());
assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.SUCCESS));
assertThat(result.getUser().principal(), equalTo(principal));
assertThat(result.getUser().email(), equalTo("cbarton@shield.gov"));
assertThat(result.getUser().fullName(), equalTo("Clinton Barton"));
assertThat(result.getUser().roles(), arrayContainingInAnyOrder("kibana_user", "role1"));
assertTrue(result.getUser().metadata().containsKey("oidc(string)"));
assertTrue(result.getUser().metadata().containsKey("oidc(number)"));
assertTrue(result.getUser().metadata().containsKey("oidc(boolean)"));
assertTrue(result.getUser().metadata().containsKey("oidc(string_array)"));
assertTrue(result.getUser().metadata().containsKey("oidc(boolean_array)"));
assertTrue(result.getUser().metadata().containsKey("oidc(number_array)"));
assertFalse(result.getUser().metadata().containsKey("oidc(object_array)"));
assertFalse(result.getUser().metadata().containsKey("oidc(object)"));
}
public void testWithAuthorizingRealm() throws Exception {
final UserRoleMapper roleMapper = mock(UserRoleMapper.class);
final String principal = randomAlphaOfLength(12);
doAnswer(invocation -> {
assert invocation.getArguments().length == 2;
@SuppressWarnings("unchecked")
ActionListener<Set<String>> listener = (ActionListener<Set<String>>) invocation.getArguments()[1];
listener.onFailure(new RuntimeException("Role mapping should not be called"));
return null;
}).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener());
final String authenticatingRealm = randomBoolean() ? REALM_NAME : null;
AuthenticationResult result = authenticateWithOidc(principal, roleMapper, randomBoolean(), true, authenticatingRealm, null);
assertThat(result, notNullValue());
assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.SUCCESS));
assertThat(result.getUser().principal(), equalTo(principal));
assertThat(result.getUser().email(), equalTo("cbarton@shield.gov"));
assertThat(result.getUser().fullName(), equalTo("Clinton Barton"));
assertThat(result.getUser().roles(), arrayContainingInAnyOrder("lookup_user_role"));
assertThat(result.getUser().metadata().entrySet(), Matchers.iterableWithSize(1));
assertThat(result.getUser().metadata().get("is_lookup"), Matchers.equalTo(true));
assertNotNull(result.getMetadata().get(CONTEXT_TOKEN_DATA));
assertThat(result.getMetadata().get(CONTEXT_TOKEN_DATA), instanceOf(Map.class));
@SuppressWarnings("unchecked")
Map<String, Object> tokenMetadata = (Map<String, Object>) result.getMetadata().get(CONTEXT_TOKEN_DATA);
assertThat(tokenMetadata.get("id_token_hint"), equalTo("thisis.aserialized.jwt"));
}
public void testAuthenticationWithWrongRealm() throws Exception {
final String principal = randomAlphaOfLength(12);
AuthenticationResult result = authenticateWithOidc(
principal,
mock(UserRoleMapper.class),
randomBoolean(),
true,
REALM_NAME + randomAlphaOfLength(8),
null
);
assertThat(result, notNullValue());
assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.CONTINUE));
}
public void testClaimPatternParsing() throws Exception {
final Settings.Builder builder = getBasicRealmSettings();
builder.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getPattern()), "^OIDC-(.+)");
final RealmConfig config = buildConfig(builder.build(), threadContext);
final OpenIdConnectRealmSettings.ClaimSetting principalSetting = new OpenIdConnectRealmSettings.ClaimSetting("principal");
final OpenIdConnectRealm.ClaimParser parser = OpenIdConnectRealm.ClaimParser.forSetting(logger, principalSetting, config, true);
final JWTClaimsSet claims = new JWTClaimsSet.Builder().subject("OIDC-cbarton")
.audience("https://rp.elastic.co/cb")
.expirationTime(Date.from(now().plusSeconds(3600)))
.issueTime(Date.from(now().minusSeconds(5)))
.jwtID(randomAlphaOfLength(8))
.issuer("https://op.company.org")
.build();
assertThat(parser.getClaimValue(claims), equalTo("cbarton"));
}
public void testInvalidPrincipalClaimPatternParsing() {
final OpenIdConnectAuthenticator authenticator = mock(OpenIdConnectAuthenticator.class);
final String authenticatingRealm = randomBoolean() ? REALM_NAME : null;
final OpenIdConnectToken token = new OpenIdConnectToken("", new State(), new Nonce(), authenticatingRealm);
final Settings.Builder builder = getBasicRealmSettings();
builder.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getPattern()), "^OIDC-(.+)");
final RealmConfig config = buildConfig(builder.build(), threadContext);
final OpenIdConnectRealm realm = new OpenIdConnectRealm(config, authenticator, null);
final JWTClaimsSet claims = new JWTClaimsSet.Builder().subject("cbarton@avengers.com")
.audience("https://rp.elastic.co/cb")
.expirationTime(Date.from(now().plusSeconds(3600)))
.issueTime(Date.from(now().minusSeconds(5)))
.jwtID(randomAlphaOfLength(8))
.issuer("https://op.company.org")
.build();
doAnswer((i) -> {
@SuppressWarnings("unchecked")
ActionListener<JWTClaimsSet> listener = (ActionListener<JWTClaimsSet>) i.getArguments()[1];
listener.onResponse(claims);
return null;
}).when(authenticator).authenticate(any(OpenIdConnectToken.class), anyActionListener());
final PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
realm.authenticate(token, future);
final AuthenticationResult result = future.actionGet();
assertThat(result.getStatus(), equalTo(AuthenticationResult.Status.CONTINUE));
assertThat(result.getMessage(), containsString("claims.principal"));
assertThat(result.getMessage(), containsString("sub"));
assertThat(result.getMessage(), containsString("^OIDC-(.+)"));
}
public void testBuildRelyingPartyConfigWithoutOpenIdScope() {
final Settings.Builder settingsBuilder = Settings.builder()
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code")
.putList(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES), Arrays.asList("scope1", "scope2"))
.setSecureSettings(getSecureSettings());
final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build(), threadContext), null, null);
final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null, null);
final String state = response.getState();
final String nonce = response.getNonce();
assertEqualUrlStrings(
response.getAuthenticationRequestUrl(),
"https://op.example.com/login?scope=scope1+scope2+openid&response_type=code"
+ "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state="
+ state
+ "&nonce="
+ nonce
+ "&client_id=rp-my"
);
assertThat(response.getRealmName(), equalTo(REALM_NAME));
}
public void testBuildingAuthenticationRequest() {
final Settings.Builder settingsBuilder = Settings.builder()
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code")
.putList(
getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REQUESTED_SCOPES),
Arrays.asList("openid", "scope1", "scope2")
)
.setSecureSettings(getSecureSettings());
final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build(), threadContext), null, null);
final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null, null);
final String state = response.getState();
final String nonce = response.getNonce();
assertEqualUrlStrings(
response.getAuthenticationRequestUrl(),
"https://op.example.com/login?scope=openid+scope1+scope2&response_type=code"
+ "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state="
+ state
+ "&nonce="
+ nonce
+ "&client_id=rp-my"
);
assertThat(response.getRealmName(), equalTo(REALM_NAME));
}
public void testBuilidingAuthenticationRequestWithDefaultScope() {
final Settings.Builder settingsBuilder = Settings.builder()
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code")
.setSecureSettings(getSecureSettings());
;
final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build(), threadContext), null, null);
final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(null, null, null);
final String state = response.getState();
final String nonce = response.getNonce();
assertEqualUrlStrings(
response.getAuthenticationRequestUrl(),
"https://op.example.com/login?scope=openid&response_type=code"
+ "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state="
+ state
+ "&nonce="
+ nonce
+ "&client_id=rp-my"
);
assertThat(response.getRealmName(), equalTo(REALM_NAME));
}
public void testBuildLogoutResponse() throws Exception {
final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(getBasicRealmSettings().build(), threadContext), null, null);
// Random strings, as we will not validate the token here
final JWT idToken = generateIdToken(randomAlphaOfLength(8), randomAlphaOfLength(8), randomAlphaOfLength(8));
final OpenIdConnectLogoutResponse logoutResponse = realm.buildLogoutResponse(idToken);
final String endSessionUrl = logoutResponse.getEndSessionUrl();
final Map<String, String> parameters = new HashMap<>();
RestUtils.decodeQueryString(endSessionUrl, endSessionUrl.indexOf("?") + 1, parameters);
assertThat(parameters, aMapWithSize(3));
assertThat(parameters, hasKey("id_token_hint"));
assertThat(parameters, hasKey("post_logout_redirect_uri"));
assertThat(parameters, hasKey("state"));
}
public void testBuildLogoutResponseFromEndsessionEndpointWithExistingParameters() throws Exception {
final Settings.Builder realmSettingsWithFunkyEndpoint = getBasicRealmSettings();
realmSettingsWithFunkyEndpoint.put(
getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ENDSESSION_ENDPOINT),
"https://op.example.org/logout?parameter=123"
);
final OpenIdConnectRealm realm = new OpenIdConnectRealm(
buildConfig(realmSettingsWithFunkyEndpoint.build(), threadContext),
null,
null
);
// Random strings, as we will not validate the token here
final JWT idToken = generateIdToken(randomAlphaOfLength(8), randomAlphaOfLength(8), randomAlphaOfLength(8));
final OpenIdConnectLogoutResponse logoutResponse = realm.buildLogoutResponse(idToken);
final String endSessionUrl = logoutResponse.getEndSessionUrl();
final Map<String, String> parameters = new HashMap<>();
RestUtils.decodeQueryString(endSessionUrl, endSessionUrl.indexOf("?") + 1, parameters);
assertThat(parameters, aMapWithSize(4));
assertThat(parameters, hasKey("parameter"));
assertThat(parameters, hasKey("post_logout_redirect_uri"));
assertThat(parameters, hasKey("state"));
assertThat(parameters, hasKey("id_token_hint"));
}
public void testBuildingAuthenticationRequestWithExistingStateAndNonce() {
final Settings.Builder settingsBuilder = Settings.builder()
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code")
.setSecureSettings(getSecureSettings());
;
final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build(), threadContext), null, null);
final String state = new State().getValue();
final String nonce = new Nonce().getValue();
final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(state, nonce, null);
assertEqualUrlStrings(
response.getAuthenticationRequestUrl(),
"https://op.example.com/login?scope=openid&response_type=code"
+ "&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state="
+ state
+ "&nonce="
+ nonce
+ "&client_id=rp-my"
);
assertThat(response.getRealmName(), equalTo(REALM_NAME));
}
public void testBuildingAuthenticationRequestWithLoginHint() {
final Settings.Builder settingsBuilder = Settings.builder()
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_AUTHORIZATION_ENDPOINT), "https://op.example.com/login")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_TOKEN_ENDPOINT), "https://op.example.com/token")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_ISSUER), "https://op.example.com")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.OP_JWKSET_PATH), "https://op.example.com/jwks.json")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.PRINCIPAL_CLAIM.getClaim()), "sub")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_REDIRECT_URI), "https://rp.my.com/cb")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_CLIENT_ID), "rp-my")
.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.RP_RESPONSE_TYPE), "code")
.setSecureSettings(getSecureSettings());
;
final OpenIdConnectRealm realm = new OpenIdConnectRealm(buildConfig(settingsBuilder.build(), threadContext), null, null);
final String state = new State().getValue();
final String nonce = new Nonce().getValue();
final String thehint = randomAlphaOfLength(8);
final OpenIdConnectPrepareAuthenticationResponse response = realm.buildAuthenticationRequestUri(state, nonce, thehint);
assertEqualUrlStrings(
response.getAuthenticationRequestUrl(),
"https://op.example.com/login?login_hint="
+ thehint
+ "&scope=openid&response_type=code&redirect_uri=https%3A%2F%2Frp.my.com%2Fcb&state="
+ state
+ "&nonce="
+ nonce
+ "&client_id=rp-my"
);
assertThat(response.getRealmName(), equalTo(REALM_NAME));
}
private void assertEqualUrlStrings(String actual, String expected) {
final int endOfPath = actual.indexOf('?');
assertThat(endOfPath, greaterThan(-1));
assertThat(actual.substring(0, endOfPath + 1), equalTo(expected.substring(0, endOfPath + 1)));
final HashMap<String, String> actualParams = new HashMap<>();
RestUtils.decodeQueryString(actual, endOfPath + 1, actualParams);
final HashMap<String, String> expectedParams = new HashMap<>();
RestUtils.decodeQueryString(expected, endOfPath + 1, expectedParams);
assertThat(actualParams, equalTo(expectedParams));
}
private AuthenticationResult authenticateWithOidc(
String principal,
UserRoleMapper roleMapper,
boolean notPopulateMetadata,
boolean useAuthorizingRealm,
String authenticatingRealm,
@Nullable Map<String, Object> additionalClaims
) throws Exception {
final MockLookupRealm lookupRealm = new MockLookupRealm(
new RealmConfig(new RealmConfig.RealmIdentifier("mock", "mock_lookup"), globalSettings, env, threadContext)
);
final OpenIdConnectAuthenticator authenticator = mock(OpenIdConnectAuthenticator.class);
final Settings.Builder builder = getBasicRealmSettings();
if (notPopulateMetadata) {
builder.put(getFullSettingKey(REALM_NAME, OpenIdConnectRealmSettings.POPULATE_USER_METADATA), false);
}
if (useAuthorizingRealm) {
builder.putList(
getFullSettingKey(new RealmConfig.RealmIdentifier("oidc", REALM_NAME), DelegatedAuthorizationSettings.AUTHZ_REALMS),
lookupRealm.name()
);
lookupRealm.registerUser(
new User(
principal,
new String[] { "lookup_user_role" },
"Clinton Barton",
"cbarton@shield.gov",
Collections.singletonMap("is_lookup", true),
true
)
);
}
final RealmConfig config = buildConfig(builder.build(), threadContext);
final OpenIdConnectRealm realm = new OpenIdConnectRealm(config, authenticator, roleMapper);
initializeRealms(realm, lookupRealm);
final OpenIdConnectToken token = new OpenIdConnectToken("", new State(), new Nonce(), authenticatingRealm);
final JWTClaimsSet.Builder claimsBuilder = new JWTClaimsSet.Builder().subject(principal)
.audience("https://rp.elastic.co/cb")
.expirationTime(Date.from(now().plusSeconds(3600)))
.issueTime(Date.from(now().minusSeconds(5)))
.jwtID(randomAlphaOfLength(8))
.issuer("https://op.company.org")
.claim("groups", Arrays.asList("group1", "group2", "groups3"))
.claim("mail", "cbarton@shield.gov")
.claim("name", "Clinton Barton")
.claim("id_token_hint", "thisis.aserialized.jwt");
if (additionalClaims != null) {
for (Map.Entry<String, Object> entry : additionalClaims.entrySet()) {
claimsBuilder.claim(entry.getKey(), entry.getValue());
}
}
final JWTClaimsSet claims = claimsBuilder.build();
doAnswer((i) -> {
@SuppressWarnings("unchecked")
ActionListener<JWTClaimsSet> listener = (ActionListener<JWTClaimsSet>) i.getArguments()[1];
listener.onResponse(claims);
return null;
}).when(authenticator).authenticate(any(OpenIdConnectToken.class), anyActionListener());
final PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
realm.authenticate(token, future);
return future.get();
}
private void initializeRealms(Realm... realms) {
MockLicenseState licenseState = mock(MockLicenseState.class);
when(licenseState.isSecurityEnabled()).thenReturn(true);
when(licenseState.isAllowed(Security.DELEGATED_AUTHORIZATION_FEATURE)).thenReturn(true);
final List<Realm> realmList = Arrays.asList(realms);
for (Realm realm : realms) {
realm.initialize(realmList, licenseState);
}
}
private Answer<Class<Void>> getAnswer(AtomicReference<UserRoleMapper.UserData> userData) {
return invocation -> {
assert invocation.getArguments().length == 2;
userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]);
@SuppressWarnings("unchecked")
ActionListener<Set<String>> listener = (ActionListener<Set<String>>) invocation.getArguments()[1];
listener.onResponse(new HashSet<>(Arrays.asList("kibana_user", "role1")));
return null;
};
}
}