Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
20 changes: 20 additions & 0 deletions src/Http/Http.Features/src/IResponseCookies.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

#if NET6_0_OR_GREATER
using System;
using System.Collections.Generic;
#endif

namespace Microsoft.AspNetCore.Http
{
/// <summary>
Expand All @@ -23,6 +28,21 @@ public interface IResponseCookies
/// <param name="options"><see cref="CookieOptions"/> included in the new cookie setting.</param>
void Append(string key, string value, CookieOptions options);

#if NET6_0_OR_GREATER
/// <summary>
/// Add elements of specified dictionary as cookies.
Comment thread
Tratcher marked this conversation as resolved.
Outdated
/// </summary>
/// <param name="keyValuePairs">Key value pair collections whose elements will be added as cookies.</param>
/// <param name="options"><see cref="CookieOptions"/> included in new cookie settings.</param>
void Append(ReadOnlySpan<KeyValuePair<string, string>> keyValuePairs, CookieOptions options)
{
foreach (var keyValuePair in keyValuePairs)
{
Append(keyValuePair.Key, keyValuePair.Value, options);
}
}
#endif

/// <summary>
/// Sets an expired cookie.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>ASP.NET Core HTTP feature interface definitions.</Description>
Expand All @@ -10,10 +10,14 @@
<Nullable>enable</Nullable>
</PropertyGroup>


<ItemGroup>
<ItemGroup>
Comment thread
uabarahona marked this conversation as resolved.
Outdated
<Reference Include="Microsoft.Extensions.Primitives" />
<Reference Include="System.IO.Pipelines" />
</ItemGroup>

<ItemGroup>
<AdditionalFiles Include="PublicAPI/$(TargetFramework)/PublicAPI.Shipped.txt" />
<AdditionalFiles Include="PublicAPI/$(TargetFramework)/PublicAPI.Unshipped.txt" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ Microsoft.AspNetCore.Http.Features.IFeatureCollection.Get<TFeature>() -> TFeatur
Microsoft.AspNetCore.Http.Features.IFeatureCollection.Set<TFeature>(TFeature? instance) -> void
Microsoft.AspNetCore.Http.Features.IServerVariablesFeature.this[string! variableName].get -> string?
Microsoft.AspNetCore.Http.ISession.TryGetValue(string! key, out byte[]? value) -> bool
Microsoft.AspNetCore.Http.Features.FeatureCollection.FeatureCollection(int initialCapacity) -> void
Microsoft.AspNetCore.Http.Features.FeatureCollection.FeatureCollection(int initialCapacity) -> void
247 changes: 247 additions & 0 deletions src/Http/Http.Features/src/PublicAPI/net6.0/PublicAPI.Shipped.txt

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#nullable enable
*REMOVED*Microsoft.AspNetCore.Http.Features.FeatureCollection.Set<TFeature>(TFeature instance) -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IFeatureCollection.Get<TFeature>() -> TFeature
*REMOVED*Microsoft.AspNetCore.Http.Features.IFeatureCollection.Set<TFeature>(TFeature instance) -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpBufferingFeature
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpBufferingFeature.DisableRequestBuffering() -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpBufferingFeature.DisableResponseBuffering() -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature.SendFileAsync(string! path, long offset, long? count, System.Threading.CancellationToken cancellation) -> System.Threading.Tasks.Task!
*REMOVED*Microsoft.AspNetCore.Http.Features.IServerVariablesFeature.this[string! variableName].get -> string!
*REMOVED*Microsoft.AspNetCore.Http.ISession.TryGetValue(string! key, out byte[]! value) -> bool
Microsoft.AspNetCore.Http.Features.FeatureCollection.Set<TFeature>(TFeature? instance) -> void
Microsoft.AspNetCore.Http.Features.IFeatureCollection.Get<TFeature>() -> TFeature?
Microsoft.AspNetCore.Http.Features.IFeatureCollection.Set<TFeature>(TFeature? instance) -> void
Microsoft.AspNetCore.Http.Features.IServerVariablesFeature.this[string! variableName].get -> string?
Microsoft.AspNetCore.Http.ISession.TryGetValue(string! key, out byte[]? value) -> bool
Microsoft.AspNetCore.Http.Features.FeatureCollection.FeatureCollection(int initialCapacity) -> void
Microsoft.AspNetCore.Http.IResponseCookies.Append(System.ReadOnlySpan<System.Collections.Generic.KeyValuePair<string!, string!>> keyValuePairs, Microsoft.AspNetCore.Http.CookieOptions! options) -> void

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#nullable enable
*REMOVED*Microsoft.AspNetCore.Http.Features.FeatureCollection.Set<TFeature>(TFeature instance) -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IFeatureCollection.Get<TFeature>() -> TFeature
*REMOVED*Microsoft.AspNetCore.Http.Features.IFeatureCollection.Set<TFeature>(TFeature instance) -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpBufferingFeature
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpBufferingFeature.DisableRequestBuffering() -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpBufferingFeature.DisableResponseBuffering() -> void
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature
*REMOVED*Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature.SendFileAsync(string! path, long offset, long? count, System.Threading.CancellationToken cancellation) -> System.Threading.Tasks.Task!
*REMOVED*Microsoft.AspNetCore.Http.Features.IServerVariablesFeature.this[string! variableName].get -> string!
*REMOVED*Microsoft.AspNetCore.Http.ISession.TryGetValue(string! key, out byte[]! value) -> bool
Microsoft.AspNetCore.Http.Features.FeatureCollection.Set<TFeature>(TFeature? instance) -> void
Microsoft.AspNetCore.Http.Features.IFeatureCollection.Get<TFeature>() -> TFeature?
Microsoft.AspNetCore.Http.Features.IFeatureCollection.Set<TFeature>(TFeature? instance) -> void
Microsoft.AspNetCore.Http.Features.IServerVariablesFeature.this[string! variableName].get -> string?
Microsoft.AspNetCore.Http.ISession.TryGetValue(string! key, out byte[]? value) -> bool
Microsoft.AspNetCore.Http.Features.FeatureCollection.FeatureCollection(int initialCapacity) -> void
50 changes: 50 additions & 0 deletions src/Http/Http/src/Internal/ResponseCookies.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,56 @@ public void Append(string key, string value, CookieOptions options)
Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
}

/// <inheritdoc />
public void Append(ReadOnlySpan<KeyValuePair<string, string>> keyValuePairs, CookieOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}

// SameSite=None cookies must be marked as Secure.
if (!options.Secure && options.SameSite == SameSiteMode.None)
{
if (_logger == null)
{
var services = _features.Get<Features.IServiceProvidersFeature>()?.RequestServices;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to log from these components like this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review, I kind of feel there is something missing after "like this", could you please tell me if I am missing something here?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@davidfowl this was copied from the existing code above, we can discuss it separately from this PR.

if (!options.Secure && options.SameSite == SameSiteMode.None)
{
if (_logger == null)
{
var services = _features.Get<Features.IServiceProvidersFeature>()?.RequestServices;
_logger = services?.GetService<ILogger<ResponseCookies>>();
}
if (_logger != null)
{
Log.SameSiteCookieNotSecure(_logger, key);
}
}

@uabarahona uabarahona Apr 10, 2021

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct I did not fully look at this yet and just copied from the original append but I will definitely look if this can be improved too, thanks

_logger = services?.GetService<ILogger<ResponseCookies>>();
}

if (_logger != null)
{
foreach (var keyValuePair in keyValuePairs)
{
Log.SameSiteCookieNotSecure(_logger, keyValuePair.Key);
}
}
}

var setCookieHeaderValue = new SetCookieHeaderValue(string.Empty)
{
Domain = options.Domain,
Path = options.Path,
Expires = options.Expires,
MaxAge = options.MaxAge,
Secure = options.Secure,
SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite,
HttpOnly = options.HttpOnly
};

var cookierHeaderValue = setCookieHeaderValue.ToString()[1..];
var cookies = new string[keyValuePairs.Length];
var position = 0;

foreach (var keyValuePair in keyValuePairs)
{
cookies[position] = string.Concat(_enableCookieNameEncoding ? Uri.EscapeDataString(keyValuePair.Key) : keyValuePair.Key, "=", Uri.EscapeDataString(keyValuePair.Value), cookierHeaderValue);
Comment thread
uabarahona marked this conversation as resolved.
Outdated
position++;
}

Headers.Append(HeaderNames.SetCookie, cookies);
}

/// <inheritdoc />
public void Delete(string key)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
Expand Down Expand Up @@ -501,4 +501,4 @@ public override byte[] Serialize(IDictionary<string, object> values)
}
}
}
}
}
29 changes: 29 additions & 0 deletions src/Security/CookiePolicy/src/ResponseCookiesWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
Expand Down Expand Up @@ -152,6 +154,33 @@ public void Append(string key, string value, CookieOptions options)
}
}

public void Append(ReadOnlySpan<KeyValuePair<string, string>> keyValuePairs, CookieOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}

var nonSuppressedValues = new List<KeyValuePair<string, string>>();
Comment thread
uabarahona marked this conversation as resolved.
Outdated

foreach (var keyValuePair in keyValuePairs)
{
var key = keyValuePair.Key;
var value = keyValuePair.Value;

if (ApplyAppendPolicy(ref key, ref value, options))
{
nonSuppressedValues.Add(KeyValuePair.Create(key, value));
}
else
{
_logger.CookieSuppressed(keyValuePair.Key);
}
}

Cookies.Append(CollectionsMarshal.AsSpan(nonSuppressedValues), options);
}

private bool ApplyAppendPolicy(ref string key, ref string value, CookieOptions options)
{
var issueCookie = CanTrack || options.IsEssential;
Expand Down
46 changes: 45 additions & 1 deletion src/Security/CookiePolicy/test/CookieChunkingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using Xunit;

namespace Microsoft.AspNetCore.Internal
Expand Down Expand Up @@ -30,7 +31,7 @@ public void AppendLargeCookie_WithOptions_Appended()
{
Domain = "foo.com",
HttpOnly = true,
SameSite = SameSiteMode.Strict,
SameSite = Http.SameSiteMode.Strict,
Path = "/bar",
Secure = true,
Expires = now.AddMinutes(5),
Expand Down Expand Up @@ -145,5 +146,48 @@ public void DeleteChunkedCookieWithOptions_AllDeleted()
"TestCookieC7=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
}, cookies);
}



[Fact]
public void DeleteChunkedCookieWithOptionsAndResponseCookies_AllDeleted()
{
var chunkingCookieManager = new ChunkingCookieManager();
HttpContext httpContext = new DefaultHttpContext();

httpContext.Request.Headers["Cookie"] = new[]
{
"TestCookie=chunks-7; domain=foo.com; path=/; secure",
Comment thread
uabarahona marked this conversation as resolved.
Outdated
"TestCookieC1=abcdefghi; domain=foo.com; path=/; secure",
"TestCookieC2=jklmnopqr; domain=foo.com; path=/; secure",
"TestCookieC3=stuvwxyz0; domain=foo.com; path=/; secure",
"TestCookieC4=123456789; domain=foo.com; path=/; secure",
"TestCookieC5=ABCDEFGHI; domain=foo.com; path=/; secure",
"TestCookieC6=JKLMNOPQR; domain=foo.com; path=/; secure",
"TestCookieC7=STUVWXYZ; domain=foo.com; path=/; secure"
};

var cookieOptions = new CookieOptions()
{
Domain = "foo.com",
Path = "/",
Secure = true
};

httpContext.Response.Headers[HeaderNames.SetCookie] = new[]
{
"TestCookie=chunks-7; domain=foo.com; path=/; secure",
"TestCookieC1=abcdefghi; domain=foo.com; path=/; secure",
"TestCookieC2=jklmnopqr; domain=foo.com; path=/; secure",
"TestCookieC3=stuvwxyz0; domain=foo.com; path=/; secure",
"TestCookieC4=123456789; domain=foo.com; path=/; secure",
"TestCookieC5=ABCDEFGHI; domain=foo.com; path=/; secure",
"TestCookieC6=JKLMNOPQR; domain=foo.com; path=/; secure",
"TestCookieC7=STUVWXYZ; domain=foo.com; path=/; secure"
};

chunkingCookieManager.DeleteCookie(httpContext, "TestCookie", cookieOptions);
Assert.Equal(8, httpContext.Response.Headers[HeaderNames.SetCookie].Count);
Comment thread
uabarahona marked this conversation as resolved.
}
}
}
1 change: 1 addition & 0 deletions src/Security/CookiePolicy/test/CookiePolicyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;

namespace Microsoft.AspNetCore.Security
{
public class ChunkingCookieManagerBenchmark
{
private ChunkingCookieManager _chunkingCookieManager;
private HttpContext _httpContext;
private CookieOptions _cookieOptions;
private string _stringToAdd;

[GlobalSetup]
public void GlobalSetup()
{
_chunkingCookieManager = new ChunkingCookieManager()
{
ChunkSize = 86
};

_httpContext = new DefaultHttpContext();

_cookieOptions = new CookieOptions()
{
Domain = "foo.com",
Path = "/",
Secure = true
};

_httpContext.Request.Headers["Cookie"] = new[]
{
"TestCookie=chunks-7; domain=foo.com; path=/; secure",
Comment thread
uabarahona marked this conversation as resolved.
Outdated
"TestCookieC1=abcdefghi; domain=foo.com; path=/; secure",
"TestCookieC2=jklmnopqr; domain=foo.com; path=/; secure",
"TestCookieC3=stuvwxyz0; domain=foo.com; path=/; secure",
"TestCookieC4=123456789; domain=foo.com; path=/; secure",
"TestCookieC5=ABCDEFGHI; domain=foo.com; path=/; secure",
"TestCookieC6=JKLMNOPQR; domain=foo.com; path=/; secure",
"TestCookieC7=STUVWXYZ; domain=foo.com; path=/; secure"
};

_stringToAdd = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}


[Benchmark]
public void AppendCookies()
{
_chunkingCookieManager.AppendResponseCookie(_httpContext, "TestCookie1", _stringToAdd, _cookieOptions);
_httpContext.Response.Headers[HeaderNames.SetCookie] = StringValues.Empty;
}

[Benchmark]
public void DeleteCookies()
{
_chunkingCookieManager.DeleteCookie(_httpContext, "TestCookie", _cookieOptions);
_httpContext.Response.Headers[HeaderNames.SetCookie] = StringValues.Empty;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
Expand All @@ -14,6 +14,7 @@
<Reference Include="Microsoft.AspNetCore.Http" />
<Reference Include="Microsoft.Extensions.DependencyInjection" />
<Reference Include="Microsoft.Extensions.Logging" />
<Reference Include="Microsoft.AspNetCore.Authentication.Cookies" />
Comment thread
uabarahona marked this conversation as resolved.
Outdated

<Compile Include="$(SharedSourceRoot)BenchmarkRunner\*.cs" />
</ItemGroup>
Expand Down
Loading