Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 63 additions & 4 deletions src/DesktopAnalytics/Analytics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Linq;
using System.Xml.XPath;
Expand Down Expand Up @@ -55,7 +56,15 @@ public class Analytics : IDisposable
private static JsonObject s_locationInfo;
private static JsonObject s_traits;
private static UserInfo s_userInfo;
private static bool s_retainPii;
private static Analytics s_singleton;

/// <summary>
/// Exposed internally only so tests can confirm whether a call actually changed the
/// current UserInfo (e.g. that IdentifyUpdate(null) is a true no-op), without needing to
/// construct a real, side-effecting Analytics singleton just to observe this.
/// </summary>
internal static UserInfo CurrentUserInfo => s_userInfo;
private readonly Dictionary<string, string> _propertiesThatGoWithEveryEvent;
private static int s_exceptionCount = 0;

Expand Down Expand Up @@ -193,7 +202,8 @@ public Analytics(
}
_propertiesThatGoWithEveryEvent = propertiesThatGoWithEveryEvent;

s_userInfo = retainPii ? userInfo : userInfo.CreateSanitized();
s_retainPii = retainPii;
s_userInfo = ApplyPiiPolicy(userInfo, retainPii);

var initializationParameters = new InitializationParameters
{
Expand Down Expand Up @@ -538,13 +548,62 @@ internal static string ExtractSetting(string current, XDocument doc, string name
}

/// <summary>
/// Use this after showing a registration dialog, so that this stuff is sent right away,
/// rather than the next time you start up Analytics
/// Matches the exact shape CreateSanitized produces for a hashed name: the original
/// first character, then the string form of a signed 32-bit hash code (an optional '-'
/// and 1-10 digits).
/// </summary>
private static readonly Regex s_hashedNamePattern = new Regex(@"^.-?\d{1,10}$", RegexOptions.Compiled);

internal static bool LooksAlreadyHashed(string value) =>
!IsNullOrEmpty(value) && s_hashedNamePattern.IsMatch(value);

/// <summary>
/// Returns userInfo unchanged if retainPii is true; otherwise returns a sanitized copy
/// (see <see cref="UserInfo.CreateSanitized"/>). If previous is given and userInfo's
/// FirstName/LastName are unchanged from previous's and look like a previously-sanitized
/// value, we keep those fields as-is, without recomputing the hash. The computed hashes
/// are essentially meaningless, and there is no known harm in having them change, but
/// leaving them stable seems appropriate and is less likely to come as a surprise to the
/// caller or cause confusion for a person analyzing the data.
/// </summary>
/// <remarks>The returned UserInfo is a new object, not the same instance as userInfo or
/// previous.</remarks>
internal static UserInfo ApplyPiiPolicy(UserInfo userInfo, bool retainPii,
UserInfo previous = null)
{
if (retainPii)
return userInfo;

var sanitized = userInfo.CreateSanitized();
if (previous != null)
{
if (userInfo.FirstName == previous.FirstName && LooksAlreadyHashed(previous.FirstName))
sanitized.FirstName = previous.FirstName;
if (userInfo.LastName == previous.LastName && LooksAlreadyHashed(previous.LastName))
sanitized.LastName = previous.LastName;
}
return sanitized;
}

/// <summary>
/// Call this to update user information (e.g., after showing a registration dialog). This
/// information is sent immediately, rather than the next time you start up Analytics.
/// Honors the retainPii policy, so this cannot be used to inadvertently leak PII.
/// </summary>
/// <param name="userInfo">The user information to update. A null userInfo is a no-op.
/// </param>
/// <remarks>
/// If called after the Analytics object was constructed, this honors the same retainPii
/// setting used in the constructor. If called before the Analytics object was constructed,
/// retainPii defaults to false.
/// </remarks>
[PublicAPI]
public static void IdentifyUpdate(UserInfo userInfo)
{
s_userInfo = userInfo;
if (userInfo == null)
return;

s_userInfo = ApplyPiiPolicy(userInfo, s_retainPii, s_userInfo);
s_singleton.UpdateServerInformationOnThisUser();
}

Expand Down
8 changes: 5 additions & 3 deletions src/DesktopAnalytics/UserInfo.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using static System.String;

namespace DesktopAnalytics
{
Expand All @@ -20,10 +21,10 @@ public class UserInfo
internal UserInfo CreateSanitized()
{
var firstName = FirstName;
if (!String.IsNullOrWhiteSpace(firstName))
if (!IsNullOrWhiteSpace(firstName))
firstName = firstName[0].ToString() + firstName.GetHashCode();
var lastName = LastName;
if (!String.IsNullOrWhiteSpace(lastName))
if (!IsNullOrWhiteSpace(lastName))
lastName = lastName[0].ToString() + lastName.GetHashCode();
var emailDomain = Email;
if (emailDomain != null)
Expand All @@ -32,7 +33,8 @@ internal UserInfo CreateSanitized()
if (charactersToStrip > 0)
emailDomain = emailDomain.Substring(charactersToStrip);
}
return new UserInfo { FirstName = firstName, LastName = lastName, Email = emailDomain, OtherProperties = OtherProperties };
return new UserInfo { FirstName = firstName, LastName = lastName, Email = emailDomain,
UILanguageCode = UILanguageCode, OtherProperties = OtherProperties };
}
}
}
106 changes: 106 additions & 0 deletions src/DesktopAnalyticsTests/AnalyticsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,5 +87,111 @@ public void GetWindowsVersionInfoFromNetworkAPI_ReturnsRecognizedWindowsString()
}

#endregion

#region ApplyPiiPolicy tests

[Test]
public void ApplyPiiPolicy_RetainPiiTrue_ReturnsSameInstanceUnchanged()
{
var userInfo = new UserInfo { Email = "real@example.com", FirstName = "Real", LastName = "Name" };
var result = Analytics.ApplyPiiPolicy(userInfo, true);
Assert.AreSame(userInfo, result);
Assert.AreEqual("real@example.com", result.Email);
}

[Test]
public void ApplyPiiPolicy_RetainPiiFalse_ReturnsSanitizedCopy()
{
var userInfo = new UserInfo { Email = "real@example.com", FirstName = "Real", LastName = "Name" };
var result = Analytics.ApplyPiiPolicy(userInfo, false);
Assert.AreNotSame(userInfo, result);
Assert.AreEqual("@example.com", result.Email);
Assert.AreNotEqual("Real", result.FirstName);
Assert.AreNotEqual("Name", result.LastName);
}

[Test]
public void ApplyPiiPolicy_NameUnchangedAndPreviousAlreadyHashed_CarriesOverPreviousHashInstead()
{
var previous = new UserInfo { Email = "real@example.com", FirstName = "Real", LastName = "Name" }.CreateSanitized();
var incoming = new UserInfo { Email = "real@example.com", FirstName = previous.FirstName, LastName = previous.LastName };

var result = Analytics.ApplyPiiPolicy(incoming, false, previous);

Assert.AreEqual(previous.FirstName, result.FirstName);
Assert.AreEqual(previous.LastName, result.LastName);
}

[Test]
public void ApplyPiiPolicy_NameChangedFromPrevious_HashesTheNewNameInstead()
{
var previous = new UserInfo { FirstName = "Real", LastName = "Name" }.CreateSanitized();
var incoming = new UserInfo { FirstName = "Different", LastName = "Person" };

var result = Analytics.ApplyPiiPolicy(incoming, false, previous);

Assert.AreNotEqual(previous.FirstName, result.FirstName);
Assert.AreNotEqual(previous.LastName, result.LastName);
Assert.AreNotEqual("Different", result.FirstName);
Assert.AreNotEqual("Person", result.LastName);
Assert.IsTrue(Analytics.LooksAlreadyHashed(result.FirstName));
Assert.IsTrue(Analytics.LooksAlreadyHashed(result.LastName));
Assert.IsTrue(result.FirstName.StartsWith("D"));
Assert.IsTrue(result.LastName.StartsWith("P"));
}

[Test]
public void ApplyPiiPolicy_NameUnchangedButPreviousDoesNotLookHashed_HashesAnyway()
{
// previous.FirstName/LastName are real, unsanitized names here (as if retainPii had
// been true before) - even though "incoming" matches them exactly, they don't match
// the hash shape, so they must still be sanitized rather than carried over verbatim.
var previous = new UserInfo { FirstName = "Real", LastName = "Name" };
var incoming = new UserInfo { FirstName = "Real", LastName = "Name" };

var result = Analytics.ApplyPiiPolicy(incoming, false, previous);

Assert.AreNotEqual("Real", result.FirstName);
Assert.AreNotEqual("Name", result.LastName);
}

[Test]
public void ApplyPiiPolicy_NoPreviousGiven_HashesNormally()
{
var incoming = new UserInfo { FirstName = "Real", LastName = "Name" };
var result = Analytics.ApplyPiiPolicy(incoming, false);
Assert.AreNotEqual("Real", result.FirstName);
Assert.AreNotEqual("Name", result.LastName);
}

[TestCase("Z", false)]
[TestCase("Z1", true)]
[TestCase("Z-1", true)]
[TestCase("Z2147483647", true)]
[TestCase("Z-2147483648", true)]
[TestCase("Z12345678901", false)] // 11 digits: one too many for a signed 32-bit hash
[TestCase("ZZ1", false)] // two leading non-digit characters
[TestCase("", false)]
[TestCase(null, false)]
public void LooksAlreadyHashed_VariousInputs_MatchesExpectation(string value, bool expected)
{
Assert.AreEqual(expected, Analytics.LooksAlreadyHashed(value));
}

#endregion

#region IdentifyUpdate tests

[Test]
public void IdentifyUpdate_NullUserInfo_IsNoOpAndDoesNotThrow()
{
var before = Analytics.CurrentUserInfo; // presumably null, but we don't care.

Analytics.IdentifyUpdate(null);

Assert.AreSame(before, Analytics.CurrentUserInfo);
}

#endregion
}
}
8 changes: 8 additions & 0 deletions src/DesktopAnalyticsTests/UserInfoTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ public void CreateSanitized_NormalData_FirstNameAndLastNameHashed_EmailDomainPre
Assert.AreEqual("stuff", sanitized.OtherProperties["Important"]);
}

[Test]
public void CreateSanitized_UILanguageCodeSet_IsPreserved()
{
var orig = new UserInfo { FirstName = "Wanda", LastName = "Finkelstein", UILanguageCode = "fr" };
var sanitized = orig.CreateSanitized();
Assert.AreEqual("fr", sanitized.UILanguageCode);
}

[Test]
public void CreateSanitized_InvalidEmailAddressMissingDomain_EmailIsAtSign()
{
Expand Down
Loading