|
| 1 | +/* |
| 2 | + * Copyright 2025 Couchbase, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.couchbase.client.core.env; |
| 18 | + |
| 19 | +import com.couchbase.client.core.annotation.SinceCouchbase; |
| 20 | +import com.couchbase.client.core.deps.com.fasterxml.jackson.databind.node.ObjectNode; |
| 21 | +import com.couchbase.client.core.deps.io.netty.channel.ChannelPipeline; |
| 22 | +import com.couchbase.client.core.endpoint.EndpointContext; |
| 23 | +import com.couchbase.client.core.io.netty.kv.SaslAuthenticationHandler; |
| 24 | +import com.couchbase.client.core.io.netty.kv.sasl.OauthBearerSaslClient; |
| 25 | +import com.couchbase.client.core.json.Mapper; |
| 26 | +import org.jspecify.annotations.NullMarked; |
| 27 | + |
| 28 | +import java.time.Duration; |
| 29 | +import java.time.Instant; |
| 30 | +import java.util.Arrays; |
| 31 | +import java.util.Base64; |
| 32 | +import java.util.EnumSet; |
| 33 | +import java.util.List; |
| 34 | +import java.util.Set; |
| 35 | + |
| 36 | +import static com.couchbase.client.core.logging.RedactableArgument.redactUser; |
| 37 | +import static java.util.Collections.unmodifiableSet; |
| 38 | +import static java.util.Objects.requireNonNull; |
| 39 | +import static java.util.stream.Collectors.toList; |
| 40 | + |
| 41 | +/** |
| 42 | + * Authenticates with the Couchbase Server cluster using a JSON Web Token (JWT) |
| 43 | + * issued by an Identity Provider. |
| 44 | + * <p> |
| 45 | + * Create a new instance by calling {@link JwtAuthenticator#create(String)}. |
| 46 | + */ |
| 47 | +@SinceCouchbase("8.1") |
| 48 | +@NullMarked |
| 49 | +public class JwtAuthenticator implements Authenticator { |
| 50 | + /** |
| 51 | + * @implNote The SASL exchange is handled by {@link OauthBearerSaslClient} |
| 52 | + */ |
| 53 | + private static final Set<SaslMechanism> supportedMechanisms = |
| 54 | + unmodifiableSet(EnumSet.of(SaslMechanism.OAUTHBEARER)); |
| 55 | + |
| 56 | + public static JwtAuthenticator create(String jwt) { |
| 57 | + return new JwtAuthenticator(jwt); |
| 58 | + } |
| 59 | + |
| 60 | + private static class Jwt { |
| 61 | + private final ObjectNode header; |
| 62 | + private final ObjectNode payload; |
| 63 | + |
| 64 | + private Jwt(ObjectNode header, ObjectNode payload) { |
| 65 | + this.header = requireNonNull(header); |
| 66 | + this.payload = requireNonNull(payload); |
| 67 | + } |
| 68 | + |
| 69 | + public static Jwt parse(String jwt) { |
| 70 | + String[] parts = jwt.split("\\."); |
| 71 | + if (parts.length != 3) { |
| 72 | + throw new IllegalArgumentException("Expected JWT to have 3 dot-separated components, but found " + parts.length); |
| 73 | + } |
| 74 | + |
| 75 | + List<byte[]> decodedParts = Arrays.stream(parts) |
| 76 | + .map(Jwt::decodeBas64Url) |
| 77 | + .collect(toList()); |
| 78 | + |
| 79 | + try { |
| 80 | + return new Jwt( |
| 81 | + (ObjectNode) Mapper.decodeIntoTree(decodedParts.get(0)), |
| 82 | + (ObjectNode) Mapper.decodeIntoTree(decodedParts.get(1)) |
| 83 | + ); |
| 84 | + } catch (Exception e) { |
| 85 | + throw new IllegalArgumentException("Malformed JWT; not JSON", e); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + private static byte[] decodeBas64Url(String s) { |
| 90 | + try { |
| 91 | + return Base64.getUrlDecoder().decode(s); |
| 92 | + } catch (Exception e) { |
| 93 | + throw new IllegalArgumentException("Malformed JWT; component not Base64URL-encoded", e); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + @Override |
| 98 | + public String toString() { |
| 99 | + long expiryEpochSeconds = payload.path("exp").longValue(); |
| 100 | + Duration timeUntilExpiry = Duration.ofSeconds(expiryEpochSeconds - Instant.now().getEpochSecond()); |
| 101 | + return "Jwt{" + |
| 102 | + "header=" + redactUser(header) + |
| 103 | + ", payload=" + redactUser(payload) + |
| 104 | + ", signature=<redacted>" + // because we don't want a valid JWT to appear in any logs. |
| 105 | + ", timeUntilExpiry=" + timeUntilExpiry + |
| 106 | + '}'; |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + private final Jwt jwt; |
| 111 | + private final String encodedJwt; |
| 112 | + private final String authHeaderValue; |
| 113 | + private final String username; |
| 114 | + |
| 115 | + private JwtAuthenticator(String encodedJwt) { |
| 116 | + this.encodedJwt = encodedJwt.trim(); |
| 117 | + this.authHeaderValue = "Bearer " + this.encodedJwt; |
| 118 | + this.jwt = Jwt.parse(this.encodedJwt); |
| 119 | + |
| 120 | + String fieldName = "sub"; |
| 121 | + this.username = jwt.payload.path(fieldName).textValue(); |
| 122 | + if (this.username == null) { |
| 123 | + throw new IllegalArgumentException("Missing '" + fieldName + "' in JWT payload"); |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + @Override |
| 128 | + public void authKeyValueConnection(EndpointContext ctx, ChannelPipeline pipeline) { |
| 129 | + pipeline.addLast(new SaslAuthenticationHandler( |
| 130 | + ctx, |
| 131 | + username, |
| 132 | + encodedJwt, |
| 133 | + supportedMechanisms |
| 134 | + )); |
| 135 | + } |
| 136 | + |
| 137 | + @Override |
| 138 | + public String getAuthHeaderValue() { |
| 139 | + return authHeaderValue; |
| 140 | + } |
| 141 | + |
| 142 | + @Override |
| 143 | + public String toString() { |
| 144 | + // Omit sensitive properties (like authHeaderValue and encodedJwt) |
| 145 | + // so they don't accidentally end up in a log. |
| 146 | + return "JwtAuthenticator{" + |
| 147 | + "jwt=" + jwt + |
| 148 | + '}'; |
| 149 | + } |
| 150 | +} |
0 commit comments