|
| 1 | +package io.opentdf.platform.sdk; |
| 2 | + |
| 3 | +import com.nimbusds.jose.JOSEException; |
| 4 | +import com.nimbusds.jose.JWSAlgorithm; |
| 5 | +import com.nimbusds.jose.jwk.RSAKey; |
| 6 | +import com.nimbusds.jwt.SignedJWT; |
| 7 | +import com.nimbusds.oauth2.sdk.AuthorizationGrant; |
| 8 | +import com.nimbusds.oauth2.sdk.ClientCredentialsGrant; |
| 9 | +import com.nimbusds.oauth2.sdk.ErrorObject; |
| 10 | +import com.nimbusds.oauth2.sdk.TokenRequest; |
| 11 | +import com.nimbusds.oauth2.sdk.TokenResponse; |
| 12 | +import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; |
| 13 | +import com.nimbusds.oauth2.sdk.dpop.DPoPProofFactory; |
| 14 | +import com.nimbusds.oauth2.sdk.dpop.DefaultDPoPProofFactory; |
| 15 | +import com.nimbusds.oauth2.sdk.http.HTTPRequest; |
| 16 | +import com.nimbusds.oauth2.sdk.http.HTTPResponse; |
| 17 | +import com.nimbusds.oauth2.sdk.token.AccessToken; |
| 18 | +import com.nimbusds.oauth2.sdk.tokenexchange.TokenExchangeGrant; |
| 19 | +import io.grpc.CallOptions; |
| 20 | +import io.grpc.Channel; |
| 21 | +import io.grpc.ClientCall; |
| 22 | +import io.grpc.ClientInterceptor; |
| 23 | +import io.grpc.ForwardingClientCall; |
| 24 | +import io.grpc.Metadata; |
| 25 | +import io.grpc.MethodDescriptor; |
| 26 | + |
| 27 | +import java.net.URI; |
| 28 | +import java.net.URISyntaxException; |
| 29 | +import java.time.Instant; |
| 30 | + |
| 31 | +/** |
| 32 | + * The GRPCAuthInterceptor class is responsible for intercepting client calls before they are sent |
| 33 | + * to the server. It adds authentication headers to the requests by fetching and caching access |
| 34 | + * tokens. |
| 35 | + */ |
| 36 | +class GRPCAuthInterceptor implements ClientInterceptor { |
| 37 | + private Instant tokenExpiryTime; |
| 38 | + private AccessToken token; |
| 39 | + private final ClientAuthentication clientAuth; |
| 40 | + private final RSAKey rsaKey; |
| 41 | + private final URI tokenEndpointURI; |
| 42 | + |
| 43 | + /** |
| 44 | + * Constructs a new GRPCAuthInterceptor with the specified client authentication and RSA key. |
| 45 | + * |
| 46 | + * @param clientAuth the client authentication to be used by the interceptor |
| 47 | + * @param rsaKey the RSA key to be used by the interceptor |
| 48 | + */ |
| 49 | + public GRPCAuthInterceptor(ClientAuthentication clientAuth, RSAKey rsaKey, URI tokenEndpointURI) { |
| 50 | + this.clientAuth = clientAuth; |
| 51 | + this.rsaKey = rsaKey; |
| 52 | + this.tokenEndpointURI = tokenEndpointURI; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Intercepts the client call before it is sent to the server. |
| 57 | + * |
| 58 | + * @param method The method descriptor for the call. |
| 59 | + * @param callOptions The call options for the call. |
| 60 | + * @param next The next channel in the channel pipeline. |
| 61 | + * @param <ReqT> The type of the request message. |
| 62 | + * @param <RespT> The type of the response message. |
| 63 | + * @return A client call with the intercepted behavior. |
| 64 | + */ |
| 65 | + @Override |
| 66 | + public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, |
| 67 | + CallOptions callOptions, Channel next) { |
| 68 | + return new ForwardingClientCall.SimpleForwardingClientCall<>(next.newCall(method, callOptions)) { |
| 69 | + @Override |
| 70 | + public void start(Listener<RespT> responseListener, Metadata headers) { |
| 71 | + // Get the access token |
| 72 | + AccessToken t = getToken(); |
| 73 | + headers.put(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), |
| 74 | + "DPoP " + t.getValue()); |
| 75 | + |
| 76 | + // Build the DPoP proof for each request |
| 77 | + try { |
| 78 | + DPoPProofFactory dpopFactory = new DefaultDPoPProofFactory(rsaKey, JWSAlgorithm.RS256); |
| 79 | + |
| 80 | + URI uri = new URI("/" + method.getFullMethodName()); |
| 81 | + SignedJWT proof = dpopFactory.createDPoPJWT("POST", uri, t); |
| 82 | + headers.put(Metadata.Key.of("DPoP", Metadata.ASCII_STRING_MARSHALLER), |
| 83 | + proof.serialize()); |
| 84 | + } catch (URISyntaxException e) { |
| 85 | + throw new RuntimeException("Invalid URI syntax for DPoP proof creation", e); |
| 86 | + } catch (JOSEException e) { |
| 87 | + throw new RuntimeException("Error creating DPoP proof", e); |
| 88 | + } |
| 89 | + super.start(responseListener, headers); |
| 90 | + } |
| 91 | + }; |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * Either fetches a new access token or returns the cached access token if it is still valid. |
| 96 | + * |
| 97 | + * @return The access token. |
| 98 | + */ |
| 99 | + private synchronized AccessToken getToken() { |
| 100 | + try { |
| 101 | + // If the token is expired or initially null, get a new token |
| 102 | + if (token == null || isTokenExpired()) { |
| 103 | + |
| 104 | + // Construct the client credentials grant |
| 105 | + AuthorizationGrant clientGrant = new ClientCredentialsGrant(); |
| 106 | + |
| 107 | + // Make the token request |
| 108 | + TokenRequest tokenRequest = new TokenRequest(this.tokenEndpointURI, |
| 109 | + clientAuth, clientGrant, null); |
| 110 | + HTTPRequest httpRequest = tokenRequest.toHTTPRequest(); |
| 111 | + |
| 112 | + DPoPProofFactory dpopFactory = new DefaultDPoPProofFactory(rsaKey, JWSAlgorithm.RS256); |
| 113 | + |
| 114 | + SignedJWT proof = dpopFactory.createDPoPJWT(httpRequest.getMethod().name(), httpRequest.getURI()); |
| 115 | + |
| 116 | + httpRequest.setDPoP(proof); |
| 117 | + TokenResponse tokenResponse; |
| 118 | + |
| 119 | + HTTPResponse httpResponse = httpRequest.send(); |
| 120 | + |
| 121 | + tokenResponse = TokenResponse.parse(httpResponse); |
| 122 | + if (!tokenResponse.indicatesSuccess()) { |
| 123 | + ErrorObject error = tokenResponse.toErrorResponse().getErrorObject(); |
| 124 | + throw new RuntimeException("Token request failed: " + error); |
| 125 | + } |
| 126 | + |
| 127 | + this.token = tokenResponse.toSuccessResponse().getTokens().getAccessToken(); |
| 128 | + // DPoPAccessToken dPoPAccessToken = tokens.getDPoPAccessToken(); |
| 129 | + |
| 130 | + |
| 131 | + if (token.getLifetime() != 0) { |
| 132 | + // Need some type of leeway but not sure whats best |
| 133 | + this.tokenExpiryTime = Instant.now().plusSeconds(token.getLifetime() / 3); |
| 134 | + } |
| 135 | + |
| 136 | + } else { |
| 137 | + // If the token is still valid or not initially null, return the cached token |
| 138 | + return this.token; |
| 139 | + } |
| 140 | + |
| 141 | + } catch (Exception e) { |
| 142 | + // TODO Auto-generated catch block |
| 143 | + throw new RuntimeException("failed to get token", e); |
| 144 | + } |
| 145 | + return this.token; |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Checks if the token has expired. |
| 150 | + * |
| 151 | + * @return true if the token has expired, false otherwise. |
| 152 | + */ |
| 153 | + private boolean isTokenExpired() { |
| 154 | + return this.tokenExpiryTime != null && this.tokenExpiryTime.isBefore(Instant.now()); |
| 155 | + } |
| 156 | +} |
0 commit comments