|
| 1 | +/* |
| 2 | + * Copyright 2022 Google 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 | + * 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 com.google.firebase.appcheck; |
| 18 | + |
| 19 | +import static com.google.common.base.Preconditions.checkArgument; |
| 20 | + |
| 21 | +import com.google.common.base.Strings; |
| 22 | +import com.google.firebase.ErrorCode; |
| 23 | +import com.nimbusds.jose.JOSEException; |
| 24 | +import com.nimbusds.jose.JWSAlgorithm; |
| 25 | +import com.nimbusds.jose.jwk.source.DefaultJWKSetCache; |
| 26 | +import com.nimbusds.jose.jwk.source.JWKSetCache; |
| 27 | +import com.nimbusds.jose.jwk.source.JWKSource; |
| 28 | +import com.nimbusds.jose.jwk.source.RemoteJWKSet; |
| 29 | +import com.nimbusds.jose.proc.BadJOSEException; |
| 30 | +import com.nimbusds.jose.proc.JWSKeySelector; |
| 31 | +import com.nimbusds.jose.proc.JWSVerificationKeySelector; |
| 32 | +import com.nimbusds.jose.proc.SecurityContext; |
| 33 | +import com.nimbusds.jwt.JWTClaimsSet; |
| 34 | +import com.nimbusds.jwt.SignedJWT; |
| 35 | +import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; |
| 36 | +import com.nimbusds.jwt.proc.DefaultJWTProcessor; |
| 37 | + |
| 38 | +import java.net.MalformedURLException; |
| 39 | +import java.net.URL; |
| 40 | +import java.text.ParseException; |
| 41 | +import java.util.concurrent.TimeUnit; |
| 42 | + |
| 43 | +final class AppCheckTokenVerifier { |
| 44 | + |
| 45 | + private final URL jwksUrl; |
| 46 | + private final String projectId; |
| 47 | + |
| 48 | + private static final String JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks"; |
| 49 | + private static final String APP_CHECK_ISSUER = "https://firebaseappcheck.googleapis.com/"; |
| 50 | + |
| 51 | + private AppCheckTokenVerifier(Builder builder) { |
| 52 | + checkArgument(!Strings.isNullOrEmpty(builder.projectId)); |
| 53 | + this.projectId = builder.projectId; |
| 54 | + try { |
| 55 | + this.jwksUrl = new URL(JWKS_URL); |
| 56 | + } catch (MalformedURLException e) { |
| 57 | + throw new IllegalArgumentException("Malformed JWK url string", e); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Verifies that the given App Check token string is a valid Firebase JWT. |
| 63 | + * |
| 64 | + * @param token The token string to be verified. |
| 65 | + * @return A decoded representation of the input token string. |
| 66 | + * @throws FirebaseAppCheckException If the input token string fails to verify due to any reason. |
| 67 | + */ |
| 68 | + DecodedAppCheckToken verifyToken(String token) throws FirebaseAppCheckException { |
| 69 | + SignedJWT signedJWT; |
| 70 | + JWTClaimsSet claimsSet; |
| 71 | + String scopedProjectId = String.format("projects/%s", projectId); |
| 72 | + String projectIdMatchMessage = " Make sure the App Check token comes from the same " |
| 73 | + + "Firebase project as the service account used to authenticate this SDK."; |
| 74 | + |
| 75 | + try { |
| 76 | + signedJWT = SignedJWT.parse(token); |
| 77 | + claimsSet = signedJWT.getJWTClaimsSet(); |
| 78 | + } catch (java.text.ParseException e) { |
| 79 | + // Invalid signed JWT encoding |
| 80 | + throw new FirebaseAppCheckException(ErrorCode.INVALID_ARGUMENT, "Invalid token"); |
| 81 | + } |
| 82 | + |
| 83 | + String errorMessage = null; |
| 84 | + |
| 85 | + if (!signedJWT.getHeader().getAlgorithm().equals(JWSAlgorithm.RS256)) { |
| 86 | + errorMessage = String.format("The provided App Check token has incorrect algorithm. " |
| 87 | + + "Expected 'RS256' but got '%s'.", signedJWT.getHeader().getAlgorithm()); |
| 88 | + } else if (!signedJWT.getHeader().getType().getType().equals("JWT")) { |
| 89 | + errorMessage = String.format("The provided App Check token has invalid type header." |
| 90 | + + "Expected %s but got %s", "JWT", signedJWT.getHeader().getType().getType()); |
| 91 | + } else if (!claimsSet.getAudience().contains(scopedProjectId)) { |
| 92 | + errorMessage = String.format("The provided App Check token has incorrect 'aud' (audience) " |
| 93 | + + "claim. Expected %s but got %s. %s", |
| 94 | + scopedProjectId, claimsSet.getAudience().toString(), projectIdMatchMessage); |
| 95 | + } else if (!claimsSet.getIssuer().startsWith(APP_CHECK_ISSUER)) { |
| 96 | + errorMessage = "invalid iss"; |
| 97 | + } else if (claimsSet.getSubject().isEmpty()) { |
| 98 | + errorMessage = "invalid sub"; |
| 99 | + } |
| 100 | + |
| 101 | + if (errorMessage != null) { |
| 102 | + throw new FirebaseAppCheckException(ErrorCode.INVALID_ARGUMENT, errorMessage); |
| 103 | + } |
| 104 | + |
| 105 | + // Create a JWT processor for the access tokens |
| 106 | + ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); |
| 107 | + |
| 108 | + // Cache the keys for 6 hours |
| 109 | + JWKSetCache jwkSetCache = new DefaultJWKSetCache(6L, 6L, TimeUnit.HOURS); |
| 110 | + JWKSource<SecurityContext> keySource = new RemoteJWKSet<>(this.jwksUrl, null, jwkSetCache); |
| 111 | + |
| 112 | + // Configure the JWT processor with a key selector to feed matching public |
| 113 | + // RSA keys sourced from the JWK set URL. |
| 114 | + JWSKeySelector<SecurityContext> keySelector = |
| 115 | + new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, keySource); |
| 116 | + |
| 117 | + jwtProcessor.setJWSKeySelector(keySelector); |
| 118 | + |
| 119 | + try { |
| 120 | + claimsSet = jwtProcessor.process(token, null); |
| 121 | + System.out.println(claimsSet.toJSONObject()); |
| 122 | + } catch (ParseException | BadJOSEException | JOSEException e) { |
| 123 | + throw new FirebaseAppCheckException(ErrorCode.INVALID_ARGUMENT, e.getMessage()); |
| 124 | + } |
| 125 | + |
| 126 | + return new DecodedAppCheckToken(claimsSet.getClaims()); |
| 127 | + } |
| 128 | + |
| 129 | + static AppCheckTokenVerifier.Builder builder() { |
| 130 | + return new AppCheckTokenVerifier.Builder(); |
| 131 | + } |
| 132 | + |
| 133 | + static final class Builder { |
| 134 | + |
| 135 | + private String projectId; |
| 136 | + |
| 137 | + private Builder() { |
| 138 | + } |
| 139 | + |
| 140 | + AppCheckTokenVerifier.Builder setProjectId(String projectId) { |
| 141 | + this.projectId = projectId; |
| 142 | + return this; |
| 143 | + } |
| 144 | + |
| 145 | + AppCheckTokenVerifier build() { |
| 146 | + return new AppCheckTokenVerifier(this); |
| 147 | + } |
| 148 | + } |
| 149 | +} |
0 commit comments