Skip to content

Commit

Permalink
Cookie Filters. Fixed Cookie invalid path. Fixed cookie values ending…
Browse files Browse the repository at this point in the history
… by comma.
  • Loading branch information
grandsilence committed Jul 3, 2018
1 parent a4d4e7c commit 35e7f2c
Show file tree
Hide file tree
Showing 3 changed files with 167 additions and 8 deletions.
92 changes: 91 additions & 1 deletion Leaf.xNet.Tests/~Http/HttpRequestTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Leaf.xNet.Tests
{
Expand Down Expand Up @@ -93,7 +94,96 @@ public void PostTestMultipart()
StringAssert.Contains(source, postValue);
}
}

[TestMethod]
public void FilterCookies()
{
var list = new Dictionary<string, string> {
{
"MS_LOGIN_COOKIE_10151=-1,R,L,null,; Expires=Sun, 30-Dec-18 16:57:13 GMT; Path=/RemovedPath",
"MS_LOGIN_COOKIE_10151=-1,R,L,null%2C; Expires=Sun, 30-Dec-18 16:57:13 GMT; Path=/"
},
{
"MS_LOGIN_COOKIE_10151=-1,R,L,null,; Expires=Sun, 30-Dec-18 16:57:13 GMT; Path=/",
"MS_LOGIN_COOKIE_10151=-1,R,L,null%2C; Expires=Sun, 30-Dec-18 16:57:13 GMT; Path=/"
}
};

foreach (var item in list)
{
Assert.AreEqual(CookieFilters.Filter(item.Key), item.Value);
}
}
/*
[TestMethod]
public void GetCookies()
{
using (var req = new HttpRequest())
{
string getToken = req.Get("https://www.ourtesco.com/login/").ToString();
string token = Regex.Match(getToken, @"name=""user_info_nonce"" value=""(.+?)""").Groups[1].ToString();
req.Referer = "https://www.ourtesco.com/login/";
req.AddHeader("Accept-Encoding", "gzip, deflate, br");
req.AddHeader("Accept-Language", "ru,en;q=0.9");
req.AddHeader("Upgrade-Insecure-Requests", "1");
req.AddHeader("Origin", "https://www.ourtesco.com");
var postData = new RequestParams
{
["redirect_to"] = "https://www.ourtesco.com/login/",
// TODO: edit
["log"] = "login",
["pwd"] = "pass",
["user_info_nonce"] = token,
["_wp_http_referer"] = "/login/",
["wplogin"] = "Sign in"
};
string postResponse = req.Post("https://www.ourtesco.com/login/", postData).ToString();
// del
var pd = new RequestParams
{
["storeId"] = "10151",
["langId"] = "-24",
["catalogId"] = "10051",
["fromOrderId"] = "*",
["toOrderId"] = ".",
["deleteIfEmpty"] = "*",
["createIfEmpty"] = "1",
["calculationUsageId"] = "-1",
["updatePrices"] = "0",
["previousPage"] = "logon",
["forgotPasswordURL"] = "MSResForgotPassword",
["rememberMe"] = "false",
["resJSON"] = "true",
["reLogonURL"] = "MSResLogin",
["resetConfirmationViewName"] = "MSPwdEmailConfirmModalView",
["myAcctMain"] = "",
["challengeAnswer"] = "-",
["errorViewName"] = "MSResLogin",
["continueSignIn"] = "1",
["migrateUserErrorMsg"] = "MS_MIGRAT_HEADERERR_MSG",
["returnPage"] = "MSUserLoyaltyOptInView",
["URL"] = "/webapp/wcs/stores/servlet/MSSecureOrdercalculate?catalogId=10051&langId=-24&mergeStatus=&storeId=10151&URL=https://www.marksandspencer.com/&page=ACCOUNT_LOGIN",
["orderMove"] = "/webapp/wcs/stores/servlet/OrderItemMove?calculationUsageIdentifier=MSLoginModalDisplay_orderMove&catalogId=10051&langId=-24&mergeStatus=&storeId=10151&toOrderId=.**.&URL=OrderCalculate?URL=https://www.marksandspencer.com/",
// todo: edit
["logonId"] = "",
["logonPassword"] = ""
};
//req.Proxy = Socks5ProxyClient.Parse("127.0.0.1:8889");
string rs = req.Post("https://www.marksandspencer.com/MSLogon", pd).ToString();
//StringAssert.Contains(source, getArgument);
//StringAssert.Contains(source, getValue);
}
}
[TestMethod]
public void PostTest2()
{
Expand Down
68 changes: 68 additions & 0 deletions Leaf.xNet/~Http/CookieFilters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;

namespace Leaf.xNet
{
public static class CookieFilters
{
public static bool Enabled = true;

public static bool Path = true;
public static bool CommaEndingValue = true;

/// <summary>
/// Фильтруем Cookie для дальнейшего использования в нативном хранилище.
/// </summary>
/// <param name="rawCookie">Запись Cookie как строка со всеми параметрами</param>
/// <returns>Отфильтрованная Cookie в виде строки со всеми отфильтрованными параметрами</returns>
public static string Filter(string rawCookie)
{
return !Enabled ? rawCookie
: rawCookie
.FilterPath()
.FilterCommaEndingValue();
}

/// <summary>Заменяем все значения path на "/"</summary>
private static string FilterPath(this string rawCookie)
{
if (!Path)
return rawCookie;

const string path = "path=/";
int pathIndex = rawCookie.IndexOf(path, 0, StringComparison.OrdinalIgnoreCase);
if (pathIndex == -1)
return rawCookie;

pathIndex += path.Length;
if (pathIndex >= rawCookie.Length - 1 || rawCookie[pathIndex] == ';')
return rawCookie;

int endPathIndex = rawCookie.IndexOf(';', pathIndex);
if (endPathIndex == -1)
endPathIndex = rawCookie.Length;

return rawCookie.Remove(pathIndex, endPathIndex - pathIndex);
}


/// <summary>Заменяем значения кук завершающиеся запятой (escape)</summary>
private static string FilterCommaEndingValue(this string rawCookie)
{
if (!CommaEndingValue)
return rawCookie;

int equalIndex = rawCookie.IndexOf('=');
if (equalIndex == -1 || equalIndex >= rawCookie.Length - 1)
return rawCookie;

int endValueIndex = rawCookie.IndexOf(';', equalIndex + 1);
if (endValueIndex == -1)
endValueIndex = rawCookie.Length - 1;

int lastCharIndex = endValueIndex - 1;
return rawCookie[lastCharIndex] != ','
? rawCookie
: rawCookie.Remove(lastCharIndex, 1).Insert(lastCharIndex, "%2C");
}
}
}
15 changes: 8 additions & 7 deletions Leaf.xNet/~Http/CookieStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,21 @@ public void Set(string name, string value, string domain, string path = "/")
}

/// <inheritdoc cref="Set(System.Net.CookieCollection)"/>
/// <param name="url">Url куки</param>
/// <param name="uri">Uri куки</param>
/// <param name="rawCookie">Сырой формат записи в виде строки</param>
// ReSharper disable once UnusedMember.Global
public void Set(string url, string rawCookie)
public void Set(Uri uri, string rawCookie)
{
Container.SetCookies(new Uri(url), rawCookie);
string filteredCookie = CookieFilters.Filter(rawCookie);
Container.SetCookies(uri, filteredCookie);
}

/// <inheritdoc cref="Set(System.Net.CookieCollection)"/>
/// <param name="uri">Uri куки</param>
/// <param name="url">Url куки</param>
/// <param name="rawCookie">Сырой формат записи в виде строки</param>
public void Set(Uri uri, string rawCookie)
// ReSharper disable once UnusedMember.Global
public void Set(string url, string rawCookie)
{
Container.SetCookies(uri, rawCookie);
Set(new Uri(url), rawCookie);
}

/// <summary>
Expand Down

0 comments on commit 35e7f2c

Please sign in to comment.