public void AffinitizeRequest_AffinityDisabled_DoNothing()
    {
        var dataProtector = GetDataProtector();
        var provider      = new ProviderStub(dataProtector.Object, AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >().Object);

        Assert.Throws <InvalidOperationException>(() => provider.AffinitizeResponse(new DefaultHttpContext(), new ClusterState("cluster"), new SessionAffinityConfig(), new DestinationState("id")));
    }
    public void AffinitizeRequest_RequestIsAffinitized_DoNothing()
    {
        var dataProtector = GetDataProtector();
        var provider      = new ProviderStub(dataProtector.Object, AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >().Object);
        var context       = new DefaultHttpContext();

        provider.DirectlySetExtractedKeyOnContext(context, "ExtractedKey");
        provider.AffinitizeResponse(context, new ClusterState("cluster"), _defaultOptions, new DestinationState("id"));
        Assert.Null(provider.LastSetEncryptedKey);
        dataProtector.Verify(p => p.Protect(It.IsAny <byte[]>()), Times.Never);
    }
    public void AffinitizeRequest_RequestIsNotAffinitized_SetAffinityKey()
    {
        var dataProtector = GetDataProtector();
        var provider      = new ProviderStub(dataProtector.Object, AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >().Object);
        var destination   = new DestinationState("dest-A");

        provider.AffinitizeResponse(new DefaultHttpContext(), new ClusterState("cluster"), _defaultOptions, destination);
        Assert.Equal("ZGVzdC1B", provider.LastSetEncryptedKey);
        var keyBytes = Encoding.UTF8.GetBytes(destination.DestinationId);

        dataProtector.Verify(p => p.Protect(It.Is <byte[]>(b => b.SequenceEqual(keyBytes))), Times.Once);
    }
示例#4
0
    public void AffinitizeRequest_CookieConfigSpecified_UseIt()
    {
        var policy = new CookieSessionAffinityPolicy(
            AffinityTestHelper.GetDataProtector().Object,
            new ManualClock(),
            AffinityTestHelper.GetLogger <CookieSessionAffinityPolicy>().Object);
        var context = new DefaultHttpContext();

        policy.AffinitizeResponse(context, new ClusterState("cluster"), _config, _destinations[1]);

        var affinityCookieHeader = context.Response.Headers["Set-Cookie"];

        Assert.Equal("My.Affinity=ZGVzdC1C; max-age=3600; domain=mydomain.my; path=/some; secure; samesite=lax", affinityCookieHeader);
    }
    public void FindAffinitizedDestination_AffinityDisabledOnCluster_ReturnsAffinityDisabled()
    {
        var provider = new ProviderStub(GetDataProtector().Object, AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >().Object);
        var options  = new SessionAffinityConfig
        {
            Enabled         = false,
            Policy          = _defaultOptions.Policy,
            FailurePolicy   = _defaultOptions.FailurePolicy,
            AffinityKeyName = _defaultOptions.AffinityKeyName
        };
        var cluster = new ClusterState("cluster");

        Assert.Throws <InvalidOperationException>(() => provider.FindAffinitizedDestinations(new DefaultHttpContext(), cluster, options, new[] { new DestinationState("1") }));
    }
示例#6
0
    public void FindAffinitizedDestination_AffinityKeyIsSetOnRequest_Success()
    {
        var policy = new CookieSessionAffinityPolicy(
            AffinityTestHelper.GetDataProtector().Object,
            new ManualClock(),
            AffinityTestHelper.GetLogger <CookieSessionAffinityPolicy>().Object);
        var context = new DefaultHttpContext();
        var affinitizedDestination = _destinations[1];

        context.Request.Headers["Cookie"] = GetCookieWithAffinity(affinitizedDestination);
        var cluster = new ClusterState("cluster");

        var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _config, _destinations);

        Assert.Equal(AffinityStatus.OK, affinityResult.Status);
        Assert.Equal(1, affinityResult.Destinations.Count);
        Assert.Same(affinitizedDestination, affinityResult.Destinations[0]);
    }
示例#7
0
    public void FindAffinitizedDestination_AffinityKeyIsNotSetOnRequest_ReturnKeyNotSet()
    {
        var policy = new CookieSessionAffinityPolicy(
            AffinityTestHelper.GetDataProtector().Object,
            new ManualClock(),
            AffinityTestHelper.GetLogger <CookieSessionAffinityPolicy>().Object);

        Assert.Equal(SessionAffinityConstants.Policies.Cookie, policy.Name);

        var context = new DefaultHttpContext();

        context.Request.Headers["Cookie"] = new[] { $"Some-Cookie=ZZZ" };
        var cluster = new ClusterState("cluster");

        var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _config, _destinations);

        Assert.Equal(AffinityStatus.AffinityKeyNotSet, affinityResult.Status);
        Assert.Null(affinityResult.Destinations);
    }
示例#8
0
    public void AffinitizedRequest_AffinityKeyIsExtracted_DoNothing()
    {
        var policy = new CookieSessionAffinityPolicy(
            AffinityTestHelper.GetDataProtector().Object,
            new ManualClock(),
            AffinityTestHelper.GetLogger <CookieSessionAffinityPolicy>().Object);
        var context = new DefaultHttpContext();
        var affinitizedDestination = _destinations[0];

        context.Request.Headers["Cookie"] = GetCookieWithAffinity(affinitizedDestination);
        var cluster = new ClusterState("cluster");

        var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _config, _destinations);

        Assert.Equal(AffinityStatus.OK, affinityResult.Status);

        policy.AffinitizeResponse(context, cluster, _config, affinitizedDestination);

        Assert.False(context.Response.Headers.ContainsKey("Cookie"));
    }
        public async Task Invoke_ErrorFlow_CallFailurePolicy(AffinityStatus affinityStatus, bool keepProcessing)
        {
            var          cluster         = GetCluster();
            var          providers       = RegisterAffinityProviders(true, Destinations, cluster.ClusterId, ("Mode-B", affinityStatus, null, _ => { }));
            var          invokedPolicy   = string.Empty;
            const string expectedPolicy  = "Policy-1";
            var          failurePolicies = RegisterFailurePolicies(
                affinityStatus,
                ("Policy-0", false, p => throw new InvalidOperationException($"Policy {p.Name} call is not expected.")),
                (expectedPolicy, keepProcessing, p => invokedPolicy = p.Name));
            var nextInvoked = false;
            var logger      = AffinityTestHelper.GetLogger <AffinitizedDestinationLookupMiddleware>();
            var middleware  = new AffinitizedDestinationLookupMiddleware(c => {
                nextInvoked = true;
                return(Task.CompletedTask);
            },
                                                                         providers.Select(p => p.Object), failurePolicies.Select(p => p.Object),
                                                                         GetOperationLogger(true),
                                                                         logger.Object);
            var context = new DefaultHttpContext();

            context.Features.Set(cluster);
            var destinationFeature = GetDestinationsFeature(Destinations);

            context.Features.Set(destinationFeature);

            await middleware.Invoke(context);

            Assert.Equal(expectedPolicy, invokedPolicy);
            Assert.Equal(keepProcessing, nextInvoked);
            failurePolicies[0].VerifyGet(p => p.Name, Times.Once);
            failurePolicies[0].VerifyNoOtherCalls();
            failurePolicies[1].VerifyAll();
            if (!keepProcessing)
            {
                logger.Verify(
                    l => l.Log(LogLevel.Warning, EventIds.AffinityResolutionFailedForCluster, It.IsAny <It.IsAnyType>(), null, (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                    Times.Once);
            }
        }
    public void Request_FindAffinitizedDestinations(
        HttpContext context,
        DestinationState[] allDestinations,
        AffinityStatus expectedStatus,
        DestinationState expectedDestination,
        byte[] expectedEncryptedKey,
        bool unprotectCalled,
        LogLevel?expectedLogLevel,
        EventId expectedEventId)
    {
        var dataProtector  = GetDataProtector();
        var logger         = AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >();
        var provider       = new ProviderStub(dataProtector.Object, logger.Object);
        var cluster        = new ClusterState("cluster");
        var affinityResult = provider.FindAffinitizedDestinations(context, cluster, _defaultOptions, allDestinations);

        if (unprotectCalled)
        {
            dataProtector.Verify(p => p.Unprotect(It.Is <byte[]>(b => b.SequenceEqual(expectedEncryptedKey))), Times.Once);
        }

        Assert.Equal(expectedStatus, affinityResult.Status);
        Assert.Same(expectedDestination, affinityResult.Destinations?.FirstOrDefault());

        if (expectedLogLevel != null)
        {
            logger.Verify(
                l => l.Log(expectedLogLevel.Value, expectedEventId, It.IsAny <It.IsAnyType>(), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                Times.Once);
        }

        if (expectedDestination != null)
        {
            Assert.Equal(1, affinityResult.Destinations.Count);
        }
        else
        {
            Assert.Null(affinityResult.Destinations);
        }
    }
    public void AffinitizedRequest_AffinityKeyIsExtracted_DoNothing()
    {
        var policy  = new CustomHeaderSessionAffinityPolicy(AffinityTestHelper.GetDataProtector().Object, AffinityTestHelper.GetLogger <CustomHeaderSessionAffinityPolicy>().Object);
        var context = new DefaultHttpContext();

        context.Request.Headers["SomeHeader"] = new[] { "SomeValue" };
        var affinitizedDestination = _destinations[1];

        context.Request.Headers[AffinityHeaderName] = new[] { affinitizedDestination.DestinationId.ToUTF8BytesInBase64() };
        var cluster = new ClusterState("cluster");

        var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _defaultOptions, _destinations);

        Assert.Equal(AffinityStatus.OK, affinityResult.Status);

        policy.AffinitizeResponse(context, cluster, _defaultOptions, affinitizedDestination);

        Assert.False(context.Response.Headers.ContainsKey(AffinityHeaderName));
    }
    public void AffinitizedRequest_AffinityKeyIsNotExtracted_SetKeyOnResponse()
    {
        var policy                      = new CustomHeaderSessionAffinityPolicy(AffinityTestHelper.GetDataProtector().Object, AffinityTestHelper.GetLogger <CustomHeaderSessionAffinityPolicy>().Object);
        var context                     = new DefaultHttpContext();
        var chosenDestination           = _destinations[1];
        var expectedAffinityHeaderValue = chosenDestination.DestinationId.ToUTF8BytesInBase64();

        policy.AffinitizeResponse(context, new ClusterState("cluster"), _defaultOptions, chosenDestination);

        Assert.True(context.Response.Headers.ContainsKey(AffinityHeaderName));
        Assert.Equal(expectedAffinityHeaderValue, context.Response.Headers[AffinityHeaderName]);
    }
    public void FindAffinitizedDestination_AffinityKeyIsSetOnRequest_Success()
    {
        var policy  = new CustomHeaderSessionAffinityPolicy(AffinityTestHelper.GetDataProtector().Object, AffinityTestHelper.GetLogger <CustomHeaderSessionAffinityPolicy>().Object);
        var context = new DefaultHttpContext();

        context.Request.Headers["SomeHeader"] = new[] { "SomeValue" };
        var affinitizedDestination = _destinations[1];

        context.Request.Headers[AffinityHeaderName] = new[] { affinitizedDestination.DestinationId.ToUTF8BytesInBase64() };
        var cluster = new ClusterState("cluster");

        var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _defaultOptions, _destinations);

        Assert.Equal(AffinityStatus.OK, affinityResult.Status);
        Assert.Equal(1, affinityResult.Destinations.Count);
        Assert.Same(affinitizedDestination, affinityResult.Destinations[0]);
    }
    public void FindAffinitizedDestination_AffinityKeyIsNotSetOnRequest_ReturnKeyNotSet()
    {
        var policy = new CustomHeaderSessionAffinityPolicy(AffinityTestHelper.GetDataProtector().Object, AffinityTestHelper.GetLogger <CustomHeaderSessionAffinityPolicy>().Object);

        Assert.Equal(SessionAffinityConstants.Policies.CustomHeader, policy.Name);

        var context = new DefaultHttpContext();

        context.Request.Headers["SomeHeader"] = new[] { "SomeValue" };
        var cluster = new ClusterState("cluster");

        var affinityResult = policy.FindAffinitizedDestinations(context, cluster, _defaultOptions, _destinations);

        Assert.Equal(AffinityStatus.AffinityKeyNotSet, affinityResult.Status);
        Assert.Null(affinityResult.Destinations);
    }