-
Notifications
You must be signed in to change notification settings - Fork 626
Refactor out cached ApkHashExtractor #3767
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
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
147 changes: 147 additions & 0 deletions
147
...distribution/src/main/java/com/google/firebase/appdistribution/impl/ApkHashExtractor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
// 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.appdistribution.impl; | ||
|
||
import static com.google.firebase.appdistribution.impl.ReleaseIdentificationUtils.getPackageInfoWithMetadata; | ||
|
||
import android.content.Context; | ||
import android.content.pm.PackageInfo; | ||
import androidx.annotation.NonNull; | ||
import androidx.annotation.Nullable; | ||
import com.google.firebase.appdistribution.FirebaseAppDistributionException; | ||
import com.google.firebase.appdistribution.FirebaseAppDistributionException.Status; | ||
import java.io.File; | ||
import java.io.IOException; | ||
import java.nio.ByteBuffer; | ||
import java.security.MessageDigest; | ||
import java.security.NoSuchAlgorithmException; | ||
import java.util.ArrayList; | ||
import java.util.Enumeration; | ||
import java.util.Locale; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.ConcurrentMap; | ||
import java.util.zip.ZipEntry; | ||
import java.util.zip.ZipFile; | ||
|
||
/** Extracts a hash of the installed APK. */ | ||
class ApkHashExtractor { | ||
|
||
private static final String TAG = "ApkHashExtractor"; | ||
private static final int BYTES_IN_LONG = 8; | ||
|
||
private final ConcurrentMap<String, String> cachedApkHashes = new ConcurrentHashMap<>(); | ||
private Context applicationContext; | ||
|
||
ApkHashExtractor(Context applicationContext) { | ||
this.applicationContext = applicationContext; | ||
} | ||
|
||
/** | ||
* Extract the SHA-256 hash of the installed APK. | ||
* | ||
* <p>The result is stored in an in-memory cache to avoid computing it repeatedly. | ||
*/ | ||
String extractApkHash() throws FirebaseAppDistributionException { | ||
PackageInfo metadataPackageInfo = getPackageInfoWithMetadata(applicationContext); | ||
String installedReleaseApkHash = extractApkHash(metadataPackageInfo); | ||
if (installedReleaseApkHash == null || installedReleaseApkHash.isEmpty()) { | ||
throw new FirebaseAppDistributionException( | ||
"Could not calculate hash of installed APK", Status.UNKNOWN); | ||
} | ||
return installedReleaseApkHash; | ||
} | ||
|
||
private String extractApkHash(PackageInfo packageInfo) { | ||
File sourceFile = new File(packageInfo.applicationInfo.sourceDir); | ||
|
||
String key = | ||
String.format( | ||
Locale.ENGLISH, "%s.%d", sourceFile.getAbsolutePath(), sourceFile.lastModified()); | ||
if (!cachedApkHashes.containsKey(key)) { | ||
cachedApkHashes.put(key, calculateApkHash(sourceFile)); | ||
} | ||
return cachedApkHashes.get(key); | ||
} | ||
|
||
@Nullable | ||
String calculateApkHash(@NonNull File file) { | ||
LogWrapper.getInstance() | ||
.v( | ||
TAG, | ||
String.format( | ||
"Calculating release id for %s (%d bytes)", file.getPath(), file.length())); | ||
|
||
long start = System.currentTimeMillis(); | ||
long entries = 0; | ||
String zipFingerprint = null; | ||
try { | ||
MessageDigest digest = MessageDigest.getInstance("SHA-256"); | ||
ArrayList<Byte> checksums = new ArrayList<>(); | ||
|
||
// Since calculating the codeHash returned from the release backend is computationally | ||
// expensive, we has the existing checksum data from the ZipFile and compare it to | ||
// (1) the apk hash returned by the backend, or (2) look up a mapping from the apk zip hash to | ||
// the full codehash, and compare that to the codehash to the backend | ||
ZipFile zis = new ZipFile(file); | ||
try { | ||
Enumeration<? extends ZipEntry> zipEntries = zis.entries(); | ||
while (zipEntries.hasMoreElements()) { | ||
ZipEntry zip = zipEntries.nextElement(); | ||
entries += 1; | ||
byte[] crcBytes = longToByteArray(zip.getCrc()); | ||
for (byte b : crcBytes) { | ||
checksums.add(b); | ||
} | ||
} | ||
} finally { | ||
zis.close(); | ||
} | ||
byte[] checksumByteArray = digest.digest(arrayListToByteArray(checksums)); | ||
StringBuilder sb = new StringBuilder(); | ||
for (byte b : checksumByteArray) { | ||
sb.append(String.format("%02x", b)); | ||
} | ||
zipFingerprint = sb.toString(); | ||
|
||
} catch (IOException | NoSuchAlgorithmException e) { | ||
LogWrapper.getInstance().v(TAG, "id calculation failed for " + file.getPath()); | ||
return null; | ||
} finally { | ||
long elapsed = System.currentTimeMillis() - start; | ||
LogWrapper.getInstance() | ||
.v( | ||
TAG, | ||
String.format( | ||
"Computed hash of %s (%d entries, %d ms elapsed): %s", | ||
file.getPath(), entries, elapsed, zipFingerprint)); | ||
} | ||
|
||
return zipFingerprint; | ||
} | ||
|
||
private static byte[] longToByteArray(long x) { | ||
ByteBuffer buffer = ByteBuffer.allocate(BYTES_IN_LONG); | ||
buffer.putLong(x); | ||
return buffer.array(); | ||
} | ||
|
||
private static byte[] arrayListToByteArray(ArrayList<Byte> list) { | ||
byte[] result = new byte[list.size()]; | ||
for (int i = 0; i < list.size(); i++) { | ||
result[i] = list.get(i); | ||
} | ||
return result; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.