Esempio n. 1
0
        public MockDocumentClient()
            : base(new Uri("http://localhost"), null)
        {
            this.authKeyHashFunction = new StringHMACSHA256Hash(MockDocumentClient.GenerateRandomKey());

            this.Init();
        }
Esempio n. 2
0
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out ArrayOwner payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateUrlEncodedAuthorizationTokenWithHashCore(
                verb: verb,
                resourceId: resourceId,
                resourceType: resourceType,
                headers: headers,
                stringHMACSHA256Helper: stringHMACSHA256Helper,
                payload: out payload);

            try
            {
                return(AuthorizationHelper.AuthorizationFormatPrefixUrlEncoded + authorizationToken);
            }
            catch
            {
                payload.Dispose();
                throw;
            }
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out ArrayOwner payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out payload);

            try
            {
                return(HttpUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, Constants.Properties.AuthorizationFormat,
                                                           Constants.Properties.MasterToken,
                                                           Constants.Properties.TokenVersion,
                                                           authorizationToken)));
            }
            catch
            {
                payload.Dispose();
                throw;
            }
        }
Esempio n. 4
0
 public Block(int blockNumber)
 {
     BlockNumber  = blockNumber;
     CreatedDate  = DateTime.UtcNow;
     Transactions = new List <ITransaction>();
     _computeHash = new ComputeHash();
 }
Esempio n. 5
0
        public MasterKeyAuthorizationBenchmark()
        {
            this.authKeyHashFunction = new StringHMACSHA256Hash(MockDocumentClient.GenerateRandomKey());
            Headers headers = new Headers();

            headers[HttpConstants.HttpHeaders.XDate] = DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture);

            this.testHeaders = headers.CosmosMessageHeaders;
        }
        public MasterKeyAuthorizationBenchmark()
        {
            this.authKeyHashFunction = new StringHMACSHA256Hash(MockDocumentClient.GenerateRandomKey());
            Headers headers = new Headers();

            headers[HttpConstants.HttpHeaders.XDate] = Rfc1123DateTimeCache.UtcNow();

            this.testHeaders = headers.CosmosMessageHeaders.INameValueCollection;
        }
Esempio n. 7
0
 public Transaction(string claimNumber, decimal settlementAmount, DateTime settlementDate, string carRegistration, int milage, ClaimType claimType)
 {
     this.ClaimNumber      = claimNumber;
     this.SettlementAmount = settlementAmount;
     this.SettlementDate   = settlementDate;
     this.CarRegistration  = carRegistration;
     this.Milage           = milage;
     this.ClaimType        = claimType;
     _computeHash          = new ComputeHash();
 }
        private static string GenerateAuthorizationTokenWithHashCore(
            string verb,
            string resourceId,
            string resourceType,
            INameValueCollection headers,
            IComputeHash stringHMACSHA256Helper,
            out MemoryStream payload)
        {
            // resourceId can be null for feed-read of /dbs
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(verb));
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException(nameof(resourceType)); // can be empty
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException(nameof(stringHMACSHA256Helper));
            }

            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            // Order of the values included in the message payload is a protocol that clients/BE need to follow exactly.
            // More headers can be added in the future.
            // If any of the value is optional, it should still have the placeholder value of ""
            // OperationType -> ResourceType -> ResourceId/OwnerId -> XDate -> Date
            string verbInput         = verb ?? string.Empty;
            string resourceIdInput   = resourceId ?? string.Empty;
            string resourceTypeInput = resourceType ?? string.Empty;

            string authResourceId = AuthorizationHelper.GetAuthorizationResourceIdOrFullName(resourceTypeInput, resourceIdInput);
            int    capacity       = AuthorizationHelper.ComputeMemoryCapacity(verbInput, authResourceId, resourceTypeInput);

            payload = new MemoryStream(capacity);
            AuthorizationHelper.SerializeMessagePayload(
                payload,
                verbInput,
                authResourceId,
                resourceTypeInput,
                headers);
            payload.Position = 0;

            byte[] hashPayLoad = stringHMACSHA256Helper.ComputeHash(payload);
            payload.Position = 0;
            string authorizationToken = Convert.ToBase64String(hashPayLoad);

            return(authorizationToken);
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out string payload)
        {
            // resourceId can be null for feed-read of /dbs

            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, "verb");
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException("resourceType"); // can be empty
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException("stringHMACSHA256Helper");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            // Order of the values included in the message payload is a protocol that clients/BE need to follow exactly.
            // More headers can be added in the future.
            // If any of the value is optional, it should still have the placeholder value of ""
            // OperationType -> ResourceType -> ResourceId/OwnerId -> XDate -> Date
            string verbInput         = verb ?? string.Empty;
            string resourceIdInput   = resourceId ?? string.Empty;
            string resourceTypeInput = resourceType ?? string.Empty;

            string authResourceId = AuthorizationHelper.GetAuthorizationResourceIdOrFullName(resourceTypeInput, resourceIdInput);

            payload = GenerateMessagePayload(verbInput,
                                             authResourceId,
                                             resourceTypeInput,
                                             headers);

            byte[] hashPayLoad        = stringHMACSHA256Helper.ComputeHash(Encoding.UTF8.GetBytes(payload));
            string authorizationToken = Convert.ToBase64String(hashPayLoad);

            return(HttpUtility.UrlEncode(String.Format(CultureInfo.InvariantCulture, Constants.Properties.AuthorizationFormat,
                                                       Constants.Properties.MasterToken,
                                                       Constants.Properties.TokenVersion,
                                                       authorizationToken)));
        }
Esempio n. 10
0
 public GatewayAccountReader(Uri serviceEndpoint,
                             IComputeHash stringHMACSHA256Helper,
                             bool hasResourceToken,
                             string resourceToken,
                             ConnectionPolicy connectionPolicy,
                             HttpClient httpClient)
 {
     this.httpClient              = httpClient;
     this.serviceEndpoint         = serviceEndpoint;
     this.authKeyHashFunction     = stringHMACSHA256Helper;
     this.hasAuthKeyResourceToken = hasResourceToken;
     this.authKeyResourceToken    = resourceToken;
     this.connectionPolicy        = connectionPolicy;
 }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper)
        {
            string payload;

            return(AuthorizationHelper.GenerateKeyAuthorizationSignature(verb,
                                                                         resourceId,
                                                                         resourceType,
                                                                         headers,
                                                                         stringHMACSHA256Helper,
                                                                         out payload));
        }
Esempio n. 12
0
 public GatewayAccountReader(Uri serviceEndpoint,
                             IComputeHash stringHMACSHA256Helper,
                             bool hasResourceToken,
                             string resourceToken,
                             ConnectionPolicy connectionPolicy,
                             ApiType apiType,
                             HttpMessageHandler messageHandler = null)
 {
     this.serviceEndpoint         = serviceEndpoint;
     this.authKeyHashFunction     = stringHMACSHA256Helper;
     this.hasAuthKeyResourceToken = hasResourceToken;
     this.authKeyResourceToken    = resourceToken;
     this.connectionPolicy        = connectionPolicy;
     this.messageHandler          = messageHandler;
     this.apiType = apiType;
 }
Esempio n. 13
0
 private static string GenerateUrlEncodedAuthorizationTokenWithHashCore(
     string verb,
     string resourceId,
     string resourceType,
     INameValueCollection headers,
     IComputeHash stringHMACSHA256Helper,
     out ArrayOwner payload)
 {
     return(AuthorizationHelper.GenerateAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                urlEncode: true,
                out payload));
 }
Esempio n. 14
0
        public async Task <IActionResult> Index(UrlModel UrlModel, [FromServices] IComputeHash computeService, [FromServices] IMakeUrl makeUrlService)
        {
            if (ModelState.IsValid)
            {
                string urlHash = computeService.Compute(UrlModel.url);

                string miniUrlHash = FindOrAddToDb(urlHash, UrlModel.url);
                await db.SaveChangesAsync();

                ViewData["url"] = makeUrlService.AddHost(HttpContext, Url.Action("Redir", "Home", new { hash = miniUrlHash }));

                return(View(UrlModel));
            }
            else
            {
                return(View());
            }
        }
        // This API is a helper method to create auth header based on client request.
        // Uri is split into resourceType/resourceId -
        // For feed/post/put requests, resourceId = parentId,
        // For point get requests,     resourceId = last segment in URI
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               Uri uri,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               string clientVersion = "")
        {
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(verb));
            }

            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException(nameof(stringHMACSHA256Helper));
            }

            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            string resourceType    = string.Empty;
            string resourceIdValue = string.Empty;
            bool   isNameBased     = false;

            AuthorizationHelper.GetResourceTypeAndIdOrFullName(uri, out isNameBased, out resourceType, out resourceIdValue, clientVersion);

            string authToken = AuthorizationHelper.GenerateKeyAuthorizationSignature(verb,
                                                                                     resourceIdValue,
                                                                                     resourceType,
                                                                                     headers,
                                                                                     stringHMACSHA256Helper,
                                                                                     out ArrayOwner arrayOwner);

            using (arrayOwner)
            {
                return(authToken);
            }
        }
Esempio n. 16
0
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper)
        {
            string authorizationToken = AuthorizationHelper.GenerateUrlEncodedAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out ArrayOwner payloadStream);

            using (payloadStream)
            {
                return(AuthorizationHelper.AuthorizationFormatPrefixUrlEncoded + authorizationToken);
            }
        }
        // This API is a helper method to create auth header based on client request.
        // Uri is split into resourceType/resourceId -
        // For feed/post/put requests, resourceId = parentId,
        // For point get requests,     resourceId = last segment in URI
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               Uri uri,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               string clientVersion = "")
        {
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, "verb");
            }

            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException("stringHMACSHA256Helper");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            string resourceType    = string.Empty;
            string resourceIdValue = string.Empty;
            bool   isNameBased     = false;

            AuthorizationHelper.GetResourceTypeAndIdOrFullName(uri, out isNameBased, out resourceType, out resourceIdValue, clientVersion);

            string payload;

            return(AuthorizationHelper.GenerateKeyAuthorizationSignature(verb,
                                                                         resourceIdValue,
                                                                         resourceType,
                                                                         headers,
                                                                         stringHMACSHA256Helper,
                                                                         out payload));
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out string payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out MemoryStream payloadStream);

            payload = AuthorizationHelper.AuthorizationEncoding.GetString(payloadStream.GetBuffer(), 0, (int)payloadStream.Length);
            return(HttpUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, Constants.Properties.AuthorizationFormat,
                                                       Constants.Properties.MasterToken,
                                                       Constants.Properties.TokenVersion,
                                                       authorizationToken)));
        }
        public static string GenerateKeyAuthorizationSignature(string verb,
                                                               string resourceId,
                                                               string resourceType,
                                                               INameValueCollection headers,
                                                               IComputeHash stringHMACSHA256Helper,
                                                               out string payload)
        {
            string authorizationToken = AuthorizationHelper.GenerateAuthorizationTokenWithHashCore(
                verb,
                resourceId,
                resourceType,
                headers,
                stringHMACSHA256Helper,
                out ArrayOwner payloadStream);

            using (payloadStream)
            {
                payload = AuthorizationHelper.AuthorizationEncoding.GetString(payloadStream.Buffer.Array, payloadStream.Buffer.Offset, (int)payloadStream.Buffer.Count);
                return(AuthorizationHelper.AuthorizationFormatPrefixUrlEncoded + HttpUtility.UrlEncode(authorizationToken));
            }
        }
        // This API is a helper method to create auth header based on client request.
        // Uri is split into resourceType/resourceId -
        // For feed/post/put requests, resourceId = parentId,
        // For point get requests,     resourceId = last segment in URI
        public static string GenerateGatewayAuthSignatureWithAddressResolution(string verb,
                                                                               Uri uri,
                                                                               INameValueCollection headers,
                                                                               IComputeHash stringHMACSHA256Helper,
                                                                               string clientVersion = "")
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            // Address request has the URI fragment (dbs/dbid/colls/colId...) as part of
            // either $resolveFor 'or' $generate queries of the context.RequestUri.
            // Extracting out the URI in the form https://localhost/dbs/dbid/colls/colId/docs to generate the signature.
            // Authorizer uses the same URI to verify signature.
            if (uri.AbsolutePath.Equals(Paths.Address_Root, StringComparison.OrdinalIgnoreCase))
            {
                uri = AuthorizationHelper.GenerateUriFromAddressRequestUri(uri);
            }

            return(GenerateKeyAuthorizationSignature(verb, uri, headers, stringHMACSHA256Helper, clientVersion));
        }
Esempio n. 21
0
        public AuthorizationTokenProviderMasterKey(IComputeHash computeHash)
        {
            this.authKeyHashFunction     = computeHash ?? throw new ArgumentNullException(nameof(computeHash));
            this.enableAuthFailureTraces = new Lazy <bool>(() =>
            {
#if NETSTANDARD20
                // GetEntryAssembly returns null when loaded from native netstandard2.0
                if (System.Reflection.Assembly.GetEntryAssembly() == null)
                {
                    return(false);
                }
#endif
                string enableAuthFailureTracesString = System.Configuration.ConfigurationManager.AppSettings[EnableAuthFailureTracesConfig];
                if (string.IsNullOrEmpty(enableAuthFailureTracesString) ||
                    !bool.TryParse(enableAuthFailureTracesString, out bool enableAuthFailureTracesFlag))
                {
                    return(false);
                }

                return(enableAuthFailureTracesFlag);
            });
        }
Esempio n. 22
0
        // This function is used by Compute
        internal static string GenerateUrlEncodedAuthorizationTokenWithHashCore(
            string verb,
            string resourceId,
            string resourceType,
            INameValueCollection headers,
            IComputeHash stringHMACSHA256Helper,
            out ArrayOwner payload)
        {
            // resourceId can be null for feed-read of /dbs
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(verb));
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException(nameof(resourceType)); // can be empty
            }

            if (stringHMACSHA256Helper == null)
            {
                throw new ArgumentNullException(nameof(stringHMACSHA256Helper));
            }

            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            // Order of the values included in the message payload is a protocol that clients/BE need to follow exactly.
            // More headers can be added in the future.
            // If any of the value is optional, it should still have the placeholder value of ""
            // OperationType -> ResourceType -> ResourceId/OwnerId -> XDate -> Date
            string verbInput         = verb ?? string.Empty;
            string resourceIdInput   = resourceId ?? string.Empty;
            string resourceTypeInput = resourceType ?? string.Empty;

            string authResourceId = AuthorizationHelper.GetAuthorizationResourceIdOrFullName(resourceTypeInput, resourceIdInput);
            int    capacity       = AuthorizationHelper.ComputeMemoryCapacity(verbInput, authResourceId, resourceTypeInput);

            byte[] buffer = ArrayPool <byte> .Shared.Rent(capacity);

            try
            {
                Span <byte> payloadBytes = buffer;
                int         length       = AuthorizationHelper.SerializeMessagePayload(
                    payloadBytes,
                    verbInput,
                    authResourceId,
                    resourceTypeInput,
                    headers);

                payload = new ArrayOwner(ArrayPool <byte> .Shared, new ArraySegment <byte>(buffer, 0, length));
                byte[] hashPayLoad = stringHMACSHA256Helper.ComputeHash(payload.Buffer);
                return(AuthorizationHelper.OptimizedConvertToBase64string(hashPayLoad));
            }
            catch
            {
                ArrayPool <byte> .Shared.Return(buffer);

                throw;
            }
        }