|
| 1 | +/* |
| 2 | + * Copyright 2021 The gRPC Authors |
| 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 | + * http://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 io.grpc.xds; |
| 18 | + |
| 19 | +import com.google.auth.oauth2.ComputeEngineCredentials; |
| 20 | +import com.google.auth.oauth2.IdTokenCredentials; |
| 21 | +import com.google.common.primitives.UnsignedLongs; |
| 22 | +import com.google.protobuf.Any; |
| 23 | +import com.google.protobuf.InvalidProtocolBufferException; |
| 24 | +import com.google.protobuf.Message; |
| 25 | +import io.envoyproxy.envoy.extensions.filters.http.gcp_authn.v3.GcpAuthnFilterConfig; |
| 26 | +import io.envoyproxy.envoy.extensions.filters.http.gcp_authn.v3.TokenCacheConfig; |
| 27 | +import io.grpc.CallCredentials; |
| 28 | +import io.grpc.CallOptions; |
| 29 | +import io.grpc.Channel; |
| 30 | +import io.grpc.ClientCall; |
| 31 | +import io.grpc.ClientInterceptor; |
| 32 | +import io.grpc.CompositeCallCredentials; |
| 33 | +import io.grpc.LoadBalancer.PickSubchannelArgs; |
| 34 | +import io.grpc.Metadata; |
| 35 | +import io.grpc.MethodDescriptor; |
| 36 | +import io.grpc.Status; |
| 37 | +import io.grpc.auth.MoreCallCredentials; |
| 38 | +import io.grpc.xds.Filter.ClientInterceptorBuilder; |
| 39 | +import java.util.LinkedHashMap; |
| 40 | +import java.util.Map; |
| 41 | +import java.util.concurrent.ScheduledExecutorService; |
| 42 | +import java.util.function.Function; |
| 43 | +import javax.annotation.Nullable; |
| 44 | + |
| 45 | +/** |
| 46 | + * A {@link Filter} that injects a {@link CallCredentials} to handle |
| 47 | + * authentication for xDS credentials. |
| 48 | + */ |
| 49 | +final class GcpAuthenticationFilter implements Filter, ClientInterceptorBuilder { |
| 50 | + |
| 51 | + static final String TYPE_URL = |
| 52 | + "type.googleapis.com/envoy.extensions.filters.http.gcp_authn.v3.GcpAuthnFilterConfig"; |
| 53 | + |
| 54 | + @Override |
| 55 | + public String[] typeUrls() { |
| 56 | + return new String[] { TYPE_URL }; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public ConfigOrError<? extends FilterConfig> parseFilterConfig(Message rawProtoMessage) { |
| 61 | + GcpAuthnFilterConfig gcpAuthnProto; |
| 62 | + if (!(rawProtoMessage instanceof Any)) { |
| 63 | + return ConfigOrError.fromError("Invalid config type: " + rawProtoMessage.getClass()); |
| 64 | + } |
| 65 | + Any anyMessage = (Any) rawProtoMessage; |
| 66 | + |
| 67 | + try { |
| 68 | + gcpAuthnProto = anyMessage.unpack(GcpAuthnFilterConfig.class); |
| 69 | + } catch (InvalidProtocolBufferException e) { |
| 70 | + return ConfigOrError.fromError("Invalid proto: " + e); |
| 71 | + } |
| 72 | + |
| 73 | + long cacheSize = 10; |
| 74 | + // Validate cache_config |
| 75 | + TokenCacheConfig cacheConfig = gcpAuthnProto.getCacheConfig(); |
| 76 | + if (cacheConfig != null) { |
| 77 | + cacheSize = cacheConfig.getCacheSize().getValue(); |
| 78 | + if (cacheSize == 0) { |
| 79 | + return ConfigOrError.fromError( |
| 80 | + "cache_config.cache_size must be greater than zero"); |
| 81 | + } |
| 82 | + // LruCache's size is an int and briefly exceeds its maximum size before evicting entries |
| 83 | + cacheSize = UnsignedLongs.min(cacheSize, Integer.MAX_VALUE - 1); |
| 84 | + } |
| 85 | + |
| 86 | + GcpAuthenticationConfig config = new GcpAuthenticationConfig((int) cacheSize); |
| 87 | + return ConfigOrError.fromConfig(config); |
| 88 | + } |
| 89 | + |
| 90 | + @Override |
| 91 | + public ConfigOrError<? extends FilterConfig> parseFilterConfigOverride(Message rawProtoMessage) { |
| 92 | + return parseFilterConfig(rawProtoMessage); |
| 93 | + } |
| 94 | + |
| 95 | + @Nullable |
| 96 | + @Override |
| 97 | + public ClientInterceptor buildClientInterceptor(FilterConfig config, |
| 98 | + @Nullable FilterConfig overrideConfig, PickSubchannelArgs args, |
| 99 | + ScheduledExecutorService scheduler) { |
| 100 | + |
| 101 | + ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); |
| 102 | + LruCache<String, CallCredentials> callCredentialsCache = |
| 103 | + new LruCache<>(((GcpAuthenticationConfig) config).getCacheSize()); |
| 104 | + return new ClientInterceptor() { |
| 105 | + @Override |
| 106 | + public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( |
| 107 | + MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { |
| 108 | + |
| 109 | + /*String clusterName = callOptions.getOption(InternalXdsAttributes.ATTR_CLUSTER_NAME); |
| 110 | + if (clusterName == null) { |
| 111 | + return next.newCall(method, callOptions); |
| 112 | + }*/ |
| 113 | + |
| 114 | + // TODO: Fetch the CDS resource for the cluster. |
| 115 | + // If the CDS resource is not available, fail the RPC with Status.UNAVAILABLE. |
| 116 | + |
| 117 | + // TODO: Extract the audience from the CDS resource metadata. |
| 118 | + // If the audience is not found or is in the wrong format, fail the RPC. |
| 119 | + String audience = "TEST_AUDIENCE"; |
| 120 | + |
| 121 | + try { |
| 122 | + CallCredentials existingCallCredentials = callOptions.getCredentials(); |
| 123 | + CallCredentials newCallCredentials = |
| 124 | + getCallCredentials(callCredentialsCache, audience, credentials); |
| 125 | + if (existingCallCredentials != null) { |
| 126 | + callOptions = callOptions.withCallCredentials( |
| 127 | + new CompositeCallCredentials(existingCallCredentials, newCallCredentials)); |
| 128 | + } else { |
| 129 | + callOptions = callOptions.withCallCredentials(newCallCredentials); |
| 130 | + } |
| 131 | + } |
| 132 | + catch (Exception e) { |
| 133 | + // If we fail to attach CallCredentials due to any reason, return a FailingClientCall |
| 134 | + return new FailingClientCall<>(Status.UNAUTHENTICATED |
| 135 | + .withDescription("Failed to attach CallCredentials.") |
| 136 | + .withCause(e)); |
| 137 | + } |
| 138 | + return next.newCall(method, callOptions); |
| 139 | + } |
| 140 | + }; |
| 141 | + } |
| 142 | + |
| 143 | + private CallCredentials getCallCredentials(LruCache<String, CallCredentials> cache, |
| 144 | + String audience, ComputeEngineCredentials credentials) { |
| 145 | + |
| 146 | + synchronized (cache) { |
| 147 | + return cache.getOrInsert(audience, key -> { |
| 148 | + IdTokenCredentials creds = IdTokenCredentials.newBuilder() |
| 149 | + .setIdTokenProvider(credentials) |
| 150 | + .setTargetAudience(audience) |
| 151 | + .build(); |
| 152 | + return MoreCallCredentials.from(creds); |
| 153 | + }); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + static final class GcpAuthenticationConfig implements FilterConfig { |
| 158 | + |
| 159 | + private final int cacheSize; |
| 160 | + |
| 161 | + public GcpAuthenticationConfig(int cacheSize) { |
| 162 | + this.cacheSize = cacheSize; |
| 163 | + } |
| 164 | + |
| 165 | + public int getCacheSize() { |
| 166 | + return cacheSize; |
| 167 | + } |
| 168 | + |
| 169 | + @Override |
| 170 | + public String typeUrl() { |
| 171 | + return GcpAuthenticationFilter.TYPE_URL; |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + /** An implementation of {@link ClientCall} that fails when started. */ |
| 176 | + private static final class FailingClientCall<ReqT, RespT> extends ClientCall<ReqT, RespT> { |
| 177 | + |
| 178 | + private final Status error; |
| 179 | + |
| 180 | + public FailingClientCall(Status error) { |
| 181 | + this.error = error; |
| 182 | + } |
| 183 | + |
| 184 | + @Override |
| 185 | + public void start(ClientCall.Listener<RespT> listener, Metadata headers) { |
| 186 | + listener.onClose(error, new Metadata()); |
| 187 | + } |
| 188 | + |
| 189 | + @Override |
| 190 | + public void request(int numMessages) {} |
| 191 | + |
| 192 | + @Override |
| 193 | + public void cancel(String message, Throwable cause) {} |
| 194 | + |
| 195 | + @Override |
| 196 | + public void halfClose() {} |
| 197 | + |
| 198 | + @Override |
| 199 | + public void sendMessage(ReqT message) {} |
| 200 | + } |
| 201 | + |
| 202 | + private static final class LruCache<K, V> { |
| 203 | + |
| 204 | + private final Map<K, V> cache; |
| 205 | + |
| 206 | + LruCache(int maxSize) { |
| 207 | + this.cache = new LinkedHashMap<K, V>( |
| 208 | + maxSize, |
| 209 | + 0.75f, |
| 210 | + true) { |
| 211 | + @Override |
| 212 | + protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { |
| 213 | + return size() > maxSize; |
| 214 | + } |
| 215 | + }; |
| 216 | + } |
| 217 | + |
| 218 | + V getOrInsert(K key, Function<K, V> create) { |
| 219 | + return cache.computeIfAbsent(key, create); |
| 220 | + } |
| 221 | + } |
| 222 | +} |
0 commit comments