Skip to content

Commit 61b3864

Browse files
authored
add internal remote config patch tool (#6380)
Task/Issue URL: https://app.asana.com/1/137249556945/project/1208671518894266/task/1210708742763735 ### Description Adds tooling to locally patch remote config. Read the details in the new README file in the diff. ### Steps to test this PR 1. Create a `privacy-config/privacy-config-internal/local-config-patches/test_patch.json` file with this content: ```json [ { "op": "replace", "path": "/features/aiChat/state", "value": "disabled" } ] ``` 2. Create a `privacy-config/privacy-config-internal/local.properties` file with this content: ``` config_patches=privacy-config/privacy-config-internal/local-config-patches/test_patch.json ``` 3. Clean install the app. 4. Verify Duck.ai is disabled and that Settings -> Duck.ai is gone. 5. Update the patch file to: ```json [ { "op": "replace", "path": "/version", "value": "2752244802866" }, { "op": "remove", "path": "/features/aiChat/hash" } ] ``` 6. Relaunch the app (without clean installing it). This will download the production config and force update the feature because of the bumped version number and mismatching hash. 7. Verify Duck.ai is enabled and that Settings -> Duck.ai is available. 8. Update the `test_patch.json` to disable Duck.ai again and bump version: ```json [ { "op": "replace", "path": "/features/aiChat/state", "value": "disabled" }, { "op": "remove", "path": "/features/aiChat/hash" }, { "op": "replace", "path": "/version", "value": "3752244802866" } ] ``` 9. Relaunch the app (without clean installing it). 10. Verify Duck.ai is disabled and that Settings -> Duck.ai is gone.
1 parent 680346a commit 61b3864

File tree

5 files changed

+302
-1
lines changed

5 files changed

+302
-1
lines changed
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1-
/build
1+
/build
2+
local.properties
3+
/local-config-patches
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Internal Privacy Config module
2+
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.
3+
4+
## Local remote config patches
5+
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.
6+
7+
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.
8+
9+
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.
10+
11+
For example, to ensure a feature flag is always enabled, you can create a patch file like this:
12+
13+
```json
14+
[
15+
{
16+
"op": "replace",
17+
"path": "/features/myFeature/state",
18+
"value": "enabled"
19+
}
20+
]
21+
```
22+
23+
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:
24+
25+
```json
26+
[
27+
{
28+
"op": "replace",
29+
"path": "/features/myFeature/state",
30+
"value": "enabled"
31+
},
32+
{
33+
"op": "remove",
34+
"path": "/features/myFeature/hash"
35+
},
36+
{
37+
"op": "replace",
38+
"path": "/version",
39+
"value": "999999999999999"
40+
}
41+
]
42+
```
43+
44+
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.
45+
46+
### Usage
47+
There are two ways to apply local remote config patches:
48+
1. Using command line parameters when building the app.
49+
2. Defining a path in your `local.properties` file.
50+
51+
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.
52+
53+
Note: Regardless of the path where each file is, **each file name needs to be unique**.
54+
55+
#### Command line parameters
56+
You can specify the patches to apply when building the app by using the `-Pconfig_patches` parameter. For example:
57+
```bash
58+
./gradlew installInternalDebug \
59+
-Pconfig_patches=\
60+
privacy-config/privacy-config-internal/local-config-patches/test_patch.json,\
61+
privacy-config/privacy-config-internal/local-config-patches/test_patch2.json
62+
```
63+
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.
64+
65+
#### `local.properties` file
66+
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:
67+
```
68+
config_patches=privacy-config/privacy-config-internal/local-config-patches/test_patch.json,privacy-config/privacy-config-internal/local-config-patches/test_patch2.json
69+
```
70+
71+
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.
72+
73+
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.

privacy-config/privacy-config-internal/build.gradle

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,30 @@ plugins {
2222

2323
apply from: "$rootProject.projectDir/gradle/android-library.gradle"
2424

25+
def getConfigPatchFiles() {
26+
def patchFiles = ""
27+
28+
// check for local.properties file in this module first
29+
def localPropertiesFile = project.file('local.properties')
30+
if (localPropertiesFile.exists()) {
31+
def localProperties = new Properties()
32+
localPropertiesFile.withInputStream { localProperties.load(it) }
33+
34+
if (localProperties.getProperty('config_patches')) {
35+
patchFiles = localProperties.getProperty('config_patches').toString()
36+
println "Using config patches from privacy-config-internal/local.properties: $patchFiles"
37+
}
38+
}
39+
40+
// command line parameter takes precedence over local.properties
41+
if (project.rootProject.hasProperty('config_patches')) {
42+
patchFiles = project.rootProject.property('config_patches').toString()
43+
println "Using config patches from command line parameter: $patchFiles"
44+
}
45+
46+
return patchFiles
47+
}
48+
2549
android {
2650
anvil {
2751
generateDaggerFactories = true // default is false
@@ -31,6 +55,28 @@ android {
3155
abortOnError = !project.hasProperty("abortOnError") || project.property("abortOnError") != "false"
3256
}
3357
namespace 'com.duckduckgo.privacy.config.internal'
58+
59+
defaultConfig {
60+
def patchFiles = getConfigPatchFiles()
61+
def patchFileNames = []
62+
63+
if (patchFiles) {
64+
patchFiles.split(',').each { patchFilePath ->
65+
def patchFile = new File(patchFilePath.trim())
66+
if (patchFile.exists()) {
67+
def fileName = patchFile.getName()
68+
if (patchFileNames.contains(fileName)) {
69+
throw new GradleException("Duplicate patch file name detected: '$fileName'. Patch files must have unique names even if they are in different directories.")
70+
}
71+
patchFileNames.add(fileName)
72+
} else {
73+
println "Config patch file not found: ${patchFile.absolutePath}"
74+
}
75+
}
76+
}
77+
78+
buildConfigField "String", "CONFIG_PATCHES", "\"${patchFileNames.join(',')}\""
79+
}
3480
}
3581

3682
dependencies {
@@ -55,4 +101,67 @@ dependencies {
55101

56102
// Dagger
57103
implementation Google.dagger
104+
105+
implementation "com.squareup.logcat:logcat:_"
106+
implementation "io.github.vishwakarma:zjsonpatch:_"
107+
}
108+
109+
tasks.register('copyConfigPatches') {
110+
doLast {
111+
def buildAssetsDir = layout.buildDirectory.dir("generated/assets/configPatches").get().asFile
112+
113+
// always clean up any existing patch files first, also ensures that when patching is disabled, the directory is cleaned up
114+
if (buildAssetsDir.exists()) {
115+
buildAssetsDir.listFiles().each { file ->
116+
if (file.name.endsWith('.json')) {
117+
file.delete()
118+
println "Removed old patch file from build assets: ${file.absolutePath}"
119+
}
120+
}
121+
if (buildAssetsDir.listFiles().length == 0) {
122+
buildAssetsDir.delete()
123+
}
124+
}
125+
126+
def patchFiles = getConfigPatchFiles()
127+
128+
if (patchFiles) {
129+
def fileNames = []
130+
patchFiles.split(',').each { patchFilePath ->
131+
def patchFile = new File(patchFilePath.trim())
132+
if (patchFile.exists()) {
133+
def fileName = patchFile.getName()
134+
if (fileNames.contains(fileName)) {
135+
throw new GradleException("Duplicate patch file name detected: '$fileName'. Patch files must have unique names even if they are in different directories.")
136+
}
137+
fileNames.add(fileName)
138+
139+
if (!buildAssetsDir.exists()) {
140+
buildAssetsDir.mkdirs()
141+
}
142+
143+
def destFile = new File(buildAssetsDir, fileName)
144+
destFile.bytes = patchFile.bytes
145+
println "Copied config patch to build assets: ${patchFile.absolutePath} -> ${destFile.absolutePath}"
146+
} else {
147+
println "Warning: Config patch file not found: ${patchFile.absolutePath}"
148+
}
149+
}
150+
}
151+
}
152+
}
153+
154+
android.sourceSets.main.assets.srcDirs += layout.buildDirectory.dir("generated/assets/configPatches").get().asFile.path
155+
156+
afterEvaluate {
157+
tasks.matching { it.name.contains('mergeAssets') }.configureEach { task ->
158+
task.dependsOn copyConfigPatches
159+
}
160+
161+
tasks.matching { it.name.contains('preBuild') }.configureEach { task ->
162+
task.dependsOn copyConfigPatches
163+
}
164+
165+
// force the task to always run (never up-to-date)
166+
copyConfigPatches.outputs.upToDateWhen { false }
58167
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/*
2+
* Copyright (c) 2025 DuckDuckGo
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.duckduckgo.privacy.config.internal.plugins
18+
19+
import android.content.Context
20+
import com.duckduckgo.app.global.api.ApiInterceptorPlugin
21+
import com.duckduckgo.di.scopes.AppScope
22+
import com.duckduckgo.privacy.config.api.PRIVACY_REMOTE_CONFIG_URL
23+
import com.duckduckgo.privacy.config.internal.BuildConfig
24+
import com.fasterxml.jackson.databind.ObjectMapper
25+
import com.flipkart.zjsonpatch.JsonPatch
26+
import com.squareup.anvil.annotations.ContributesMultibinding
27+
import javax.inject.Inject
28+
import logcat.LogPriority.ERROR
29+
import logcat.logcat
30+
import okhttp3.Interceptor
31+
import okhttp3.MediaType.Companion.toMediaType
32+
import okhttp3.Response
33+
import okhttp3.ResponseBody.Companion.toResponseBody
34+
35+
@ContributesMultibinding(
36+
scope = AppScope::class,
37+
boundType = ApiInterceptorPlugin::class,
38+
)
39+
class DevPrivacyConfigPatchApiInterceptor @Inject constructor(
40+
private val context: Context,
41+
) : ApiInterceptorPlugin, Interceptor {
42+
43+
private val objectMapper = ObjectMapper()
44+
45+
override fun intercept(chain: Interceptor.Chain): Response {
46+
val request = chain.request()
47+
val url = request.url
48+
49+
if (url.toString() == PRIVACY_REMOTE_CONFIG_URL) {
50+
val response = chain.proceed(request)
51+
52+
if (response.isSuccessful) {
53+
val responseBody = response.body?.string()
54+
if (responseBody != null) {
55+
val modifiedJson = patchPrivacyConfigResponse(responseBody)
56+
val mediaType = response.body?.contentType() ?: "application/json".toMediaType()
57+
return response.newBuilder()
58+
.body(modifiedJson.toResponseBody(mediaType))
59+
.build()
60+
}
61+
}
62+
63+
return response
64+
}
65+
66+
return chain.proceed(chain.request())
67+
}
68+
69+
private fun patchPrivacyConfigResponse(originalJson: String): String {
70+
return try {
71+
val configPatches = BuildConfig.CONFIG_PATCHES
72+
if (configPatches.isBlank()) {
73+
return originalJson
74+
}
75+
76+
var jsonNode = objectMapper.readTree(originalJson)
77+
val patchFileNames = configPatches.split(',').filter { it.isNotBlank() }
78+
79+
logcat { "Applying ${patchFileNames.size} config patches: $patchFileNames" }
80+
81+
patchFileNames.forEach { patchFileName ->
82+
try {
83+
val patchJson = loadPatchFromAssets(patchFileName)
84+
if (patchJson != null) {
85+
val patchArray = objectMapper.readTree(patchJson)
86+
jsonNode = JsonPatch.apply(patchArray, jsonNode)
87+
logcat { "Successfully applied patch: $patchFileName" }
88+
} else {
89+
logcat(ERROR) { "Failed to load patch file: $patchFileName" }
90+
}
91+
} catch (e: Exception) {
92+
logcat(ERROR) { "Failed to apply patch $patchFileName: ${e.message}" }
93+
}
94+
}
95+
96+
objectMapper.writeValueAsString(jsonNode)
97+
} catch (e: Exception) {
98+
logcat(ERROR) { "Failed to patch privacy config response: ${e.message}" }
99+
originalJson
100+
}
101+
}
102+
103+
private fun loadPatchFromAssets(fileName: String): String? {
104+
return try {
105+
context.assets.open(fileName).bufferedReader().use { it.readText() }
106+
} catch (e: Exception) {
107+
logcat { "Failed to load patch file from assets: $fileName - ${e.message}" }
108+
null
109+
}
110+
}
111+
112+
override fun getInterceptor(): Interceptor {
113+
return this
114+
}
115+
}

versions.properties

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ version.google.dagger=2.51.1
101101

102102
version.io.github.pcmind..leveldb=1.2
103103

104+
version.io.github.vishwakarma..zjsonpatch=0.5.0
105+
104106
version.io.jsonwebtoken..jjwt-api=0.12.6
105107

106108
version.io.jsonwebtoken..jjwt-impl=0.12.6

0 commit comments

Comments
 (0)