<commit_before>﻿/*
 * Copyright 2014, 2015 <NAME>, <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer3.Core;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Services;
using IdentityServer3.Core.Validation;
using IdentityServer3.Tests.Endpoints;
using Xunit;

namespace IdentityServer3.Tests.Connect.Endpoints
{
    public class IdentityTokenValidationControllerTests : IdSvrHostTestBase
    {
        const String Category = "Identity token validation endpoint";
        static readonly String Url = Constants.RoutePaths.Oidc.IdentityTokenValidation;

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_IdTokenValidationEndpointDisabled_ReturnsNotFound()
        {
            base.options.Endpoints.EnableIdentityTokenValidationEndpoint = false;
            var resp = Get();
            resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_MissingTokenInQueryString_ReturnsBadRequest()
        {
            var resp = Get();
            resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_MissingClientIdInQueryString_ReturnsBadRequest()
        {
            var resp = Get(token: "token");
            resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_ValidIdToken_ReturnsClaims()
        {
            ConfigureIdentityServerOptions = x =>
            {
                x.Factory.Register(new Registration<TokenValidator, AlwaysValidIdentityTokenValidator>());
            };
            Init();

            var resp = Get("token", "client_id");
            resp.StatusCode.Should().Be(HttpStatusCode.OK);
            var claims = resp.GetJson<IDictionary<String, String>>();

            claims.Should().NotBeNull();
            claims.Count.Should().Be(2);

            Action<KeyValuePair<String, String>, String, String> assertClaim = (claim, claimType, claimValue) =>
            {
                claim.Should().NotBeNull();
                claim.Key.Should().Be(claimType);
                claim.Value.Should().Be(claimValue);
            };

            assertClaim(claims.ElementAt(0), Constants.ClaimTypes.Subject, "unique_subject");
            assertClaim(claims.ElementAt(1), Constants.ClaimTypes.Name, "subject name");
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_InvalidIdToken_ReturnsBadRequest()
        {
            ConfigureIdentityServerOptions = x =>
            {
                x.Factory.Register(new Registration<TokenValidator, AlwaysInvalidIdentityTokenValidator>());
            };
            Init();

            var resp = Get("token", "client_id");
            var error = resp.GetJson<IDictionary<String, String>>(successExpected: false);

            error.Should().NotBeNull();
            error.Count.Should().Be(1);
            error.First().Key.Should().Be("Message");
            error.First().Value.Should().Be(Constants.ProtectedResourceErrors.InvalidToken);
        }

        private HttpResponseMessage Get(String token = null, String clientId = null)
        {
            var parameters = new NameValueCollection();

            if (token.IsPresent())
            {
                parameters.Add("token", token);
            }

            if (clientId.IsPresent())
            {
                parameters.Add("client_id", clientId);
            }

            var url = Url.AddQueryString(parameters.ToQueryString());
            return base.Get(url);
        }

        private class AlwaysValidIdentityTokenValidator : TokenValidator
        {
            public AlwaysValidIdentityTokenValidator(IdentityServerOptions options, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator)
                : base(options, clients, tokenHandles, customValidator)
            {
            }

            public override Task<TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true)<commit_msg>rename url property<commit_after>﻿/*
 * Copyright 2014, 2015 <NAME>, <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer3.Core;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Services;
using IdentityServer3.Core.Validation;
using IdentityServer3.Tests.Endpoints;
using Xunit;

namespace IdentityServer3.Tests.Connect.Endpoints
{
    public class IdentityTokenValidationControllerTests : IdSvrHostTestBase
    {
        const String Category = "Identity token validation endpoint";
        static readonly String TestUrl = Constants.RoutePaths.Oidc.IdentityTokenValidation;

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_IdTokenValidationEndpointDisabled_ReturnsNotFound()
        {
            base.options.Endpoints.EnableIdentityTokenValidationEndpoint = false;
            var resp = Get();
            resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_MissingTokenInQueryString_ReturnsBadRequest()
        {
            var resp = Get();
            resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_MissingClientIdInQueryString_ReturnsBadRequest()
        {
            var resp = Get(token: "token");
            resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_ValidIdToken_ReturnsClaims()
        {
            ConfigureIdentityServerOptions = x =>
            {
                x.Factory.Register(new Registration<TokenValidator, AlwaysValidIdentityTokenValidator>());
            };
            Init();

            var resp = Get("token", "client_id");
            resp.StatusCode.Should().Be(HttpStatusCode.OK);
            var claims = resp.GetJson<IDictionary<String, String>>();

            claims.Should().NotBeNull();
            claims.Count.Should().Be(2);

            Action<KeyValuePair<String, String>, String, String> assertClaim = (claim, claimType, claimValue) =>
            {
                claim.Should().NotBeNull();
                claim.Key.Should().Be(claimType);
                claim.Value.Should().Be(claimValue);
            };

            assertClaim(claims.ElementAt(0), Constants.ClaimTypes.Subject, "unique_subject");
            assertClaim(claims.ElementAt(1), Constants.ClaimTypes.Name, "subject name");
        }

        [Fact]
        [Trait("Category", Category)]
        public void GetIdTokenValidation_InvalidIdToken_ReturnsBadRequest()
        {
            ConfigureIdentityServerOptions = x =>
            {
                x.Factory.Register(new Registration<TokenValidator, AlwaysInvalidIdentityTokenValidator>());
            };
            Init();

            var resp = Get("token", "client_id");
            var error = resp.GetJson<IDictionary<String, String>>(successExpected: false);

            error.Should().NotBeNull();
            error.Count.Should().Be(1);
            error.First().Key.Should().Be("Message");
            error.First().Value.Should().Be(Constants.ProtectedResourceErrors.InvalidToken);
        }

        private HttpResponseMessage Get(String token = null, String clientId = null)
        {
            var parameters = new NameValueCollection();

            if (token.IsPresent())
            {
                parameters.Add("token", token);
            }

            if (clientId.IsPresent())
            {
                parameters.Add("client_id", clientId);
            }

            var url = TestUrl.AddQueryString(parameters.ToQueryString());
            return base.Get(url);
        }

        private class AlwaysValidIdentityTokenValidator : TokenValidator
        {
            public AlwaysValidIdentityTokenValidator(IdentityServerOptions options, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator)
                : base(options, clients, tokenHandles, customValidator)
            {
            }

            public override Task<TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true)
{'fraction_non_alphanumeric': 0.09731740747992951, 'fraction_numerical': 0.0045036224789504605, 'mean_word_length': 2.6057183198023295, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4559015', 'n_tokens_mistral': 2525, 'n_tokens_neox': 2470, 'n_words': 573}