Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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
Expand Up @@ -46,11 +46,13 @@ public static class SdkConfigParams {
public static class SdkConfigStreamParams {
String baseUri;
Long initialRetryDelayMs;
String filter;
}

public static class SdkConfigPollParams {
String baseUri;
Long pollIntervalMs;
String filter;
}

public static class SdkConfigEventParams {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,12 @@ private LDConfig buildSdkConfig(SdkConfigParams params, LDLogAdapter logAdapter,
builder.events(eventsBuilder);
}

if (params.streaming != null && params.streaming.filter != null) {
builder.payloadFilter(params.streaming.filter);
} else if (params.polling != null && params.polling.filter != null) {
builder.payloadFilter(params.polling.filter);
}

builder.evaluationReasons(params.clientSide.evaluationReasons);
HttpConfigurationBuilder httpBuilder = Components.httpConfiguration()
.useReport(params.clientSide.useReport)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ public class TestService extends NanoHTTPD {
"retry-conformance-fdv1-streaming",
"retry-conformance-fdv1-polling",
"client-use-post",
"fdv1-fallback"
"fdv1-fallback",
"filtering",
"filtering-strict"
};
private static final String MIME_JSON = "application/json";
static final Gson gson = new GsonBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ final class DataSourceBuildInputsInternal extends DataSourceBuildInputs {
@Nullable
private final PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData perEnvironmentData;

@Nullable
private final String payloadFilter;

DataSourceBuildInputsInternal(
LDContext evaluationContext,
ServiceEndpoints serviceEndpoints,
Expand All @@ -39,11 +42,13 @@ final class DataSourceBuildInputsInternal extends DataSourceBuildInputs {
ScheduledExecutorService sharedExecutor,
@NonNull File cacheDir,
LDLogger baseLogger,
@Nullable PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData perEnvironmentData
@Nullable PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData perEnvironmentData,
@Nullable String payloadFilter
) {
super(evaluationContext, serviceEndpoints, http, evaluationReasons,
selectorSource, sharedExecutor, cacheDir, baseLogger);
this.perEnvironmentData = perEnvironmentData;
this.payloadFilter = payloadFilter;
}

/**
Expand All @@ -64,6 +69,7 @@ static DataSourceBuildInputsInternal get(DataSourceBuildInputs inputs) {
inputs.getSharedExecutor(),
inputs.getCacheDir(),
inputs.getBaseLogger(),
null,
null
);
}
Expand All @@ -72,4 +78,9 @@ static DataSourceBuildInputsInternal get(DataSourceBuildInputs inputs) {
PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData getPerEnvironmentDataIfAvailable() {
return perEnvironmentData;
}

@Nullable
String getPayloadFilter() {
return payloadFilter;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ public Synchronizer build(DataSourceBuildInputs inputs) {
FeatureFetcher fetcher = new HttpFeatureFlagFetcher(
pollingBase,
inputs.isEvaluationReasons(),
DataSourceBuildInputsInternal.get(inputs).getPayloadFilter(),
inputs.getHttp().shouldUsePost(),
LDUtil.makeHttpProperties(inputs.getHttp()),
inputs.getCacheDir(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,8 @@ private DataSourceBuildInputsInternal makeInputs(ClientContext clientContext) {
sharedExecutor,
impl.getPlatformState().getCacheDir(),
clientContext.getBaseLogger(),
impl.getPerEnvironmentDataIfAvailable()
impl.getPerEnvironmentDataIfAvailable(),
LDUtil.payloadFilter(clientContext)
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.launchdarkly.sdk.android;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.launchdarkly.logging.LDLogger;
import com.launchdarkly.sdk.LDContext;
Expand Down Expand Up @@ -32,6 +33,7 @@ class HttpFeatureFlagFetcher implements FeatureFetcher {

private final URI pollUri;
private final boolean evaluationReasons;
private final String payloadFilter;
private final boolean useReport;
private final HttpProperties httpProperties;
private final OkHttpClient client;
Expand All @@ -43,6 +45,7 @@ class HttpFeatureFlagFetcher implements FeatureFetcher {
this(
clientContext.getServiceEndpoints().getPollingBaseUri(),
clientContext.isEvaluationReasons(),
LDUtil.payloadFilter(clientContext),
clientContext.getHttp().isUseReport(),
LDUtil.makeHttpProperties(clientContext),
ClientContextImpl.get(clientContext).getPlatformState().getCacheDir(),
Expand All @@ -53,13 +56,15 @@ class HttpFeatureFlagFetcher implements FeatureFetcher {
HttpFeatureFlagFetcher(
@NonNull URI pollUri,
boolean evaluationReasons,
@Nullable String payloadFilter,
boolean useReport,
@NonNull HttpProperties httpProperties,
@NonNull File platformCacheDir,
@NonNull LDLogger logger
) {
this.pollUri = pollUri;
this.evaluationReasons = evaluationReasons;
this.payloadFilter = payloadFilter;
this.useReport = useReport;
this.httpProperties = httpProperties;
this.logger = logger;
Expand Down Expand Up @@ -159,6 +164,7 @@ private Request getDefaultRequest(LDContext ldContext) throws IOException {
if (evaluationReasons) {
uri = URI.create(uri.toString() + "?withReasons=true");
}
uri = LDUtil.withPayloadFilter(uri, payloadFilter);
logger.debug("Attempting to fetch Feature flags using uri: {}", uri);
return new Request.Builder().url(uri.toURL())
.headers(httpProperties.toHeadersBuilder().build())
Expand All @@ -170,6 +176,7 @@ private Request getReportRequest(LDContext ldContext) throws IOException {
if (evaluationReasons) {
uri = URI.create(uri.toString() + "?withReasons=true");
}
uri = LDUtil.withPayloadFilter(uri, payloadFilter);
logger.debug("Attempting to report user using uri: {}", uri);
String contextJson = JsonSerialization.serialize(ldContext);
RequestBody reportBody = RequestBody.create(contextJson, JSON);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import com.launchdarkly.logging.LDLogAdapter;
import com.launchdarkly.logging.LDLogLevel;
import com.launchdarkly.logging.LDLogger;
import com.launchdarkly.logging.Logs;
import com.launchdarkly.sdk.ContextKind;
import com.launchdarkly.sdk.LDContext;
Expand All @@ -28,6 +29,7 @@
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import okhttp3.MediaType;

Expand Down Expand Up @@ -64,6 +66,7 @@ public class LDConfig {

static final int DEFAULT_MAX_CACHED_CONTEXTS = 5;
static final int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 10_000; // 10 seconds
private static final Pattern PAYLOAD_FILTER_PATTERN = Pattern.compile("^[a-zA-Z0-9][._\\-a-zA-Z0-9]*$");

private final Map<String, String> mobileKeys;

Expand All @@ -88,6 +91,7 @@ public class LDConfig {
private final int maxCachedContexts;
private final boolean offline;
private final long connectionModeStateDebounceMs;
private final Map<String, String> payloadFilters; // by environment name; a null value means no filter
private final PersistentDataStore persistentDataStore; // configurable for testing only

LDConfig(Map<String, String> mobileKeys,
Expand All @@ -107,6 +111,7 @@ public class LDConfig {
boolean generateAnonymousKeys,
boolean autoEnvAttributes,
long connectionModeStateDebounceMs,
Map<String, String> payloadFilters,
PersistentDataStore persistentDataStore,
LDLogAdapter logAdapter,
String loggerName) {
Expand All @@ -127,6 +132,7 @@ public class LDConfig {
this.generateAnonymousKeys = generateAnonymousKeys;
this.autoEnvAttributes = autoEnvAttributes;
this.connectionModeStateDebounceMs = connectionModeStateDebounceMs;
this.payloadFilters = payloadFilters;
this.persistentDataStore = persistentDataStore;
this.logAdapter = logAdapter;
this.loggerName = loggerName;
Expand Down Expand Up @@ -181,6 +187,27 @@ public boolean isEvaluationReasons() {
return evaluationReasons;
}

/**
* @return the payload filter key for the primary environment, or null if no valid filter was configured
* @see Builder#payloadFilter(String)
*/
public String getPayloadFilter() {
return payloadFilters.get(primaryEnvironmentName);
}

/**
* Returns the payload filter key for an environment: the one set with {@link Builder#payloadFilter(String)}
* for the primary environment, or with {@link Builder#secondaryEnvironment(String, String, String)} for a
* secondary one.
*
* @param environmentName an environment name
* @return the payload filter key, or null if the environment has no valid filter or is not one of this
* configuration's environments
*/
public String getPayloadFilter(String environmentName) {
return payloadFilters.get(environmentName);
}

/**
* @return true if opting out of diagnostics, false otherwise
*/
Expand Down Expand Up @@ -278,6 +305,9 @@ public enum AutoEnvAttributes {

private long connectionModeStateDebounceMs = StateDebounceManager.DEFAULT_DEBOUNCE_MS;

private String payloadFilter = null;
private Map<String, String> secondaryPayloadFilters = new HashMap<>(); // by environment name

private LDLogAdapter logAdapter = defaultLogAdapter();
private String loggerName = LDPackageConsts.DEFAULT_LOGGER_NAME;
private LDLogLevel logLevel = null;
Expand Down Expand Up @@ -321,6 +351,7 @@ public Builder mobileKey(String mobileKey) {
public Builder secondaryMobileKeys(Map<String, String> secondaryMobileKeys) {
if (secondaryMobileKeys == null) {
this.secondaryMobileKeys = null;
this.secondaryPayloadFilters.clear();
return this;
}

Expand All @@ -337,6 +368,45 @@ public Builder secondaryMobileKeys(Map<String, String> secondaryMobileKeys) {
}

this.secondaryMobileKeys = unmodifiable;
this.secondaryPayloadFilters.clear();
return this;
}

/**
* Adds a secondary environment, optionally with a payload filter.
* <p>
* The payload filter must be defined in the mobile key's project, and works as
* {@link #payloadFilter(String)} does for the primary environment, including applying only to
* FDv1 requests. To filter by views with FDv2, pass a mobile key with a custom payload. Calling
* {@link #secondaryMobileKeys(Map)} afterwards replaces every secondary environment, including
* the ones added here.
*
* @param name the name that identifies the environment, as passed to {@link LDClient#getForMobileKey(String)}
* @param mobileKey the environment's mobile key
* @param payloadFilter the key of a payload filter to apply to the environment's flag data
* requests, or null for no filter
* @return the builder
* @throws IllegalArgumentException if the name is the primary environment name or is already
* used, or if the mobile key is the primary key or is already used
*/
public Builder secondaryEnvironment(String name, String mobileKey, String payloadFilter) {
if (primaryEnvironmentName.equals(name)) {
throw new IllegalArgumentException("The primary environment name is not a valid key.");
}
if (secondaryMobileKeys != null && secondaryMobileKeys.containsKey(name)) {
throw new IllegalArgumentException("A secondary environment with this name already exists.");
}
if (mobileKey != null && mobileKey.equals(this.mobileKey)) {
throw new IllegalArgumentException("The primary environment key cannot be in the secondary mobile keys.");
}
if (secondaryMobileKeys != null && secondaryMobileKeys.containsValue(mobileKey)) {
throw new IllegalArgumentException("A key can only be used once.");
}

Map<String, String> keys = secondaryMobileKeys == null ? new HashMap<>() : new HashMap<>(secondaryMobileKeys);
keys.put(name, mobileKey);
this.secondaryMobileKeys = Collections.unmodifiableMap(keys);
this.secondaryPayloadFilters.put(name, payloadFilter);
return this;
}

Expand Down Expand Up @@ -594,6 +664,33 @@ public Builder evaluationReasons(boolean evaluationReasons) {
return this;
}

/**
* Sets the key of a payload filter to apply to flag data requests.
* <p>
* Payload filters are defined per project in LaunchDarkly. When a filter key is set, the SDK
* adds it as the {@code filter} query parameter to its streaming and polling requests, and
* LaunchDarkly limits the flags it sends to the ones selected by that filter.
* <p>
* Payload filters are an FDv1 feature. When {@link #dataSystem(DataSystemBuilder)} is set, the
* SDK sends the filter only on FDv1 fallback requests and logs a warning. FDv2 filters flag data
* by the views linked to the mobile key instead: use a mobile key with a custom payload. Such a
* key does not work with FDv1 requests, which LaunchDarkly rejects with a 422 status.
* <p>
* This key applies only to the primary environment. To filter a secondary environment, add it
* with {@link #secondaryEnvironment(String, String, String)}.
* <p>
* The key must contain only alphanumeric characters, periods, underscores, and hyphens, and
* must start with an alphanumeric character. If the key is invalid, the SDK logs an error and
* requests the full environment instead.
*
* @param payloadFilter the payload filter key, or null for no filter
* @return the builder
*/
public Builder payloadFilter(String payloadFilter) {
this.payloadFilter = payloadFilter;
return this;
}

/**
* Set to true to opt out of sending diagnostics data.
*
Expand Down Expand Up @@ -774,6 +871,33 @@ private static LDLogAdapter defaultLogAdapter() {
return LDTimberLogging.adapter();
}

private static String validPayloadFilterOrNull(String payloadFilter, String environmentName, LDLogger logger) {
if (payloadFilter == null || payloadFilter.isEmpty()) {
return null;
}
if (!PAYLOAD_FILTER_PATTERN.matcher(payloadFilter).matches()) {
logger.error("Payload filter \"{}\" is invalid; the full \"{}\" environment will be requested instead",
payloadFilter, environmentName);
return null;
}
return payloadFilter;
}

private Map<String, String> validPayloadFilters(Map<String, String> mobileKeys, LDLogger logger) {
HashMap<String, String> payloadFilters = new HashMap<>();
for (String environmentName : mobileKeys.keySet()) {
String filter = validPayloadFilterOrNull(environmentName.equals(primaryEnvironmentName)
? payloadFilter : secondaryPayloadFilters.get(environmentName), environmentName, logger);
if (filter != null && dataSystemBuilder != null) {
logger.warn("Payload filter \"{}\" for the \"{}\" environment applies only to FDv1 fallback requests;"
+ " FDv2 requests receive the flags in the views linked to the mobile key",
filter, environmentName);
}
payloadFilters.put(environmentName, filter);
}
return Collections.unmodifiableMap(payloadFilters);
}

/**
* Returns the configured {@link LDConfig} object.
* @return the configuration
Expand Down Expand Up @@ -840,6 +964,7 @@ public LDConfig build() {
generateAnonymousKeys,
autoEnvAttributes,
connectionModeStateDebounceMs,
validPayloadFilters(mobileKeys, LDLogger.withAdapter(actualLogAdapter, loggerName)),
persistentDataStore,
actualLogAdapter,
loggerName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
import com.launchdarkly.sdk.android.subsystems.ClientContext;
import com.launchdarkly.sdk.android.subsystems.HttpConfiguration;
import com.launchdarkly.sdk.internal.http.HeadersTransformer;
import com.launchdarkly.sdk.internal.http.HttpHelpers;
import com.launchdarkly.sdk.internal.http.HttpProperties;
import com.launchdarkly.sdk.json.JsonSerialization;

import java.net.URI;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
Expand Down Expand Up @@ -202,6 +204,16 @@ static String urlSafeBase64(LDContext context) {
Base64.URL_SAFE + Base64.NO_WRAP);
}

@Nullable
static String payloadFilter(ClientContext clientContext) {
LDConfig config = clientContext.getConfig();
return config == null ? null : config.getPayloadFilter(clientContext.getEnvironmentName());
}

static URI withPayloadFilter(URI uri, @Nullable String payloadFilter) {
return payloadFilter == null ? uri : HttpHelpers.addQueryParam(uri, "filter", payloadFilter);
}

static HttpProperties makeHttpProperties(ClientContext clientContext) {
return makeHttpProperties(clientContext.getHttp());
}
Expand Down
Loading