forked from cloudfoundry/uaa
/
ClientAdminEndpoints.java
450 lines (374 loc) · 17.3 KB
/
ClientAdminEndpoints.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
/*
* Cloud Foundry 2012.02.03 Beta
* Copyright (c) [2009-2012] VMware, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*/
package org.cloudfoundry.identity.uaa.oauth;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cloudfoundry.identity.uaa.security.DefaultSecurityContextAccessor;
import org.cloudfoundry.identity.uaa.security.SecurityContextAccessor;
import org.cloudfoundry.identity.uaa.util.UaaStringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jmx.export.annotation.ManagedMetric;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.support.MetricType;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.BaseClientDetails;
import org.springframework.security.oauth2.provider.ClientAlreadyExistsException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* Controller for listing and manipulating OAuth2 clients.
*
* @author Dave Syer
*/
@Controller
@ManagedResource
public class ClientAdminEndpoints implements InitializingBean {
private final Log logger = LogFactory.getLog(getClass());
private static final Set<String> VALID_GRANTS = new HashSet<String>(Arrays.asList("implicit", "password",
"client_credentials", "authorization_code", "refresh_token"));
private static final Collection<String> NON_ADMIN_INVALID_GRANTS = new HashSet<String>(Arrays.asList("password"));
private static final Collection<String> NON_ADMIN_VALID_AUTHORITIES = new HashSet<String>(Arrays.asList("uaa.none"));
private ClientRegistrationService clientRegistrationService;
private ClientDetailsService clientDetailsService;
private SecurityContextAccessor securityContextAccessor = new DefaultSecurityContextAccessor();
private final Map<String, AtomicInteger> errorCounts = new ConcurrentHashMap<String, AtomicInteger>();
private AtomicInteger clientUpdates = new AtomicInteger();
private AtomicInteger clientDeletes = new AtomicInteger();
private AtomicInteger clientSecretChanges = new AtomicInteger();
private Set<String> reservedClientIds = StringUtils.commaDelimitedListToSet("uaa");
/**
* @param clientRegistrationService the clientRegistrationService to set
*/
public void setClientRegistrationService(ClientRegistrationService clientRegistrationService) {
this.clientRegistrationService = clientRegistrationService;
}
/**
* @param clientDetailsService the clientDetailsService to set
*/
public void setClientDetailsService(ClientDetailsService clientDetailsService) {
this.clientDetailsService = clientDetailsService;
}
void setSecurityContextAccessor(SecurityContextAccessor securityContextAccessor) {
this.securityContextAccessor = securityContextAccessor;
}
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Client Registration Count")
public int getTotalClients() {
return clientRegistrationService.listClientDetails().size();
}
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Client Update Count (Since Startup)")
public int getClientUpdates() {
return clientUpdates.get();
}
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Client Delete Count (Since Startup)")
public int getClientDeletes() {
return clientDeletes.get();
}
@ManagedMetric(metricType = MetricType.COUNTER, displayName = "Client Secret Change Count (Since Startup)")
public int getClientSecretChanges() {
return clientSecretChanges.get();
}
@ManagedMetric(displayName = "Errors Since Startup")
public Map<String, AtomicInteger> getErrorCounts() {
return errorCounts;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(clientRegistrationService != null, "A ClientRegistrationService must be provided");
Assert.state(clientDetailsService != null, "A ClientDetailsService must be provided");
}
@RequestMapping(value = "/oauth/clients/{client}", method = RequestMethod.GET)
@ResponseBody
public ClientDetails getClientDetails(@PathVariable String client) throws Exception {
try {
return removeSecret(clientDetailsService.loadClientByClientId(client));
}
catch (InvalidClientException e) {
throw new NoSuchClientException("No such client: " + client);
}
catch (BadClientCredentialsException e) {
// Defensive check, in case the clientDetailsService starts throwing these instead
throw new NoSuchClientException("No such client: " + client);
}
}
@RequestMapping(value = "/oauth/clients", method = RequestMethod.POST)
public ResponseEntity<Void> createClientDetails(@RequestBody BaseClientDetails client) throws Exception {
ClientDetails details = validateClient(client, true);
clientRegistrationService.addClientDetails(details);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
@RequestMapping(value = "/oauth/clients/{client}", method = RequestMethod.PUT)
public ResponseEntity<Void> updateClientDetails(@RequestBody BaseClientDetails client,
@PathVariable("client") String clientId) throws Exception {
Assert.state(clientId.equals(client.getClientId()),
String.format("The client id (%s) does not match the URL (%s)", client.getClientId(), clientId));
ClientDetails details = client;
try {
ClientDetails existing = getClientDetails(clientId);
details = syncWithExisting(existing, client);
}
catch (Exception e) {
logger.warn("Couldn't fetch client config for client_id: " + clientId, e);
}
details = validateClient(details, false);
clientRegistrationService.updateClientDetails(details);
clientUpdates.incrementAndGet();
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
@RequestMapping(value = "/oauth/clients/{client}", method = RequestMethod.DELETE)
public ResponseEntity<Void> removeClientDetails(@PathVariable String client) throws Exception {
clientRegistrationService.removeClientDetails(client);
clientDeletes.incrementAndGet();
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
@RequestMapping(value = "/oauth/clients", method = RequestMethod.GET)
public ResponseEntity<Map<String, ClientDetails>> listClientDetails() throws Exception {
List<ClientDetails> details = clientRegistrationService.listClientDetails();
Map<String, ClientDetails> map = new LinkedHashMap<String, ClientDetails>();
for (ClientDetails client : details) {
map.put(client.getClientId(), removeSecret(client));
}
return new ResponseEntity<Map<String, ClientDetails>>(map, HttpStatus.OK);
}
@RequestMapping(value = "/oauth/clients/{client}/secret", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void changeSecret(@PathVariable String client, @RequestBody SecretChangeRequest change) {
ClientDetails clientDetails;
try {
clientDetails = clientDetailsService.loadClientByClientId(client);
}
catch (InvalidClientException e) {
throw new NoSuchClientException("No such client: " + client);
}
checkPasswordChangeIsAllowed(clientDetails, change.getOldSecret());
clientRegistrationService.updateClientSecret(client, change.getSecret());
clientSecretChanges.incrementAndGet();
}
@ExceptionHandler(InvalidClientDetailsException.class)
public ResponseEntity<InvalidClientDetailsException> handleInvalidClientDetails(InvalidClientDetailsException e) {
incrementErrorCounts(e);
return new ResponseEntity<InvalidClientDetailsException>(e, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(NoSuchClientException.class)
public ResponseEntity<Void> handleNoSuchClient(NoSuchClientException e) {
incrementErrorCounts(e);
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
@ExceptionHandler(ClientAlreadyExistsException.class)
public ResponseEntity<InvalidClientDetailsException> handleClientAlreadyExists(ClientAlreadyExistsException e) {
incrementErrorCounts(e);
return new ResponseEntity<InvalidClientDetailsException>(new InvalidClientDetailsException(e.getMessage()) , HttpStatus.CONFLICT);
}
private void incrementErrorCounts(Exception e) {
String series = UaaStringUtils.getErrorName(e);
AtomicInteger value = errorCounts.get(series);
if (value == null) {
synchronized (errorCounts) {
value = errorCounts.get(series);
if (value == null) {
value = new AtomicInteger();
errorCounts.put(series, value);
}
}
}
value.incrementAndGet();
}
private ClientDetails validateClient(ClientDetails prototype, boolean create) {
BaseClientDetails client = new BaseClientDetails(prototype);
String clientId = client.getClientId();
if (create && reservedClientIds.contains(clientId)) {
throw new InvalidClientDetailsException("Not allowed: " + clientId + " is a reserved client_id");
}
Set<String> requestedGrantTypes = client.getAuthorizedGrantTypes();
if (requestedGrantTypes.isEmpty()) {
throw new InvalidClientDetailsException("An authorized grant type must be provided. Must be one of: "
+ VALID_GRANTS.toString());
}
for (String grant : requestedGrantTypes) {
if (!VALID_GRANTS.contains(grant)) {
throw new InvalidClientDetailsException(grant + " is not an allowed grant type. Must be one of: "
+ VALID_GRANTS.toString());
}
}
if (!securityContextAccessor.isAdmin()) {
// Not admin, so be strict with grant types and scopes
for (String grant : requestedGrantTypes) {
if (NON_ADMIN_INVALID_GRANTS.contains(grant)) {
throw new InvalidClientDetailsException(grant
+ " is not an allowed grant type for non-admin caller.");
}
}
if (requestedGrantTypes.contains("implicit")
&& (requestedGrantTypes.contains("authorization_code") || requestedGrantTypes
.contains("refresh_token"))) {
throw new InvalidClientDetailsException(
"Not allowed: implicit grant type is not allowed together with authorization_code or refresh_token");
}
String callerId = securityContextAccessor.getClientId();
if (callerId != null) {
// New scopes are allowed if they are for the caller or the new client.
String callerPrefix = callerId + ".";
String clientPrefix = clientId + ".";
ClientDetails caller = clientDetailsService.loadClientByClientId(callerId);
Set<String> validScope = caller.getScope();
for (String scope : client.getScope()) {
if (scope.startsWith(callerPrefix) || scope.startsWith(clientPrefix)) {
// Allowed
continue;
}
if (!validScope.contains(scope)) {
throw new InvalidClientDetailsException(scope + " is not an allowed scope for caller="
+ callerId + ". Must have prefix in [" + callerPrefix + "," + clientPrefix
+ "] or be one of: " + validScope.toString());
}
}
}
else { // No client caller. Shouldn't happen in practice, but let's be defensive
// New scopes are allowed if they are for the caller or the new client.
String clientPrefix = clientId + ".";
for (String scope : client.getScope()) {
if (!scope.startsWith(clientPrefix)) {
throw new InvalidClientDetailsException(scope
+ " is not an allowed scope for null caller and client_id=" + clientId
+ ". Must start with '" + clientPrefix + "'");
}
}
}
Set<String> validAuthorities = new HashSet<String>(NON_ADMIN_VALID_AUTHORITIES);
if (requestedGrantTypes.contains("client_credentials")) {
// If client_credentials is used then the client might be a resource server
validAuthorities.add("uaa.resource");
}
for (String authority : AuthorityUtils.authorityListToSet(client.getAuthorities())) {
if (!validAuthorities.contains(authority)) {
throw new InvalidClientDetailsException(authority + " is not an allowed authority for caller="
+ callerId + ". Must be one of: " + validAuthorities.toString());
}
}
}
if (client.getAuthorities().isEmpty()) {
client.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("uaa.none"));
}
// The UAA does not allow or require resource ids to be registered because they are determined dynamically
client.setResourceIds(Collections.singleton("none"));
if (client.getScope().isEmpty()) {
client.setScope(Collections.singleton("uaa.none"));
}
if (requestedGrantTypes.contains("implicit")) {
if (StringUtils.hasText(client.getClientSecret())) {
throw new InvalidClientDetailsException("Implicit grant should not have a client_secret");
}
}
if (create) {
// Only check for missing secret if client is being created.
if (!isImplicit(requestedGrantTypes) && !StringUtils.hasText(client.getClientSecret())) {
throw new InvalidClientDetailsException("client_secret is required for non-implicit grant types");
}
}
return client;
}
private boolean isImplicit(Set<String> requestedGrantTypes) {
return Collections.singleton("implicit").equals(requestedGrantTypes);
}
private void checkPasswordChangeIsAllowed(ClientDetails clientDetails, String oldSecret) {
if (!securityContextAccessor.isClient()) {
// Trusted client (not acting on behalf of user)
throw new IllegalStateException("Only a client can change client secret");
}
String clientId = clientDetails.getClientId();
// Call is by client
String currentClientId = securityContextAccessor.getClientId();
if (securityContextAccessor.isAdmin()) {
// even an admin needs to provide the old value to change password
if (clientId.equals(currentClientId) && !StringUtils.hasText(oldSecret)) {
throw new IllegalStateException("Previous secret is required even for admin");
}
}
else {
if (!clientId.equals(currentClientId)) {
logger.warn("Client with id " + currentClientId + " attempting to change password for client "
+ clientId);
// TODO: This should be audited when we have non-authentication events in the log
throw new IllegalStateException("Bad request. Not permitted to change another client's secret");
}
// Client is changing their own secret, old password is required
if (!StringUtils.hasText(oldSecret)) {
throw new IllegalStateException("Previous secret is required");
}
}
}
private ClientDetails removeSecret(ClientDetails client) {
if (client == null) {
return null;
}
BaseClientDetails details = new BaseClientDetails();
details.setClientId(client.getClientId());
details.setScope(client.getScope());
details.setResourceIds(client.getResourceIds());
details.setAuthorizedGrantTypes(client.getAuthorizedGrantTypes());
details.setRegisteredRedirectUri(client.getRegisteredRedirectUri());
details.setAuthorities(client.getAuthorities());
details.setAccessTokenValiditySeconds(client.getAccessTokenValiditySeconds());
return details;
}
private ClientDetails syncWithExisting(ClientDetails existing, ClientDetails input) {
BaseClientDetails details = new BaseClientDetails(input);
if (details.getAccessTokenValiditySeconds() == null) {
details.setAccessTokenValiditySeconds(existing.getAccessTokenValiditySeconds());
}
if (details.getRefreshTokenValiditySeconds() == null) {
details.setRefreshTokenValiditySeconds(existing.getRefreshTokenValiditySeconds());
}
if (details.getAuthorities() == null || details.getAuthorities().isEmpty()) {
details.setAuthorities(existing.getAuthorities());
}
if (details.getAuthorizedGrantTypes() == null || details.getAuthorizedGrantTypes().isEmpty()) {
details.setAuthorizedGrantTypes(existing.getAuthorizedGrantTypes());
}
if (details.getRegisteredRedirectUri() == null || details.getRegisteredRedirectUri().isEmpty()) {
details.setRegisteredRedirectUri(existing.getRegisteredRedirectUri());
}
if (details.getResourceIds() == null || details.getResourceIds().isEmpty()) {
details.setResourceIds(existing.getResourceIds());
}
if (details.getScope() == null || details.getScope().isEmpty()) {
details.setScope(existing.getScope());
}
return details;
}
}