We are going to design a telemetry SDK that is privacy-by-default. This means:
We have a set of contracts (interfaces) that define how telemetry is collected, stored, and sent.
We will have a redaction mechanism to remove or mask sensitive data.
We will use purpose tags to indicate the reason for collecting each piece of data, and we will enforce that only data for allowed purposes is collected.
Steps:
Define purpose tags (enums or constants) that describe the purpose of collection.
Define a contract for a telemetry event that includes:
A dictionary of properties (key-value pairs) where the values can be of basic types (string, number, boolean) or nested objects.
A set of purpose tags associated with the event (or each property? we'll decide).
We need to be able to redact sensitive data. This could be done by:
a. Having a list of keys that are always redacted (like "password", "credit_card", etc.)
b. Allowing custom redaction rules per purpose? Or per key? We'll design for flexibility.
We want to enforce that when an event is created, we check that each property (or the event as a whole) has at least one allowed purpose?
Alternatively, we can have a configuration that specifies which purposes are allowed for the current context (e.g., user consent).
Let's break down:
Purposes:
Analytics
CrashReporting
PerformanceMonitoring
UserExperience
We can have an enum for these.
However, note: an event might be used for multiple purposes. So we can have a set of purposes.
Design:
public enum TelemetryPurpose {
Analytics,
CrashReporting,
PerformanceMonitoring,
UserExperience
}
But note: we might want to extend without changing code? So maybe string constants or a class with static readonly strings.
Alternatively, we can use flags enum if we want to combine purposes. But let's keep it simple and use a set of strings.
We can define:
public static class TelemetryPurposes {
public const string Analytics = "analytics";
public const string CrashReporting = "crash_reporting";
public const string PerformanceMonitoring = "performance_monitoring";
public const string UserExperience = "user_exience";
}
Then an event can have a list of purposes (List).
However, we want to enforce that the event's purposes are within a set of allowed purposes (based on user consent, etc.). So we need a way to set allowed purposes.
Let's design the event:
public class TelemetryEvent {
public string Name { get; set; }
public Dictionary<string, object> Properties { get; set; } = new Dictionary<string, object>();
public HashSet Purposes { get; set; } = new HashSet();
}
But note: we might want to have purpose per property? Because one property might be used for multiple purposes? Actually, the event as a whole is for a set of purposes.
However, we might have an event that is sent for multiple purposes and then we want to redact differently per purpose? That complicates.
Alternatively, we can have:
The event has a set of purposes.
When we redact, we look at the event's purposes and apply redaction rules that are applicable for any of the event's purposes.
But note: a property might be sensitive for one purpose but not for another? That's unlikely. Usually, the sensitivity of the data is independent of the purpose.
So let's think: we want to redact certain keys (like "password") regardless of purpose? Or we might want to redact only if the event is for a purpose that doesn't allow that key?
Actually, the privacy-by-default means we redact by default and then only allow if explicitly permitted.
We can have:
A set of keys that are always redacted (like "password", "ssn", etc.) because they are always sensitive.
Additionally, we can have a set of keys that are conditionally redacted based on the purpose? But that might be too complex.
Alternatively, we can have a redaction rule that says: for a given key, it is redacted unless the event has a purpose that is allowed for that key?
But note: we are privacy-by-default, so we start with redacting everything and then whitelist? Or we start with no redaction and then blacklist?
Privacy-by-default: we should redact by default. So we should have a list of keys that are always redacted (the sensitive ones) and then we can have a whitelist per purpose?
Actually, let's invert:
We can have a configuration that says:
For each purpose, what keys are allowed? Then when creating an event, we check that the event's purposes are allowed and then for each property, we check if the key is allowed for at least one of the event's purposes?
But that's a lot of configuration.
Alternatively, we can have:
A set of globally allowed keys (for all purposes) -> but that's not privacy by default because we are allowing by default.
We want to redact by default, meaning: if a key is not explicitly allowed for the current set of purposes, then it is redacted.
So we need:
A mapping from purpose to set of allowed keys? But then an event can have multiple purposes, so we take the union of allowed keys for the event's purposes.
But note: we might have a key that is allowed for analytics but not for crash reporting. If an event is for both, then we allow it? That might be acceptable.
However, we also have globally sensitive keys (like "password") that we never want to send, regardless of purpose. So we can have a global blacklist.
Steps for redaction:
Remove any key that is in the global blacklist (always redact).
Then, for the remaining keys, check if the key is allowed for at least one of the event's purposes. If not, redact (remove or mask).
But wait: what if we want to mask instead of remove? We might have a rule that says for a key, we mask (e.g., replace with "***") rather than remove.
So we need to define redaction actions:
Remove: the key is removed from the event.
Mask: the value is replaced with a masked string (or for numbers, maybe a fixed number?).
We can have:
public enum RedactionAction {
Remove,
Mask
}
Then, for each key (or pattern) we can define:
For a given key, what redaction action to take? And for which purposes?
But again, we want to redact by default, so if a key is not explicitly allowed, we remove it? Or we mask it? We can set a default action (remove) and then override per key.
Let's design the redaction rule:
public class RedactionRule {
public string KeyPattern { get; set; } // could be a regex or just a string? We can use string and treat it as exact match? Or we can support wildcards?
public RedactionAction Action { get; set; }
public HashSet AllowedPurposes { get; set; } // if empty, then it's globally allowed? Or if the rule is for redaction, then we redact if the purpose is not in this set?
}
Actually, we are building a set of rules that say: for a key, if the event does not have any of the allowed purposes, then apply the action.
But note: we also have the global blacklist. We can treat the global blacklist as rules with no allowed purposes (i.e., always redact).
Alternatively, we can have two sets:
GlobalBlacklist: keys that are always redacted (with a fixed action, say remove).
PurposeBasedRules: for a given key, if the event's purposes do not intersect with the rule's allowed purposes, then redact.
However, we might want to have a rule that says: for key "user_id", allow for analytics and crash reporting, but for any other purpose, mask.
So we need to be able to specify:
For key X, if the event has purpose P, then do not redact (or use a specific action). Otherwise, use the default redaction.
But note: we are privacy-by-default, so the default is to redact (remove). So we only specify when to NOT redact? Or we specify when to redact and with what action?
Let's think from the perspective of the data controller (the app using the SDK):
They want to send data for a purpose, and they want to ensure that only the allowed data for that purpose is sent.
So we can have:
A configuration that lists, for each purpose, the keys that are allowed (and optionally, a transformation for the value?).
But we also want to have a global blacklist (keys that are never allowed).
So:
Step 1: Remove all keys that are in the global blacklist.
Step 2: For each remaining key, check if the key is allowed for at least one of the event's purposes. If not, remove.
But what about masking? We might want to mask the value instead of removing for some keys?
Alternatively, we can have:
For each key, we define a set of allowed purposes and a redaction action (which is applied if the current event's purposes do not match any of the allowed purposes). The redaction action can be Remove or Mask.
Then, for a given event and a key:
if the key is in global blacklist -> remove (or mask, but we can set global blacklist to remove).
else:
if the event's purposes intersect with the rule's allowed purposes -> keep the value as is.
else -> apply the rule's action (remove or mask).
But note: we might have multiple rules for the same key? We can have the most specific rule (by key pattern) take precedence? Or we can have a priority.
Alternatively, we can have a single rule per key? But then we cannot have:
For key "user_id", allow for analytics and crash reporting, but for performance monitoring, mask.
But then if an event has purposes {analytics, performance_monitoring}, then which rule applies? We want to keep because analytics allows it? Or mask because performance monitoring would mask?
Actually, we want to allow if any of the event's purposes are in the allowed set? Then we don't redact? But then the masking rule for performance monitoring would never apply if analytics is also present.
So we need to think about the intention:
The app developer wants to say:
For analytics and crash reporting, I want to send the raw user_id.
For performance monitoring, I want to send a masked user_id.
But if an event is for both analytics and performance monitoring, what should happen?
We can say: the event is sent for multiple purposes, so we have to satisfy the most restrictive? Or we can split the event?
Actually, in telemetry, an event is usually sent to multiple endpoints (for different purposes) and we might want to send different data for each purpose? That would require splitting the event.
Alternatively, we can have the event's data be a union of what is allowed for each purpose? But then if one purpose requires masking and another doesn't, we have to choose?
This is getting complex.
Let's simplify:
We are going to design the SDK to send one event to one backend, and the backend might use the event for multiple purposes. But the data we send must be safe for all the stated purposes.
So we take the intersection of allowed keys? Or we take the union and then for keys that are allowed for some purposes but not others, we mask?
Actually, if a key is allowed for one purpose but not for another, and the event is for both, then we cannot send the raw value because it's not allowed for one purpose. So we must either remove or mask.
We can have:
For each key, we determine the action based on the event's purposes:
If the key is in global blacklist: remove.
Else, if there is a rule for this key and the event's purposes do not intersect with the rule's allowed purposes, then apply the rule's action.
But if the event's purposes intersect with the rule's allowed purposes, then we keep? But what if there are multiple rules for the same key? We need to take the most restrictive action among the rules that do not match?
Alternatively, we can have:
For a given key, we look at all rules that match the key (by pattern) and then:
If any rule's allowed purposes intersect with the event's purposes, then we keep (or use the action of that rule? but then we might have conflicting actions).
Actually, we can think of it as:
For a key, we want to know: is it allowed for at least one of the event's purposes? If yes, then we keep. But then what about masking?
We can have:
A rule that says: for key X, if the event has purpose P, then keep. Otherwise, mask.
But then if the event has multiple purposes, and one of them is P, then we keep. But if the event has another purpose Q that requires masking, then we are not masking.
So we need to consider all purposes in the event. We can say: if the key is allowed for all the event's purposes? Then keep. Otherwise, we mask? But then if one purpose allows and another doesn't, we mask.
But what if we have:
Purpose1: allows key X.
Purpose2: does not allow key X.
Then for an event with both purposes, we cannot send the raw X because purpose2 does not allow. So we must mask or remove.
So we need to know, for each key, the set of purposes for which it is allowed. Then:
If the event's purposes are a subset of the allowed purposes for the key, then keep?
Actually, we want: if the event's purposes are entirely within the allowed set, then keep. Otherwise, we have to apply a redaction (mask or remove).
But note: the allowed set for a key might be defined by multiple rules? We can define the allowed set for a key as the union of allowed purposes from all rules that match the key?
Then:
Let A = union of allowed purposes for the key from all matching rules.
Then, if eventPurposes is a subset of A, then keep? But that would be too permissive? Because if a key is allowed for analytics and crash reporting, and the event is for analytics and performance monitoring, then eventPurposes = {analytics, performance_monitoring} is not a subset of {analytics, crash_reporting} -> so we would redact.
But wait: the key is allowed for analytics (which is in the event) but not for performance monitoring. So we cannot send the raw value because performance monitoring doesn't allow. So we must redact.
So the condition is: if eventPurposes is a subset of the key's allowed purposes, then keep. Otherwise, we redact.
But what if we want to mask for performance monitoring? We don't have a rule for performance monitoring, so the union doesn't include performance monitoring, so for an event with performance monitoring, we redact (by default remove). But we might want to mask instead.
So we need to be able to specify: for a key, if the event has a purpose that is not in the allowed set, then what action?
We can have:
For a key, we define a default redaction action (for when the event's purposes are not entirely within the allowed set). And then we can have specific rules that override the default for specific purposes?
Actually, we can think of it as:
For each key, we have a set of allowed purposes (the union of all rule's allowed purposes for that key) and a default redaction action (which is applied when the event's purposes are not a subset of the allowed set).
But then we cannot have:
For key "user_id", allow for analytics and crash reporting (keep), but for performance monitoring, mask.
Because if the event has performance monitoring and analytics, then eventPurposes = {analytics, performance_monitoring} is not a subset of {analytics, crash_reporting} -> so we apply the default redaction (which might be remove). But we want to mask for performance monitoring.
So we need to be able to specify per purpose?
Alternatively, we can have:
For each key, we define a mapping from purpose to action? But then we have to specify for every purpose? That's a lot.
Let's step back.
We want:
The event has a set of purposes.
For each key in the event, we want to apply a redaction action based on the event's purposes and the key.
We can define:
public class KeyRedactionPolicy {
public string Key { get; set; }
// If the event has any of these purposes, then we keep the value (no redaction). But note: if the event has a purpose that is not in this set, we still might want to keep? No, because we are privacy by default.
// Actually, we want to redact if the event has a purpose that is not allowed for this key? But wait, the event might have multiple purposes.
code
// Alternatively, we can say: the key is allowed only if the event's purposes are a subset of the allowed purposes? That seems too strict.
// Let's change: the key is allowed if the event has at least one purpose that is in the allowed set? Then we keep? But then if the event has a purpose that does not allow the key, we are still sending the key because one purpose allows it.
// That is not safe because the purpose that does not allow the key would be receiving data it shouldn't.
// So we must redact if there is any purpose in the event that does not allow the key.
// Therefore, we need to know for each key, the set of purposes that allow it. Then, if the event's purposes are a subset of that set, then keep. Otherwise, redact.
// But what if we want to mask for some purposes and remove for others? We can't have two different actions for the same key in the same event.
// So we can have:
// For a key, we define:
// AllowedPurposes: the set of purposes for which the key is allowed (without redaction).
// DefaultRedactionAction: the action to take if the event's purposes are not a subset of AllowedPurposes.
// Then, for an event with purposes P, if P is a subset of AllowedPurposes, then keep. Otherwise, apply DefaultRedactionAction.
// But then we cannot have:
// For analytics: allow (keep)
// For crash reporting: allow (keep)
// For performance monitoring: mask
// Because the AllowedPurposes would be {analytics, crash_reporting} and the default action would be remove. Then for an event with {analytics, performance_monitoring} we remove, but we wanted to mask.
// So we need to be able to specify the action per purpose? Or we need to have a more complex rule.
// Alternatively, we can have multiple policies for the same key with different allowed purposes and different actions? And then we take the first matching rule? Or the most specific?
// Let's try:
// We have a list of rules. Each rule has:
// KeyPattern
// AllowedPurposes (if empty, then it applies to all purposes? or none? We can say: if empty, then it's a global rule that applies to all purposes? But then we cannot have an exception for a specific purpose? We can have multiple rules and the first match wins? Or the last? We need an order.
// We can order by specificity (longer key pattern first) and then by priority? Or we can have a priority number.
// But let's keep it simple: one rule per key? Then we cannot have the above scenario.
// Alternatively, we can have:
// For key X, we can have:
// If the event has purpose P, then action A.
// Else, action B.
// But we have multiple purposes. So we can say:
// Let P_event be the set of purposes of the event.
// Let P_rule be the set of purposes for which the rule applies (the allowed purposes?).
// If P_event is a subset of P_rule, then keep? Or if P_event intersects P_rule?
// We are back to the same problem.
}
Given the complexity, maybe we should not try to have per-purpose redaction actions. Instead, we can have:
A set of keys that are always allowed (for any purpose) -> but that's not privacy by default.
A set of keys that are never allowed (global blacklist).
For the rest, we require that the event's purposes must be exactly a set of purposes that are allowed for that key? That is too restrictive.
Alternatively, we can have:
The app developer, when creating an event, must specify the purposes for the event.
Then, for each key, the SDK will check: is this key allowed for all the purposes in the event? If yes, keep. If not, remove (or mask, but we can start with remove).
And then we have a configuration that maps:
Key -> Set
Then, for an event with purposes P, a key is allowed if P is a subset of the key's allowed purposes.
This is safe: if the key is allowed for all the purposes in the event, then we keep. Otherwise, we remove.
But then we cannot have:
For key "user_id", allowed for analytics and crash reporting, but for performance monitoring we want to mask.
Because if the event has performance monitoring and analytics, then the event's purposes are {analytics, performance_monitoring}. The key's allowed purposes are {analytics, crash_reporting}. Since {analytics, performance_monitoring} is not a subset of {analytics, crash_reporting}, we remove. But we wanted to mask for performance monitoring.
So we need to be able to say: for performance monitoring, we allow but mask? That is, we allow the key but transform the value.
So we need to have:
For a key, we can have:
AllowedPurposes: the set of purposes for which the key is allowed to be sent in raw form.
For purposes not in AllowedPurposes, we can have a transformation (like masking) or remove.
But then if the event has multiple purposes, and one of them is in AllowedPurposes and one is not, what do we do?
We can say: if any purpose in the event is not in AllowedPurposes, then we apply the transformation (or remove). But then the raw value would be sent to the purposes that allow it? But the event is the same for all purposes. So we cannot send raw for one and masked for another.
Therefore, we must choose: either we send the raw value (if allowed for all) or we transform (if not allowed for at least one).
So:
Let P_event = event's purposes.
Let P_allowed = key's allowed purposes.
If P_event is a subset of P_allowed, then keep raw.
Else, transform (or remove).
Then, for the example:
We want:
analytics: raw
crash reporting: raw
performance monitoring: masked
So for key "user_id", we set AllowedPurposes = {analytics, crash_reporting} and we set a transformation for when the event has performance monitoring? But note: the transformation is applied when the event's purposes are not a subset of {analytics, crash_reporting}. So if the event has performance monitoring, then we transform.
But what if the event has analytics and performance monitoring? Then we transform (mask) because the event's purposes are not a subset of {analytics, crash_reporting}. So we mask, which is what we want for performance monitoring.
What if the event has only performance monitoring? Then we mask.
What if the event has only analytics? Then we keep raw.
This works.
But what if we want to remove for some purposes and mask for others? We can only have one transformation for the key (when the event's purposes are not a subset of allowed). So we cannot have:
For key "user_id":
allowed for analytics and crash reporting (keep raw).
for performance monitoring: remove.
for user_experience: mask.
Then we would need two different transformations? We can't with one rule.
So we might need multiple rules for the same key? But then how do we combine?
Alternatively, we can have:
For each key, we define a set of purposes for which we keep raw, and then for any other purpose, we remove? Or we define a default transformation.
But then we cannot have different transformations for different non-allowed purposes.
Given the complexity, let's stick to:
AllowedPurposes: set of purposes for which the key is allowed in raw form.
DefaultRedactionAction: the action to take when the event's purposes are not a subset of AllowedPurposes.
Then, the app developer can set:
For key "user_id":
AllowedPurposes = {analytics, crash_reporting}
DefaultRedactionAction = Mask
Then, for an event with {analytics, performance_monitoring}, we mask.
If they want to remove for performance monitoring, they set DefaultRedactionAction = Remove, but then for an event with {analytics, performance_monitoring} we remove, which is not what we want (we wanted to mask for performance monitoring but keep for analytics).
Wait, in the example above, we wanted to mask for performance monitoring and keep for analytics. But with the rule above, if the event has analytics and performance monitoring, we mask (because the event's purposes are not a subset of {analytics, crash_reporting}). So we are masking the user_id, which is not raw. That means the analytics purpose gets a masked user_id, but we wanted raw for analytics.
So our rule does not satisfy: we want raw for analytics even if the event also has performance monitoring.
Therefore, we need to be able to say: for analytics, always raw, regardless of other purposes? But then we are sending raw user_id to the backend, and the backend might use it for performance monitoring? But the event is tagged for both purposes, so the backend must treat the user_id as allowed for both? But we don't want that.
Actually, the problem is: we are sending one event for multiple purposes, and the data in the event must be safe for all the purposes. So if one purpose does not allow raw user_id, then we cannot send raw user_id.
So the condition is: if the event has any purpose that does not allow the key, then we cannot send raw. So we must transform or remove.
Therefore, the condition is: if the event's purposes are a subset of the key's allowed purposes, then keep raw. Otherwise, transform.
This means that if we want raw for analytics, then we must not include any purpose that does not allow user_id in the same event. So we have to split the event: one event for analytics (with raw user_id) and another for performance monitoring (with masked user_id).
So the SDK should enforce that? Or we leave it to the app developer to split events?
We can leave it to the app developer: they should not put an event with purposes that have conflicting data requirements.
But then our redaction policy is:
For each key, we have:
AllowedPurposes: the set of purposes for which the key is allowed in raw form.
If the event's purposes are a subset of AllowedPurposes, then keep raw.
Otherwise, apply the DefaultRedactionAction.
And the DefaultRedactionAction can be Mask or Remove.
Now, what about the global blacklist? We can treat the global blacklist as keys with AllowedPurposes = empty set? Then any event with any purpose will not be a subset of empty (unless the event has no purpose? which is invalid). So they will be redacted by the default action.
But we want to always remove for global blacklist. So we can set:
For global blacklist keys, we set AllowedPurposes = empty and DefaultRedactionAction = Remove.
Then, for any event, since the event's purposes are not a subset of empty (unless the event has no purpose, which we don't allow), we remove.
But wait: if the event has no purpose, then the empty set is a subset of empty? Yes, so we would keep? That's not what we want.
So we must ensure that every event has at least one purpose.
Alternatively, we can handle global blacklist separately: before applying the rule-based redaction, we remove any key that is in the global blacklist.
Let's do:
Step 1: Remove all keys that are in the global blacklist.
Step 2: For each remaining key, check if the key is in the configuration (i.e., we have a rule for it). If not, then we remove (because we don't know if it's allowed). But wait, we might have keys that are allowed for all purposes? We don't have that.
Alternatively, we can have:
A set of keys that are allowed for all purposes? That would be a whitelist. But we want privacy by default, so we don't want to allow by default.
So we can say: if a key is not in the configuration, then we remove it. That is safe.
Then, for keys in the configuration, we have:
code
AllowedPurposes: set of purposes for which the key is allowed in raw form.
DefaultRedactionAction: what to do if the event's purposes are not a subset of AllowedPurposes.
Then:
code
if eventPurposes is a subset of AllowedPurposes -> keep raw.
else -> apply DefaultRedactionAction.
But note: what if the key is allowed for a purpose that is not in the event? That doesn't matter because we only care about the event's purposes.
Example:
Key "user_id" has AllowedPurposes = {analytics, crash_reporting}.
Now, what if we want to have a key that is allowed for analytics but we want to mask for crash reporting? We cannot with one rule because the rule is for the key and the allowed purposes are the ones for which we keep raw. If we want to mask for crash reporting, then we would not include crash_reporting in AllowedPurposes, and then for an event with crash reporting, we would apply the default action (mask). But then for an event with analytics and crash reporting, we would mask because the event's purposes are not a subset of {analytics} (since crash_reporting is not in AllowedPurposes). So we mask, which is what we want for crash reporting, but we are also masking for analytics? No, because the event has analytics and crash reporting, so we mask the whole key. But we wanted raw for analytics?
So we cannot have: for analytics keep raw, for crash reporting mask, and then have an event with both. We must split the event.
Therefore, the app developer must split events if they have conflicting requirements for the same key.
So our policy is:
For a given key, we define:
AllowedPurposes: the set of purposes for which the key can be sent in raw form.
DefaultRedactionAction: the action for any event that has at least one purpose not in AllowedPurposes.
Then, if an event has purposes that are entirely within AllowedPurposes, we keep raw. Otherwise, we apply the default action.
This is safe and simple.
Now, we need to design the SDK:
Components:
TelemetryEvent:
Name
Properties (Dictionary<string, object>)
Purposes (HashSet)
IRedactionPolicy:
Contains the global blacklist (HashSet)
Contains a dictionary of key -> KeyRedactionPolicy (where KeyRedactionPolicy has AllowedPurposes and DefaultRedactionAction)
The SDK will have a method to create an event, and then a method to process the event (apply redaction) before sending.
We also want to enforce that the event's purposes are within the allowed purposes for the SDK? Actually, we might have a set of purposes that the SDK is configured for. We can have:
AllowedPurposesForSDK: the purposes that the SDK is allowed to collect (based on user consent). Then, when creating an event, we check that the event's purposes are a subset of AllowedPurposesForSDK. If not, we throw or remove the event.
So:
Step 0: Check that the event's purposes are allowed by the SDK (i.e., subset of AllowedPurposesForSDK). If not, reject the event.
Step 1: Remove keys in global blacklist.
Step 2: For each remaining key, if the key is not in the redaction policy (i.e., we don't have a rule for it), then remove the key (because we don't know if it's allowed).
Step 3: For each key that has a rule, check if the event's purposes are a subset of the key's AllowedPurposes. If yes, keep. If not, apply the DefaultRedactionAction.
Step 4: If the DefaultRedactionAction is Mask, then we mask the value. How to mask? We can have a masking function that takes the value and returns a masked string. But note: the value can be of any type? We only support basic types and nested objects? We can convert to string and then mask? Or we can have a mask function that works on the type.
Since we are dealing with telemetry, the values are usually strings, numbers, booleans, or nested objects. We can convert everything to string and then mask? But then we lose the structure.
Alternatively, we can only mask string values? Or we can have a mask function that works on the value's type.
Let's assume we only allow string values for masking? Or we can have:
For a key, we can specify a masking function that takes an object and returns an object? But then the masking function must know the type.
We can simplify: we only support string values for masking? But then what about numbers? We can convert to string and mask? But then we lose the number type.
Alternatively, we can have:
For string: replace with a fixed string (like "***").
For number: replace with 0 or null? But then the type changes.
We can define:
public interface IValueMasker {
object Mask(object value);
}
And then we can have:
StringMasker: returns "***"
NumberMasker: returns 0
BooleanMasker: returns false? or null? But boolean is primitive, we can change to string?
But note: the telemetry event properties are Dictionary<string, object>. So we can replace the value with any object.
However, when we send the event, we might serialize to JSON. So we need to be careful.
Alternatively, we can say: when masking, we convert the value to string and then mask? But then the type is changed to string.
We can have:
For a key, we define a MaskFunction that takes the value and returns a masked value (of the same type? or object). But then we have to handle all types.
Given the complexity, let's start with:
For string: replace with "***"
For number: replace with 0
For boolean: replace with false
For nested objects: we can recursively mask? But then we need to know the structure.
Alternatively, we can only mask leaf values? And we remove the key if the value is an object? But then we lose the structure.
We can decide: we only mask string, number, boolean. For objects and arrays, we remove the key? Or we recursively apply the same redaction policy to the nested object? That would be complex.
Let's keep it simple: we only support flat dictionaries? Or we can support nested but then we have to apply the same policy to nested keys?
Actually, we can treat the nested object as a whole? But then the key is the full path?
Alternatively, we can have the redaction policy work on the full path? For example, "user.address.city". Then we can have rules for nested keys.
But then we have to flatten the dictionary? Or we can have a recursive redaction.
Given time, let's assume we only have flat properties. If we have nested, we can flatten the keys with dot notation? Or we can require that the event properties are flat.
We'll design for flat. If we want nested, we can have a rule that matches the prefix? But that's more complex.
So:
The TelemetryEvent.Properties is a flat dictionary (no nesting). Then we can have rules for each key.
Now, for masking:
We'll have:
public enum RedactionAction {
Remove,
Mask
}
And then for Mask, we have a function that takes an object and returns an object.
We can have:
public delegate object ValueMasker(object value);
Then in the KeyRedactionPolicy, we can have:
code
public RedactionAction DefaultRedactionAction { get; set; }
public ValueMasker MaskFunction { get; set; } // only used if DefaultRedactionAction == Mask
But then we have to set the MaskFunction for every rule that uses Mask.
Alternatively, we can have a global mask function? Or we can have a default mask function that does:
code
if (value is string) return "***";
if (value is number) return 0;
if (value is boolean) return false;
else return null; // or remove?
public class KeyRedactionPolicy {
public HashSet AllowedPurposes { get; set; }
public RedactionAction DefaultRedactionAction { get; set; }
// If DefaultRedactionAction is Mask, then we use the MaskFunction. If not, we ignore.
public ValueMasker MaskFunction { get; set; }
}
Then, the SDK:
public class TelemetrySDK {
private readonly IRedactionPolicy _redactionPolicy;
private readonly HashSet _allowedPurposesForSDK;
code
}
However, note: the DefaultMask function might not handle all types. We can improve.
But also, the MaskFunction in the policy might be set by the user to handle custom types.
Now, we have to consider: what about nested objects? We said we only support flat. But what if the value is a dictionary? We can recursively apply? But then the keys in the nested dictionary are not the same as the top-level key.
We can change the design: instead of having a flat dictionary, we can have a nested structure and then we flatten with dot notation for the purpose of redaction? Or we can have a recursive redaction that applies the same policy to nested dictionaries? But then the policy is keyed by the full path.
Given the complexity, let's stick to flat.
But note: the TelemetryEvent.Properties is Dictionary<string, object>. The value can be a dictionary? We can disallow that? Or we can convert nested dictionaries to a JSON string? Then we treat the value as a string and we can mask the whole string? But then we lose the structure.
Alternatively, we can have a rule that applies to a key and if the value is a dictionary, we recursively apply the same policy to the dictionary? But then the keys in the dictionary are not the same as the top-level key. We would need to have rules for "nested.key" as well.
So it's better to require that the properties are flat. If the user has nested data, they should flatten it (e.g., "user.name", "user.age") and then set rules for those keys.
So we assume flat.
Now, what about arrays? We can treat them as objects? We can disallow arrays? Or we can convert to string?
Let's disallow non-primitive values? But then we lose flexibility.
We can say: the value must be a primitive (string, number, boolean) or a stringified JSON? Then we can mask the string? But then if it's a JSON string, we cannot mask individual fields.
So we require flat and primitive.
We can adjust: the value can be any type, but for masking we only handle string, number, boolean. For other types, we remove? Or we convert to string and mask?
In the DefaultMask, we return null for unknown types. Then when we set properties[key] = null, we are sending the key with null. That might be acceptable? But then we are still sending the key.
Alternatively, we can remove the key if the value is of an unsupported type? But the action is Mask, not Remove.
We can change: if the value is of an unsupported type, we remove the key? But that's a different action.
Given the time, let's keep it simple: we only support string, number, boolean. For other types, we throw? Or we ignore (remove) the key?
We can do:
In ProcessEvent, when we are about to mask, we check the type. If it's not supported, we remove the key? But that's not what the policy said (it said mask). So we should support the type.
We can require that the user provides a MaskFunction for keys that have non-primitive values.
So we leave it to the user to handle non-primitive values.
Now, we have to consider: what if the value is null? We can treat null as a string? or we can remove the key?
We can say: if the value is null, we remove the key? Or we keep it as null?
Let's keep it as null.
Now, we have the design.
Let's write the contracts:
We have:
TelemetryPurpose (static class with constants) or enum? We used string constants.
We can define:
public static class TelemetryPurposes {
public const string Analytics = "analytics";
public const string CrashReporting = "crash_reporting";
public const string PerformanceMonitoring = "performance_monitoring";
public const string UserExperience = "user_experience";
}
Then:
public class TelemetryEvent {
public string Name { get; set; }
public Dictionary<string, object> Properties { get; set; } = new Dictionary<string, object>();
public HashSet Purposes { get; set; } = new HashSet();
}
public enum RedactionAction {
Remove,
Mask
}
public delegate object ValueMasker(object value);
public class KeyRedactionPolicy {
public HashSet AllowedPurposes { get; set; } = new HashSet();
public RedactionAction DefaultRedactionAction { get; set; } = RedactionAction.Remove;
public ValueMasker MaskFunction { get; set; }
}
But note: we might want to have the redaction policy be configurable and then the SDK is built with that policy.
Also, we might want to have a way to add events without processing? But we want privacy by default, so we should process every event.
We can have:
code
public void SendEvent(TelemetryEvent ev) {
var processed = ProcessEvent(ev);
// then send processed event to the backend.
}
Now, we have to consider: what if the event's properties are changed after creation? We should not allow that? Or we process at send time.
We process at send time, so if the event is modified after creation, we process the modified version.
But then the purposes are set at creation and cannot be changed? We can make the Purposes property read-only? Or we can allow changing but then we have to re-check the allowed purposes for the SDK?
We can make the TelemetryEvent immutable? Or we can process at creation and then store the processed version?
Let's make the TelemetryEvent immutable after creation? Not necessary.
We can have:
code
public TelemetryEvent CreateEvent(...) returns an event with the given properties and purposes.
Then, when we send, we process.
But note: the app might change the properties after creation. We cannot prevent that. So we process at send time.
Now, we have to consider: what if the app adds a property after creation and before sending? Then that property will be processed.
That's acceptable.
Now, we have to consider: what if the redaction policy changes after the event is created? Then we process with the current policy. That's acceptable.
Now, let's write the code for the SDK with the above design.
We'll also need to handle the case when the MaskFunction is not set and the value is of a type we don't handle in DefaultMask? We can throw? Or we can remove?
We can change the DefaultMask to:
code
private object DefaultMask(object value) {
if (value is string) return "***";
if (value is int || value is long || value is float || value is double || value is decimal) return 0;
if (value is bool) return false;
// For other types, we return null? But then we are setting the value to null, which is different from removing.
// We can remove the key? But the action is Mask, not Remove.
// So we throw an exception? That would break the sending.
// Alternatively, we can remove the key and log a warning.
// We can do:
// return null; // and then when serializing, null might be omitted? But we are setting the value to null.
// Or we can remove the key in the masking step? But then we are doing a remove, which is not the action.
// So we should require that the user provides a MaskFunction for non-primitive types.
// We'll throw an exception for unsupported types.
throw new NotSupportedException($"Masking is not supported for type {value.GetType()}");
}
But then if the user sets a MaskFunction, we use that.
Now, we have to consider: what if the value is a nested dictionary? We said we don't support. So we can throw? Or we can convert to JSON string and then mask the whole string?
We can do:
code
if (value is Dictionary<string, object> dict) {
// We can convert to JSON and then mask? But then we lose structure.
// Or we can recursively apply the policy? But then we need the full path.
// We can throw and say we don't support nested.
throw new NotSupportedException("Nested dictionaries are not supported for masking.");
}
But then the user might have a nested dictionary and we are going to remove the key? Because we don't have a rule for the nested keys?
Actually, if the value is a dictionary, we don't have a rule for the top-level key? We have a rule for the top-level key, but the value is a dictionary. We are going to mask the whole dictionary? That would turn it into a string?
We can decide: if the value is a dictionary, we convert to JSON string and then mask the string? But then we lose the structure and the backend might expect a dictionary.
So we should not allow dictionaries as values. We should require that the properties are flat and primitive.
We can validate in CreateEvent? Or in ProcessEvent?
We can validate in ProcessEvent: if the value is a dictionary, we remove the key? Or we throw?
We can remove the key and log a warning.
Given the complexity, let's assume the properties are flat and primitive. We'll document that.
Now, we have the design.
Let's write the code accordingly.
We'll also need to consider: what if the event has no purposes? We should throw in CreateEvent.
We'll adjust:
code
public TelemetryEvent CreateEvent(string name, Dictionary<string, object> properties, IEnumerable<string> purposes) {
var eventPurposes = new HashSet<string>(purposes);
if (eventPurposes.Count == 0) {
throw new InvalidOperationException("Event must have at least one purpose.");
}
// ... rest
}
Now, we have a basic design.
But note: the redaction policy might have a rule for a key that is not in the event? That's fine.
We only process keys that are in the event.
Now, we can extend:
We might want to have a way to add a property to the event and have it automatically redacted? We are doing that in ProcessEvent.
Now, we can write an example of configuration:
code
var redactionPolicy = new RedactionPolicyImpl();
redactionPolicy.GlobalBlacklist.Add("password");
redactionPolicy.GlobalBlacklist.Add("credit_card");
redactionPolicy.KeyPolicies["user_id"] = new KeyRedactionPolicy {
AllowedPurposes = new HashSet<string> { TelemetryPurposes.Analytics, TelemetryPurposes.CrashReporting },
DefaultRedactionAction = RedactionAction.Mask,
MaskFunction = value => {
// for user_id, we want to mask by hashing? or replace with fixed string?
// We can do:
if (value is string s) {
return s.Substring(0, 3) + "***"; // example
}
return "***";
}
};
var sdk = new TelemetrySDK(redactionPolicy, new [] { TelemetryPurposes.Analytics, TelemetryPurposes.CrashReporting, TelemetryPurposes.PerformanceMonitoring });
var ev = sdk.CreateEvent("app_started", new Dictionary<string, object> {
{ "user_id", "12345" },
{ "session_id", "abcde" },
{ "password", "secret" }
}, new [] { TelemetryPurposes.Analytics, TelemetryPurposes.PerformanceMonitoring });
var processed = sdk.ProcessEvent(ev);
// processed.Properties should have:
// "user_id": masked (because performance_monitoring is not in allowed purposes for user_id)
// "session_id": removed (because no policy for session_id, so removed)
// "password": removed (global blacklist)
This seems to work.
Now, we can think about performance: we are processing every event and every property. But telemetry events are usually small.
We can optimize by caching the processed event? But then if the policy changes, we have to re-process.
We can also precompute a set of keys to remove for a given set of purposes? But the set of purposes can vary per event.
Given the complexity, we leave it as is.
Now, we have to consider: what about nested properties? We said we don't support. But what if we have a property that is a dictionary? We remove the whole key?
We can change the redaction to:
code
Step 1: remove global blacklist keys.
Step 2: for each key, if the key is not in KeyPolicies, remove.
Step 3: for each key in KeyPolicies, if the event's purposes are not a subset, then apply action.
But if the value is a dictionary, we are treating it as a single value. We don't look inside.
Then the key is "user". We don't have a rule for "user", so we remove the whole key.
If we have a rule for "user", then we apply the action to the whole dictionary? But the action is Remove or Mask. If Mask, we call the MaskFunction with the dictionary? That would require the MaskFunction to handle dictionary.
So we can say: if the value is a dictionary, we don't support masking? We can only remove?
We can change the MaskFunction to handle dictionary? But then we have to recursively apply the policy? That's complex.
So we decide: the value must be a primitive (string, number, boolean) or a string (which we can mask). If it's a dictionary, we remove the key (if the action is Mask, we cannot mask a dictionary without knowing the structure). So we can change the DefaultMask to:
code
if (value is Dictionary<string, object> dict) {
// We cannot mask a dictionary without knowing the structure, so we remove the key? But the action is Mask, not Remove.
// We can throw? Or we can remove and log?
// We can remove and log a warning.
return null; // and then we remove the key? But we are in the masking step, we are setting the value.
// Actually, we are setting the value to null, which is different from removing.
// So we should remove the key in the masking step? But then we are doing a remove, which is not the action.
// So we throw.
throw new NotSupportedException("Masking a dictionary is not supported. Use a flat structure.");
}
But then the user might have a dictionary and we throw. That's not good.
Alternatively, we can automatically flatten the dictionary? But then the keys become "user.name", "user.age". But we don't have rules for those.
So we require that the properties are flat.
We can validate in CreateEvent? We can check that the values are primitive or string? But then we lose the ability to have numbers and booleans? They are primitive.
We can check:
code
foreach (var value in properties.Values) {
if (value != null && !(value is string) && !(value is int) && !(value is long) && !(value is float) && !(value is double) && !(value is decimal) && !(value is bool)) {
throw new InvalidOperationException("Only primitive types (string, number, boolean) are supported for property values.");
}
}
But then we cannot have a dictionary.
We can do that.
Let's change the CreateEvent to validate that all property values are of supported types.
Alternatively, we can do the validation in ProcessEvent and remove keys with unsupported types?
We can do:
code
In ProcessEvent, when we process a key, if the value is not a supported type, we remove the key and log.
But then the app might expect the key to be there.
We can throw in CreateEvent to fail fast.
Let's do:
code
public TelemetryEvent CreateEvent(string name, Dictionary<string, object> properties, IEnumerable<string> purposes) {
var eventPurposes = new HashSet<string>(purposes);
if (eventPurposes.Count == 0) {
throw new InvalidOperationException("Event must have at least one purpose.");
}
// Validate property values
foreach (var value in properties.Values) {
if (value != null) {
var type = value.GetType();
if (type != typeof(string) && type != typeof(int) && type != typeof(long) && type != typeof(float) && type != typeof(double) && type != typeof(decimal) && type != typeof(bool)) {
throw new InvalidOperationException($"Property value of type {type} is not supported. Only string, number, and boolean are supported.");
}
}
}
return new TelemetryEvent {
Name = name,
Properties = new Dictionary<string, object>(properties),
Purposes = eventPurposes
};
}
Then we don't have to worry about nested dictionaries.
Now, we have a complete design.
Let's write the code for the interfaces and classes.
We'll also need to consider: what if the same key appears multiple times? The dictionary doesn't allow duplicates, so that's fine.
Now, we can write the code.
Note: We are using .NET, so we have to use the appropriate types.
Let's code:
We'll create:
TelemetryPurposes static class
TelemetryEvent class
RedactionAction enum
ValueMasker delegate
KeyRedactionPolicy class
IRedactionPolicy interface
TelemetrySDK class
We'll also create a default implementation of IRedactionPolicy.
Let's do it.
I'll design a comprehensive privacy-by-default telemetry SDK with contracts, redaction, and purpose tagging. This design focuses on privacy-first principles where data minimization and transparency are enforced by default.
1. Core Contracts & Types
1.1 Purpose Taxonomy (Immutable Set)
csharp
public sealed class TelemetryPurposes
{
// Core purposes (must be explicitly declared)
public static readonly IReadOnlySet<string> AllowedPurposes = new HashSet<string>
{
"bug_fix_analysis", // Debugging, crash reporting
"service_health", // System performance, uptime monitoring
"security_monitoring", // Fraud detection, abuse prevention
"compliance_auditing", // Regulatory requirements (GDPR, CCPA, etc.)
"product_improvement", // Feature usage analytics (non-identifying)
"user_experience" // UI/UX optimization (aggregated/anonymized)
};
// Purposes requiring explicit user consent (additive to above)
public static readonly IReadOnlySet<string> ConsentRequiredPurposes = new HashSet<string>
{
"personalized_experience", // Personalization based on identity
"marketing_analytics", // Targeted advertising, conversion tracking
"cross_device_tracking" // Linking activity across devices
};
// Purposes that automatically trigger higher redaction
public static readonly IReadOnlySet<string> HighSensitivityPurposes = new HashSet<string>
{
"security_monitoring",
"compliance_auditing"
};
}
1.2 Event Contract
csharp
public sealed class TelemetryEvent
{
public string EventName { get; init; } // snake_case, namespaced
public DateTimeOffset Timestamp { get; init; } = DateTimeOffset.UtcNow;
public string? SessionId { get; init; } // Anonymous session identifier
public string? UserId { get; init; } // Pseudonymized user identifier
public IReadOnlySet<string> Purposes { get; init; } // Must be subset of AllowedPurposes
public IReadOnlyDictionary<string, object> Properties { get; init; }
public IReadOnlyDictionary<string, string>? Context { get; init; } // Device, OS, app version
// Builder pattern for safe construction
public static EventBuilder For(string eventName) => new(eventName);
public sealed class EventBuilder
{
private readonly string _eventName;
private readonly Dictionary<string, object> _properties = new();
private readonly HashSet<string> _purposes = new();
private string? _sessionId;
private string? _userId;
private Dictionary<string, string>? _context;
public EventBuilder(string eventName)
{
if (string.IsNullOrWhiteSpace(eventName))
throw new ArgumentException("Event name required", nameof(eventName));
_eventName = eventName.ToSnakeCase(); // Extension method
}
public EventBuilder WithPurpose(string purpose)
{
if (!TelemetryPurposes.AllowedPurposes.Contains(purpose))
throw new ArgumentException($"Purpose '{purpose}' not in allowed set", nameof(purpose));
_purposes.Add(purpose);
return this;
}
public EventBuilder WithPurposes(IEnumerable<string> purposes)
{
foreach (var p in purposes) WithPurpose(p);
return this;
}
public EventBuilder WithProperty(string key, object value)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("Property key required", nameof(key));
_properties[key] = value ?? throw new ArgumentNullException(nameof(value));
return this;
}
public EventBuilder WithSession(string sessionId)
{
_sessionId = sessionId;
return this;
}
public TelemetryEvent Build()
{
if (_purposes.Count == 0)
throw new InvalidOperationException("At least one purpose must be specified");
return new TelemetryEvent
{
EventName = _eventName,
Timestamp = DateTimeOffset.UtcNow,
SessionId = _sessionId,
UserId = _userId,
Purposes = _purposes.ToHashSet(),
Properties = _properties.ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
Context = _context
};
}
}
}
1.3 Redaction Rules Contract
csharp
2. Privacy Processor Engine
csharp
3. SDK Facade with Telemetry Pipeline
csharp
4. Transport Layer + Envelope for Transmission
csharp
public interface ITransport
{
Task SendAsync(TelemetryEvent @event, CancellationToken ct = default);
}
public sealed class HttpTelemetryTransport : ITransport, IAsyncDisposable
{
private readonly HttpClient _httpClient;
private readonly string _endpoint;
private readonly string _apiKey;
public HttpTelemetryTransport(string endpoint, string apiKey, HttpMessageHandler? handler = null)
{
_endpoint = endpoint;
_apiKey = apiKey;
_httpClient = handler != null ? new HttpClient(handler) : new HttpClient();
_httpClient.DefaultRequestHeaders.Add("X-Privacy-Version", "1.0");
}
public async Task SendAsync(TelemetryEvent @event, CancellationToken ct = default)
{
var envelope = CreateEnvelope(@event);
var json = JsonSerializer.Serialize(envelope, new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.Add("X-Event-Purposes", string.Join(',', @event.Purposes));
content.Headers.Add("X-Redaction-Applied", "true");
var response = await _httpClient.PostAsync(_endpoint, content, ct);
response.EnsureSuccessStatusCode();
}
private TelemetryEnvelope CreateEnvelope(TelemetryEvent @event)
{
return new TelemetryEnvelope
{
EventId = Guid.NewGuid().ToString(),
Timestamp = @event.Timestamp,
Source = "sdk",
Version = "1.0",
Event = @event,
Privacy = new PrivacyMetadata
{
Purposes = @event.Purposes.ToList(),
RedactionApplied = true,
RetentionDays = 90
}
};
}
public async ValueTask DisposeAsync()
{
_httpClient?.Dispose();
await Task.CompletedTask;
}
}
public sealed record TelemetryEnvelope
{
public string EventId { get; init; } = default!;
public DateTimeOffset Timestamp { get; init; }
public string Source { get; init; } = default!;
public string Version { get; init; } = default!;
public TelemetryEvent Event { get; init; } = default!;
public PrivacyMetadata Privacy { get; init; } = default!;
}
public sealed record PrivacyMetadata
{
public List<string> Purposes { get; init; } = new();
public bool RedactionApplied { get; init; }
public int RetentionDays { get; init; }
}
5. Usage Examples
csharp
// Setup
var redactionPolicy = new DefaultRedactionPolicy();
var processor = new PrivacyFirstTelemetryProcessor(logger);
processor.Configure(redactionPolicy, new PrivacyOptions
{
MaxRetentionDays = 30,
PrivacyVersion = "1.2"
});
var transport = new HttpTelemetryTransport(
"https://telemetry.example.com/ingest",
Environment.GetEnvironmentVariable("TELEMETRY_API_KEY")
);
var consentManager = new ConsentManager(logger);
var client = new PrivacyTelemetryClient(
processor, redactionPolicy,
new PrivacyOptions(), transport, consentManager);
// Track event with explicit purposes
await client.TrackAsync(TelemetryEvent
.For("app.start")
.WithPurpose("service_health")
.WithPurpose("product_improvement")
.WithProperty("app_version", "1.2.3")
.WithProperty("os_version", "iOS 16.4")
.WithProperty("session_duration", 42.5)
.Build());
// Track with consent check
client.SetConsent("product_improvement", true);
await client.TrackAsync(TelemetryEvent
.For("user.action")
.WithPurpose("product_improvement")
.WithProperty("button_clicked", "submit")
.WithProperty("screen", "checkout")
.Build());
// Custom builder pattern
await client.TrackAsync<CustomEvent>(b => b
.WithPurpose("bug_fix_analysis")
.WithProperty("error_code", "ERR_500")
.WithProperty("stack_trace", GetSanitizedStackTrace())
.WithProperty("user_id", GetPseudonymizedUserId()));
// Get privacy report
var report = client.GetPrivacyReport();
Console.WriteLine($"Data minimization rate: {report.DataMinimizationRate:P}");
6. Validation & Compliance Features
csharp
public static class PrivacyValidator
{
// Validate that event complies with privacy policy
public static ValidationResult ValidateEvent(TelemetryEvent @event, PrivacyPolicy policy)
{
var errors = new List<string>();
// 1. Purpose validation
if (!@event.Purposes.All(p => TelemetryPurposes.AllowedPurposes.Contains(p)))
errors.Add("Event contains invalid purposes");
// 2. PII detection
var piiKeys = @event.Properties.Keys.Where(k =>
RedactionRuleSet.Default.AlwaysRedactKeys.Contains(k) ||
RedactionRuleSet.Default.KeyPatterns.Any(r => r.IsMatch(k)));
if (piiKeys.Any())
errors.Add($"Event contains potentially sensitive keys: {string.Join(", ", piiKeys)}");
// 3. Consent check
var missingConsent = @event.Purposes.Where(p =>
TelemetryPurposes.ConsentRequiredPurposes.Contains(p) &&
!CurrentConsentManager.HasConsent(p));
if (missingConsent.Any())
errors.Add($"Missing consent for purposes: {string.Join(", ", missingConsent)}");
return new ValidationResult(errors);
}
// Generate privacy impact assessment for an event type
public static PrivacyImpactAssessment AssessEventType(string eventName,
IEnumerable<string> properties, IEnumerable<string> purposes)
{
var riskScore = 0;
var recommendations = new List<string>();
foreach (var purpose in purposes)
{
if (TelemetryPurposes.HighSensitivityPurposes.Contains(purpose))
riskScore += 3;
else if (TelemetryPurposes.ConsentRequiredPurposes.Contains(purpose))
riskScore += 2;
else
riskScore += 1;
}
var sensitiveProperties = properties.Count(p =>
RedactionRuleSet.Default.AlwaysRedactKeys.Contains(p.ToLowerInvariant()));
riskScore += sensitiveProperties * 2;
if (riskScore > 5)
recommendations.Add("Require explicit opt-in consent");
if (sensitiveProperties > 0)
recommendations.Add("Ensure all PII is redacted before transmission");
if (purposes.Count > 2)
recommendations.Add("Consider splitting event for different purposes");
return new PrivacyImpactAssessment
{
EventName = eventName,
RiskLevel = riskScore > 8 ? "HIGH" : riskScore > 4 ? "MEDIUM" : "LOW",
RiskScore = riskScore,
Recommendations = recommendations
};
}
}
7. Extension Points & Customization
csharp
// Custom redaction for specific regulations
public sealed class GdprRedactionPolicy : IRedactionPolicy
{
private readonly IRedactionPolicy _inner;
private readonly HashSet<string> _gdprSpecialCategories = new()
{
"race", "ethnicity", "political_opinion", "religious_belief",
"trade_union_membership", "genetic_data", "biometric_data",
"health_data", "sexual_orientation", "sex_life"
};
public GdprRedactionPolicy(IRedactionPolicy inner) => _inner = inner;
public bool ShouldRemoveKey(string key, IReadOnlySet<string> eventPurposes)
{
var normalized = key.ToLowerInvariant();
if (_gdprSpecialCategories.Contains(normalized))
return true;
return _inner.ShouldRemoveKey(key, eventPurposes);
}
public object? TransformValue(string key, object originalValue, IReadOnlySet<string> eventPurposes)
{
// GDPR requires explicit consent for special categories
if (_gdprSpecialCategories.Contains(key.ToLowerInvariant()) &&
!eventPurposes.Contains("explicit_gdpr_consent"))
{
return null;
}
return _inner.TransformValue(key, originalValue, eventPurposes);
}
public bool ShouldDropEvent(TelemetryEvent @event) => _inner.ShouldDropEvent(@event);
}
// Regional compliance wrapper
public sealed class RegionalComplianceWrapper : ITelemetryProcessor
{
private readonly ITelemetryProcessor _inner;
private readonly string _region;
public RegionalComplianceWrapper(ITelemetryProcessor inner, string region)
{
_inner = inner;
_region = region.ToUpperInvariant();
}
public Task<TelemetryEvent> ProcessAsync(TelemetryEvent @event, CancellationToken ct = default)
{
// Apply region-specific rules
if (_region == "EU" && !@event.Purposes.Contains("gdpr_legal_basis"))
{
throw new EventDroppedException("GDPR legal basis required for EU region");
}
return _inner.ProcessAsync(@event, ct);
}
}
8. Key Design Principles
Privacy-by-Default Enforcement:
No telemetry without explicit purposes - Every event must declare its purposes
Automatic redaction - Sensitive keys are removed/transformed by default
Consent gate - Purpose-based consent checking before processing
Data minimization - Only specified properties are transmitted after redaction
Purpose-Based Access Control:
Purposes are immutable and from approved list
Consent required purposes are separate from operational purposes
Event dropping when purpose combinations are invalid
This design ensures privacy is the default state, not an opt-in feature, while maintaining flexibility for legitimate telemetry needs. The SDK actively prevents privacy violations rather than just detecting them.
public TelemetrySDK(IRedactionPolicy redactionPolicy, IEnumerable<string> allowedPurposesForSDK) {
_redactionPolicy = redactionPolicy;
_allowedPurposesForSDK = new HashSet<string>(allowedPurposesForSDK);
}
public TelemetryEvent CreateEvent(string name, Dictionary<string, object> properties, IEnumerable<string> purposes) {
var eventPurposes = new HashSet<string>(purposes);
// Check that eventPurposes is a subset of _allowedPurposesForSDK
if (!eventPurposes.IsSubsetOf(_allowedPurposesForSDK)) {
throw new InvalidOperationException("Event purposes are not allowed by the SDK.");
}
return new TelemetryEvent {
Name = name,
Properties = new Dictionary<string, object>(properties),
Purposes = eventPurposes
};
}
public TelemetryEvent ProcessEvent(TelemetryEvent ev) {
// Step 1: Remove global blacklist keys
var properties = new Dictionary<string, object>(ev.Properties);
foreach (var key in _redactionPolicy.GlobalBlacklist) {
properties.Remove(key);
}
// Step 2: For each key, if not in KeyPolicies, remove.
var keysToRemove = new List<string>();
foreach (var key in properties.Keys) {
if (!_redactionPolicy.KeyPolicies.ContainsKey(key)) {
keysToRemove.Add(key);
}
}
foreach (var key in keysToRemove) {
properties.Remove(key);
}
// Step 3: For each key in KeyPolicies, check if event's purposes are subset of allowed purposes.
foreach (var key in properties.Keys.ToList()) { // ToList because we might remove
var policy = _redactionPolicy.KeyPolicies[key];
if (!ev.Purposes.IsSubsetOf(policy.AllowedPurposes)) {
// Not allowed for all purposes, so apply default action.
if (policy.DefaultRedactionAction == RedactionAction.Remove) {
properties.Remove(key);
} else if (policy.DefaultRedactionAction == RedactionAction.Mask) {
var originalValue = properties[key];
var maskedValue = policy.MaskFunction != null ? policy.MaskFunction(originalValue) : DefaultMask(originalValue);
properties[key] = maskedValue;
}
}
// else: keep as is
}
return new TelemetryEvent {
Name = ev.Name,
Properties = properties,
Purposes = ev.Purposes
};
}
private object DefaultMask(object value) {
switch (value) {
case string s:
return "***";
case int i:
case long l:
case float f:
case double d:
case decimal m:
return 0;
case bool b:
return false;
default:
return null; // or remove? but we are setting the value, so null might be acceptable? or we remove the key?
// Actually, if we return null, then when serializing, it might become null. But we want to remove?
// We are in the mask action, so we are setting the value to something. But if we return null, then the key remains with value null.
// That might be acceptable? But then we are sending the key with null value, which might be considered as sending the key.
// So maybe we should remove the key? But the action is Mask, not Remove.
// So we return a masked value of the same type? For unknown types, we return null? or we throw?
// Let's return null for unknown types.
}
}
public interface IRedactionPolicy
{
/// <summary>
/// Returns true if the key should be completely removed (not transmitted)
/// </summary>
bool ShouldRemoveKey(string key, IReadOnlySet<string> eventPurposes);
/// <summary>
/// Returns masked/transformed value or null to remove
/// </summary>
object? TransformValue(string key, object originalValue, IReadOnlySet<string> eventPurposes);
/// <summary>
/// Check if entire event should be dropped based on purpose combination
/// </summary>
bool ShouldDropEvent(TelemetryEvent @event);
}
public sealed class DefaultRedactionPolicy : IRedactionPolicy
{
private readonly RedactionRuleSet _ruleSet;
public DefaultRedactionPolicy(RedactionRuleSet? customRules = null)
{
_ruleSet = customRules ?? RedactionRuleSet.Default;
}
public bool ShouldRemoveKey(string key, IReadOnlySet<string> eventPurposes)
{
var normalizedKey = key.ToLowerInvariant();
// 1. Always remove high-risk keys
if (_ruleSet.AlwaysRedactKeys.Contains(normalizedKey))
return true;
// 2. Check purpose-specific rules
foreach (var purpose in eventPurposes)
{
if (_ruleSet.PurposeRedactMap.TryGetValue(purpose, out var keys) &&
keys.Contains(normalizedKey))
return true;
}
// 3. Check pattern-based rules
foreach (var pattern in _ruleSet.KeyPatterns)
{
if (pattern.IsMatch(normalizedKey))
return true;
}
return false;
}
public object? TransformValue(string key, object originalValue, IReadOnlySet<string> eventPurposes)
{
var normalizedKey = key.ToLowerInvariant();
// Check if we have a custom transformer for this key
if (_ruleSet.KeyTransformers.TryGetValue(normalizedKey, out var transformer))
{
return transformer(originalValue, eventPurposes);
}
// Default transformations based on type and sensitivity
if (originalValue is string str)
{
// Apply different redaction based on purpose sensitivity
if (eventPurposes.Overlaps(TelemetryPurposes.HighSensitivityPurposes))
return "***REDACTED***";
return str.Length > 8 ? $"{str.Substring(0, 3)}***" : "***";
}
if (originalValue is int || originalValue is long || originalValue is double)
{
// For numeric PII, return sentinel value
return eventPurposes.Overlaps(TelemetryPurposes.HighSensitivityPurposes)
? -1
: 0;
}
// Complex objects are removed by default
return null;
}
public bool ShouldDropEvent(TelemetryEvent @event)
{
// 1. Drop if no valid purposes
if (@event.Purposes.Count == 0 ||
!@event.Purposes.Any(p => TelemetryPurposes.AllowedPurposes.Contains(p)))
return true;
// 2. Drop if high-sensitivity purpose without proper redaction configuration
if (@event.Purposes.Overlaps(TelemetryPurposes.HighSensitivityPurposes) &&
!_ruleSet.ConfiguredForHighSensitivity)
{
return true;
}
return false;
}
}
public sealed class RedactionRuleSet
{
public static readonly RedactionRuleSet Default = new()
{
AlwaysRedactKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"password", "passwd", "pwd", "secret", "token", "api_key", "apikey",
"auth", "credential", "private_key", "ssn", "social_security",
"credit_card", "cvv", "cvc", "card_number", "iban", "account_number"
},
PurposeRedactMap = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase)
{
["security_monitoring"] = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"ip_address", "user_agent", "device_id", "mac_address"
}
},
KeyPatterns = new List<Regex>
{
new(@"^token_", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new(@"^auth_", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new(@"_secret$", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new(@"^bearer\s+", RegexOptions.IgnoreCase | RegexOptions.Compiled)
},
KeyTransformers = new Dictionary<string, Func<object, IReadOnlySet<string>, object?>>(StringComparer.OrdinalIgnoreCase)
{
["email"] = (value, purposes) =>
purposes.Overlaps(TelemetryPurposes.HighSensitivityPurposes)
? "***REDACTED***"
: RedactEmail(value?.ToString()),
["phone"] = (value, purposes) =>
purposes.Overlaps(TelemetryPurposes.HighSensitivityPurposes)
? "***REDACTED***"
: RedactPhone(value?.ToString())
},
ConfiguredForHighSensitivity = true
};
public HashSet<string> AlwaysRedactKeys { get; init; } = new();
public Dictionary<string, HashSet<string>> PurposeRedactMap { get; init; } = new();
public List<Regex> KeyPatterns { get; init; } = new();
public Dictionary<string, Func<object, IReadOnlySet<string>, object?>> KeyTransformers { get; init; } = new();
public bool ConfiguredForHighSensitivity { get; init; }
private static string RedactEmail(string? email)
{
if (string.IsNullOrEmpty(email) || !email.Contains('@')) return "***";
var parts = email.Split('@');
return $"{parts[0].Substring(0, Math.Min(2, parts[0].Length))}***@{parts[1]}";
}
private static string RedactPhone(string? phone)
{
if (string.IsNullOrEmpty(phone)) return "***";
var digits = new string(phone.Where(char.IsDigit).ToArray());
return digits.Length >= 4 ? $"***-***-{digits[^4..]}" : "***";
}
}
public interface ITelemetryProcessor
{
Task<TelemetryEvent> ProcessAsync(TelemetryEvent @event, CancellationToken ct = default);
void Configure(IRedactionPolicy redactionPolicy, PrivacyOptions options);
}
public sealed class PrivacyFirstTelemetryProcessor : ITelemetryProcessor
{
private IRedactionPolicy? _redactionPolicy;
private PrivacyOptions? _options;
private readonly ILogger<PrivacyFirstTelemetryProcessor> _logger;
public PrivacyFirstTelemetryProcessor(ILogger<PrivacyFirstTelemetryProcessor> logger)
{
_logger = logger;
}
public void Configure(IRedactionPolicy redactionPolicy, PrivacyOptions options)
{
_redactionPolicy = redactionPolicy ?? throw new ArgumentNullException(nameof(redactionPolicy));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public async Task<TelemetryEvent> ProcessAsync(TelemetryEvent @event, CancellationToken ct = default)
{
if (_redactionPolicy == null || _options == null)
throw new InvalidOperationException("Processor not configured");
// 1. Validate event structure
ValidateEvent(@event);
// 2. Check if event should be dropped entirely
if (_redactionPolicy.ShouldDropEvent(@event))
{
_logger.LogDebug("Event {EventName} dropped due to purpose constraints", @event.EventName);
throw new EventDroppedException("Event not allowed for specified purposes");
}
// 3. Apply redaction to properties
var processedProperties = new Dictionary<string, object>();
foreach (var kvp in @event.Properties)
{
var key = kvp.Key;
var value = kvp.Value;
// Check if key should be removed
if (_redactionPolicy.ShouldRemoveKey(key, @event.Purposes))
{
_logger.LogDebug("Property {Key} removed from event {EventName}", key, @event.EventName);
continue;
}
// Transform value if needed
var transformed = _redactionPolicy.TransformValue(key, value, @event.Purposes);
if (transformed != null)
{
processedProperties[key] = transformed;
}
else
{
_logger.LogDebug("Property {Key} transformed to null/removed", key);
}
}
// 4. Apply retention policy (simplified)
var finalEvent = new TelemetryEvent
{
EventName = @event.EventName,
Timestamp = @event.Timestamp,
SessionId = @event.SessionId,
UserId = @event.UserId,
Purposes = @event.Purposes,
Properties = processedProperties,
Context = @event.Context
};
// 5. Add required privacy metadata
finalEvent = finalEvent.WithContext(new Dictionary<string, string>
{
["privacy_version"] = _options.PrivacyVersion,
["redaction_applied"] = "true",
["data_minimized"] = processedProperties.Count < @event.Properties.Count ? "true" : "false"
});
return await Task.FromResult(finalEvent);
}
private void ValidateEvent(TelemetryEvent @event)
{
// Check expired retention (optional)
if (_options.MaxRetentionDays.HasValue &&
@event.Timestamp < DateTimeOffset.UtcNow.AddDays(-_options.MaxRetentionDays.Value))
{
throw new EventDroppedException("Event exceeds retention period");
}
// Validate purpose combination (business logic)
if (@event.Purposes.Contains("marketing_analytics") &&
@event.Purposes.Contains("security_monitoring"))
{
throw new InvalidOperationException(
"Marketing analytics and security monitoring purposes cannot be combined");
}
}
}
public sealed class PrivacyOptions
{
public string PrivacyVersion { get; init; } = "1.0";
public int? MaxRetentionDays { get; init; } = 90;
public bool EnableAggregation { get; init; } = true;
public bool RequireExplicitConsentForAll { get; init; } = false;
public IReadOnlySet<string>? AdditionalAllowedPurposes { get; init; }
}
public interface IPrivacyTelemetryClient
{
Task TrackAsync(TelemetryEvent @event, CancellationToken ct = default);
Task<T> TrackAsync<T>(Func<TelemetryEvent.Builder, TelemetryEvent.Builder> configure,
CancellationToken ct = default) where T : class;
void SetConsent(string purpose, bool granted);
bool HasConsent(string purpose);
PrivacyReport GetPrivacyReport();
}
public sealed class PrivacyTelemetryClient : IPrivacyTelemetryClient, IAsyncDisposable
{
private readonly ITelemetryProcessor _processor;
private readonly IRedactionPolicy _redactionPolicy;
private readonly PrivacyOptions _options;
private readonly ITransport _transport;
private readonly ConsentManager _consentManager;
private readonly PrivacyMetrics _metrics;
public PrivacyTelemetryClient(
ITelemetryProcessor processor,
IRedactionPolicy redactionPolicy,
PrivacyOptions options,
ITransport transport,
ConsentManager consentManager)
{
_processor = processor;
_redactionPolicy = redactionPolicy;
_options = options;
_transport = transport;
_consentManager = consentManager;
_metrics = new PrivacyMetrics();
}
public async Task TrackAsync(TelemetryEvent @event, CancellationToken ct = default)
{
// 1. Check consent first (privacy-by-default)
foreach (var purpose in @event.Purposes)
{
if (!_consentManager.HasConsent(purpose))
{
_metrics.EventsDroppedConsent++;
throw new EventDroppedException($"No consent for purpose: {purpose}");
}
}
// 2. Apply privacy processing
var processed = await _processor.ProcessAsync(@event, ct);
// 3. Send to transport
await _transport.SendAsync(processed, ct);
_metrics.EventsProcessed++;
}
public async Task<T> TrackAsync<T>(Func<TelemetryEvent.Builder, TelemetryEvent.Builder> configure,
CancellationToken ct = default) where T : class
{
var builder = TelemetryEvent.For($"custom.{typeof(T).Name.ToSnakeCase()}");
var configured = configure(builder);
var @event = configured.Build();
await TrackAsync(@event, ct);
return default!; // Or return processed result if needed
}
public void SetConsent(string purpose, bool granted)
{
_consentManager.SetConsent(purpose, granted);
}
public bool HasConsent(string purpose) => _consentManager.HasConsent(purpose);
public PrivacyReport GetPrivacyReport()
{
return new PrivacyReport
{
ProcessedEvents = _metrics.EventsProcessed,
DroppedEvents = _metrics.EventsDroppedConsent + _metrics.EventsDroppedPolicy,
DataMinimizationRate = _metrics.CalculateMinimizationRate(),
ActivePurposes = _consentManager.GetGrantedPurposes().ToList(),
RedactionRulesLoaded = _redactionPolicy is DefaultRedactionPolicy ?
((DefaultRedactionPolicy)_redactionPolicy)._ruleSet.AlwaysRedactKeys.Count : 0
};
}
public async ValueTask DisposeAsync()
{
if (_transport is IAsyncDisposable asyncDisposable)
await asyncDisposable.DisposeAsync();
}
}
public sealed class ConsentManager
{
private readonly ConcurrentDictionary<string, bool> _consents = new();
private readonly ILogger<ConsentManager> _logger;
public ConsentManager(ILogger<ConsentManager> logger)
{
_logger = logger;
}
public void SetConsent(string purpose, bool granted)
{
if (!TelemetryPurposes.AllowedPurposes.Contains(purpose))
throw new ArgumentException($"Invalid purpose: {purpose}", nameof(purpose));
_consents[purpose] = granted;
_logger.LogInformation("Consent for {Purpose} set to {Granted}", purpose, granted);
}
public bool HasConsent(string purpose) =>
_consents.TryGetValue(purpose, out var granted) && granted;
public IEnumerable<string> GetGrantedPurposes() =>
_consents.Where(kvp => kvp.Value).Select(kvp => kvp.Key);
}
public sealed class PrivacyMetrics
{
public long EventsProcessed { get; set; }
public long EventsDroppedConsent { get; set; }
public long EventsDroppedPolicy { get; set; }
public long PropertiesRedacted { get; set; }
public decimal CalculateMinimizationRate()
{
var total = EventsProcessed + EventsDroppedConsent + EventsDroppedPolicy;
return total > 0 ? (decimal)PropertiesRedacted / total : 0;
}
}
public sealed class PrivacyReport
{
public long ProcessedEvents { get; set; }
public long DroppedEvents { get; set; }
public decimal DataMinimizationRate { get; set; }
public List<string> ActivePurposes { get; set; } = new();
public int RedactionRulesLoaded { get; set; }
}