Skip to content

Implement Play Integrity attestation flow. #3618

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 7, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.appcheck.playintegrity.internal;

import androidx.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;

/**
* Client-side model of the GeneratePlayIntegrityChallengeRequest payload from the Firebase App
* Check Token Exchange API.
*/
public class GeneratePlayIntegrityChallengeRequest {

public GeneratePlayIntegrityChallengeRequest() {}

@NonNull
public String toJsonString() throws JSONException {
JSONObject jsonObject = new JSONObject();

return jsonObject.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.appcheck.playintegrity.internal;

import static com.google.android.gms.common.internal.Preconditions.checkNotNull;
import static com.google.android.gms.common.util.Strings.emptyToNull;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import org.json.JSONException;
import org.json.JSONObject;

/**
* Client-side model of the GeneratePlayIntegrityChallengeResponse payload from the Firebase App
* Check Token Exchange API.
*/
public class GeneratePlayIntegrityChallengeResponse {

@VisibleForTesting static final String CHALLENGE_KEY = "challenge";
@VisibleForTesting static final String TIME_TO_LIVE_KEY = "ttl";

private String challenge;
private String timeToLive;

@NonNull
public static GeneratePlayIntegrityChallengeResponse fromJsonString(@NonNull String jsonString)
throws JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
String challenge = emptyToNull(jsonObject.optString(CHALLENGE_KEY));
String timeToLive = emptyToNull(jsonObject.optString(TIME_TO_LIVE_KEY));
return new GeneratePlayIntegrityChallengeResponse(challenge, timeToLive);
}

private GeneratePlayIntegrityChallengeResponse(
@NonNull String challenge, @NonNull String timeToLive) {
checkNotNull(challenge);
checkNotNull(timeToLive);
this.challenge = challenge;
this.timeToLive = timeToLive;
}

@NonNull
public String getChallenge() {
return challenge;
}

@NonNull
public String getTimeToLive() {
return timeToLive;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.android.play.core.integrity.IntegrityManager;
import com.google.android.play.core.integrity.IntegrityManagerFactory;
import com.google.android.play.core.integrity.IntegrityTokenRequest;
import com.google.android.play.core.integrity.IntegrityTokenResponse;
import com.google.firebase.FirebaseApp;
import com.google.firebase.appcheck.AppCheckProvider;
import com.google.firebase.appcheck.AppCheckToken;
Expand All @@ -33,19 +37,30 @@ public class PlayIntegrityAppCheckProvider implements AppCheckProvider {

private static final String UTF_8 = "UTF-8";

private final String projectNumber;
private final IntegrityManager integrityManager;
private final NetworkClient networkClient;
private final ExecutorService backgroundExecutor;
private final RetryManager retryManager;

public PlayIntegrityAppCheckProvider(@NonNull FirebaseApp firebaseApp) {
this(new NetworkClient(firebaseApp), Executors.newCachedThreadPool(), new RetryManager());
this(
firebaseApp.getOptions().getGcmSenderId(),
IntegrityManagerFactory.create(firebaseApp.getApplicationContext()),
new NetworkClient(firebaseApp),
Executors.newCachedThreadPool(),
new RetryManager());
}

@VisibleForTesting
PlayIntegrityAppCheckProvider(
@NonNull String projectNumber,
@NonNull IntegrityManager integrityManager,
@NonNull NetworkClient networkClient,
@NonNull ExecutorService backgroundExecutor,
@NonNull RetryManager retryManager) {
this.projectNumber = projectNumber;
this.integrityManager = integrityManager;
this.networkClient = networkClient;
this.backgroundExecutor = backgroundExecutor;
this.retryManager = retryManager;
Expand All @@ -54,24 +69,61 @@ public PlayIntegrityAppCheckProvider(@NonNull FirebaseApp firebaseApp) {
@NonNull
@Override
public Task<AppCheckToken> getToken() {
// TODO(rosalyntan): Obtain the Play Integrity challenge nonce.
ExchangePlayIntegrityTokenRequest request =
new ExchangePlayIntegrityTokenRequest("placeholder");
Task<AppCheckTokenResponse> networkTask =
return getPlayIntegrityAttestation()
.continueWithTask(
new Continuation<IntegrityTokenResponse, Task<AppCheckTokenResponse>>() {
@Override
public Task<AppCheckTokenResponse> then(@NonNull Task<IntegrityTokenResponse> task) {
if (task.isSuccessful()) {
ExchangePlayIntegrityTokenRequest request =
new ExchangePlayIntegrityTokenRequest(task.getResult().token());
return Tasks.call(
backgroundExecutor,
() ->
networkClient.exchangeAttestationForAppCheckToken(
request.toJsonString().getBytes(UTF_8),
NetworkClient.PLAY_INTEGRITY,
retryManager));
}
return Tasks.forException(task.getException());
}
})
.continueWithTask(
new Continuation<AppCheckTokenResponse, Task<AppCheckToken>>() {
@Override
public Task<AppCheckToken> then(@NonNull Task<AppCheckTokenResponse> task) {
if (task.isSuccessful()) {
return Tasks.forResult(
DefaultAppCheckToken.constructFromAppCheckTokenResponse(task.getResult()));
}
// TODO: Surface more error details.
return Tasks.forException(task.getException());
}
});
}

@NonNull
private Task<IntegrityTokenResponse> getPlayIntegrityAttestation() {
GeneratePlayIntegrityChallengeRequest generateChallengeRequest =
new GeneratePlayIntegrityChallengeRequest();
Task<GeneratePlayIntegrityChallengeResponse> generateChallengeTask =
Tasks.call(
backgroundExecutor,
() ->
networkClient.exchangeAttestationForAppCheckToken(
request.toJsonString().getBytes(UTF_8),
NetworkClient.PLAY_INTEGRITY,
retryManager));
return networkTask.continueWithTask(
new Continuation<AppCheckTokenResponse, Task<AppCheckToken>>() {
GeneratePlayIntegrityChallengeResponse.fromJsonString(
networkClient.generatePlayIntegrityChallenge(
generateChallengeRequest.toJsonString().getBytes(UTF_8), retryManager)));
return generateChallengeTask.continueWithTask(
new Continuation<GeneratePlayIntegrityChallengeResponse, Task<IntegrityTokenResponse>>() {
@Override
public Task<AppCheckToken> then(@NonNull Task<AppCheckTokenResponse> task) {
public Task<IntegrityTokenResponse> then(
@NonNull Task<GeneratePlayIntegrityChallengeResponse> task) {
if (task.isSuccessful()) {
return Tasks.forResult(
DefaultAppCheckToken.constructFromAppCheckTokenResponse(task.getResult()));
return integrityManager.requestIntegrityToken(
IntegrityTokenRequest.builder()
.setCloudProjectNumber(Long.parseLong(projectNumber))
.setNonce(task.getResult().getChallenge())
.build());
}
// TODO: Surface more error details.
return Tasks.forException(task.getException());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.appcheck.playintegrity.internal;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

/** Tests for {@link GeneratePlayIntegrityChallengeRequest}. */
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class GeneratePlayIntegrityChallengeRequestTest {
private static final String EMPTY_JSON = "{}";

@Test
public void toJsonString_expectSerialized() throws Exception {
GeneratePlayIntegrityChallengeRequest generatePlayIntegrityChallengeRequest =
new GeneratePlayIntegrityChallengeRequest();

assertThat(generatePlayIntegrityChallengeRequest.toJsonString()).isEqualTo(EMPTY_JSON);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.appcheck.playintegrity.internal;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

/** Tests for {@link GeneratePlayIntegrityChallengeResponse}. */
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class GeneratePlayIntegrityChallengeResponseTest {
private static final String CHALLENGE = "testChallenge";
private static final String TIME_TO_LIVE = "3600s";

@Test
public void fromJsonString_expectDeserialized() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put(GeneratePlayIntegrityChallengeResponse.CHALLENGE_KEY, CHALLENGE);
jsonObject.put(GeneratePlayIntegrityChallengeResponse.TIME_TO_LIVE_KEY, TIME_TO_LIVE);

GeneratePlayIntegrityChallengeResponse generatePlayIntegrityChallengeResponse =
GeneratePlayIntegrityChallengeResponse.fromJsonString(jsonObject.toString());
assertThat(generatePlayIntegrityChallengeResponse.getChallenge()).isEqualTo(CHALLENGE);
assertThat(generatePlayIntegrityChallengeResponse.getTimeToLive()).isEqualTo(TIME_TO_LIVE);
}

@Test
public void fromJsonString_nullChallenge_throwsException() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put(GeneratePlayIntegrityChallengeResponse.TIME_TO_LIVE_KEY, TIME_TO_LIVE);

assertThrows(
NullPointerException.class,
() -> GeneratePlayIntegrityChallengeResponse.fromJsonString(jsonObject.toString()));
}

@Test
public void fromJsonString_nullTimeToLive_throwsException() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put(GeneratePlayIntegrityChallengeResponse.CHALLENGE_KEY, CHALLENGE);

assertThrows(
NullPointerException.class,
() -> GeneratePlayIntegrityChallengeResponse.fromJsonString(jsonObject.toString()));
}
}
Loading