Skip to content

KeyFlowAuthenticator stays signed out after the refresh token is refused; it never signs in again with the service account key #1294

Open

Description

@sashomasho

Description

Once the token endpoint refuses the stored refresh token (for example, because it has expired), KeyFlowAuthenticator cannot recover. Every later request on that client fails with AuthenticationException: Failed to obtain access token until the client is recreated or the process restarts.

This hits long-running services that keep one API client for the life of the process. That is the usage the docs recommend, since the deprecated constructors leak resources.

Versions

  • cloud.stackit.sdk:core 0.4.1 (latest on Maven Central)
  • cloud.stackit.sdk:objectstorage 0.4.0 / 0.5.0
  • The same code is on main as of this issue.

Stack trace

cloud.stackit.sdk.core.exception.AuthenticationException: Failed to obtain access token
  at cloud.stackit.sdk.core.KeyFlowAuthenticator.authenticate(KeyFlowAuthenticator.java:163)
  at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(...)
  ...
  at cloud.stackit.sdk.objectstorage.v2api.api.DefaultApi.listCredentialsGroups(...)
Caused by: cloud.stackit.sdk.core.exception.ApiException: Message: Bad Request

Cause

getAccessToken() renews an expired token only through the refresh-token grant:

synchronized (tokenRefreshMonitor) {
    if (token == null) {
        createAccessToken();                  // JWT assertion, signed with the service account key
    } else if (token.isExpired()) {
        createAccessTokenWithRefreshToken();  // refresh_token grant
    }
    return token.getAccessToken();
}

When the refresh-token grant fails (the token endpoint answers 400 Bad Request), parseTokenResponse throws before token is replaced. So:

  1. The expired token, with its refused refresh token, stays in token.
  2. The next request takes the same token.isExpired() branch and sends the same refresh token, which is refused again.
  3. The authenticator never falls back to createAccessToken(), even though the service account key it holds would get a new token.

The client stays broken permanently, although it has everything it needs to recover.

Steps to reproduce

  1. Build an API client with key-flow auth: new ObjectStorageApi(new CoreConfiguration().serviceAccountKey(...)).
  2. Make a call, so a token is issued.
  3. Let the access token expire, and make the refresh token invalid (wait until it expires, or revoke it).
  4. Make another call. It throws AuthenticationException: Failed to obtain access token, caused by ApiException: Bad Request.
  5. Every later call fails the same way.

To reproduce without waiting, use a mock token endpoint (CoreConfiguration.tokenCustomUrl(...)):

  • Answer the first jwt-bearer grant with an access token whose exp falls inside the 60-second leeway, so the SDK treats it as already expired.
  • Answer every refresh_token grant with 400.

The second API call then fails, and so does every call after it. Against the real token endpoint, a malformed refresh token is answered with 400 Bad Request, the same error as in the trace above.

Expected behaviour

When the refresh-token grant is refused, the authenticator should request a new token with the service account key (the jwt-bearer assertion grant), as it does on first use. It should fail only if that request is refused too.

Suggested fix

Fall back to a new assertion when the refresh fails:

protected void createAccessTokenWithRefreshToken() throws IOException, ApiException {
    synchronized (tokenRefreshMonitor) {
        String refreshToken = token.refreshToken;
        try (Response response = requestToken(REFRESH_TOKEN, refreshToken).execute()) {
            parseTokenResponse(response);
        } catch (ApiException e) {
            // Refresh token refused (expired or revoked): sign in again with the key.
            try {
                createAccessToken();
            } catch (InvalidKeySpecException keyError) {
                throw new AuthenticationException("Failed to obtain access token", keyError);
            }
        }
    }
}

Alternatively, getAccessToken() could set token = null when the refresh fails, so the next call goes through createAccessToken().

Workaround

Pass a custom OkHttpClient to the API client constructor, with a KeyFlowAuthenticator subclass that overrides createAccessTokenWithRefreshToken() as above. When given its own client, the SDK leaves authentication to the caller. We've confirmed this against the real token endpoint.

Related

#160 ("prevent loops in key flow authenticator") changes the same class but doesn't seem to cover this case.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions