Skip to content
Merged
45 changes: 42 additions & 3 deletions openespi-authserver/docs/OAUTH2_CLIENT_MANAGEMENT_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Retrieve a paginated list of OAuth2 clients with filtering and sorting capabilit
- `size` (optional): Page size (default: 20, max: 100)
- `sortBy` (optional): Sort field - client_id, client_name, client_id_issued_at or last_used_at (default: client_id); any other value is 400
- `sortDirection` (optional): Sort direction - asc/desc (default: asc); any other value is 400
- `status` (optional): Filter by client status - active/suspended/revoked
- `status` (optional): Filter by the status in force - active/suspended/revoked (see Update Client Status); any other value is 400
- `securityLevel` (optional): Filter by security level - standard/high/maximum
- `espiVersion` (optional): Filter by ESPI version
- `search` (optional): Text the client name or client ID contains; `%` and `_` match only themselves
Expand Down Expand Up @@ -230,8 +230,47 @@ Update a client's status (activate, suspend, revoke).
}
```

`reason`, `lock_duration_minutes` and `updated_by` are optional. The status is stored, but the token, authorization
and introspection endpoints do not check it yet, so a suspended client still gets tokens (#345). An unknown client
`reason`, `lock_duration_minutes` and `updated_by` are optional. `lock_duration_minutes` (1 to 43200) applies only
with `suspended`, and with any other status it is refused with 400 `invalid_request`. The suspension then ends on its
own when that time has passed (`locked_until`, in whole seconds). Without it, a suspension lasts until the client is
set `active` again. A `revoked` client stays revoked until it is set `active` again. The audit record of the change
holds the status asked for, `lock_duration_minutes` and the resulting `locked_until`.

**A lock only ever restricts.** In the database, `client_status` is what only a status change ends, and
`locked_until` is a lock that ends on its own: it suspends an `active` client while it runs and never ends a stored
`suspended` or `revoked`. So a suspension with `lock_duration_minutes` is stored as `client_status = 'active'` with
`locked_until` set, and a suspension without it as `suspended` with no lock. Anything else that sets a lock, such as
a failure lockout (#353), may only extend one, never shorten it. A status change is the administrator's act and
replaces the client's earlier state, whatever it was: a timed suspension of a `revoked` client ends when its lock
does, as setting the client `active` would end the revocation at once.

Client details and the list report the status in force, not the one stored: a client on a timed suspension is
`suspended` until its lock ends and `active` after. Both also give `locked_until` while it decides the status, that
is, while a timed suspension or lock is running on a client stored `active` (or NULL, the column default);
otherwise it is left out, so a `suspended` client without `locked_until` stays suspended until it is set `active`.
The list's `status` filter uses the same rule, and takes only `active`, `suspended` or `revoked` (an empty value
means no filter; any other value, including a blank one, is 400 `invalid_request`).

**What a status does (#345).** It takes effect on the client's next request, on every database:

- **`suspended`** (stored; until the client is set `active`) **or `revoked`**, or an `active` client whose `locked_until`
is still in the future (a timed suspension, or a lock set by other means; it ends on its own):
- the token endpoint refuses the client with 401 `invalid_client`, as for a wrong secret: no new access token, no
refresh, no `client_credentials` token. The response does not say why;
- the introspection and revocation endpoints refuse the client the same way;
- `/oauth2/authorize` answers 400, as for an unknown `client_id`, without redirecting to the client and before the
customer is sent to the Data Custodian;
- the client's tokens already issued introspect as `active: false`, so the Data Custodian releases no data for
them. They are not deleted.
A customer still at the Data Custodian when the client is suspended gets an error page, and the client receives
neither a code nor `access_denied`.
- **`active`** again, or the end of a timed suspension: the client works again at once, and its unexpired tokens
introspect as active again.

While they last, `revoked` and `suspended` act the same. To end a client's tokens for good, delete the client
(`DELETE /admin/oauth2/clients/{clientId}`, which deletes its authorizations).

An unknown client
is 404 whatever the body holds, as long as it is JSON of the right shape; the body's values are checked after the
client is found (#344). The audit record names the signed-in administrator; `updated_by`, when given, is stored on
the client and kept in the audit record's data, and without it the client records the administrator.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,8 @@ public SecurityFilterChain clientRegistrationSecurityFilterChain(
HttpSecurity http,
RegisteredClientRepository registeredClientRepository,
OAuth2AuthorizationService authorizationService,
PasswordEncoder passwordEncoder) throws Exception {
PasswordEncoder passwordEncoder,
org.greenbuttonalliance.espi.authserver.service.ClientStatusService clientStatus) throws Exception {

OAuth2ClientRegistrationAuthenticationProvider registrationProvider =
new OAuth2ClientRegistrationAuthenticationProvider(registeredClientRepository, authorizationService);
Expand All @@ -315,7 +316,8 @@ public SecurityFilterChain clientRegistrationSecurityFilterChain(
.csrf(csrf -> csrf.ignoringRequestMatchers(CLIENT_REGISTRATION_ENDPOINT))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(rs -> rs.opaqueToken(opaque -> opaque
.introspector(new AuthorizationServiceOpaqueTokenIntrospector(authorizationService))))
.introspector(new AuthorizationServiceOpaqueTokenIntrospector(authorizationService,
clientStatus))))
.addFilterAfter(registrationFilter, AuthorizationFilter.class);
return http.build();
}
Expand Down Expand Up @@ -471,6 +473,9 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h
var grantContexts = context.getBean(org.greenbuttonalliance.espi.authserver.grant.GrantContextSessionStore.class);
var singleUseResponseHandler = new org.greenbuttonalliance.espi.authserver.web.delegate
.SingleUseCustomerAuthorizationResponseHandler();
// #345: a suspended, revoked or locked client gets no authorization, token or active introspection.
ClientStatusEnforcement clientStatusEnforcement = new ClientStatusEnforcement(
context.getBean(org.greenbuttonalliance.espi.authserver.service.ClientStatusService.class));
// #305: the customer is signed in only on the replayed /oauth2/authorize that names a live delegation of
// this session, and only for that request (never saved to the session). After the SecurityContextHolder
// filter, so the session's context is loaded first and restored afterwards.
Expand All @@ -490,8 +495,12 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h
// provider and to the pre-validation filter that checks redirect_uri and scope before the customer
// is authenticated. Setting it on the provider alone leaves that filter on Spring's default scope
// check: a narrowed scope is refused and an administrative scope is delegated to the customer.
.authorizationCodeRequestAuthenticationValidator(
org.greenbuttonalliance.espi.authserver.grant.EspiGrantScopePolicy.authorizationCodeValidator()));
// #345: a client that is not active gets the error of an unknown client_id, checked before the
// redirect URI and scope. Spring checks the grant type first, so a client not registered for
// authorization_code still gets unauthorized_client.
.authorizationCodeRequestAuthenticationValidator(clientStatusEnforcement.authorizationCodeRequest()
.andThen(org.greenbuttonalliance.espi.authserver.grant.EspiGrantScopePolicy
.authorizationCodeValidator())));

// Advertise the RFC 7591 endpoint (wired on its own chain, see clientRegistrationSecurityFilterChain)
// in /.well-known/oauth-authorization-server. The stock clientRegistrationEndpoint(...) configurer
Expand Down Expand Up @@ -532,7 +541,12 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h
// invalid_client with a Basic challenge (RFC 6749 §5.2), whether it sent no credentials or wrong ones.
OAuth2ClientChallenge clientChallenge = new OAuth2ClientChallenge();
authorizationServerConfigurer.clientAuthentication(clientAuthentication -> clientAuthentication
// #345: a client that is not active fails authentication like a wrong secret.
.authenticationProviders(providers -> providers.replaceAll(clientStatusEnforcement::clientAuthentication))
.errorResponseHandler(clientChallenge));
// #345: a token of a client that is not active introspects as active: false.
authorizationServerConfigurer.tokenIntrospectionEndpoint(introspection -> introspection
.authenticationProviders(providers -> providers.replaceAll(clientStatusEnforcement::introspection)));
AuthorizationServerSettings settings = context.getBean(AuthorizationServerSettings.class);
RequestMatcher clientEndpoints = new OrRequestMatcher(
PathPatternRequestMatcher.withDefaults().matcher(settings.getTokenEndpoint()),
Expand Down Expand Up @@ -582,9 +596,10 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain actuatorSecurityFilterChain(
HttpSecurity http, OAuth2AuthorizationService authorizationService) throws Exception {
HttpSecurity http, OAuth2AuthorizationService authorizationService,
org.greenbuttonalliance.espi.authserver.service.ClientStatusService clientStatus) throws Exception {
OpaqueTokenIntrospector introspector = new AdminScopeOpaqueTokenIntrospector(
new AuthorizationServiceOpaqueTokenIntrospector(authorizationService));
new AuthorizationServiceOpaqueTokenIntrospector(authorizationService, clientStatus));

http
.securityMatcher(EndpointRequest.toAnyEndpoint())
Expand All @@ -611,9 +626,10 @@ public SecurityFilterChain actuatorSecurityFilterChain(
@Bean
@Order(2)
public SecurityFilterChain adminApiBearerSecurityFilterChain(
HttpSecurity http, OAuth2AuthorizationService authorizationService) throws Exception {
HttpSecurity http, OAuth2AuthorizationService authorizationService,
org.greenbuttonalliance.espi.authserver.service.ClientStatusService clientStatus) throws Exception {
OpaqueTokenIntrospector introspector = new AdminScopeOpaqueTokenIntrospector(
new AuthorizationServiceOpaqueTokenIntrospector(authorizationService));
new AuthorizationServiceOpaqueTokenIntrospector(authorizationService, clientStatus));

List<RequestMatcher> adminPaths = new ArrayList<>();
for (String path : ADMIN_BEARER_API_PATHS) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.greenbuttonalliance.espi.authserver.service.ClientStatusService;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
Expand All @@ -50,14 +51,21 @@
* <p>Attributes are built from the stored {@link OAuth2AccessToken} itself (not the persisted claims
* map) so {@code iat}/{@code exp} are always {@link java.time.Instant}s, which
* {@code OpaqueTokenAuthenticationProvider} requires. Scopes become {@code SCOPE_*} authorities.</p>
*
* <p>A token of a client that is suspended, revoked or locked is not active (#345), as at
* {@code /oauth2/introspect} ({@link ClientStatusEnforcement}).</p>
*/
public final class AuthorizationServiceOpaqueTokenIntrospector implements OpaqueTokenIntrospector {

private final OAuth2AuthorizationService authorizationService;
private final ClientStatusService clientStatus;

public AuthorizationServiceOpaqueTokenIntrospector(OAuth2AuthorizationService authorizationService) {
public AuthorizationServiceOpaqueTokenIntrospector(OAuth2AuthorizationService authorizationService,
ClientStatusService clientStatus) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(clientStatus, "clientStatus cannot be null");
this.authorizationService = authorizationService;
this.clientStatus = clientStatus;
}

@Override
Expand All @@ -71,6 +79,10 @@ public OAuth2AuthenticatedPrincipal introspect(String token) {
if (accessToken == null || !accessToken.isActive()) {
throw new BadOpaqueTokenException("Access token is not active");
}
// #345: as at /oauth2/introspect, a token of a suspended, revoked or locked client is not active.
if (!clientStatus.isActiveId(authorization.getRegisteredClientId())) {
throw new BadOpaqueTokenException("Access token is not active");
}

OAuth2AccessToken value = accessToken.getToken();
Map<String, Object> attributes = new HashMap<>();
Expand Down
Loading
Loading