public static JsonWebToken Create(string issuer, string audience, DateTime validFrom, DateTime validTo, DateTime issuedAt, IEnumerable <Claim> additionalClaims, VssSigningCredentials credentials)
        {
            //if you are calling this version claims can't be null
            ArgumentUtility.CheckForNull(additionalClaims, nameof(additionalClaims));

            return(Create(issuer, audience, validFrom, validTo, issuedAt, additionalClaims, null, null, credentials, allowExpiredCertificate: false));
        }
        public static void AddMultiple <T>(this IList <KeyValuePair <String, String> > collection, String key, IEnumerable <T> values, Func <T, String> convert)
        {
            ArgumentUtility.CheckForNull(collection, "collection");
            ArgumentUtility.CheckStringForNullOrEmpty(key, "name");

            if (convert == null)
            {
                convert = (val) => val.ToString();
            }

            if (values != null && values.Any())
            {
                StringBuilder newValue = new StringBuilder();
                KeyValuePair <String, String> matchingKvp = collection.FirstOrDefault(kvp => kvp.Key.Equals(key));
                if (matchingKvp.Key == key)
                {
                    collection.Remove(matchingKvp);
                    newValue.Append(matchingKvp.Value);
                }

                foreach (var value in values)
                {
                    if (newValue.Length > 0)
                    {
                        newValue.Append(",");
                    }
                    newValue.Append(convert(value));
                }

                collection.Add(new KeyValuePair <String, String>(key, newValue.ToString()));
            }
        }
        public int IndexOf(string main, string pattern)
        {
            ArgumentUtility.CheckForNull(main, "main");
            ArgumentUtility.CheckForNull(pattern, "pattern");

            return(main.IndexOf(pattern, m_stringComparison));
        }
        public bool EndsWith(string main, string pattern)
        {
            ArgumentUtility.CheckForNull(main, "main");
            ArgumentUtility.CheckForNull(pattern, "pattern");

            return(main.EndsWith(pattern, m_stringComparison));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Copies the ReferenceLinks to another ReferenceLinks and secures using the specified object.
        /// </summary>
        /// <param name="target"></param>
        public void CopyTo(ReferenceLinks target, ISecuredObject securedObject)
        {
            ArgumentUtility.CheckForNull(target, nameof(target));

            foreach (var link in this.Links)
            {
                if (link.Value is IList <ReferenceLink> )
                {
                    var hrefs = link.Value as IList <ReferenceLink>;
                    if (hrefs != null)
                    {
                        foreach (var href in hrefs)
                        {
                            target.AddLink(link.Key, href.Href, securedObject);
                        }
                    }
                }
                else if (link.Value is ReferenceLink)
                {
                    var href = link.Value as ReferenceLink;
                    if (href != null)
                    {
                        target.AddLink(link.Key, href.Href, securedObject);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates a new <c>VssSigningCredentials</c> instance using the specified <paramref name="key"/> as the signing
        /// key. The returned signing token performs symmetric key signing and verification.
        /// </summary>
        /// <param name="rsa">The key used for signing and verification</param>
        /// <returns>A new <c>VssSigningCredentials</c> instance which uses the specified key for signing</returns>
        public static VssSigningCredentials Create(Byte[] key)
        {
            ArgumentUtility.CheckForNull(key, nameof(key));

            // Probably should have validation here, but there was none previously
            return(new SymmetricKeySigningToken(key));
        }
Ejemplo n.º 7
0
        public static ClaimsPrincipal ValidateToken(this JsonWebToken token, JsonWebTokenValidationParameters parameters)
        {
            ArgumentUtility.CheckForNull(token, nameof(token));
            ArgumentUtility.CheckForNull(parameters, nameof(parameters));

            ClaimsIdentity actorIdentity = ValidateActor(token, parameters);

            ValidateLifetime(token, parameters);
            ValidateAudience(token, parameters);
            ValidateSignature(token, parameters);
            ValidateIssuer(token, parameters);

            ClaimsIdentity identity = new ClaimsIdentity("Federation", parameters.IdentityNameClaimType, ClaimTypes.Role);

            if (actorIdentity != null)
            {
                identity.Actor = actorIdentity;
            }

            IEnumerable <Claim> claims = token.ExtractClaims();

            foreach (Claim claim in claims)
            {
                identity.AddClaim(new Claim(claim.Type, claim.Value, claim.ValueType, token.Issuer));
            }

            return(new ClaimsPrincipal(identity));
        }
        /// <summary>
        /// Partitions items from a source IEnumerable into N+1 lists, where the first N lists are determened
        /// by the sequential check of the provided predicates, with the N+1 list containing those items
        /// which matched none of the provided predicates.
        /// </summary>
        /// <typeparam name="T">The type of the elements in source.</typeparam>
        /// <param name="source">The source containing the elements to partition</param>
        /// <param name="predicates">The predicates to determine which list the results end up in</param>
        /// <returns>An item containing the matching collections and a collection containing the non-matching items.</returns>
        public static MultiPartitionResults <T> Partition <T>(this IEnumerable <T> source, params Predicate <T>[] predicates)
        {
            ArgumentUtility.CheckForNull(source, nameof(source));
            ArgumentUtility.CheckForNull(predicates, nameof(predicates));

            var range = Enumerable.Range(0, predicates.Length).ToList();

            var results = new MultiPartitionResults <T>();

            results.MatchingPartitions.AddRange(range.Select(_ => new List <T>()));

            foreach (var item in source)
            {
                bool added = false;

                foreach (var predicateIndex in range.Where(predicateIndex => predicates[predicateIndex](item)))
                {
                    results.MatchingPartitions[predicateIndex].Add(item);
                    added = true;
                    break;
                }

                if (!added)
                {
                    results.NonMatchingPartition.Add(item);
                }
            }

            return(results);
        }
        internal EvaluationContext(
            ITraceWriter trace,
            ISecretMasker secretMasker,
            Object state,
            EvaluationOptions options,
            ExpressionNode node)
        {
            ArgumentUtility.CheckForNull(trace, nameof(trace));
            ArgumentUtility.CheckForNull(secretMasker, nameof(secretMasker));
            Trace        = trace;
            SecretMasker = secretMasker;
            State        = state;

            // Copy the options
            options = new EvaluationOptions(copy: options);
            if (options.MaxMemory == 0)
            {
                // Set a reasonable default max memory
                options.MaxMemory = 1048576; // 1 mb
            }
            Options = options;
            Memory  = new EvaluationMemory(options.MaxMemory, node);

            m_traceResults = new Dictionary <ExpressionNode, String>();
            m_traceMemory  = new MemoryCounter(null, options.MaxMemory);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Retrieves the token provider for the provided server URL if one has been created.
        /// </summary>
        /// <param name="serverUrl">The targeted server</param>
        /// <param name="provider">Stores the active token provider, if one exists</param>
        /// <returns>True if a token provider was found, false otherwise</returns>
        public bool TryGetTokenProvider(
            Uri serverUrl,
            out IssuedTokenProvider provider)
        {
            ArgumentUtility.CheckForNull(serverUrl, "serverUrl");

            lock (m_thisLock)
            {
                // Ensure that we attempt to use the most appropriate authentication mechanism by default.
                if (m_currentProvider == null)
                {
                    if (m_federatedCredential != null)
                    {
                        m_currentProvider = m_federatedCredential.CreateTokenProvider(serverUrl, null, null);
                    }

                    if (m_currentProvider != null)
                    {
                        VssHttpEventSource.Log.IssuedTokenProviderCreated(VssTraceActivity.Current, m_currentProvider);
                    }
                }

                provider = m_currentProvider;
            }

            return(provider != null);
        }
        //use this method to instantiate the token with user information
        public static JsonWebToken Create(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable <Claim> additionalClaims, string actorToken)
        {
            //if you are calling this version of the method additionalClaims and actor cannot be null
            ArgumentUtility.CheckForNull(additionalClaims, nameof(additionalClaims));
            ArgumentUtility.CheckStringForNullOrEmpty(actorToken, nameof(actorToken));

            return(Create(issuer, audience, validFrom, validTo, default(DateTime), additionalClaims, null, actorToken, null, allowExpiredCertificate: false));
        }
Ejemplo n.º 12
0
        internal static string JsonEncode(object o)
        {
            ArgumentUtility.CheckForNull(o, nameof(o));

            string json = JsonConvert.SerializeObject(o, DefaultSerializerSettings);

            return(Encoding.UTF8.GetBytes(json).ToBase64StringNoPadding());
        }
Ejemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceDefinition"></param>
        /// <param name="accessMapping"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <String> LocationForAccessMappingAsync(
            ServiceDefinition serviceDefinition,
            AccessMapping accessMapping,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ArgumentUtility.CheckForNull(serviceDefinition, "serviceDefinition");
            ArgumentUtility.CheckForNull(accessMapping, "accessMapping");

            // If this is FullyQualified then look through our location mappings
            if (serviceDefinition.RelativeToSetting == RelativeToSetting.FullyQualified)
            {
                LocationMapping locationMapping = serviceDefinition.GetLocationMapping(accessMapping);

                if (locationMapping != null)
                {
                    return(Task.FromResult <String>(locationMapping.Location));
                }

                // We weren't able to find the location for the access mapping.  Return null.
                return(Task.FromResult <String>(null));
            }
            else
            {
                // Make sure the AccessMapping has a valid AccessPoint.
                if (String.IsNullOrEmpty(accessMapping.AccessPoint))
                {
                    throw new InvalidAccessPointException(WebApiResources.InvalidAccessMappingLocationServiceUrl());
                }

                String webApplicationRelativeDirectory = m_locationDataCacheManager.WebApplicationRelativeDirectory;

                if (accessMapping.VirtualDirectory != null)
                {
                    webApplicationRelativeDirectory = accessMapping.VirtualDirectory;
                }

                Uri uri = new Uri(accessMapping.AccessPoint);

                String properRoot = String.Empty;
                switch (serviceDefinition.RelativeToSetting)
                {
                case RelativeToSetting.Context:
                    properRoot = PathUtility.Combine(uri.AbsoluteUri, webApplicationRelativeDirectory);
                    break;

                case RelativeToSetting.WebApplication:
                    properRoot = accessMapping.AccessPoint;
                    break;

                default:
                    Debug.Assert(true, "Found an unknown RelativeToSetting");
                    break;
                }

                return(Task.FromResult <String>(PathUtility.Combine(properRoot, serviceDefinition.RelativePath)));
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Used for Testing Only
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="type"></param>
        internal void RegisterExtensibleType(
            String typeName,
            Type type)
        {
            ArgumentUtility.CheckStringForNullOrEmpty(typeName, "typeName");
            ArgumentUtility.CheckForNull(type, "type");

            m_extensibleServiceTypes[typeName] = type;
        }
        /// <summary>
        /// Initializes a new <c>VssOAuthJwtBearerClientCredential</c> with the specified JWT bearer assertion.
        /// </summary>
        /// <param name="clientId">The client identifier issued by the authorization server</param>
        /// <param name="assertion">The client assertion for proof of identity</param>
        public VssOAuthJwtBearerClientCredential(
            String clientId,
            VssOAuthJwtBearerAssertion assertion)
            : base(VssOAuthClientCredentialType.JwtBearer, clientId)
        {
            ArgumentUtility.CheckForNull(assertion, nameof(assertion));

            m_assertion = assertion;
        }
 public SerializerKey(string rootNamespace, string elementName, Type elementType)
 {
     // root namespace can be null, but element name and type must be nonnull
     ArgumentUtility.CheckForNull(elementName, nameof(elementName));
     ArgumentUtility.CheckForNull(elementType, nameof(elementType));
     RootNamespace = rootNamespace;
     ElementName   = elementName;
     ElementType   = elementType;
 }
 private JsonWebToken(JWTHeader header, JWTPayload payload, byte[] signature)
 {
     ArgumentUtility.CheckForNull(header, nameof(header));
     ArgumentUtility.CheckForNull(payload, nameof(payload));
     //signature allowed to be null
     _header    = header;
     _payload   = payload;
     _signature = signature;
 }
Ejemplo n.º 18
0
 public Task <TaskAgent> ReplaceAgentAsync(
     Int32 poolId,
     TaskAgent agent,
     Object userState = null,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     ArgumentUtility.CheckForNull(agent, "agent");
     return(ReplaceAgentAsync(poolId, agent.Id, agent, userState, cancellationToken));
 }
        public static IList <P> PartitionSolveAndMergeBack <T, P>(this IList <T> source, Predicate <T> predicate, Func <IList <T>, IList <P> > matchingPartitionSolver, Func <IList <T>, IList <P> > nonMatchingPartitionSolver)
        {
            ArgumentUtility.CheckForNull(source, nameof(source));
            ArgumentUtility.CheckForNull(predicate, nameof(predicate));
            ArgumentUtility.CheckForNull(matchingPartitionSolver, nameof(matchingPartitionSolver));
            ArgumentUtility.CheckForNull(nonMatchingPartitionSolver, nameof(nonMatchingPartitionSolver));

            var partitionedSource = new PartitionResults <Tuple <int, T> >();

            for (int sourceCnt = 0; sourceCnt < source.Count; sourceCnt++)
            {
                var item = source[sourceCnt];

                if (predicate(item))
                {
                    partitionedSource.MatchingPartition.Add(new Tuple <int, T>(sourceCnt, item));
                }
                else
                {
                    partitionedSource.NonMatchingPartition.Add(new Tuple <int, T>(sourceCnt, item));
                }
            }

            var solvedResult = new List <P>(source.Count);

            if (partitionedSource.MatchingPartition.Any())
            {
                solvedResult.AddRange(matchingPartitionSolver(partitionedSource.MatchingPartition.Select(x => x.Item2).ToList()));
            }

            if (partitionedSource.NonMatchingPartition.Any())
            {
                solvedResult.AddRange(nonMatchingPartitionSolver(partitionedSource.NonMatchingPartition.Select(x => x.Item2).ToList()));
            }

            var result = Enumerable.Repeat(default(P), source.Count).ToList();

            if (solvedResult.Count != source.Count)
            {
                return(solvedResult); // either we can throw here or just return solvedResult and ignore!
            }

            for (int resultCnt = 0; resultCnt < source.Count; resultCnt++)
            {
                if (resultCnt < partitionedSource.MatchingPartition.Count)
                {
                    result[partitionedSource.MatchingPartition[resultCnt].Item1] = solvedResult[resultCnt];
                }
                else
                {
                    result[partitionedSource.NonMatchingPartition[resultCnt - partitionedSource.MatchingPartition.Count].Item1] = solvedResult[resultCnt];
                }
            }

            return(result);
        }
        /// <summary>
        /// Executes the specified action to each of the items in the collection
        /// <typeparam name="T">The type of the elements in the collection.</typeparam>
        /// <param name="collection">The collection on which the action will be performed</param>
        /// <param name="action">The action to be performed</param>
        /// </summary>
        public static void ForEach <T>(this IEnumerable <T> collection, Action <T> action)
        {
            ArgumentUtility.CheckForNull(action, nameof(action));
            ArgumentUtility.CheckForNull(collection, nameof(collection));

            foreach (T item in collection)
            {
                action(item);
            }
        }
        public static void ValidateDictionary(IDictionary <String, Object> source)
        {
            ArgumentUtility.CheckForNull(source, "source");

            foreach (var entry in source)
            {
                ValidatePropertyName(entry.Key);
                ValidatePropertyValue(entry.Key, entry.Value);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="moniker"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <AccessMapping> GetAccessMappingAsync(
            String moniker,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ArgumentUtility.CheckForNull(moniker, "moniker");

            await EnsureConnectedAsync(ConnectOptions.IncludeServices, cancellationToken).ConfigureAwait(false);

            return(m_locationDataCacheManager.GetAccessMapping(moniker));
        }
        /// <summary>
        /// Initializes a new <c>VssOAuthTokenRequest</c> instance with the specified grant and client credential.
        /// Additional parameters specified by the token parameters will be provided in the token request.
        /// </summary>
        /// <param name="grant">The authorization grant to use for the token request</param>
        /// <param name="clientCredential">The client credential to use for the token request</param>
        /// <param name="tokenParameters">An optional set of additional parameters for the token request</param>
        public VssOAuthTokenRequest(
            VssOAuthGrant grant,
            VssOAuthClientCredential clientCredential,
            VssOAuthTokenParameters tokenParameters)
        {
            ArgumentUtility.CheckForNull(grant, nameof(grant));

            m_grant            = grant;
            m_clientCredential = clientCredential;
            m_tokenParameters  = tokenParameters;
        }
        /// <summary>
        /// Merges two sorted IEnumerables using the given comparison function which defines a total ordering of the data.  Unlike Merge, this method requires that
        /// both IEnumerables contain distinct elements.  Likewise, the returned IEnumerable will only contain distinct elements.  If the same element appears in both inputs,
        /// it will appear only once in the output.
        ///
        /// Example:
        ///     first:  [1, 3, 5]
        ///     second: [4, 5, 7]
        ///     result: [1, 3, 4, 5, 7]
        /// </summary>
        public static IEnumerable <T> MergeDistinct <T>(
            this IEnumerable <T> first,
            IEnumerable <T> second,
            Func <T, T, int> comparer)
        {
            ArgumentUtility.CheckForNull(first, nameof(first));
            ArgumentUtility.CheckForNull(second, nameof(second));
            ArgumentUtility.CheckForNull(comparer, nameof(comparer));

            using (IEnumerator <T> e1 = first.GetEnumerator())
                using (IEnumerator <T> e2 = second.GetEnumerator())
                {
                    bool e1Valid = e1.MoveNext();
                    bool e2Valid = e2.MoveNext();

                    while (e1Valid && e2Valid)
                    {
                        if (comparer(e1.Current, e2.Current) < 0)
                        {
                            yield return(e1.Current);

                            e1Valid = e1.MoveNext();
                        }
                        else if (comparer(e1.Current, e2.Current) > 0)
                        {
                            yield return(e2.Current);

                            e2Valid = e2.MoveNext();
                        }
                        else
                        {
                            yield return(e1.Current);

                            e1Valid = e1.MoveNext();
                            e2Valid = e2.MoveNext();
                        }
                    }

                    while (e1Valid)
                    {
                        yield return(e1.Current);

                        e1Valid = e1.MoveNext();
                    }

                    while (e2Valid)
                    {
                        yield return(e2.Current);

                        e2Valid = e2.MoveNext();
                    }
                }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Construct a new API Version info
        /// </summary>
        /// <param name="apiVersion">Public API version</param>
        /// <param name="resourceVersion">Resource version</param>
        public ApiResourceVersion(Version apiVersion, int resourceVersion = 0)
        {
            ArgumentUtility.CheckForNull(apiVersion, "apiVersion");

            ApiVersion      = apiVersion;
            ResourceVersion = resourceVersion;

            if (resourceVersion > 0)
            {
                IsPreview = true;
            }
        }
Ejemplo n.º 26
0
        private static void ValidateSignature(JsonWebToken token, JsonWebTokenValidationParameters parameters)
        {
            ArgumentUtility.CheckForNull(token, nameof(token));
            ArgumentUtility.CheckForNull(parameters, nameof(parameters));

            if (!parameters.ValidateSignature)
            {
                return;
            }

            string encodedData = token.EncodedToken;

            string[] parts = encodedData.Split('.');

            if (parts.Length != 3)
            {
                throw new InvalidTokenException(JwtResources.EncodedTokenDataMalformed()); //validation exception
            }

            if (string.IsNullOrEmpty(parts[2]))
            {
                throw new InvalidTokenException(JwtResources.SignatureNotFound()); //validation exception
            }

            if (token.Algorithm == JWTAlgorithm.None)
            {
                throw new InvalidTokenException(JwtResources.InvalidSignatureAlgorithm()); //validation exception
            }

            ArgumentUtility.CheckForNull(parameters.SigningCredentials, nameof(parameters.SigningCredentials));

            //ArgumentUtility.CheckEnumerableForNullOrEmpty(parameters.SigningToken.SecurityKeys, nameof(parameters.SigningToken.SecurityKeys));

            byte[] sourceInput = Encoding.UTF8.GetBytes(string.Format("{0}.{1}", parts[0], parts[1]));

            byte[] sourceSignature = parts[2].FromBase64StringNoPadding();


            try
            {
                if (parameters.SigningCredentials.VerifySignature(sourceInput, sourceSignature))
                {
                    return;
                }
            }
            catch (Exception)
            {
                //swallow exceptions here, we'll throw if nothing works...
            }

            throw new SignatureValidationException(); //valiation exception
        }
Ejemplo n.º 27
0
        protected IssuedTokenProvider(
            IssuedTokenCredential credential,
            Uri serverUrl,
            Uri signInUrl)
        {
            ArgumentUtility.CheckForNull(credential, "credential");

            this.SignInUrl  = signInUrl;
            this.Credential = credential;
            this.ServerUrl  = serverUrl;

            m_thisLock = new object();
        }
        /// <summary>
        /// Initializes a new <c>VssOAuthCredential</c> instance with the specified authorization grant and client
        /// credentials.
        /// </summary>
        /// <param name="authorizationUrl">The location of the token endpoint for the target authorization server</param>
        /// <param name="grant">The grant to provide for the token exchange</param>
        /// <param name="clientCredential">The client credentials to provide for the token exchange</param>
        /// <param name="tokenParameters">An optional set of token parameters which, if present, are sent in the request body of the token request</param>
        /// <param name="accessToken">An optional access token which, if present, is used prior to requesting new tokens</param>
        public VssOAuthCredential(
            Uri authorizationUrl,
            VssOAuthGrant grant,
            VssOAuthClientCredential clientCredential,
            VssOAuthTokenParameters tokenParameters = null,
            VssOAuthAccessToken accessToken         = null)
            : base(accessToken)
        {
            ArgumentUtility.CheckForNull(authorizationUrl, nameof(authorizationUrl));
            ArgumentUtility.CheckForNull(grant, nameof(grant));

            m_authorizationUrl = authorizationUrl;
            m_grant            = grant;
            m_tokenParameters  = tokenParameters;
            m_clientCredential = clientCredential;
        }
        public static Uri AppendQuery(this Uri uri, String name, String value)
        {
            ArgumentUtility.CheckForNull(uri, "uri");
            ArgumentUtility.CheckStringForNullOrEmpty(name, "name");
            ArgumentUtility.CheckStringForNullOrEmpty(value, "value");

            StringBuilder stringBuilder = new StringBuilder(uri.Query.TrimStart('?'));

            AppendSingleQueryValue(stringBuilder, name, value);

            UriBuilder uriBuilder = new UriBuilder(uri);

            uriBuilder.Query = stringBuilder.ToString();

            return(uriBuilder.Uri);
        }
Ejemplo n.º 30
0
        public async Task AddServer([FromBody] DataContract.V1.ServerInfo serverInfo)
        {
            ArgumentUtility.CheckForNull(serverInfo, nameof(serverInfo));

            string requestIpAddress = this.GetRequestIpAddress();

            this.logger.LogInformation("Request to add server from {IPAddress}", requestIpAddress);

            var serverInfoEntity = this.mapper.Map <Services.ServerInfo>(serverInfo);

            serverInfoEntity.HostIpAddress = requestIpAddress.ToString();
            serverInfoEntity.LastHeartbeat = DateTime.UtcNow;

            await this.serverRegistryService.AddServer(serverInfoEntity);

            this.logger.LogInformation("Added server successfully for {IPAddress}", requestIpAddress);
        }