Skip to content

fix(datafile-parsing): Prevent newer versions datafile #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 6, 2018
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
1 change: 1 addition & 0 deletions OptimizelySDK.Tests/OptimizelySDK.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<EmbeddedResource Include="unsupported_version_datafile.json" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
Expand Down
27 changes: 26 additions & 1 deletion OptimizelySDK.Tests/OptimizelyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
using OptimizelySDK.Notifications;
using OptimizelySDK.Tests.NotificationTests;
using OptimizelySDK.Utils;
using Newtonsoft.Json;

namespace OptimizelySDK.Tests
{
Expand Down Expand Up @@ -185,7 +186,31 @@ public void TestValidateInputsInvalidFileJsonValidationSkipped()
{
string datafile = "{\"name\":\"optimizely\"}";
Optimizely optimizely = new Optimizely(datafile, null, null, null, skipJsonValidation: true);
Assert.IsTrue(optimizely.IsValid);
Assert.IsFalse(optimizely.IsValid);
}

[Test]
public void TestErrorHandlingWithNullDatafile()
{
var optimizelyNullDatafile = new Optimizely(null, null, LoggerMock.Object, ErrorHandlerMock.Object, null, true);
LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Unable to parse null datafile."), Times.Once);
ErrorHandlerMock.Verify(e => e.HandleError(It.Is<ConfigParseException>(ex => ex.Message == "Unable to parse null datafile.")), Times.Once);
}

[Test]
public void TestErrorHandlingWithEmptyDatafile()
{
var optimizelyEmptyDatafile = new Optimizely("", null, LoggerMock.Object, ErrorHandlerMock.Object, null, true);
LoggerMock.Verify(l => l.Log(LogLevel.ERROR, "Unable to parse empty datafile."), Times.Once);
ErrorHandlerMock.Verify(e => e.HandleError(It.Is<ConfigParseException>(ex => ex.Message == "Unable to parse empty datafile.")), Times.Once);
}

[Test]
public void TestErrorHandlingWithUnsupportedConfigVersion()
{
var optimizelyUnsupportedVersion = new Optimizely(TestData.UnsupportedVersionDatafile, null, LoggerMock.Object, ErrorHandlerMock.Object, null, true);
LoggerMock.Verify(l => l.Log(LogLevel.ERROR, $"This version of the C# SDK does not support the given datafile version: 5"), Times.Once);
ErrorHandlerMock.Verify(e => e.HandleError(It.Is<ConfigParseException>(ex => ex.Message == $"This version of the C# SDK does not support the given datafile version: 5")), Times.Once);
}

[Test]
Expand Down
27 changes: 27 additions & 0 deletions OptimizelySDK.Tests/ProjectConfigTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -863,5 +863,32 @@ public void TestGetAttributeIdWithInvalidAttributeKey()
Assert.Null(Config.GetAttributeId("invalid_attribute"));
LoggerMock.Verify(l => l.Log(LogLevel.ERROR, @"Attribute key ""invalid_attribute"" is not in datafile."));
}

[Test]
public void TestCreateThrowsWithNullDatafile()
{
var exception = Assert.Throws<ConfigParseException>(() => ProjectConfig.Create(null, null, null));
Assert.AreEqual("Unable to parse null datafile.", exception.Message);
}

[Test]
public void TestCreateThrowsWithEmptyDatafile()
{
var exception = Assert.Throws<ConfigParseException>(() => ProjectConfig.Create("", null, null));
Assert.AreEqual("Unable to parse empty datafile.", exception.Message);
}

[Test]
public void TestCreateThrowsWithUnsupportedDatafileVersion()
{
var exception = Assert.Throws<ConfigParseException>(() => ProjectConfig.Create(TestData.UnsupportedVersionDatafile, null, null));
Assert.AreEqual($"This version of the C# SDK does not support the given datafile version: 5", exception.Message);
}

[Test]
public void TestCreateDoesNotThrowWithValidDatafile()
{
Assert.DoesNotThrow(() => ProjectConfig.Create(TestData.Datafile, null, null));
}
}
}
13 changes: 11 additions & 2 deletions OptimizelySDK.Tests/TestData.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017, Optimizely
* Copyright 2017-2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -25,6 +25,7 @@ public class TestData
{
private static string cachedDataFile = null;
private static string simpleABExperimentsDatafile = null;
private static string unsupportedVersionDatafile = null;

public static string Datafile
{
Expand All @@ -41,7 +42,15 @@ public static string SimpleABExperimentsDatafile
return simpleABExperimentsDatafile ?? (simpleABExperimentsDatafile = LoadJsonData("simple_ab_experiments.json"));
}
}


public static string UnsupportedVersionDatafile
{
get
{
return unsupportedVersionDatafile ?? (unsupportedVersionDatafile = LoadJsonData("unsupported_version_datafile.json"));
}
}

private static string LoadJsonData(string fileName = "TestData.json")
{
var assembly = Assembly.GetExecutingAssembly();
Expand Down
42 changes: 42 additions & 0 deletions OptimizelySDK.Tests/unsupported_version_datafile.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"version": "5",
"rollouts": [],
"projectId": "10431130345",
"variables": [],
"featureFlags": [],
"experiments": [{
"status": "Running",
"key": "ab_running_exp_untargeted",
"layerId": "10417730432",
"trafficAllocation": [{
"entityId": "10418551353",
"endOfRange": 10000
}],
"audienceIds": [],
"variations": [{
"variables": [],
"id": "10418551353",
"key": "all_traffic_variation"
},
{
"variables": [],
"id": "10418510624",
"key": "no_traffic_variation"
}
],
"forcedVariations": {},
"id": "10420810910"
}],
"audiences": [],
"groups": [],
"attributes": [],
"accountId": "10367498574",
"events": [{
"experimentIds": [
"10420810910"
],
"id": "10404198134",
"key": "winning"
}],
"revision": "1337"
}
9 changes: 9 additions & 0 deletions OptimizelySDK/Exceptions/OptimizelyException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,13 @@ public InvalidRolloutException(string message)
{
}
}

public class ConfigParseException : OptimizelyException
{
public ConfigParseException(string message)
: base(message)
{

}
}
}
10 changes: 9 additions & 1 deletion OptimizelySDK/Optimizely.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using OptimizelySDK.ErrorHandler;
using OptimizelySDK.Event.Builder;
using OptimizelySDK.Event.Dispatcher;
using OptimizelySDK.Exceptions;
using OptimizelySDK.Logger;
using OptimizelySDK.Utils;
using OptimizelySDK.Notifications;
Expand Down Expand Up @@ -113,7 +114,14 @@ public Optimizely(string datafile,
}
catch (Exception ex)
{
Logger.Log(LogLevel.ERROR, "Provided 'datafile' is in an invalid format. " + ex.Message);
string error = String.Empty;
if (ex.GetType() == typeof(ConfigParseException))
error = ex.Message;
else
error = "Provided 'datafile' is in an invalid format. " + ex.Message;

Logger.Log(LogLevel.ERROR, error);
ErrorHandler.HandleError(ex);
}
}

Expand Down
33 changes: 32 additions & 1 deletion OptimizelySDK/ProjectConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Newtonsoft.Json;
using OptimizelySDK.Entity;
using OptimizelySDK.ErrorHandler;
using OptimizelySDK.Exceptions;
using OptimizelySDK.Logger;
using OptimizelySDK.Utils;
using System.Collections.Generic;
Expand All @@ -25,6 +26,13 @@ namespace OptimizelySDK
{
public class ProjectConfig
{
public enum OPTLYSDKVersion
{
V2 = 2,
V3 = 3,
V4 = 4
}

public const string RESERVED_ATTRIBUTE_PREFIX = "$opt_";

/// <summary>
Expand Down Expand Up @@ -60,6 +68,14 @@ public class ProjectConfig
/// </summary>
public bool? BotFiltering { get; set; }


private static List<OPTLYSDKVersion> SupportedVersions = new List<OPTLYSDKVersion> {
OPTLYSDKVersion.V2,
OPTLYSDKVersion.V3,
OPTLYSDKVersion.V4
};


//========================= Mappings ===========================

/// <summary>
Expand Down Expand Up @@ -270,7 +286,7 @@ private void Initialize()

public static ProjectConfig Create(string content, ILogger logger, IErrorHandler errorHandler)
{
ProjectConfig config = JsonConvert.DeserializeObject<ProjectConfig>(content);
ProjectConfig config = GetConfig(content);

config.Logger = logger;
config.ErrorHandler = errorHandler;
Expand All @@ -280,6 +296,21 @@ public static ProjectConfig Create(string content, ILogger logger, IErrorHandler
return config;
}

private static ProjectConfig GetConfig(string configData)
{
if (configData == null)
throw new ConfigParseException("Unable to parse null datafile.");

if (string.IsNullOrEmpty(configData))
throw new ConfigParseException("Unable to parse empty datafile.");

var config = JsonConvert.DeserializeObject<ProjectConfig>(configData);

if (SupportedVersions.TrueForAll((supportedVersion) => !(((int)supportedVersion).ToString() == config.Version)))
throw new ConfigParseException(string.Format(@"This version of the C# SDK does not support the given datafile version: {0}", config.Version));

return config;
}

//========================= Getters ===========================

Expand Down