001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.oauth; 018 019import com.revetsec.internal.encoding.StrictUtf8; 020import com.revetsec.jose.JwsAlgorithm; 021import com.revetsec.internal.Limits; 022import com.google.errorprone.annotations.CheckReturnValue; 023import java.time.Duration; 024import javax.annotation.concurrent.NotThreadSafe; 025import java.util.Set; 026 027import com.revetsec.internal.encoding.EncodingException; 028import com.revetsec.internal.encoding.FormUrlEncoding; 029import org.jspecify.annotations.NonNull; 030import org.jspecify.annotations.Nullable; 031 032import javax.annotation.concurrent.ThreadSafe; 033import java.nio.charset.StandardCharsets; 034import java.util.Arrays; 035import java.util.Base64; 036import java.util.Map; 037import java.util.function.Supplier; 038 039import static java.util.Objects.requireNonNull; 040 041/** 042 * One OAuth client authentication strategy. A supplier is consulted once per outgoing request, supporting a 043 * rotating client secret; its result is never placed in a URL, exception or string rendering. Supplier 044 * implementations must be thread-safe when the client is shared between threads. 045 * 046 * @author <a href="https://www.revetkn.com">Mark Allen</a> 047 * @since 1.0.0 048 */ 049@ThreadSafe 050public final class ClientAuthentication { 051 private enum Method { NONE, BASIC, POST, PRIVATE_KEY_JWT } 052 private static final ClientAuthentication NONE = new ClientAuthentication(Method.NONE, null, 053 ClientSecretBasicEncoding.FORM_URLENCODED); 054 private final @NonNull Method method; 055 private final @Nullable Supplier<@NonNull String> secretSupplier; 056 private final @NonNull ClientSecretBasicEncoding encoding; 057 private final @Nullable ClientAssertionKeyProvider keyProvider; 058 private final @NonNull ClientAssertionAudience assertionAudience; 059 private final @NonNull Duration assertionLifetime; 060 061 private ClientAuthentication(@NonNull Method method, @Nullable Supplier<@NonNull String> secretSupplier, 062 @NonNull ClientSecretBasicEncoding encoding) { 063 this.method = method; 064 this.secretSupplier = secretSupplier; 065 this.encoding = encoding; 066 this.keyProvider = null; 067 this.assertionAudience = ClientAssertionAudience.ISSUER; 068 this.assertionLifetime = Limits.CLIENT_ASSERTION_LIFETIME.getDefaultDuration(); 069 } 070 071 /** 072 * Selects no client authentication for a public client. 073 * 074 * @return the shared public-client strategy 075 * @since 1.0.0 076 */ 077 public static @NonNull ClientAuthentication noneInstance() { return NONE; } 078 079 /** 080 * Selects RFC 6749 client-secret Basic with form encoding. 081 * 082 * @param secret the nonempty secret 083 * @return the strategy 084 * @since 1.0.0 085 */ 086 public static @NonNull ClientAuthentication fromClientSecretBasic(@NonNull String secret) { 087 return fromClientSecretBasic(secret, ClientSecretBasicEncoding.FORM_URLENCODED); 088 } 089 090 /** 091 * Selects client-secret Basic with an explicit encoding choice. 092 * 093 * @param secret the nonempty secret 094 * @param encoding the encoding 095 * @return the strategy 096 * @since 1.0.0 097 */ 098 public static @NonNull ClientAuthentication fromClientSecretBasic(@NonNull String secret, 099 @NonNull ClientSecretBasicEncoding encoding) { 100 String checked = requireSecret(secret); 101 return new ClientAuthentication(Method.BASIC, () -> checked, requireNonNull(encoding)); 102 } 103 104 /** 105 * Selects client-secret POST with a fixed secret. 106 * 107 * @param secret the nonempty secret 108 * @return the strategy 109 * @since 1.0.0 110 */ 111 public static @NonNull ClientAuthentication fromClientSecretPost(@NonNull String secret) { 112 String checked = requireSecret(secret); 113 return new ClientAuthentication(Method.POST, () -> checked, ClientSecretBasicEncoding.FORM_URLENCODED); 114 } 115 116 /** 117 * Selects client-secret POST with a supplier called once per request. 118 * 119 * @param secretSupplier the supplier 120 * @return the strategy 121 * @since 1.0.0 122 */ 123 public static @NonNull ClientAuthentication fromClientSecretPost( 124 @NonNull Supplier<@NonNull String> secretSupplier) { 125 return new ClientAuthentication(Method.POST, requireNonNull(secretSupplier), 126 ClientSecretBasicEncoding.FORM_URLENCODED); 127 } 128 129 private ClientAuthentication(@NonNull PrivateKeyJwtBuilder builder) { 130 this.method = Method.PRIVATE_KEY_JWT; 131 this.secretSupplier = null; 132 this.encoding = ClientSecretBasicEncoding.FORM_URLENCODED; 133 this.keyProvider = builder.keyProvider; 134 this.assertionAudience = builder.audience; 135 this.assertionLifetime = builder.lifetime; 136 } 137 /** 138 * Selects generated private-key assertions with the issuer audience and 60-second lifetime. 139 * @param keyProvider thread-safe cooperative key provider 140 * @return the strategy 141 * @since 1.0.0 142 */ 143 @CheckReturnValue 144 public static @NonNull ClientAuthentication fromPrivateKeyJwt(@NonNull ClientAssertionKeyProvider keyProvider) { 145 return withPrivateKeyJwt(keyProvider).build(); 146 } 147 /** 148 * Starts private-key assertion configuration without selecting a key or signing. 149 * @param keyProvider thread-safe cooperative key provider 150 * @return the builder 151 * @since 1.0.0 152 */ 153 @CheckReturnValue 154 public static @NonNull PrivateKeyJwtBuilder withPrivateKeyJwt(@NonNull ClientAssertionKeyProvider keyProvider) { 155 return new PrivateKeyJwtBuilder(keyProvider); 156 } 157 boolean isPrivateKeyJwt() { return this.method == Method.PRIVATE_KEY_JWT; } 158 @NonNull ClientAssertionKeyProvider keyProvider() { return requireNonNull(this.keyProvider); } 159 @NonNull ClientAssertionAudience assertionAudience() { return this.assertionAudience; } 160 @NonNull Duration assertionLifetime() { return this.assertionLifetime; } 161 162 /** 163 * Configures assertion audience and lifetime. Building makes no application callback or signing call. 164 * @author <a href="https://www.revetkn.com">Mark Allen</a> 165 * @since 1.0.0 166 */ 167 @NotThreadSafe @CheckReturnValue 168 public static final class PrivateKeyJwtBuilder { 169 private final @NonNull ClientAssertionKeyProvider keyProvider; 170 private @NonNull ClientAssertionAudience audience = ClientAssertionAudience.ISSUER; 171 private @NonNull Duration lifetime = Limits.CLIENT_ASSERTION_LIFETIME.getDefaultDuration(); 172 private PrivateKeyJwtBuilder(@NonNull ClientAssertionKeyProvider keyProvider) { this.keyProvider = requireNonNull(keyProvider); } 173 /** 174 * Selects the sole assertion audience. Endpoint compatibility uses the actual outgoing POST URI. 175 * @param value audience, or null to restore ISSUER 176 * @return this builder 177 * @since 1.0.0 178 */ 179 public @NonNull PrivateKeyJwtBuilder audience(@Nullable ClientAssertionAudience value) { 180 this.audience = value == null ? ClientAssertionAudience.ISSUER : value; return this; 181 } 182 /** 183 * Replaces assertion lifetime with exact whole seconds in [1, 300]. 184 * @param value lifetime, or null to restore 60 seconds 185 * @return this builder 186 * @since 1.0.0 187 */ 188 public @NonNull PrivateKeyJwtBuilder assertionLifetime(@Nullable Duration value) { 189 if (value != null && value.toNanosPart() != 0) throw new IllegalArgumentException("The assertion lifetime must contain exact whole seconds."); 190 this.lifetime = value == null ? Limits.CLIENT_ASSERTION_LIFETIME.getDefaultDuration() : Limits.CLIENT_ASSERTION_LIFETIME.require(value); 191 return this; 192 } 193 /** 194 * Builds without key selection or signing. 195 * @return strategy 196 * @since 1.0.0 197 */ 198 public @NonNull ClientAuthentication build() { return new ClientAuthentication(this); } 199 /** 200 * Redacts configured keys and identifiers. 201 * @return redacted description 202 * @since 1.0.0 203 */ 204 @Override public @NonNull String toString() { return "ClientAuthentication.PrivateKeyJwtBuilder{key=<redacted>}"; } 205 } 206 207 @NonNull String methodName() { return switch (this.method) { case NONE -> "none"; case BASIC -> "client_secret_basic"; case POST -> "client_secret_post"; case PRIVATE_KEY_JWT -> "private_key_jwt"; }; } 208 boolean isPublicClient() { return this.method == Method.NONE; } 209 boolean isUnencodedBasic() { 210 return this.method == Method.BASIC && this.encoding == ClientSecretBasicEncoding.UNENCODED; 211 } 212 213 void checkHmac(@NonNull Set<@NonNull JwsAlgorithm> algorithms) { 214 if (algorithms.isEmpty()) return; 215 if (isPublicClient() || isPrivateKeyJwt()) throw new IllegalArgumentException("HMAC ID tokens require confidential client authentication."); 216 checkHmacSecret(readSecret(), algorithms); 217 } 218 private @NonNull String readSecret() { 219 try { return requireSecret(requireNonNull(this.secretSupplier).get()); } 220 catch (RuntimeException unavailable) { throw new IllegalArgumentException("The client secret is unavailable."); } 221 } 222 private static void checkHmacSecret(@NonNull String secret, @NonNull Set<@NonNull JwsAlgorithm> algorithms) { 223 if (algorithms.isEmpty()) return; 224 byte[] bytes; 225 try { bytes = StrictUtf8.encode(secret); } 226 catch (EncodingException malformed) { throw new IllegalArgumentException("The OIDC client secret contains invalid text."); } 227 try { 228 for (JwsAlgorithm algorithm : algorithms) { 229 int minimum = switch (algorithm) { case HS256 -> 32; case HS384 -> 48; case HS512 -> 64; 230 default -> throw new IllegalArgumentException("Only HMAC algorithms use a client secret."); }; 231 if (bytes.length < minimum) throw new IllegalArgumentException("The OIDC client secret is shorter than an allowed HMAC hash."); 232 } 233 } finally { Arrays.fill(bytes, (byte) 0); } 234 } 235 void apply(@NonNull String clientId, @NonNull Map<@NonNull String, @NonNull String> headers, @NonNull Map<@NonNull String, @NonNull String> form) { 236 applyForOidc(clientId, headers, form, Set.of()); 237 } 238 @Nullable String applyForOidc(@NonNull String clientId, @NonNull Map<@NonNull String, @NonNull String> headers, @NonNull Map<@NonNull String, @NonNull String> form, 239 @NonNull Set<@NonNull JwsAlgorithm> hmacAlgorithms) { 240 if (this.method == Method.NONE) { 241 form.put("client_id", clientId); 242 if (!hmacAlgorithms.isEmpty()) throw new IllegalArgumentException("HMAC ID tokens require confidential client authentication."); 243 return null; 244 } 245 if (isPrivateKeyJwt()) throw new IllegalStateException("Client assertions require endpoint preparation."); 246 String secret = readSecret(); 247 checkHmacSecret(secret, hmacAlgorithms); 248 if (this.method == Method.POST) { 249 form.put("client_id", clientId); 250 form.put("client_secret", secret); 251 return secret; 252 } 253 try { 254 String idPart = this.encoding == ClientSecretBasicEncoding.FORM_URLENCODED 255 ? FormUrlEncoding.encode(clientId) : clientId; 256 String secretPart = this.encoding == ClientSecretBasicEncoding.FORM_URLENCODED 257 ? FormUrlEncoding.encode(secret) : secret; 258 String credentials = idPart + ":" + secretPart; 259 byte[] bytes = credentials.getBytes(StandardCharsets.UTF_8); 260 try { 261 headers.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(bytes)); 262 } finally { 263 Arrays.fill(bytes, (byte) 0); 264 } 265 } catch (EncodingException exception) { 266 throw new IllegalArgumentException("A client identifier or secret contains invalid text."); 267 } 268 return secret; 269 } 270 271 private static @NonNull String requireSecret(@NonNull String value) { 272 if (requireNonNull(value).isEmpty()) 273 throw new IllegalArgumentException("A client secret must not be empty."); 274 return value; 275 } 276 277 /** 278 * Redacts the strategy and any secret. 279 * 280 * @return a redacted description 281 * @since 1.0.0 282 */ 283 @Override 284 public @NonNull String toString() { return "ClientAuthentication{secret=<redacted>}"; } 285}