Esempio n. 1
0
        // name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax}; httponly
        private static int GetSetCookieLength(StringSegment input, int startIndex, out SetCookieHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);
            var offset = startIndex;

            parsedValue = null;

            if (StringSegment.IsNullOrEmpty(input) || (offset >= input.Length))
            {
                return(0);
            }

            var result = new SetCookieHeaderValue();

            // The caller should have already consumed any leading whitespace, commas, etc..

            // Name=value;

            // Name
            var itemLength = ProtoRuleParser.GetTokenLength(input, offset);

            if (itemLength == 0)
            {
                return(0);
            }
            result._name = input.Subsegment(offset, itemLength);
            offset      += itemLength;

            // = (no spaces)
            if (!ReadEqualsSign(input, ref offset))
            {
                return(0);
            }

            // value or "quoted value"
            // The value may be empty
            result._value = CookieHeaderValue.GetCookieValue(input, ref offset);

            // *(';' SP cookie-av)
            while (offset < input.Length)
            {
                if (input[offset] == ',')
                {
                    // Divider between headers
                    break;
                }
                if (input[offset] != ';')
                {
                    // Expecting a ';' between parameters
                    return(0);
                }
                offset++;

                offset += ProtoRuleParser.GetWhitespaceLength(input, offset);

                //  cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / samesite-av / httponly-av / extension-av
                itemLength = ProtoRuleParser.GetTokenLength(input, offset);
                if (itemLength == 0)
                {
                    // Trailing ';' or leading into garbage. Let the next parser fail.
                    break;
                }
                var token = input.Subsegment(offset, itemLength);
                offset += itemLength;

                //  expires-av = "Expires=" sane-cookie-date
                if (StringSegment.Equals(token, ExpiresToken, StringComparison.OrdinalIgnoreCase))
                {
                    // = (no spaces)
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        return(0);
                    }
                    var            dateString = ReadToSemicolonOrEnd(input, ref offset);
                    DateTimeOffset expirationDate;
                    if (!ProtoRuleParser.TryStringToDate(dateString, out expirationDate))
                    {
                        // Invalid expiration date, abort
                        return(0);
                    }
                    result.Expires = expirationDate;
                }
                // max-age-av = "Max-Age=" non-zero-digit *DIGIT
                else if (StringSegment.Equals(token, MaxAgeToken, StringComparison.OrdinalIgnoreCase))
                {
                    // = (no spaces)
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        return(0);
                    }

                    itemLength = ProtoRuleParser.GetNumberLength(input, offset, allowDecimal: false);
                    if (itemLength == 0)
                    {
                        return(0);
                    }
                    var  numberString = input.Subsegment(offset, itemLength);
                    long maxAge;
                    if (!HeaderUtilities.TryParseNonNegativeInt64(numberString, out maxAge))
                    {
                        // Invalid expiration date, abort
                        return(0);
                    }
                    result.MaxAge = TimeSpan.FromSeconds(maxAge);
                    offset       += itemLength;
                }
                // domain-av = "Domain=" domain-value
                // domain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as enhanced by [RFC1123], Section 2.1
                else if (StringSegment.Equals(token, DomainToken, StringComparison.OrdinalIgnoreCase))
                {
                    // = (no spaces)
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        return(0);
                    }
                    // We don't do any detailed validation on the domain.
                    result.Domain = ReadToSemicolonOrEnd(input, ref offset);
                }
                // path-av = "Path=" path-value
                // path-value = <any CHAR except CTLs or ";">
                else if (StringSegment.Equals(token, PathToken, StringComparison.OrdinalIgnoreCase))
                {
                    // = (no spaces)
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        return(0);
                    }
                    // We don't do any detailed validation on the path.
                    result.Path = ReadToSemicolonOrEnd(input, ref offset);
                }
                // secure-av = "Secure"
                else if (StringSegment.Equals(token, SecureToken, StringComparison.OrdinalIgnoreCase))
                {
                    result.Secure = true;
                }
                // samesite-av = "SameSite" / "SameSite=" samesite-value
                // samesite-value = "Strict" / "Lax"
                else if (StringSegment.Equals(token, SameSiteToken, StringComparison.OrdinalIgnoreCase))
                {
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        result.SameSite = SameSiteMode.Strict;
                    }
                    else
                    {
                        var enforcementMode = ReadToSemicolonOrEnd(input, ref offset);

                        if (StringSegment.Equals(enforcementMode, SameSiteLaxToken, StringComparison.OrdinalIgnoreCase))
                        {
                            result.SameSite = SameSiteMode.Lax;
                        }
                        else
                        {
                            result.SameSite = SameSiteMode.Strict;
                        }
                    }
                }
                // httponly-av = "ProtoOnly"
                else if (StringSegment.Equals(token, ProtoOnlyToken, StringComparison.OrdinalIgnoreCase))
                {
                    result.ProtoOnly = true;
                }
                // extension-av = <any CHAR except CTLs or ";">
                else
                {
                    // TODO: skiping it for now to avoid parsing failure? Store it in a list?
                    // = (no spaces)
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        return(0);
                    }
                    ReadToSemicolonOrEnd(input, ref offset);
                }
            }

            parsedValue = result;
            return(offset - startIndex);
        }
Esempio n. 2
0
        public void TryParseSeconds_Fails(string headerValues, string targetValue)
        {
            TimeSpan?value;

            Assert.False(HeaderUtilities.TryParseSeconds(new StringValues(headerValues), targetValue, out value));
        }
Esempio n. 3
0
        // name="value"; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax}; httponly
        public override string ToString()
        {
            var length = _name.Length + EqualsToken.Length + _value.Length;

            string maxAge = null;

            if (Expires.HasValue)
            {
                length += SeparatorToken.Length + ExpiresToken.Length + EqualsToken.Length + ExpiresDateLength;
            }

            if (MaxAge.HasValue)
            {
                maxAge  = HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds);
                length += SeparatorToken.Length + MaxAgeToken.Length + EqualsToken.Length + maxAge.Length;
            }

            if (Domain != null)
            {
                length += SeparatorToken.Length + DomainToken.Length + EqualsToken.Length + Domain.Length;
            }

            if (Path != null)
            {
                length += SeparatorToken.Length + PathToken.Length + EqualsToken.Length + Path.Length;
            }

            if (Secure)
            {
                length += SeparatorToken.Length + SecureToken.Length;
            }

            if (SameSite != SameSiteMode.None)
            {
                var sameSite = SameSite == SameSiteMode.Lax ? SameSiteLaxToken : SameSiteStrictToken;
                length += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }

            if (ProtoOnly)
            {
                length += SeparatorToken.Length + ProtoOnlyToken.Length;
            }

            return(string.Create(length, (this, maxAge), (span, tuple) =>
            {
                var(headerValue, maxAgeValue) = tuple;

                Append(ref span, headerValue._name);
                Append(ref span, EqualsToken);
                Append(ref span, headerValue._value);

                if (headerValue.Expires is DateTimeOffset expiresValue)
                {
                    Append(ref span, SeparatorToken);
                    Append(ref span, ExpiresToken);
                    Append(ref span, EqualsToken);

                    var formatted = expiresValue.TryFormat(span, out var charsWritten, ExpiresDateFormat);
                    span = span.Slice(charsWritten);

                    Debug.Assert(formatted);
                }

                if (maxAgeValue != null)
                {
                    AppendSegment(ref span, MaxAgeToken, maxAgeValue);
                }

                if (headerValue.Domain != null)
                {
                    AppendSegment(ref span, DomainToken, headerValue.Domain);
                }

                if (headerValue.Path != null)
                {
                    AppendSegment(ref span, PathToken, headerValue.Path);
                }

                if (headerValue.Secure)
                {
                    AppendSegment(ref span, SecureToken, null);
                }

                if (headerValue.SameSite != SameSiteMode.None)
                {
                    AppendSegment(ref span, SameSiteToken, headerValue.SameSite == SameSiteMode.Lax ? SameSiteLaxToken : SameSiteStrictToken);
                }

                if (headerValue.ProtoOnly)
                {
                    AppendSegment(ref span, ProtoOnlyToken, null);
                }
            }));
        }
Esempio n. 4
0
 public void SetAndEscapeValue_ControlCharactersThrowFormatException(string input)
 {
     Assert.Throws <FormatException>(() => { var actual = HeaderUtilities.EscapeAsQuotedString(input); });
 }
Esempio n. 5
0
 public void SetAndEscapeValue_ThrowsFormatExceptionOnDelCharacter()
 {
     Assert.Throws <FormatException>(() => { var actual = HeaderUtilities.EscapeAsQuotedString($"{(char)0x7F}"); });
 }
Esempio n. 6
0
        public void IsQuoted_BehaviorCheck(string input, bool expected)
        {
            var actual = HeaderUtilities.IsQuoted(input);

            Assert.Equal(expected, actual);
        }
Esempio n. 7
0
        public void SetAndEscapeValue_BehaviorCheck(string input, string expected)
        {
            var actual = HeaderUtilities.EscapeAsQuotedString(input);

            Assert.Equal(expected, actual);
        }
Esempio n. 8
0
        public void RemoveQuotes_BehaviorCheck(string input, string expected)
        {
            var actual = HeaderUtilities.RemoveQuotes(input);

            Assert.Equal(expected, actual);
        }
Esempio n. 9
0
 public void ContainsCacheDirective_MatchesExactValue(string headerValues, string targetValue, bool contains)
 {
     Assert.Equal(contains, HeaderUtilities.ContainsCacheDirective(new StringValues(headerValues), targetValue));
 }
Esempio n. 10
0
 public void FormatNonNegativeInt64_Throws_ForNegativeValues(long value)
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => HeaderUtilities.FormatNonNegativeInt64(value));
 }
Esempio n. 11
0
 public void FormatNonNegativeInt64_MatchesToString(long value)
 {
     Assert.Equal(value.ToString(CultureInfo.InvariantCulture), HeaderUtilities.FormatNonNegativeInt64(value));
 }
Esempio n. 12
0
        public StringWithQualityHeaderValue(StringSegment value)
        {
            HeaderUtilities.CheckValidToken(value, nameof(value));

            _value = value;
        }