Skip to content

add internal remote config patch tool #6380

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion privacy-config/privacy-config-internal/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/build
/build
local.properties
/local-config-patches
73 changes: 73 additions & 0 deletions privacy-config/privacy-config-internal/README.md
Original file line number Diff line number Diff line change
@@ -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.
109 changes: 109 additions & 0 deletions privacy-config/privacy-config-internal/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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 }
}
Original file line number Diff line number Diff line change
@@ -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(
Comment on lines +35 to +39
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All interceptors are currently added in default order, sorted by class name. If I assign a low priority to this interceptor without changing the others, it would run first, since it would be the only one with a defined priority. I tried giving all plugins the same priority (to preserve class name sorting as PriorityKey docs suggest) and setting this interceptor last, but the build fails due to duplicate priority keys, despite what the docs say.

I don’t want to risk changing any production behavior, so it’s fine if this interceptor doesn’t run last for now. If it ever becomes a problem, we can revisit.

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
}
}
2 changes: 2 additions & 0 deletions versions.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading