From 4c0a2892e91205eb7f64caadebb03692cc21488d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Paczos?= Date: Fri, 11 Jul 2025 13:50:04 +0200 Subject: [PATCH] add internal remote config patch tool --- .../privacy-config-internal/.gitignore | 4 +- .../privacy-config-internal/README.md | 73 +++++++++++ .../privacy-config-internal/build.gradle | 109 +++++++++++++++++ .../DevPrivacyConfigPatchApiInterceptor.kt | 115 ++++++++++++++++++ versions.properties | 2 + 5 files changed, 302 insertions(+), 1 deletion(-) create mode 100644 privacy-config/privacy-config-internal/README.md create mode 100644 privacy-config/privacy-config-internal/src/main/java/com/duckduckgo/privacy/config/internal/plugins/DevPrivacyConfigPatchApiInterceptor.kt diff --git a/privacy-config/privacy-config-internal/.gitignore b/privacy-config/privacy-config-internal/.gitignore index 42afabfd2abe..2a0f52597943 100644 --- a/privacy-config/privacy-config-internal/.gitignore +++ b/privacy-config/privacy-config-internal/.gitignore @@ -1 +1,3 @@ -/build \ No newline at end of file +/build +local.properties +/local-config-patches \ No newline at end of file diff --git a/privacy-config/privacy-config-internal/README.md b/privacy-config/privacy-config-internal/README.md new file mode 100644 index 000000000000..ca2ba819abf0 --- /dev/null +++ b/privacy-config/privacy-config-internal/README.md @@ -0,0 +1,73 @@ +# Internal Privacy Config module +This module is only available in `internal` build variants of the app. It contains the implementation of some utility functions and dev tools to test, modify, and debug the remote privacy config integration. + +## Local remote config patches +This module provides options to locally patch the remote config. This is useful for testing purposes, allowing to simulate different configurations without needing to deploy changes to the remote server. + +For example, you can use this to ensure a build of your app always has a specific feature flag state, while otherwise using the production remote configuration. + +Patching process leverages the [JSON Patch format](https://jsonpatch.com/), allowing you to specify changes in a structured way. The patches are applied at runtime, overriding the actual remote config values. + +For example, to ensure a feature flag is always enabled, you can create a patch file like this: + +```json +[ + { + "op": "replace", + "path": "/features/myFeature/state", + "value": "enabled" + } +] +``` + +Optionally, you can also adjust the remote config version and remove the features hash to ensure the updated version of the remote config is picked up by the app even if the remote config is already cached: + +```json +[ + { + "op": "replace", + "path": "/features/myFeature/state", + "value": "enabled" + }, + { + "op": "remove", + "path": "/features/myFeature/hash" + }, + { + "op": "replace", + "path": "/version", + "value": "999999999999999" + } +] +``` + +Make sure to provide a version number higher than the one currently used in production, so the app will recognize it as a new version of the remote config. + +### Usage +There are two ways to apply local remote config patches: +1. Using command line parameters when building the app. +2. Defining a path in your `local.properties` file. + +Both methods take a list of comma (`,`) separated paths to JSON patch files. The app will apply all patches in the order they are specified. + +Note: Regardless of the path where each file is, **each file name needs to be unique**. + +#### Command line parameters +You can specify the patches to apply when building the app by using the `-Pconfig_patches` parameter. For example: +```bash +./gradlew installInternalDebug \ +-Pconfig_patches=\ +privacy-config/privacy-config-internal/local-config-patches/test_patch.json,\ +privacy-config/privacy-config-internal/local-config-patches/test_patch2.json +``` +This method is useful, for example, for end-to-end tests, where you can specify different patches for different test scenarios and commit them to repository. + +#### `local.properties` file +You can also define the patches in a `privacy-config/privacy-config-internal/local.properties` file (create one if it doesn't exist) using the `config_patches` property. For example: +``` +config_patches=privacy-config/privacy-config-internal/local-config-patches/test_patch.json,privacy-config/privacy-config-internal/local-config-patches/test_patch2.json +``` + +This way, you can easily switch between different patch configurations and the modifications will be applied automatically when building the app, even when you build and deploy through Android Studio. + +For convenience, the `local.properties` file as well as a `local-config-patches` directory in the `privacy-config-internal` module are ignored by Git, so you can safely use it to store your local patches without affecting the repository. \ No newline at end of file diff --git a/privacy-config/privacy-config-internal/build.gradle b/privacy-config/privacy-config-internal/build.gradle index 79c207842e6b..cbbc8ed65d78 100644 --- a/privacy-config/privacy-config-internal/build.gradle +++ b/privacy-config/privacy-config-internal/build.gradle @@ -22,6 +22,30 @@ plugins { apply from: "$rootProject.projectDir/gradle/android-library.gradle" +def getConfigPatchFiles() { + def patchFiles = "" + + // check for local.properties file in this module first + def localPropertiesFile = project.file('local.properties') + if (localPropertiesFile.exists()) { + def localProperties = new Properties() + localPropertiesFile.withInputStream { localProperties.load(it) } + + if (localProperties.getProperty('config_patches')) { + patchFiles = localProperties.getProperty('config_patches').toString() + println "Using config patches from privacy-config-internal/local.properties: $patchFiles" + } + } + + // command line parameter takes precedence over local.properties + if (project.rootProject.hasProperty('config_patches')) { + patchFiles = project.rootProject.property('config_patches').toString() + println "Using config patches from command line parameter: $patchFiles" + } + + return patchFiles +} + android { anvil { generateDaggerFactories = true // default is false @@ -31,6 +55,28 @@ android { abortOnError = !project.hasProperty("abortOnError") || project.property("abortOnError") != "false" } namespace 'com.duckduckgo.privacy.config.internal' + + defaultConfig { + def patchFiles = getConfigPatchFiles() + def patchFileNames = [] + + if (patchFiles) { + patchFiles.split(',').each { patchFilePath -> + def patchFile = new File(patchFilePath.trim()) + if (patchFile.exists()) { + def fileName = patchFile.getName() + if (patchFileNames.contains(fileName)) { + throw new GradleException("Duplicate patch file name detected: '$fileName'. Patch files must have unique names even if they are in different directories.") + } + patchFileNames.add(fileName) + } else { + println "Config patch file not found: ${patchFile.absolutePath}" + } + } + } + + buildConfigField "String", "CONFIG_PATCHES", "\"${patchFileNames.join(',')}\"" + } } dependencies { @@ -55,4 +101,67 @@ dependencies { // Dagger implementation Google.dagger + + implementation "com.squareup.logcat:logcat:_" + implementation "io.github.vishwakarma:zjsonpatch:_" +} + +tasks.register('copyConfigPatches') { + doLast { + def buildAssetsDir = layout.buildDirectory.dir("generated/assets/configPatches").get().asFile + + // always clean up any existing patch files first, also ensures that when patching is disabled, the directory is cleaned up + if (buildAssetsDir.exists()) { + buildAssetsDir.listFiles().each { file -> + if (file.name.endsWith('.json')) { + file.delete() + println "Removed old patch file from build assets: ${file.absolutePath}" + } + } + if (buildAssetsDir.listFiles().length == 0) { + buildAssetsDir.delete() + } + } + + def patchFiles = getConfigPatchFiles() + + if (patchFiles) { + def fileNames = [] + patchFiles.split(',').each { patchFilePath -> + def patchFile = new File(patchFilePath.trim()) + if (patchFile.exists()) { + def fileName = patchFile.getName() + if (fileNames.contains(fileName)) { + throw new GradleException("Duplicate patch file name detected: '$fileName'. Patch files must have unique names even if they are in different directories.") + } + fileNames.add(fileName) + + if (!buildAssetsDir.exists()) { + buildAssetsDir.mkdirs() + } + + def destFile = new File(buildAssetsDir, fileName) + destFile.bytes = patchFile.bytes + println "Copied config patch to build assets: ${patchFile.absolutePath} -> ${destFile.absolutePath}" + } else { + println "Warning: Config patch file not found: ${patchFile.absolutePath}" + } + } + } + } +} + +android.sourceSets.main.assets.srcDirs += layout.buildDirectory.dir("generated/assets/configPatches").get().asFile.path + +afterEvaluate { + tasks.matching { it.name.contains('mergeAssets') }.configureEach { task -> + task.dependsOn copyConfigPatches + } + + tasks.matching { it.name.contains('preBuild') }.configureEach { task -> + task.dependsOn copyConfigPatches + } + + // force the task to always run (never up-to-date) + copyConfigPatches.outputs.upToDateWhen { false } } \ No newline at end of file diff --git a/privacy-config/privacy-config-internal/src/main/java/com/duckduckgo/privacy/config/internal/plugins/DevPrivacyConfigPatchApiInterceptor.kt b/privacy-config/privacy-config-internal/src/main/java/com/duckduckgo/privacy/config/internal/plugins/DevPrivacyConfigPatchApiInterceptor.kt new file mode 100644 index 000000000000..1ec4bb203a9e --- /dev/null +++ b/privacy-config/privacy-config-internal/src/main/java/com/duckduckgo/privacy/config/internal/plugins/DevPrivacyConfigPatchApiInterceptor.kt @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2025 DuckDuckGo + * + * 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.duckduckgo.privacy.config.internal.plugins + +import android.content.Context +import com.duckduckgo.app.global.api.ApiInterceptorPlugin +import com.duckduckgo.di.scopes.AppScope +import com.duckduckgo.privacy.config.api.PRIVACY_REMOTE_CONFIG_URL +import com.duckduckgo.privacy.config.internal.BuildConfig +import com.fasterxml.jackson.databind.ObjectMapper +import com.flipkart.zjsonpatch.JsonPatch +import com.squareup.anvil.annotations.ContributesMultibinding +import javax.inject.Inject +import logcat.LogPriority.ERROR +import logcat.logcat +import okhttp3.Interceptor +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody + +@ContributesMultibinding( + scope = AppScope::class, + boundType = ApiInterceptorPlugin::class, +) +class DevPrivacyConfigPatchApiInterceptor @Inject constructor( + private val context: Context, +) : ApiInterceptorPlugin, Interceptor { + + private val objectMapper = ObjectMapper() + + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + val url = request.url + + if (url.toString() == PRIVACY_REMOTE_CONFIG_URL) { + val response = chain.proceed(request) + + if (response.isSuccessful) { + val responseBody = response.body?.string() + if (responseBody != null) { + val modifiedJson = patchPrivacyConfigResponse(responseBody) + val mediaType = response.body?.contentType() ?: "application/json".toMediaType() + return response.newBuilder() + .body(modifiedJson.toResponseBody(mediaType)) + .build() + } + } + + return response + } + + return chain.proceed(chain.request()) + } + + private fun patchPrivacyConfigResponse(originalJson: String): String { + return try { + val configPatches = BuildConfig.CONFIG_PATCHES + if (configPatches.isBlank()) { + return originalJson + } + + var jsonNode = objectMapper.readTree(originalJson) + val patchFileNames = configPatches.split(',').filter { it.isNotBlank() } + + logcat { "Applying ${patchFileNames.size} config patches: $patchFileNames" } + + patchFileNames.forEach { patchFileName -> + try { + val patchJson = loadPatchFromAssets(patchFileName) + if (patchJson != null) { + val patchArray = objectMapper.readTree(patchJson) + jsonNode = JsonPatch.apply(patchArray, jsonNode) + logcat { "Successfully applied patch: $patchFileName" } + } else { + logcat(ERROR) { "Failed to load patch file: $patchFileName" } + } + } catch (e: Exception) { + logcat(ERROR) { "Failed to apply patch $patchFileName: ${e.message}" } + } + } + + objectMapper.writeValueAsString(jsonNode) + } catch (e: Exception) { + logcat(ERROR) { "Failed to patch privacy config response: ${e.message}" } + originalJson + } + } + + private fun loadPatchFromAssets(fileName: String): String? { + return try { + context.assets.open(fileName).bufferedReader().use { it.readText() } + } catch (e: Exception) { + logcat { "Failed to load patch file from assets: $fileName - ${e.message}" } + null + } + } + + override fun getInterceptor(): Interceptor { + return this + } +} diff --git a/versions.properties b/versions.properties index ee2fb678c824..611a05f5ded1 100644 --- a/versions.properties +++ b/versions.properties @@ -105,6 +105,8 @@ version.google.dagger=2.51.1 version.io.github.pcmind..leveldb=1.2 +version.io.github.vishwakarma..zjsonpatch=0.5.0 + version.io.jsonwebtoken..jjwt-api=0.12.6 version.io.jsonwebtoken..jjwt-impl=0.12.6