コード例 #1
0
            public override string GetArguments(KeyResolver resolver)
            {
                //TODO: use resolver!
                string s = this.Begin.PrettyPrint(FdbKey.PrettyPrintMode.Begin) + " <= k < " + this.End.PrettyPrint(FdbKey.PrettyPrintMode.End);

                if (this.Iteration > 1)
                {
                    s += ", #" + this.Iteration.ToString();
                }
                if (this.Options != null)
                {
                    if ((this.Options.Limit ?? 0) > 0)
                    {
                        s += ", limit(" + this.Options.Limit + ")";
                    }
                    if (this.Options.Reverse == true)
                    {
                        s += ", reverse";
                    }
                    if (this.Options.Mode.HasValue)
                    {
                        s += ", " + this.Options.Mode;
                    }
                }
                return(s);
            }
コード例 #2
0
 public override string GetResult(KeyResolver resolver)
 {
     if (this.CommitVersion != null)
     {
         return("@" + this.CommitVersion);
     }
     return(base.GetResult(resolver));
 }
コード例 #3
0
 /// <summary>Returns a formatted representation of the results, for logging purpose</summary>
 public virtual string GetResult(KeyResolver resolver)
 {
     if (this.Error != null)
     {
         return(this.Error is FdbException fdbEx
                                     ? "[" + fdbEx.Code.ToString() + "] " + fdbEx.Message
                                     : "[" + this.Error.GetType().Name + "] " + this.Error.Message);
     }
     return(String.Empty);
 }
コード例 #4
0
        // <Main>
        public static async Task Main(string[] _)
        {
            try
            {
                // Read the Cosmos endpointUrl and authorizationKey from configuration.
                // These values are available from the Azure Management Portal on the Cosmos Account Blade under "Keys".
                // Keep these values in a safe and secure location. Together they provide administrative access to your Cosmos account.
                IConfigurationRoot configuration = new ConfigurationBuilder()
                                                   .AddJsonFile("appSettings.json")
                                                   .Build();

                // Get the Source Database name.
                SourceDatabase = configuration["SourceDatabase"];
                if (string.IsNullOrEmpty(SourceDatabase))
                {
                    throw new ArgumentNullException("Please specify a valid database name. ");
                }

                // Get the Source Container name.
                SourceContainer = configuration["SourceContainer"];
                if (string.IsNullOrEmpty(SourceContainer))
                {
                    throw new ArgumentNullException("Please specify a valid container name. ");
                }

                // Get the Destination Container name.
                DestinationContainer = configuration["DestinationContainer"];
                if (string.IsNullOrEmpty(DestinationContainer))
                {
                    throw new ArgumentNullException("Please specify a valid container name. ");
                }

                // Get the Token Credential that is capable of providing an OAuth Token.
                TokenCredential tokenCredential = Program.GetTokenCredential(configuration);
                KeyResolver     keyResolver     = new KeyResolver(tokenCredential);

                Program.client = Program.CreateClientInstance(configuration, keyResolver);

                await Program.CreateAndRunReEncryptionTasks();
            }
            catch (CosmosException cosmosException)
            {
                Console.WriteLine(cosmosException.ToString());
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                Console.WriteLine("Message: {0} Error: {1}", baseException.Message, e);
            }
            finally
            {
                Console.WriteLine("ReEncryption activity has been stopped successfully.");
                Console.ReadKey();
            }
        }
コード例 #5
0
        public void ShouldRequireGetPermissionForSecret()
        {
            // Test for https://github.com/Azure/azure-sdk-for-net/issues/11574
            MockTransport transport = new MockTransport(request => new MockResponse((int)HttpStatusCode.Forbidden, nameof(HttpStatusCode.Forbidden)));

            KeyResolver resolver = GetResolver(transport);

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(() => resolver.ResolveAsync(new Uri("https://mock.vault.azure.net/secrets/mock-secret")));

            Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.Status);
        }
コード例 #6
0
 public override string GetResult(KeyResolver resolver)
 {
     if (this.Result.HasValue)
     {
         if (this.Result.Value == null)
         {
             return("<null>");
         }
     }
     return(base.GetResult(resolver));
 }
コード例 #7
0
            public override string ToString(KeyResolver resolver)
            {
                resolver = resolver ?? KeyResolver.Default;
                var sb = new StringBuilder();

                if (this.Snapshot)
                {
                    sb.Append("Snapshot.");
                }
                sb.Append("Atomic_").Append(this.Mutation.ToString()).Append(' ').Append(resolver.Resolve(this.Key)).Append(", <").Append(this.Param.ToHexaString(' ')).Append('>');
                return(sb.ToString());
            }
コード例 #8
0
        public async Task ShouldNotRequireGetPermissionForKey()
        {
            // Test for https://github.com/Azure/azure-sdk-for-net/issues/11574
            MockTransport transport = new MockTransport(request => new MockResponse((int)HttpStatusCode.Forbidden, nameof(HttpStatusCode.Forbidden)));

            KeyResolver        resolver = GetResolver(transport);
            CryptographyClient client   = await resolver.ResolveAsync(new Uri("https://mock.vault.azure.net/keys/mock-key"));

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(() => client.UnwrapKeyAsync(KeyWrapAlgorithm.A256KW, new byte[] { 0, 1, 2, 3 }));

            Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.Status);
        }
コード例 #9
0
 public override string GetArguments(KeyResolver resolver)
 {
     if (this.IntValue.HasValue)
     {
         return($"{this.Option.ToString()} = {this.IntValue.Value}");
     }
     if (this.StringValue != null)
     {
         return($"{this.Option.ToString()} = '{this.StringValue}'");
     }
     return(this.Option.ToString());
 }
コード例 #10
0
 public override string GetResult(KeyResolver resolver)
 {
     if (this.Result.HasValue)
     {
         string s = $"{this.Result.Value.Count:N0} result(s)";
         if (this.Result.Value.HasMore)
         {
             s += ", has_more";
         }
         return(s);
     }
     return(base.GetResult(resolver));
 }
コード例 #11
0
 public override string GetResult(KeyResolver resolver)
 {
     if (this.Result.HasValue)
     {
         string s = String.Format("{0} result(s)", this.Result.Value.Count);
         if (this.Result.Value.HasMore)
         {
             s += ", has_more";
         }
         return(s);
     }
     return(base.GetResult(resolver));
 }
コード例 #12
0
        public async Task GetEncryptionKeyAsync_PublicRSA_NoKeysFound_Throws()
        {
            // Arrange
            var keyResolver = new KeyResolver(
                new List <JsonWebKey>(),
                this.publicOctJwksService.Object,                  // Get Oct key
                this.cacheDurationSeconds);

            // Act
            var jsonWebKey = await keyResolver.GetEncryptionKeyAsync();

            // Assert
            // EncryptionException: "Unable to retrieve public EC or RSA key from JWK store.")]
        }
コード例 #13
0
            public override string GetArguments(KeyResolver resolver)
            {
                string s = String.Concat("[", this.Keys.Length.ToString(), "] {");

                if (this.Keys.Length > 0)
                {
                    s += resolver.Resolve(this.Keys[0]);
                }
                if (this.Keys.Length > 1)
                {
                    s += " ... " + resolver.Resolve(this.Keys[this.Keys.Length - 1]);
                }
                return(s + " }");
            }
        public async Task <WizardViewResponse> CreateWizardViewAsync(ViewedWizard model)
        {
            var validationResult = _validatorLocator.Validate <ViewedWizardValidator>(model);

            if (!validationResult.IsValid)
            {
                _logger.Error("Validation failed while attempting to create a ViewedWizard resource.");
                throw new ValidationFailedException(validationResult.Errors);
            }

            try
            {
                var existingWizards = await RetrieveViewedWizardsAsync(model.UserId);

                var wizardsOfType = existingWizards.Where(w => w.WizardType == model.WizardType).ToList();

                if (wizardsOfType.Count > 0)
                {
                    return(new WizardViewResponse
                    {
                        WizardViews = wizardsOfType,
                        ResultMessage = $"Wizard(s) already viewed by user '{model.UserId}'.",
                        ResultCode = ResultCode.RecordAlreadyExists
                    });
                }

                var viewedWizard = await _dbService.CreateViewedWizardAsync(model);

                var key = KeyResolver.ViewedWizards(model.UserId);
                await _cache.KeyDeleteAsync(key, CacheCommandOptions.FireAndForget);

                return(new WizardViewResponse
                {
                    WizardViews = new List <ViewedWizard> {
                        viewedWizard
                    },
                    ResultMessage = $"Wizard marked as viewed successfully for user '{model.UserId}'.",
                    ResultCode = ResultCode.Success
                });
            }
            catch (Exception ex)
            {
                _logger.Error("A ViewedWizard resource has not been created due to an unknown error.", ex);
                return(new WizardViewResponse()
                {
                    ResultMessage = ex.ToString(),
                    ResultCode = ResultCode.Failed
                });
            }
        }
コード例 #15
0
 public override string GetArguments(KeyResolver resolver)
 {
     if (this.IntValue.HasValue)
     {
         return(String.Format("{0} = {1}", this.Option.ToString(), this.IntValue.Value));
     }
     else if (this.StringValue != null)
     {
         return(String.Format("{0} = '{1}'", this.Option.ToString(), this.StringValue));
     }
     else
     {
         return(this.Option.ToString());
     }
 }
コード例 #16
0
 public override string GetResult(KeyResolver resolver)
 {
     if (this.Result.HasValue)
     {
         if (this.Result.Value.IsNull)
         {
             return("not_found");
         }
         if (this.Result.Value.IsEmpty)
         {
             return("''");
         }
     }
     return(base.GetResult(resolver));
 }
        private async Task <List <ViewedWizard> > RetrieveViewedWizardsAsync(Guid userId)
        {
            var key = KeyResolver.ViewedWizards(userId);

            if (_cache.KeyExists(key))
            {
                return(await _cache.ItemGetAsync <List <ViewedWizard> >(key));
            }

            var wizardViews = await _dbService.GetViewedWizardsAsync(userId);

            await _cache.ItemSetAsync(key, wizardViews, _expirationTime);

            return(wizardViews);
        }
コード例 #18
0
            public override string GetArguments(KeyResolver resolver)
            {
                string s = String.Concat("[", this.Selectors.Length.ToString(), "] {");

                //TODO: use resolver!
                if (this.Selectors.Length > 0)
                {
                    s += this.Selectors[0].ToString();
                }
                if (this.Selectors.Length > 1)
                {
                    s += " ... " + this.Selectors[this.Selectors.Length - 1].ToString();
                }
                return(s + " }");
            }
コード例 #19
0
        public async Task TestKeyResolverReturnsKey()
        {
            var mockKeyStoreClient = new Mock <IKeyStoreClient>();

            mockKeyStoreClient.Setup(x => x.Keys.GetWithHttpMessagesAsync("keyId", null, It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpOperationResponse <object>
            {
                Body = new KeyCreatedResponse("testBody", "keyId")
            });

            var keyResolver = new KeyResolver(mockKeyStoreClient.Object);
            var key         = await keyResolver.ResolveKey("keyId");

            Assert.AreEqual("testBody", key);
        }
コード例 #20
0
        public void TestKeyResolverThrowsWhenKeyIsNotFound()
        {
            var mockKeyStoreClient = new Mock <IKeyStoreClient>();

            mockKeyStoreClient.Setup(x => x.Keys.GetWithHttpMessagesAsync("keyId", null, It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpOperationResponse <object>
            {
                Body = new ProblemDetails
                {
                    Status = StatusCodes.Status404NotFound
                }
            });

            var keyResolver = new KeyResolver(mockKeyStoreClient.Object);

            Assert.ThrowsAsync <KeyNotFoundException>(() => keyResolver.ResolveKey("keyId"), "key: 'keyId' not found");
        }
コード例 #21
0
        // <Main>
        public static async Task Main(string[] _)
        {
            try
            {
                // Read the Cosmos endpointUrl and authorizationKey from configuration.
                // These values are available from the Azure Management Portal on the Cosmos Account Blade under "Keys".
                // Keep these values in a safe and secure location. Together they provide administrative access to your Cosmos account.
                IConfigurationRoot configuration = new ConfigurationBuilder()
                                                   .AddJsonFile("appSettings.json")
                                                   .Build();

                // Get the Akv Master Key Path.
                MasterKeyUrl = configuration["MasterKeyUrl"];
                if (string.IsNullOrEmpty(MasterKeyUrl))
                {
                    throw new ArgumentNullException("Please specify a valid Azure Key Path in the appSettings.json");
                }

                // Get the Token Credential that is capable of providing an OAuth Token.
                TokenCredential tokenCredential = GetTokenCredential(configuration);
                KeyResolver     keyResolver     = new KeyResolver(tokenCredential);

                Program.client = Program.CreateClientInstance(configuration, keyResolver);

                await Program.AdminSetupAsync(client);

                await Program.RunDemoAsync();
            }
            catch (CosmosException cre)
            {
                Console.WriteLine(cre.ToString());
            }
            catch (Exception e)
            {
                Exception baseException = e.GetBaseException();
                Console.WriteLine("Message: {0} Error: {1}", baseException.Message, e);
            }
            finally
            {
                Console.WriteLine("End of demo, press any key to exit.");
                Console.ReadKey();
                await Program.CleanupAsync();
            }
        }
コード例 #22
0
            public override string GetResult(KeyResolver resolver)
            {
                if (!this.Result.HasValue)
                {
                    return(base.GetResult(resolver));
                }
                var    res = this.Result.Value;
                string s   = String.Concat("[", res.Length.ToString(), "] {");

                if (res.Length > 0)
                {
                    s += res[0].ToString("P");
                }
                if (res.Length > 1)
                {
                    s += " ... " + res[res.Length - 1].ToString("P");
                }
                return(s + " }");
            }
コード例 #23
0
        public async Task <ActionResult> Index(string submitButton, string encryptedJwe, EncryptedJweViewModel encryptedJweViewModel)
        {
            try
            {
                var jwksUrl = ConfigurationManager.AppSettings["JwksUrl"];
                var cacheDurationSeconds = long.Parse(ConfigurationManager.AppSettings["CacheDurationSeconds"]);

                var privateJsonWebKeyList = new List <JsonWebKey>();
                var privateRsaJson        = System.IO.File.ReadAllText(AppDomain.CurrentDomain.RelativeSearchPath + @"\TestData\RsaPrivate.json");
                var privateRsaJsonWebKey  = JsonConvert.DeserializeObject <JsonWebKey>(privateRsaJson);
                privateJsonWebKeyList.Add(privateRsaJsonWebKey);

                var httpClient = new HttpClient();

                var jwksService = new JwksService(httpClient, jwksUrl);
                var keyResolver = new KeyResolver(privateJsonWebKeyList, jwksService, cacheDurationSeconds);

                var loggerFactory = new LoggerFactory();
                var logger        = LoggerFactoryExtensions.CreateLogger <Encryption>(loggerFactory);
                var encryption    = new Encryption(keyResolver, logger);

                if (submitButton == "Encrypt")
                {
                    encryptedJweViewModel.EncryptedJwe = await encryption.EncryptAsync(encryptedJweViewModel.PhoneNumber);
                }
                else if (submitButton == "Decrypt")
                {
                    encryptedJweViewModel.DecryptedPhoneNumber = await encryption.DecryptAsync(encryptedJwe);
                }
            }
            catch (Exception ex)
            {
                encryptedJweViewModel.DecryptedPhoneNumber = string.Empty;
                encryptedJweViewModel.ErrorMessage         = ex.Message;
                if (ex.InnerException != null)
                {
                    encryptedJweViewModel.ErrorMessage += " " + ex.InnerException.Message;
                }
            }

            return(View(encryptedJweViewModel));
        }
コード例 #24
0
        public async Task GetEncryptionKeyAsync_PublicRSA_TimerExpires_Success()
        {
            // Arrange
            int cacheDurationSeconds = 2;
            var keyResolver          = new KeyResolver(
                new List <JsonWebKey>(),
                this.publicRsaJwksService.Object,
                cacheDurationSeconds);

            // Act
            var jsonWebKey = await keyResolver.GetEncryptionKeyAsync();             // Initial call to JWKS

            Thread.Sleep(2050);
            jsonWebKey = await keyResolver.GetEncryptionKeyAsync();                 // Timer expired. Call JWKS

            Thread.Sleep(1);
            jsonWebKey = await keyResolver.GetEncryptionKeyAsync();                 // Timer not expired. Use cache

            // Assert
            this.publicRsaJwksService.Verify(m => m.GetJsonWebKeyListAsync(), Times.Exactly(2));
        }
コード例 #25
0
            public virtual string ToString(KeyResolver resolver)
            {
                resolver = resolver ?? KeyResolver.Default;
                var arg = this.GetArguments(resolver);
                var res = this.GetResult(resolver);
                var sb  = new StringBuilder(255);

                if (this.Snapshot)
                {
                    sb.Append("Snapshot.");
                }
                sb.Append(this.Op.ToString());
                if (!string.IsNullOrEmpty(arg))
                {
                    sb.Append(' ').Append(arg);
                }
                if (!string.IsNullOrEmpty(res))
                {
                    sb.Append(" => ").Append(res);
                }
                return(sb.ToString());
            }
コード例 #26
0
        public async Task GetEncryptionKeyAsync_PublicRSA_Success()
        {
            // Arrange
            var keyResolver = new KeyResolver(
                new List <JsonWebKey>(),
                this.publicRsaJwksService.Object,
                this.cacheDurationSeconds);

            // Act
            var jsonWebKey = await keyResolver.GetEncryptionKeyAsync();

            // Assert
            Assert.IsNotNull(jsonWebKey);
            Assert.IsFalse(jsonWebKey.HasPrivateKey);
            Assert.AreEqual("RSA", jsonWebKey.Kty);
            Assert.AreEqual(false, jsonWebKey.HasPrivateKey);
            Assert.AreEqual("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", jsonWebKey.N);
            Assert.AreEqual("AQAB", jsonWebKey.E);
            Assert.AreEqual("RS256", jsonWebKey.Alg);
            Assert.AreEqual("3072F4C6-193D-481B-BDD2-0F09F5A7DDFB", jsonWebKey.Kid);
            Assert.AreEqual(2048, jsonWebKey.KeySize);
        }
コード例 #27
0
        public async Task GetEncryptionKeyAsync_PublicEC_Success()
        {
            // Arrange
            var keyResolver = new KeyResolver(
                new List <JsonWebKey>(),
                this.publicEcJwksService.Object,
                this.cacheDurationSeconds);

            // Act
            var jsonWebKey = await keyResolver.GetEncryptionKeyAsync();

            // Assert
            Assert.IsNotNull(jsonWebKey);
            Assert.IsFalse(jsonWebKey.HasPrivateKey);
            Assert.AreEqual("EC", jsonWebKey.Kty);
            Assert.AreEqual(false, jsonWebKey.HasPrivateKey);
            Assert.AreEqual("P-256", jsonWebKey.Crv);
            Assert.AreEqual("MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", jsonWebKey.X);
            Assert.AreEqual("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", jsonWebKey.Y);
            Assert.AreEqual("enc", jsonWebKey.Use);
            Assert.AreEqual("B7B4F5C7-2B46-4F54-A81A-51E8A886B094", jsonWebKey.Kid);
            Assert.AreEqual(256, jsonWebKey.KeySize);
        }
コード例 #28
0
        public async Task ShouldNotAttemptSubsequentDownload()
        {
            // Test for https://github.com/Azure/azure-sdk-for-net/issues/25254
            MockTransport transport = new((MockRequest request) =>
            {
                if (request.Method == RequestMethod.Get)
                {
                    // Any attempt to get the key must return 403 Forbidden.
                    return(new MockResponse((int)HttpStatusCode.Forbidden, nameof(HttpStatusCode.Forbidden)));
                }

                return(new MockResponse((int)HttpStatusCode.OK).WithContent(@"{""kid"":""https://mock.vault.azure.net/keys/mock-key/mock-version"",""value"":""dGVzdA""}"));
            });

            KeyResolver resolver = GetResolver(transport);

            // This would otherwise throw if "keys/get" permission was denied and #11574 was not resolved.
            CryptographyClient client = await resolver.ResolveAsync(new Uri("https://mock.vault.azure.net/keys/mock-key"));

            WrapResult result = await client.WrapKeyAsync(KeyWrapAlgorithm.A256KW, new byte[] { 0, 1, 2, 3 });

            Assert.AreEqual("https://mock.vault.azure.net/keys/mock-key/mock-version", result.KeyId);
        }
コード例 #29
0
        public string GetTimingsReport(bool showCommands = false, KeyResolver keyResolver = null)
        {
            var culture = CultureInfo.InvariantCulture;

            var      sb       = new StringBuilder();
            TimeSpan duration = this.TotalDuration;
            // ideal range is between 10 and 80 chars
            double scale = 0.0005d;
            int    width;
            bool   flag     = false;
            int    maxWidth = showCommands ? 80 : 160;

            while ((width = (int)(duration.TotalSeconds / scale)) > maxWidth)
            {
                if (flag)
                {
                    scale *= 5d;
                }
                else
                {
                    scale *= 2d;
                }
                flag = !flag;
            }

            var cmds = this.Commands.ToArray();

            // Header
            sb.AppendFormat(culture, "Transaction #{0} ({4}, {1} operations, '#' = {2:N1} ms, started {3}Z", this.Id, cmds.Length, (scale * 1000d), this.StartedUtc.TimeOfDay, this.IsReadOnly ? "read-only" : "read/write");
            if (this.StoppedUtc.HasValue)
            {
                sb.AppendFormat(culture, ", ended {0}Z)", this.StoppedUtc.Value.TimeOfDay);
            }
            else
            {
                sb.Append(", did not finish");
            }
            sb.AppendLine();
            if (cmds.Length > 0)
            {
                var bar = new string('─', width + 2);
                sb.AppendLine(String.Format(culture, "┌  oper. ┬{0}┬──── start ──── end ── duration ──┬─ sent  recv ┐", bar));

                // look for the timestamps of the first and last commands
                var first = TimeSpan.Zero;
                var last  = duration;
                for (int i = 0; i < cmds.Length; i++)
                {
                    if (cmds[i].Op == Operation.Log)
                    {
                        continue;
                    }
                    first = cmds[i].StartOffset;
                    break;
                }
                for (int i = cmds.Length - 1; i >= 0; i--)
                {
                    if (cmds[i].Op == Operation.Log)
                    {
                        continue;
                    }
                    if (cmds[i].EndOffset.HasValue)
                    {
                        duration = cmds[i].EndOffset.Value;
                    }
                    break;
                }
                duration -= first;

                int  step = -1;
                bool previousWasOnError = false;
                int  attempts           = 1;
                int  charsToSkip        = 0;
                foreach (var cmd in cmds)
                {
                    if (previousWasOnError)
                    {
                        sb.AppendLine(String.Format(culture, "├────────┼{0}┼──────────────────────────────────┼─────────────┤ == Attempt #{1:N0} ==", bar, (++attempts)));
                    }

                    long   ticks = cmd.Duration.Ticks;
                    string w     = GetFancyGraph(width, (cmd.StartOffset - first).Ticks, ticks, duration.Ticks, charsToSkip);

                    if (ticks > 0)
                    {
                        sb.AppendFormat(
                            culture,
                            "│{6}{1,-3:##0}{10}{0,2}{7}│ {2} │ T+{3,7:##0.000} ~ {4,7:##0.000} ({5,7:##,##0} µs) │ {8,5} {9,5} │ {11}",
                            /* 0 */ cmd.ShortName,
                            /* 1 */ cmd.Step,
                            /* 2 */ w,
                            /* 3 */ cmd.StartOffset.TotalMilliseconds,
                            /* 4 */ (cmd.EndOffset ?? TimeSpan.Zero).TotalMilliseconds,
                            /* 5 */ ticks / 10.0,
                            /* 6 */ cmd.Step == step ? ":" : " ",
                            /* 7 */ ticks >= TimeSpan.TicksPerMillisecond * 10 ? '*' : ticks >= TimeSpan.TicksPerMillisecond ? '°' : ' ',
                            /* 8 */ cmd.ArgumentBytes,
                            /* 9 */ cmd.ResultBytes,
                            /* 10 */ cmd.Error != null ? "!" : " ",
                            /* 11 */ showCommands ? cmd.ToString(keyResolver) : String.Empty
                            );
                    }
                    else
                    {                     // annotation
                        sb.AppendFormat(
                            culture,
                            "│{0}{1,-3:##0}{2}{3,2}{4}│ {5} │ T+{6,7:##0.000}                        │     -     - │ {7}",
                            /* 0 */ cmd.Step == step ? ":" : " ",
                            /* 1 */ cmd.Step,
                            /* 2 */ cmd.Error != null ? "!" : " ",
                            /* 3 */ cmd.ShortName,
                            /* 4 */ ticks >= TimeSpan.TicksPerMillisecond * 10 ? '*' : ticks >= TimeSpan.TicksPerMillisecond ? '°' : ' ',
                            /* 5 */ w,
                            /* 6 */ cmd.StartOffset.TotalMilliseconds,
                            /* 7 */ showCommands ? cmd.ToString(keyResolver) : String.Empty
                            );
                    }

                    if (showCommands && cmd.CallSite != null)
                    {
                        var f = GetFirstInterestingStackFrame(cmd.CallSite);
                        if (f != null)
                        {
                            var    m    = f.GetMethod();
                            string name = GetUserFriendlyMethodName(m);
                            sb.Append(" // ").Append(name);
                            string fn = f.GetFileName();
                            if (fn != null)
                            {
                                sb.AppendFormat(culture, " at {0}:{1}", fn, f.GetFileLineNumber());
                            }
                        }
                    }

                    sb.AppendLine();

                    previousWasOnError = cmd.Op == Operation.OnError;
                    if (previousWasOnError)
                    {
                        charsToSkip = (int)Math.Floor(1.0d * width * (cmd.EndOffset ?? TimeSpan.Zero).Ticks / duration.Ticks);
                    }

                    step = cmd.Step;
                }

                sb.AppendLine(String.Format(culture, "└────────┴{0}┴──────────────────────────────────┴─────────────┘", bar));

                // Footer
                if (this.Completed)
                {
                    sb.Append("> ");
                    flag = false;
                    if (this.ReadSize > 0)
                    {
                        sb.AppendFormat(culture, "Read {0:N0} bytes", this.ReadSize);
                        flag = true;
                    }
                    if (this.CommitSize > 0)
                    {
                        if (flag)
                        {
                            sb.Append(" and ");
                        }
                        sb.AppendFormat(culture, "Committed {0:N0} bytes", this.CommitSize);
                        flag = true;
                    }
                    if (!flag)
                    {
                        sb.Append("Completed");
                    }
                    sb.AppendLine(String.Format(culture, " in {0:N3} ms and {1:N0} attempt(s)", this.TotalDuration.TotalMilliseconds, attempts));
                }
            }
            else
            {             // empty transaction
                sb.AppendLine(String.Format(culture, "> Completed after {0:N3} ms without performing any operation", this.TotalDuration.TotalMilliseconds));
            }
            return(sb.ToString());
        }
コード例 #30
0
		public Modem(KeyResolver<IDeviceState, DeviceState> states)
		{
			_states = states; 
			SwitchOn();
		} 
コード例 #31
0
        public override void ExecuteCmdlet()
        {
            if (ParameterSetName.Equals(ParentObjectParameterSet, StringComparison.Ordinal))
            {
                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(SqlDatabaseObject.Id);
                ResourceGroupName = resourceIdentifier.ResourceGroupName;
                DatabaseName      = resourceIdentifier.ResourceName;
                AccountName       = ResourceIdentifierExtensions.GetDatabaseAccountName(resourceIdentifier);
            }

            KeyWrapMetadata encryptionKeyWrapMetadata;

            if (KeyWrapMetadata != null)
            {
                encryptionKeyWrapMetadata = PSSqlKeyWrapMetadata.ToSDKModel(KeyWrapMetadata);
            }
            else
            {
                throw new ArgumentException("KeyWrapMetadata cannot be null");
            }

            if (!string.Equals(EncryptionAlgorithmName, "AEAD_AES_256_CBC_HMAC_SHA256"))
            {
                throw new ArgumentException($"Invalid encryption algorithm '{EncryptionAlgorithmName}' passed. Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            if (!string.Equals(encryptionKeyWrapMetadata.Algorithm, "RSA-OAEP"))
            {
                throw new ArgumentException($"Invalid key wrap algorithm '{encryptionKeyWrapMetadata.Algorithm}' passed. Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            if (string.Equals(encryptionKeyWrapMetadata.Type, "AZURE_KEY_VAULT") && KeyEncryptionKeyResolver == null)
            {
                // get the token credential for key vault audience.
                TokenCredential tokenCredential = new CosmosDBSessionCredential(DefaultContext, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);

                KeyEncryptionKeyResolver = new KeyResolver(tokenCredential);
            }
            else
            {
                if (KeyEncryptionKeyResolver == null)
                {
                    throw new ArgumentException("KeyEncryptionKeyResolver cannot be null.");
                }
            }

            byte[] plainTextDataEncryptionKey = new byte[32];
            RandomNumberGenerator rng         = RandomNumberGenerator.Create();

            rng.GetBytes(plainTextDataEncryptionKey);


            byte[] wrappedDataEncryptionKey = KeyEncryptionKeyResolver.Resolve(encryptionKeyWrapMetadata.Value)
                                              .WrapKey(encryptionKeyWrapMetadata.Algorithm, plainTextDataEncryptionKey);

            ClientEncryptionKeyResource clientEncryptionKeyResource = new ClientEncryptionKeyResource
            {
                Id = Name,
                EncryptionAlgorithm      = EncryptionAlgorithmName,
                KeyWrapMetadata          = encryptionKeyWrapMetadata,
                WrappedDataEncryptionKey = wrappedDataEncryptionKey
            };

            ClientEncryptionKeyCreateUpdateParameters clientEncryptionKeyCreateUpdateParameters = new ClientEncryptionKeyCreateUpdateParameters
            {
                Resource = clientEncryptionKeyResource
            };

            if (ShouldProcess(Name, "Creating a new CosmosDB Client Encryption Key"))
            {
                // FIXME : This requires a backend fix since its not honoring If-None-Match header with a *. This is required to prevent a race which might result in
                // accidental replace of a key. This is a best effort approach to check for resource conflict.
                ClientEncryptionKeyGetResults readClientEncryptionKeyGetResults = null;
                try
                {
                    readClientEncryptionKeyGetResults = CosmosDBManagementClient.SqlResources.GetClientEncryptionKey(ResourceGroupName, AccountName, DatabaseName, Name);
                }
                catch (CloudException e)
                {
                    if (e.Response.StatusCode != System.Net.HttpStatusCode.NotFound)
                    {
                        throw;
                    }
                }

                if (readClientEncryptionKeyGetResults != null)
                {
                    throw new ConflictingResourceException(message: string.Format(ExceptionMessage.Conflict, Name));
                }

                ClientEncryptionKeyGetResults clientEncryptionKeyGetResults = CosmosDBManagementClient.SqlResources.CreateUpdateClientEncryptionKeyWithHttpMessagesAsync(ResourceGroupName, AccountName, DatabaseName, Name, clientEncryptionKeyCreateUpdateParameters).GetAwaiter().GetResult().Body;
                WriteObject(new PSSqlClientEncryptionKeyGetResults(clientEncryptionKeyGetResults));
            }
        }
コード例 #32
0
		public string GetTimingsReport(bool showCommands = false, KeyResolver keyResolver = null)
		{
			var culture = CultureInfo.InvariantCulture;

			var sb = new StringBuilder();
			TimeSpan duration = this.TotalDuration;
			// ideal range is between 10 and 80 chars
			double scale = 0.0005d;
			int width;
			bool flag = false;
			int maxWidth = showCommands ? 80 : 160;
			while ((width = (int)(duration.TotalSeconds / scale)) > maxWidth)
			{
				if (flag) scale *= 5d; else scale *= 2d;
				flag = !flag;
			}

			var cmds = this.Commands.ToArray();

			// Header
			sb.AppendFormat(culture, "Transaction #{0} ({4}, {1} operations, '#' = {2:N1} ms, started {3}Z", this.Id, cmds.Length, (scale * 1000d), this.StartedUtc.TimeOfDay, this.IsReadOnly ? "read-only" : "read/write");
			if (this.StoppedUtc.HasValue)
				sb.AppendFormat(culture, ", ended {0}Z)", this.StoppedUtc.Value.TimeOfDay);
			else
				sb.Append(", did not finish");
			sb.AppendLine();
			if (cmds.Length > 0)
			{
				var bar = new string('─', width + 2);
				sb.AppendLine(String.Format(culture, "┌  oper. ┬{0}┬──── start ──── end ── duration ──┬─ sent  recv ┐", bar));

				// look for the timestamps of the first and last commands
				var first = TimeSpan.Zero;
				var last = duration;
				for (int i = 0; i < cmds.Length;i++)
				{
					if (cmds[i].Op == Operation.Log) continue;
					first = cmds[i].StartOffset;
					break;
				}
				for(int i = cmds.Length - 1; i >= 0; i--)
				{
					if (cmds[i].Op == Operation.Log) continue;
					if (cmds[i].EndOffset.HasValue) duration = cmds[i].EndOffset.Value;
					break;
				}
				duration -= first;

				int step = -1;
				bool previousWasOnError = false;
				int attempts = 1;
				int charsToSkip = 0;
				foreach (var cmd in cmds)
				{
					if (previousWasOnError)
					{
						sb.AppendLine(String.Format(culture, "├────────┼{0}┼──────────────────────────────────┼─────────────┤ == Attempt #{1:N0} ==", bar, (++attempts)));
					}

					long ticks = cmd.Duration.Ticks;
					string w = GetFancyGraph(width, (cmd.StartOffset - first).Ticks, ticks, duration.Ticks, charsToSkip);

					if (ticks > 0)
					{
						sb.AppendFormat(
							culture,
							"│{6}{1,-3:##0}{10}{0,2}{7}│ {2} │ T+{3,7:##0.000} ~ {4,7:##0.000} ({5,7:##,##0} µs) │ {8,5} {9,5} │ {11}",
							/* 0 */ cmd.ShortName,
							/* 1 */ cmd.Step,
							/* 2 */ w,
							/* 3 */ cmd.StartOffset.TotalMilliseconds,
							/* 4 */ (cmd.EndOffset ?? TimeSpan.Zero).TotalMilliseconds,
							/* 5 */ ticks / 10.0,
							/* 6 */ cmd.Step == step ? ":" : " ",
							/* 7 */ ticks >= TimeSpan.TicksPerMillisecond * 10 ? '*' : ticks >= TimeSpan.TicksPerMillisecond ? '°' : ' ',
							/* 8 */ cmd.ArgumentBytes,
							/* 9 */ cmd.ResultBytes,
							/* 10 */ cmd.Error != null ? "!" : " ",
							/* 11 */ showCommands ? cmd.ToString(keyResolver) : String.Empty
						);
					}
					else
					{ // annotation
						sb.AppendFormat(
							culture,
							"│{0}{1,-3:##0}{2}{3,2}{4}│ {5} │ T+{6,7:##0.000}                        │     -     - │ {7}",
							/* 0 */ cmd.Step == step ? ":" : " ",
							/* 1 */ cmd.Step,
							/* 2 */ cmd.Error != null ? "!" : " ",
							/* 3 */ cmd.ShortName,
							/* 4 */ ticks >= TimeSpan.TicksPerMillisecond * 10 ? '*' : ticks >= TimeSpan.TicksPerMillisecond ? '°' : ' ',
							/* 5 */ w,
							/* 6 */ cmd.StartOffset.TotalMilliseconds,
							/* 7 */ showCommands ? cmd.ToString(keyResolver) : String.Empty
						);
					}

					if (showCommands && cmd.CallSite != null)
					{
						var f = GetFirstInterestingStackFrame(cmd.CallSite);
						if (f != null)
						{
							var m = f.GetMethod();
							string name = GetUserFriendlyMethodName(m);
							sb.Append(" // ").Append(name);
							string fn = f.GetFileName();
							if (fn != null) sb.AppendFormat(culture, " at {0}:{1}", fn, f.GetFileLineNumber());
						}
					}

					sb.AppendLine();

					previousWasOnError = cmd.Op == Operation.OnError;
					if (previousWasOnError)
					{
						charsToSkip = (int)Math.Floor(1.0d * width * (cmd.EndOffset ?? TimeSpan.Zero).Ticks / duration.Ticks);
					}

					step = cmd.Step;
				}

				sb.AppendLine(String.Format(culture, "└────────┴{0}┴──────────────────────────────────┴─────────────┘", bar));

				// Footer
				if (this.Completed)
				{
					sb.Append("> ");
					flag = false;
					if (this.ReadSize > 0)
					{
						sb.AppendFormat(culture, "Read {0:N0} bytes", this.ReadSize);
						flag = true;
					}
					if (this.CommitSize > 0)
					{
						if (flag) sb.Append(" and ");
						sb.AppendFormat(culture, "Committed {0:N0} bytes", this.CommitSize);
						flag = true;
					}
					if (!flag) sb.Append("Completed");
					sb.AppendLine(String.Format(culture, " in {0:N3} ms and {1:N0} attempt(s)", this.TotalDuration.TotalMilliseconds, attempts));
				}
			}
			else
			{ // empty transaction
				sb.AppendLine(String.Format(culture, "> Completed after {0:N3} ms without performing any operation", this.TotalDuration.TotalMilliseconds));
			}
			return sb.ToString();
		}