Add OAuth token revocation support Add RFC 7009 revocation to the native HTTP client and wire Google and Keycloak to their provider revocation endpoints. Flush cached Git-over-HTTP validations when core revokes a token, using targeted invalidation when possible and a full flush when the account cannot be mapped safely. Depends-On: https://gerrit-review.googlesource.com/c/gerrit/+/630424 Change-Id: I74514da03cd5a75e26ec7549c1f0a9ebec9c032d
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java index 96878e1..8d91a90 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/Module.java
@@ -18,8 +18,10 @@ import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider; import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider; +import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.server.account.AccountExternalIdCreator; import com.google.gerrit.server.account.externalids.ExternalIdFactory; +import com.google.gerrit.server.auth.oauth.OAuthTokenRevokedListener; import com.google.gerrit.server.config.GerritServerConfig; import com.google.inject.AbstractModule; import com.google.inject.Inject; @@ -34,6 +36,7 @@ import com.googlesource.gerrit.plugins.oauth.base.OAuthServiceProviderConfig; import com.googlesource.gerrit.plugins.oauth.base.OAuthServiceProviderExternalIdScheme; import com.googlesource.gerrit.plugins.oauth.base.OAuthTokenValidationCache; +import com.googlesource.gerrit.plugins.oauth.base.OAuthTokenValidationCacheCleaner; import com.googlesource.gerrit.plugins.oauth.bitbucket.BitbucketOAuthService; import com.googlesource.gerrit.plugins.oauth.cas.CasOAuthService; import com.googlesource.gerrit.plugins.oauth.dex.DexOAuthService; @@ -116,6 +119,10 @@ bind(OAuthPluginConfigFactory.class); bind(HttpOAuthClientFactory.class); install(OAuthTokenValidationCache.module()); + // Drop cached Git-over-HTTP validations when core revokes a token, so a revoked token stops + // being accepted immediately instead of lingering until the validation entry's TTL. + DynamicSet.bind(binder(), OAuthTokenRevokedListener.class) + .to(OAuthTokenValidationCacheCleaner.class); bindServiceProviders(); bindExternalIdCreators(); bindOAuthProviders();
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCache.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCache.java index f6b9c88..b4ff4c9 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCache.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCache.java
@@ -26,7 +26,11 @@ import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -104,6 +108,40 @@ } } + /** + * Invalidates every cached validation whose resolved identity ({@link + * OAuthUserInfo#getExternalId}) is in {@code externalIds}. Used on the (rare) revocation path: a + * single scan, no hot-path index. + */ + public void invalidateForExternalIds(Set<String> externalIds) { + if (externalIds.isEmpty()) { + return; + } + List<String> toDrop = new ArrayList<>(); + for (Map.Entry<String, Entry> e : cache.asMap().entrySet()) { + String externalId = e.getValue().userInfo.getExternalId(); + if (externalId != null && externalIds.contains(externalId)) { + toDrop.add(e.getKey()); + } + } + cache.invalidateAll(toDrop); + if (log.isDebugEnabled()) { + log.debug( + "{} invalidated {} entr(ies) for {} external id(s)", + CACHE_NAME, + toDrop.size(), + externalIds.size()); + } + } + + /** Drops every cached validation (bulk revocation / site compromise). */ + public void invalidateAll() { + cache.invalidateAll(); + if (log.isDebugEnabled()) { + log.debug("{} INVALIDATE ALL", CACHE_NAME); + } + } + private static String hash(String token) { return Hashing.sha256().hashString(token, StandardCharsets.UTF_8).toString(); }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheCleaner.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheCleaner.java new file mode 100644 index 0000000..3702e20 --- /dev/null +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheCleaner.java
@@ -0,0 +1,95 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.googlesource.gerrit.plugins.oauth.base; + +import com.google.gerrit.entities.Account; +import com.google.gerrit.server.account.externalids.ExternalIds; +import com.google.gerrit.server.auth.oauth.OAuthTokenRevokedListener; +import com.google.inject.Inject; +import com.google.inject.Singleton; +import java.io.IOException; +import java.util.Set; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * On core OAuth-token revocation, invalidates the revoked account's Git-over-HTTP validation-cache + * entries. The cache is token-hash keyed, so the account is mapped to its external ids ({@link + * ExternalIds#byAccount}) and matching entries are dropped; {@link #onAllTokensRevoked} flushes + * all. + */ +@Singleton +public class OAuthTokenValidationCacheCleaner implements OAuthTokenRevokedListener { + private static final Logger log = LoggerFactory.getLogger(OAuthTokenValidationCacheCleaner.class); + + private final OAuthTokenValidationCache validationCache; + private final ExternalIds externalIds; + + @Inject + OAuthTokenValidationCacheCleaner( + OAuthTokenValidationCache validationCache, ExternalIds externalIds) { + this.validationCache = validationCache; + this.externalIds = externalIds; + } + + @Override + public void onTokenRevoked(Account.Id accountId) { + Set<String> accountExternalIds; + try { + accountExternalIds = + externalIds.byAccount(accountId).stream() + .map(id -> id.key().get()) + .collect(Collectors.toSet()); + } catch (IOException e) { + // Cannot map the account to its external ids, so we cannot target its entries. A revoked + // token must not keep authenticating a cached Git-over-HTTP hit until TTL; flush the whole + // cache instead (over-invalidation is a brief, acceptable revalidation cost). + log.warn( + "Cannot resolve external ids for account {}; flushing all {} entries instead", + accountId, + OAuthTokenValidationCache.CACHE_NAME, + e); + validationCache.invalidateAll(); + return; + } + if (accountExternalIds.isEmpty()) { + // No external ids resolved (unexpected for an OAuth account). We cannot target this account's + // entries, so flush all rather than let a revoked token survive until TTL, same as the + // lookup-failure path above. + log.warn( + "No external ids for account {}; flushing all {} entries instead", + accountId, + OAuthTokenValidationCache.CACHE_NAME); + validationCache.invalidateAll(); + return; + } + log.info( + "OAuth token revoked for account {}; invalidating its {} entries", + accountId, + OAuthTokenValidationCache.CACHE_NAME); + validationCache.invalidateForExternalIds(accountExternalIds); + } + + @Override + public void onAllTokensRevoked() { + // Bulk revocation: blast-radius semantics, so drop the whole cache rather than scan per + // account. + log.info( + "bulk OAuth token revocation; flushing all {} entries", + OAuthTokenValidationCache.CACHE_NAME); + validationCache.invalidateAll(); + } +}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClient.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClient.java index 7f5d498..653a487 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClient.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClient.java
@@ -257,6 +257,51 @@ } @Override + public boolean supportsRevoke() { + return endpoints.revocationEndpoint() != null; + } + + @Override + public void revoke(OAuthToken token) throws IOException { + String revocationEndpoint = endpoints.revocationEndpoint(); + if (revocationEndpoint == null) { + throw new UnsupportedOperationException("Provider has no revocation endpoint configured"); + } + // Prefer the refresh token: revoking it invalidates the whole grant (access + refresh). Google + // otherwise revokes only the presented token. Fall back to the access token when offline access + // was never granted. + String refreshToken = extractRefreshToken(token.getRaw()); + boolean haveRefresh = refreshToken != null && !refreshToken.isEmpty(); + String toRevoke = haveRefresh ? refreshToken : token.getToken(); + if (toRevoke == null || toRevoke.isEmpty()) { + throw new IOException("No token available to revoke"); + } + String hint = haveRefresh ? "refresh_token" : "access_token"; + List<String[]> body = new ArrayList<>(); + body.add(new String[] {"token", toRevoke}); + body.add(new String[] {"token_type_hint", hint}); + // Request-body client auth only (Google's revocation endpoint takes token-only; adding Basic + // auth is not required and is omitted to match the verified request shape). + addRequestBodyClientAuth(body); + logger.atFine().log("OAuth revoke: POST token_type_hint=%s to %s", hint, revocationEndpoint); + Map<String, String> headers = new LinkedHashMap<>(); + headers.put("Content-Type", "application/x-www-form-urlencoded"); + OAuthHttpTransport.Response response = + httpRequest("POST", revocationEndpoint, headers, formEncode(body)); + // RFC 7009 §2.2: a successful or unnecessary revocation returns 200; an unknown/already-invalid + // token is a no-op, which Google signals as 400 invalid_token. + if (response.code == 400 && isInvalidToken(response.body)) { + logger.atFine().log("OAuth revoke: token already invalid at the IdP (no-op)"); + return; + } + if (response.code < 200 || response.code >= 300) { + throw new IOException( + "Revocation request failed: HTTP " + response.code + " " + safeError(response)); + } + logger.atFine().log("OAuth revoke succeeded (HTTP %d)", response.code); + } + + @Override public String get(URI resource, OAuthToken token) throws IOException { return get(resource, token, Map.of()); } @@ -421,6 +466,21 @@ return false; } + private boolean isInvalidToken(@Nullable String body) { + if (body == null) { + return false; + } + try { + JsonElement parsed = gson.fromJson(body, JsonElement.class); + if (parsed != null && parsed.isJsonObject()) { + return "invalid_token".equals(asString(parsed.getAsJsonObject().get("error"))); + } + } catch (JsonSyntaxException ignored) { + // fall through + } + return false; + } + @Nullable private static Long asLong(@Nullable JsonElement e) { if (e == null || e.isJsonNull()) {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthClient.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthClient.java index bafc9fa..9124ce10 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthClient.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthClient.java
@@ -64,6 +64,21 @@ OAuthToken refresh(OAuthToken expiredToken) throws IOException; /** + * Revokes a token at the identity provider (OAuth 2.0 Token Revocation, RFC 7009 §2.1) by POSTing + * it to the provider's configured {@code revocationEndpoint}. Prefers the refresh token carried + * in {@code token.getRaw()} (revoking it invalidates the whole grant); falls back to the access + * token. Per RFC 7009 §2.2 an unknown or already-invalid token is a successful no-op. + * + * @param token the token whose grant should be revoked + * @throws IOException on a transient IdP/network failure + * @throws UnsupportedOperationException if the provider has no revocation endpoint configured + */ + void revoke(OAuthToken token) throws IOException; + + /** Whether a revocation endpoint is configured, i.e. {@link #revoke} is usable. */ + boolean supportsRevoke(); + + /** * Fetches a protected resource with the given token. * * @return the response body; throws if the provider did not return success.
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthProviderEndpoints.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthProviderEndpoints.java index abae447..01d8d06 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthProviderEndpoints.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/client/OAuthProviderEndpoints.java
@@ -41,6 +41,9 @@ * instead of failing (CAS). * <li>{@code enablePkce} -- initialize PKCE on the authorization redirect and replay the verifier * on token exchange. + * <li>{@code revocationEndpoint} -- the provider's OAuth 2.0 token revocation endpoint (RFC + * 7009), or {@code null} when the provider does not support revocation. Providers that omit + * it use the 8-argument constructor. * </ul> */ public record OAuthProviderEndpoints( @@ -51,7 +54,8 @@ BearerPlacement bearerPlacement, TokenResponseFormat tokenResponseFormat, boolean tolerateMissingTokenType, - boolean enablePkce) { + boolean enablePkce, + @Nullable String revocationEndpoint) { public OAuthProviderEndpoints { requireNonBlank(authorizationEndpoint, "authorizationEndpoint"); requireNonBlank(tokenEndpoint, "tokenEndpoint"); @@ -63,6 +67,32 @@ if (scope != null && scope.isEmpty()) { scope = null; } + // Same "empty means absent" normalization for the optional revocation endpoint. + if (revocationEndpoint != null && revocationEndpoint.isBlank()) { + revocationEndpoint = null; + } + } + + /** Convenience constructor for the providers that do not support token revocation (RFC 7009). */ + public OAuthProviderEndpoints( + String authorizationEndpoint, + String tokenEndpoint, + @Nullable String scope, + ClientAuthStyle clientAuthStyle, + BearerPlacement bearerPlacement, + TokenResponseFormat tokenResponseFormat, + boolean tolerateMissingTokenType, + boolean enablePkce) { + this( + authorizationEndpoint, + tokenEndpoint, + scope, + clientAuthStyle, + bearerPlacement, + tokenResponseFormat, + tolerateMissingTokenType, + enablePkce, + /* revocationEndpoint= */ null); } private static void requireNonBlank(String value, String field) {
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/google/Google2Api.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/google/Google2Api.java index 40d56db..a8c1cf8 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/google/Google2Api.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/google/Google2Api.java
@@ -28,4 +28,9 @@ public String getTokenInfoEndpoint() { return "https://oauth2.googleapis.com/tokeninfo"; } + + /** OAuth 2.0 token revocation endpoint (RFC 7009); revoking a refresh token kills the grant. */ + public String getRevocationEndpoint() { + return "https://oauth2.googleapis.com/revoke"; + } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/google/GoogleOAuthService.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/google/GoogleOAuthService.java index 98f392c..0978d17 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/google/GoogleOAuthService.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/google/GoogleOAuthService.java
@@ -108,7 +108,8 @@ BearerPlacement.AUTHORIZATION_HEADER, TokenResponseFormat.JSON, /* tolerateMissingTokenType= */ false, - enablePkce); + enablePkce, + api.getRevocationEndpoint()); this.client = clientFactory.create(PROVIDER_NAME, endpoints); extIdScheme = OAuthServiceProviderExternalIdScheme.create(PROVIDER_NAME); @@ -256,4 +257,14 @@ public OAuthToken refresh(OAuthToken token) throws IOException { return client.refresh(token); } + + @Override + public boolean supportsRevoke() { + return client.supportsRevoke(); + } + + @Override + public void revoke(OAuthToken token) throws IOException { + client.revoke(token); + } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakApi.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakApi.java index 6b15c7b..bb5822f 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakApi.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakApi.java
@@ -35,6 +35,11 @@ return String.format("%s/realms/%s/protocol/openid-connect/token", rootUrl, realm); } + /** Realm OAuth 2.0 token revocation endpoint (RFC 7009). */ + public String getRevocationEndpoint() { + return String.format("%s/realms/%s/protocol/openid-connect/revoke", rootUrl, realm); + } + /** Realm issuer URL — the {@code iss} claim in Keycloak's JWTs. */ public String getIssuer() { return String.format("%s/realms/%s", rootUrl, realm);
diff --git a/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakOAuthService.java b/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakOAuthService.java index b454b18..2a3e600 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakOAuthService.java +++ b/src/main/java/com/googlesource/gerrit/plugins/oauth/keycloak/KeycloakOAuthService.java
@@ -87,7 +87,8 @@ BearerPlacement.URI_QUERY_ACCESS_TOKEN, TokenResponseFormat.JSON, /* tolerateMissingTokenType= */ false, - enablePKCE); + enablePKCE, + api.getRevocationEndpoint()); client = clientFactory.create(PROVIDER_NAME, endpoints); if (providedValidator != null) { this.validator = providedValidator; @@ -124,4 +125,14 @@ public OAuthToken refresh(OAuthToken token) throws IOException { return client.refresh(token); } + + @Override + public boolean supportsRevoke() { + return client.supportsRevoke(); + } + + @Override + public void revoke(OAuthToken token) throws IOException { + client.revoke(token); + } }
diff --git a/src/main/resources/Documentation/providers.md b/src/main/resources/Documentation/providers.md new file mode 100644 index 0000000..a2ad05f --- /dev/null +++ b/src/main/resources/Documentation/providers.md
@@ -0,0 +1,150 @@ +# Provider capability matrix + +A per-provider view of the security-relevant features. "Git path" means +Git-over-HTTP token validation (`enable-git-over-http`); browser login (the +OAuth authorization-code flow) is supported by every provider and is not listed. + +Every provider's browser login runs on the `HttpOAuthClient` +(JDK + Gson only); see the implementation note below. + +| Provider | Defense-in-depth (Git path) | User-info mapper | PKCE | Git-over-HTTP | Refresh | Revocation | Notes | +|-------------|--------------------------------|--------------------|------|-------------------|---------|------------|------------------------------------------------------------------------------------------------------------------------------------------| +| Google | `aud`+`azp`, `ev`, `intro` | inline (by design) | yes | opt-in, `cache` | yes | yes | opaque `tokeninfo`; `trusted-audience`; `domain` unsupported on Git path | +| GitHub | `app`, `intro` | shared | yes | opt-in, `cache`\* | n/a | – | opaque check-token; needs `client-secret`; GHE via `root-url` | +| Discovery | `jwks`, `aud`+`iss` | shared | yes | opt-in | yes | – | generic OIDC; JWT bearer; needs `jwks_uri` | +| Keycloak | `jwks`, `aud`+`iss` | shared | yes | opt-in | yes | yes | OIDC; rejects the default `account` audience; realm RFC 7009 revoke endpoint | +| SAP IAS | `jwks` (id_token) | inline | yes | on by default | – | – | grandfathered before the opt-in default; also supports the resource-owner password grant | +| GitLab | `app`, `scope`, `sub`, `state`, `intro` | shared | yes | opt-in, `cache` | yes | – | opaque `token/info` + `/api/v4/user`; `required-scope` (default `read_user`); `trusted-audience` | +| Bitbucket | – | inline | yes | – | – | – | resource fetch; query-parameter bearer | +| Azure | `app`, `jwt`, `intro`, `tid` | shared | yes | opt-in, `cache`\* | yes | – | Entra ID; `tenant`; Office365 account-linking alias; Git path introspects Graph `/me` (tokens must be minted by this Gerrit's Azure app) | +| Dex | – | inline | yes | – | – | – | id_token based; query-parameter bearer | +| CAS | – | inline | yes | – | – | – | query-parameter bearer; form or JSON token (`use-json-extractor`); tolerates missing `token_type` | +| AirVantage | – | inline | yes | – | – | – | query-parameter bearer | +| Facebook | – | inline | yes | – | – | – | request-body client auth | +| Phabricator | – | inline | yes | – | – | – | query-parameter bearer | + +## Legend + +Defense-in-depth (Git path) tokens: + +- `aud` — token audience must be a trusted client id — confused-deputy defense + (Google also checks `azp` when present). +- `trusted-audience` — a Git-path option for Google and GitLab (not a separate + check): it extends the accepted audience set from just `client-id` to + `client-id` plus configured helper/CI client ids. For Google the token's `aud` + and `azp`/`issued_to` must be in that set; for GitLab the token's + `application.uid` must be. It is a policy input to the `aud`/`app` check, not + an additional layer. +- `app` — token must belong to this Gerrit's OAuth app (GitHub `app.client_id`, + GitLab `application.uid`, Azure `appid`/`azp`: at least one present and every + present one equal to `client-id`). +- `jwt` — Azure only: the access token must be a parseable JWT. An opaque or + unparseable token is rejected up front, because the `app`/`tid` bindings are + read from its claims — accepting it after the Graph `/me` call would let a + token minted for another app through (confused-deputy hole). +- `scope` — token must carry the configured `required-scope` (GitLab; default + `read_user`). +- `sub` — subject binding: the token's subject matches the user-info subject + (GitLab: `token/info` `resource_owner_id` == `/api/v4/user` id). +- `state` — GitLab only: the account must be `active`; a token for a blocked, + deactivated, banned, or `ldap_blocked` account is rejected even when otherwise + valid. +- `iss` — token issuer must match the configured issuer. +- `tid` — Azure tenant binding: the access token's `tid` claim must equal the + configured fixed tenant (skipped for the multi-tenant aliases + `organizations`/`common`/`consumers`). +- `ev` — a verified email is required (`email_verified` / `verified_email`). +- `jwks` — the JWT signature is verified against the IdP JWKS with an algorithm + allowlist (RS\*/ES\*/EdDSA; `HS*`/`none` rejected). +- `intro` — the opaque token is introspected at the IdP (remote call). + +Other columns: + +- **User-info mapper** — `shared`: a `*UserInfoMapper` reused by the browser and + Git paths; `inline`: mapped in the service (fine for browser-only providers); + `inline (by design)`: Google keeps two inline mappings because its `tokeninfo` + and `userinfo` responses have different shapes. +- **PKCE** — the plugin can send PKCE (RFC 7636) for every provider; opt in per + provider with `enable-pkce = true`. Default off; enable it when your IdP supports + or accepts it (a server that does not simply ignores the extra parameters). +- **Git-over-HTTP** — `opt-in`: set `enable-git-over-http = true`; `on by + default`: SAP IAS is grandfathered on; `–`: not implemented yet. +- **Refresh** — the provider can renew an *expired* access token from its refresh + token. Renewal is enabled by the provider's `enable-token-refresh` and happens + on read: browser/REST reads (`GET /accounts/{id}/oauthtoken`) refresh via + `OAuthTokenRefresher`, and the `oauth-token` SSH command refreshes on demand. + Neither needs `enable-git-over-http`. Token *delivery* by + `oauth-token` is provider-agnostic: it prints whichever provider's cached token + the caller holds — a non-expiring token (e.g. GitHub OAuth-App tokens) + is printed as-is, no refresh involved. `yes`: refresh supported; `–`: feasible + but not implemented yet; `n/a`: the provider issues no refreshable token — for + GitHub, the OAuth-App tokens this plugin mints do not expire and carry no refresh + token (expiring GitHub-App `ghu_*` user tokens are a separate case; see + config-github.md). +- **Revocation** — the provider can revoke a token at the IdP (OAuth 2.0 Token + Revocation, [RFC 7009](https://www.rfc-editor.org/rfc/rfc7009)): a `POST` of the + token to the IdP's revocation endpoint, through the core + `OAuthServiceProvider.supportsRevoke()`/`revoke()` extension point. Unlike + `oauth-token evict`, which only purges Gerrit's cached copy, revocation + invalidates the token *upstream*. `yes`: implemented — Google + (`POST https://oauth2.googleapis.com/revoke`) and Keycloak (realm + `.../protocol/openid-connect/revoke`). RFC 7009 §2.2 mandates HTTP 200 even for + an unknown/already-invalid token; Google instead returns HTTP 400 + `invalid_token`, which the client tolerates as a successful no-op. `–`: the IdP + may expose a revocation endpoint but the provider does not implement `revoke()` + yet. +- `cache` — the provider caches a successful **Git-path** token validation in the + `oauth_token_validation` cache (keyed by a SHA-256 token hash) so that repeated + Git operations with the same token do not re-hit the IdP. This is a + Git-over-HTTP optimization, not a security check: it is the only cache in the + plugin, and only the four introspection providers (Google, GitHub, GitLab, Azure) + use it. The browser authorization-code flow never consults it, and the `jwks` + providers (Keycloak, Discovery, SAP IAS) validate locally and never cache. An + entry is stored **only when the token or the IdP response carries an expiry**, and + is then served for min(that expiry, the configured hard TTL; 60 s by default); a + token with no known expiry is re-validated at the IdP on every request. In + practice Google (`tokeninfo` `exp`/`expires_in`) and GitLab (`token/info` + `expires_in`) normally carry one. +- `cache`\* (GitHub, Azure) — the common no-expiry cases. GitHub's classic + OAuth-App tokens (`gho_*`) carry no `expires_at`, and Azure Graph `/me` returns no + expiry, so these cache only when the access token is itself a JWT with a parseable + `exp` — otherwise every request re-validates. + +Exactly one provider may have `enable-git-over-http = true` at a time. + +**Implementation note:** browser OAuth authorization-code flows run on the +`HttpOAuthClient` (a pure JDK + Gson implementation), and Git-over-HTTP +token validation uses provider-specific HTTP/JWKS validation. The plugin carries +no third-party OAuth or JSON library; `oauth_dependency_allowlist_test` pins the +exact set of runtime jars packaged into the WAR (nimbus for JWT validation and +the SAP cloud-security libraries), failing if an unexpected dependency reappears. + +## Future Git-over-HTTP candidates + +The providers below support browser login but not Git-over-HTTP token validation +(`enable-git-over-http`, the `–` in the matrix). They are plausible future +candidates, in rough priority order. **Not implemented** — listed so the analysis +is not lost. No work is scheduled. + +The gate for each is **confused-deputy defense**: Git-over-HTTP validation must +prove the token was minted for *this* Gerrit's OAuth app (as GitLab does with +`application.uid` and Azure with `appid`), not merely that the token is valid. A +provider is a good candidate only if its token-introspection response exposes a +client/app binding (`client_id` / `aud`); without that, the Git path would accept a +token minted for a different app and the defense-in-depth is weaker than the +existing providers. + +- **Facebook** — `debug_token` returns `app_id`, `is_valid`, `user_id`, scopes and + expiry, then bind to `/me` id. App binding is available, so this is the cleanest. +- **AirVantage** — exposes an RFC 7662 introspection endpoint + (`/api/oauth/introspect`); a good candidate *if* the response carries the client + binding. Would bind the introspected subject to `/api/v1/users/current` `uid`. +- **CAS** — modern CAS has `/oauth2.0/introspect` (`active`, `client_id`, `sub`, + `scope`, `aud`), but CAS deployments vary widely, so support would be best-effort. +- **Dex** — browser id_token validation already works via JWKS; a Git path could + accept a Dex `id_token` as the password, but that is less standard for credential + helpers. + +Bitbucket and Phabricator have no obvious app-bound introspection surface (`/user` +and `user.whoami` prove token validity, not app binding), so they are not good +candidates for strong Git-over-HTTP defense-in-depth.
diff --git a/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheCleanerTest.java b/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheCleanerTest.java new file mode 100644 index 0000000..e7d613b --- /dev/null +++ b/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheCleanerTest.java
@@ -0,0 +1,106 @@ +// Copyright (C) 2026 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.googlesource.gerrit.plugins.oauth.base; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.when; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.collect.ImmutableSet; +import com.google.gerrit.entities.Account; +import com.google.gerrit.extensions.auth.oauth.OAuthUserInfo; +import com.google.gerrit.server.account.externalids.ExternalId; +import com.google.gerrit.server.account.externalids.ExternalIds; +import com.googlesource.gerrit.plugins.oauth.base.OAuthTokenValidationCache.Entry; +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class OAuthTokenValidationCacheCleanerTest { + private static final Account.Id ACCOUNT = Account.id(1); + private static final String TOKEN_ALICE = "token-alice"; + private static final String TOKEN_BOB = "token-bob"; + private static final OAuthUserInfo ALICE = + new OAuthUserInfo("keycloak-oauth:alice", "alice", "alice@example.com", "Alice", null); + private static final OAuthUserInfo BOB = + new OAuthUserInfo("keycloak-oauth:bob", "bob", "bob@example.com", "Bob", null); + + @Mock private ExternalIds externalIds; + + private OAuthTokenValidationCache validationCache; + private OAuthTokenValidationCacheCleaner cleaner; + + @Before + public void setUp() { + Clock clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC")); + Cache<String, Entry> backing = CacheBuilder.newBuilder().build(); + validationCache = new OAuthTokenValidationCache(backing, clock); + cleaner = new OAuthTokenValidationCacheCleaner(validationCache, externalIds); + long expiresAt = clock.millis() + 60_000; + validationCache.put(TOKEN_ALICE, ALICE, expiresAt); + validationCache.put(TOKEN_BOB, BOB, expiresAt); + } + + private static ExternalId externalId(String scheme, String id) { + return ExternalId.create(ExternalId.Key.create(scheme, id, false), ACCOUNT, null, null); + } + + @Test + public void onTokenRevoked_targeted_dropsOnlyThatIdentity() throws Exception { + when(externalIds.byAccount(ACCOUNT)) + .thenReturn(ImmutableSet.of(externalId("keycloak-oauth", "alice"))); + + cleaner.onTokenRevoked(ACCOUNT); + + assertThat(validationCache.get(TOKEN_ALICE)).isEmpty(); // targeted identity dropped + assertThat(validationCache.get(TOKEN_BOB)).hasValue(BOB); // other identity untouched + } + + @Test + public void onTokenRevoked_lookupFails_flushesAll() throws Exception { + when(externalIds.byAccount(ACCOUNT)).thenThrow(new IOException("boom")); + + cleaner.onTokenRevoked(ACCOUNT); + + assertThat(validationCache.get(TOKEN_ALICE)).isEmpty(); + assertThat(validationCache.get(TOKEN_BOB)).isEmpty(); + } + + @Test + public void onTokenRevoked_noExternalIds_flushesAll() throws Exception { + when(externalIds.byAccount(ACCOUNT)).thenReturn(ImmutableSet.of()); + + cleaner.onTokenRevoked(ACCOUNT); + + assertThat(validationCache.get(TOKEN_ALICE)).isEmpty(); + assertThat(validationCache.get(TOKEN_BOB)).isEmpty(); + } + + @Test + public void onAllTokensRevoked_flushesAll() { + cleaner.onAllTokensRevoked(); + + assertThat(validationCache.get(TOKEN_ALICE)).isEmpty(); + assertThat(validationCache.get(TOKEN_BOB)).isEmpty(); + } +}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheTest.java b/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheTest.java index 63eeeae..d4840fb 100644 --- a/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheTest.java +++ b/src/test/java/com/googlesource/gerrit/plugins/oauth/base/OAuthTokenValidationCacheTest.java
@@ -24,6 +24,7 @@ import java.time.Instant; import java.time.ZoneId; import java.util.Optional; +import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -99,6 +100,62 @@ assertThat(validationCache.get(TOKEN_A)).hasValue(replacement); } + @Test + public void invalidateForExternalIds_dropsMatchingIdentity_keepsOthers() { + OAuthUserInfo bob = + new OAuthUserInfo("keycloak-oauth:bob", "bob", "bob@example.com", "Bob", null); + validationCache.put(TOKEN_A, USER_INFO, clock.millis() + 60_000); // alice + validationCache.put(TOKEN_B, bob, clock.millis() + 60_000); // bob + + validationCache.invalidateForExternalIds(Set.of("keycloak-oauth:alice")); + + assertThat(validationCache.get(TOKEN_A)).isEmpty(); // alice dropped + assertThat(validationCache.get(TOKEN_B)).hasValue(bob); // bob untouched + } + + @Test + public void invalidateForExternalIds_dropsEveryTokenForSameIdentity() { + // Two tokens that resolved to the same identity (e.g. the user's own token and a CI token). + validationCache.put(TOKEN_A, USER_INFO, clock.millis() + 60_000); + validationCache.put(TOKEN_B, USER_INFO, clock.millis() + 60_000); + + validationCache.invalidateForExternalIds(Set.of("keycloak-oauth:alice")); + + assertThat(validationCache.get(TOKEN_A)).isEmpty(); + assertThat(validationCache.get(TOKEN_B)).isEmpty(); + } + + @Test + public void invalidateForExternalIds_isCaseSensitive() { + // OAuth external-id schemes are case-sensitive (unlike username/gerrit), so a case variant + // does not match. This mirrors how core stores and resolves the external id. + validationCache.put(TOKEN_A, USER_INFO, clock.millis() + 60_000); + + validationCache.invalidateForExternalIds(Set.of("keycloak-oauth:ALICE")); + + assertThat(validationCache.get(TOKEN_A)).hasValue(USER_INFO); + } + + @Test + public void invalidateForExternalIds_emptySet_isNoOp() { + validationCache.put(TOKEN_A, USER_INFO, clock.millis() + 60_000); + + validationCache.invalidateForExternalIds(Set.of()); + + assertThat(validationCache.get(TOKEN_A)).hasValue(USER_INFO); + } + + @Test + public void invalidateAll_dropsEverything() { + validationCache.put(TOKEN_A, USER_INFO, clock.millis() + 60_000); + validationCache.put(TOKEN_B, USER_INFO, clock.millis() + 60_000); + + validationCache.invalidateAll(); + + assertThat(validationCache.get(TOKEN_A)).isEmpty(); + assertThat(validationCache.get(TOKEN_B)).isEmpty(); + } + private static final class MutableClock extends Clock { private Instant now;
diff --git a/src/test/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClientTest.java b/src/test/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClientTest.java index c720d71..85920f9 100644 --- a/src/test/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClientTest.java +++ b/src/test/java/com/googlesource/gerrit/plugins/oauth/client/HttpOAuthClientTest.java
@@ -35,6 +35,7 @@ private static final String CALLBACK = "https://gerrit.example.com/oauth"; private static final String AUTHZ = "https://idp.example.com/authorize"; private static final String TOKEN = "https://idp.example.com/token"; + private static final String REVOKE = "https://idp.example.com/revoke"; /** Captures the last request the client made through the transport seam. */ private static final class Captured { @@ -81,6 +82,107 @@ }; } + private static OAuthProviderEndpoints revokable() { + return new OAuthProviderEndpoints( + AUTHZ, + TOKEN, + "openid email", + ClientAuthStyle.BASIC, + BearerPlacement.AUTHORIZATION_HEADER, + TokenResponseFormat.JSON, + false, + false, + REVOKE); + } + + @Test + public void revoke_prefersRefreshToken_postsToRevocationEndpoint() throws Exception { + Captured out = new Captured(); + OAuthToken token = + new OAuthToken("access-x", "bearer", "{\"refresh_token\":\"rt-123\"}", 0, "p:x"); + + client(revokable(), CLIENT_SECRET, 200, "", out).revoke(token); + + assertThat(out.method).isEqualTo("POST"); + assertThat(out.url).isEqualTo(REVOKE); + assertThat(out.body).contains("token=rt-123"); + assertThat(out.body).contains("token_type_hint=refresh_token"); + } + + @Test + public void revoke_noRefreshToken_fallsBackToAccessToken() throws Exception { + Captured out = new Captured(); + OAuthToken token = new OAuthToken("access-x", "bearer", "{}", 0, "p:x"); + + client(revokable(), CLIENT_SECRET, 200, "", out).revoke(token); + + assertThat(out.body).contains("token=access-x"); + assertThat(out.body).contains("token_type_hint=access_token"); + } + + @Test + public void revoke_400InvalidToken_isNoOp() throws Exception { + Captured out = new Captured(); + OAuthToken token = new OAuthToken("access-x", "bearer", "{}", 0, "p:x"); + + // Google returns 400 invalid_token for an already-invalid token; tolerated as a no-op. + client(revokable(), CLIENT_SECRET, 400, "{\"error\":\"invalid_token\"}", out).revoke(token); + } + + @Test + public void revoke_non2xx_throws() { + Captured out = new Captured(); + OAuthToken token = new OAuthToken("access-x", "bearer", "{}", 0, "p:x"); + + assertThrows( + IOException.class, + () -> client(revokable(), CLIENT_SECRET, 500, "boom", out).revoke(token)); + } + + @Test + public void revoke_noRevocationEndpoint_throwsUnsupported() { + Captured out = new Captured(); + OAuthToken token = new OAuthToken("access-x", "bearer", "{}", 0, "p:x"); + + assertThrows( + UnsupportedOperationException.class, + () -> client(standard(ClientAuthStyle.BASIC), CLIENT_SECRET, 200, "", out).revoke(token)); + } + + @Test + public void revoke_requestBodyAuth_includesClientCredentials() throws Exception { + // Keycloak uses ClientAuthStyle.REQUEST_BODY: the revoke body must carry + // client_id/client_secret. + OAuthProviderEndpoints ep = + new OAuthProviderEndpoints( + AUTHZ, + TOKEN, + "openid", + ClientAuthStyle.REQUEST_BODY, + BearerPlacement.AUTHORIZATION_HEADER, + TokenResponseFormat.JSON, + false, + false, + REVOKE); + Captured out = new Captured(); + OAuthToken token = new OAuthToken("access-x", "bearer", "{}", 0, "p:x"); + + client(ep, CLIENT_SECRET, 200, "", out).revoke(token); + + assertThat(out.body).contains("token=access-x"); + assertThat(out.body).contains("client_id=" + CLIENT_ID); + assertThat(out.body).contains("client_secret=" + CLIENT_SECRET); + } + + @Test + public void supportsRevoke_reflectsRevocationEndpointPresence() { + Captured out = new Captured(); + assertThat(client(revokable(), CLIENT_SECRET, 200, "", out).supportsRevoke()).isTrue(); + assertThat( + client(standard(ClientAuthStyle.BASIC), CLIENT_SECRET, 200, "", out).supportsRevoke()) + .isFalse(); + } + @Test public void authorizationUrl_noPkce_hasStandardShape() { OAuthAuthorizationInfo info =