예제 #1
0
        private static async Task Import(
            SecretService secretService, string csvFile)
        {
            var csvImportService = new CsvImportService();
            var fi      = new FileInfo(csvFile);
            var secrets = csvImportService.Load(fi);
            var count   = 0;

            try
            {
                foreach (var secret in secrets)
                {
                    await secretService.StoreAsync(secret);

                    count++;
                    Console.WriteLine($"\tAdded {secret.Name}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    $"Error after importing {count} records! {ex}");
                Console.ReadLine();
            }
            Console.WriteLine($"\tAdded {count} secrets");
        }
예제 #2
0
        public async Task ShouldReturnSingleSecretInfoWhenGetSecretCalled()
        {
            //Given
            const string secretName = "api";
            var          spec       = new SecretSpec {
                Name = secretName
            };

            _swarmClient.GetSecrets().Returns(x => {
                return(Task.FromResult <IEnumerable <Secret> >(new [] { _any.Create <Secret>(),
                                                                        _any.Build <Secret>().With(t => t.Spec, spec).Create() }));
            });
            var secretService    = new SecretService(_swarmClient, _loggerFactory);
            var secretController = new SecretController(secretService);

            //When
            var response = await secretController.GetSecret(secretName);

            var jsonResult = response as JsonResult;
            var value      = jsonResult?.Value as Secret;

            //Then
            Assert.NotNull(jsonResult);
            Assert.NotNull(value);
            Assert.Equal(200, jsonResult.StatusCode);
        }
예제 #3
0
        private static async Task Delete(
            SecretService service, string name)
        {
            await service.DeleteAsync(name);

            Console.WriteLine($"\tDeleted {name}");
        }
예제 #4
0
        public async Task StoreSecretsThenListTheirNamesSorted()
        {
            var testDataFileLocation = $"{DateTime.Now.ToFileTime()}.json";
            var service = new SecretService(
                "testPassword", testDataFileLocation);

            var testSecret = GetTestSecret("test2");

            await service.StoreAsync(testSecret);

            testSecret = GetTestSecret("test1");

            await service.StoreAsync(testSecret);

            var list = await service.ListAsync();

            Assert.IsNotNull(list);
            Assert.AreEqual(2, list.Count());
            Assert.AreEqual("test1", list.FirstOrDefault());

            var testDataFile = new FileInfo(testDataFileLocation);

            if (testDataFile.Exists)
            {
                testDataFile.Delete();
            }
        }
예제 #5
0
        private static async Task Show(
            SecretService service, string name)
        {
            var value = await service.ShowAsync(name);

            Console.WriteLine(value);
        }
예제 #6
0
        public async Task StoreSecretsThenFilterListOnSearch()
        {
            var testDataFileLocation = $"{DateTime.Now.ToFileTime()}.json";
            var service = new SecretService(
                "testPassword", testDataFileLocation);

            var testSecret = GetTestSecret("test2");
            await service.StoreAsync(testSecret);

            testSecret = GetTestSecret("test1");
            await service.StoreAsync(testSecret);

            testSecret = GetTestSecret("anothertest");
            await service.StoreAsync(testSecret);

            testSecret = GetTestSecret("shouldntfindthis");
            await service.StoreAsync(testSecret);

            var list = await service.SearchAsync("test");

            Assert.IsNotNull(list);
            Assert.AreEqual(3, list.Count());
            Assert.AreEqual("anothertest", list.FirstOrDefault());

            var testDataFile = new FileInfo(testDataFileLocation);

            if (testDataFile.Exists)
            {
                testDataFile.Delete();
            }
        }
예제 #7
0
        public async Task StoreSecretThenShowIt()
        {
            var testDataFileLocation = $"{DateTime.Now.ToFileTime()}.json";
            var service = new SecretService(
                "testPassword", testDataFileLocation);

            var testSecret = GetTestSecret("test");

            await service.StoreAsync(testSecret);

            var result = await service.ShowAsync(testSecret.Name);

            Assert.AreEqual(testSecret.Name, result.Name);
            Assert.AreEqual(testSecret.Username, result.Username);
            Assert.AreEqual(testSecret.Host, result.Host);
            Assert.AreEqual(testSecret.Note, result.Note);
            Assert.AreEqual(testSecret.Tag, result.Tag);
            Assert.AreEqual(testSecret.Password, result.Password);

            var testDataFile = new FileInfo(testDataFileLocation);

            if (testDataFile.Exists)
            {
                testDataFile.Delete();
            }
        }
예제 #8
0
        public async Task StoreSecretThenUpdateIt()
        {
            var testDataFileLocation = $"{DateTime.Now.ToFileTime()}.json";
            var service = new SecretService(
                "testPassword", testDataFileLocation);

            var testSecret = GetTestSecret("test");

            await service.StoreAsync(testSecret);

            var tmp             = testSecret.ToString();
            var preUpdateSecret = JsonConvert.DeserializeObject <Secret>(tmp);

            testSecret.Note     = "new note";
            testSecret.Password = "******";

            await service.UpdateAsync(testSecret);

            var result = await service.ShowAsync(testSecret.Name);

            Assert.AreNotEqual(preUpdateSecret.Note, result.Note);
            Assert.AreNotEqual(preUpdateSecret.Password, result.Password);

            var testDataFile = new FileInfo(testDataFileLocation);

            if (testDataFile.Exists)
            {
                testDataFile.Delete();
            }
        }
예제 #9
0
        public async Task <IActionResult> GenerateLink(int id)
        {
            var cuser = await GetCurrentUserAsync();

            var fileinfo = await ApiService.ViewOneFileAsync(id);

            if (fileinfo.File == null)
            {
                return(NotFound());
            }
            var bucketInfo = await ApiService.ViewBucketDetailAsync(fileinfo.File.BucketId);

            var app = await _dbContext.Apps.FindAsync(bucketInfo.BelongingAppId);

            if (bucketInfo.BelongingAppId != app.AppId)
            {
                return(Unauthorized());
            }
            var secret = await SecretService.GenerateAsync(id, await AppsContainer.AccessToken(app.AppId, app.AppSecret)());

            var model = new GenerateLinkViewModel(cuser)
            {
                Address  = secret.Value,
                BucketId = bucketInfo.BucketId
            };

            return(View(model));
        }
        public void GivenADirectory_ThenInteractiveLoginShouldBeUsed()
        {
            var provider = SecretService.ResolveTokenProvider(new Configuration {
                Directory = Guid.NewGuid().ToString()
            });

            Assert.IsInstanceOf <InteractiveAuthToken>(provider);
        }
        public void GivenADClientId_ThenCredentialsShouldBeUsed()
        {
            var provider = SecretService.ResolveTokenProvider(new Configuration {
                ServicePrincipal = Guid.NewGuid().ToString(), ServicePrincipalSecret = Guid.NewGuid().ToString()
            });

            Assert.IsInstanceOf <ServicePrincipalAuthToken>(provider);
        }
예제 #12
0
        private static async Task Export(SecretService service)
        {
            var index = await service.IndexAsync();

            var json = JsonConvert.SerializeObject(index);

            Console.WriteLine(json);
        }
예제 #13
0
        private static async Task Password(
            SecretService service, string name)
        {
            var secret = await service.ShowAsync(name);

            var value = secret.Password;

            Console.WriteLine(value);
        }
예제 #14
0
        public string Put()
        {
            LambdaLogger.Log($"Credential-only Test invoked");

            var secretJson = SecretService.GetSecret("dynamo_iam_user").Result;

            LambdaLogger.Log($"Secret received");

            return(secretJson);
        }
예제 #15
0
        public void GivenToomanyColon_ThenExceptionIsThrown()
        {
            Assert.Throws <Exception>(() =>
            {
                var keyVaultClient = Substitute.For <IKeyVaultClient>();
                var service        = new SecretService(new AuthedClient(keyVaultClient));

                var readKey = service.ResolveSingleKey("#{abc:def:ghi:jkl}");
            });
        }
예제 #16
0
        private static async Task Search(
            SecretService service, string partName)
        {
            var list = await service.SearchAsync(partName);

            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }
예제 #17
0
        public void GivenAValidInput_ThenKeyAndVaultAreParsed()
        {
            var keyVaultClient = Substitute.For <IKeyVaultClient>();
            var service        = new SecretService(new AuthedClient(keyVaultClient));

            var readKey = service.ResolveSingleKey("#{keyvault:vault:key}");

            Assert.AreEqual("vault", readKey.Vault);
            Assert.AreEqual("key", readKey.Key);
        }
예제 #18
0
        private void LoadCredentials()
        {
            var secretJson = SecretService.GetSecret(dynamo_iam_user_secretName).Result;

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(secretJson));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DynamoDbCredential));

            _dynamoDbCredential = ser.ReadObject(ms) as DynamoDbCredential;

            log("Retrieved Dynamo DB credentials");
        }
 public IActionResult Decrypt([FromBody] DecryptionRequest request)
 {
     try
     {
         var decrypted = SecretService.Decrypt(request.Payload, request.Key);
         return(Ok(decrypted));
     }
     catch (Exception)
     {
         return(BadRequest(request.Key));
     }
 }
예제 #20
0
        private static DynamicsTokenService ConfigureDynamicsTokenService(HttpClient client, HttpRequest req, string keyVaultBaseUrl, string urlDynamics, Guid keyVaultClientId, string keyVaultClientSecret)
        {
            var _secretService = new SecretService(keyVaultBaseUrl, keyVaultClientId, keyVaultClientSecret);
            var clientId       = _secretService.GetSecretAsync("Dynamics365-AppCredentialClientId").Result;
            var clientSecret   = _secretService.GetSecretAsync("Dynamics365-AppCredentialClientSecret").Result;

            //Create Service Instance
            var ap          = AD.AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(urlDynamics)).Result;
            var authContext = new AD.AuthenticationContext(ap.Authority);
            var clientCred  = new AD.ClientCredential(clientId.Value, clientSecret.Value);

            return(new DynamicsTokenService(authContext, clientCred, ap.Resource));
        }
예제 #21
0
        private static async Task List(SecretService service)
        {
            var list = await service.ListAsync();

            if (list.Count() == 0)
            {
                Console.WriteLine("Empty");
            }
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }
예제 #22
0
        public void GivenAVaultAlias_ThenVaultIsOverriden()
        {
            var keyVaultClient = Substitute.For <IKeyVaultClient>();
            var vaultAlias     = new Dictionary <string, string>
            {
                ["vault"] = "vault-dev"
            };

            var service = new SecretService(new AuthedClient(keyVaultClient), vaultAlias);

            var readKey = service.ResolveSingleKey("#{keyvault:vault:key}");

            Assert.AreEqual("vault-dev", readKey.Vault);
        }
예제 #23
0
        private static async Task New(
            SecretService service, string name)
        {
            var secret = new Secret {
                Name = name
            };

            secret.Host     = GetValue(nameof(secret.Host));
            secret.Username = GetValue(nameof(secret.Username));
            secret.Password = GetValue(nameof(secret.Password));
            secret.Note     = GetValue(nameof(secret.Note));
            secret.Tag      = GetValue(nameof(secret.Tag));
            await service.StoreAsync(secret);

            Console.WriteLine($"\tAdded {secret.Name}");
        }
예제 #24
0
        private static async Task Update(
            SecretService service, string name)
        {
            var secret = await service.ShowAsync(name);

            secret.Host     = GetValue(nameof(secret.Host), secret.Host);
            secret.Username = GetValue(
                nameof(secret.Username), secret.Username);
            secret.Password = GetValue(
                nameof(secret.Password), secret.Password);
            secret.Note = GetValue(nameof(secret.Note), secret.Note);
            secret.Tag  = GetValue(nameof(secret.Tag));
            await service.StoreAsync(secret);

            Console.WriteLine($"\tUpdated {secret.Name}");
        }
예제 #25
0
        public async Task ShouldReturnBadRequestWhenDeleteSecretCalledWithEmptyId()
        {
            //Given
            _swarmClient.DeleteSecret(Arg.Any <string>()).Returns(x => Task.CompletedTask);
            var secretService    = new SecretService(_swarmClient, _loggerFactory);
            var secretController = new SecretController(secretService);

            //When
            var response = await secretController.DeleteSecret(string.Empty);

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(400, result.StatusCode);
        }
 public FilesController(
     UserManager <ApplicationUser> userManager,
     ApplicationDbContext dbContext,
     IConfiguration configuration,
     ServiceLocation serviceLocation,
     StorageService storageService,
     AppsContainer appsContainer,
     SecretService secretService)
 {
     _userManager     = userManager;
     _dbContext       = dbContext;
     _configuration   = configuration;
     _serviceLocation = serviceLocation;
     _storageService  = storageService;
     _appsContainer   = appsContainer;
     _secretService   = secretService;
 }
예제 #27
0
        public async Task NotCrashIfListIsEmpty()
        {
            var testDataFileLocation = $"{DateTime.Now.ToFileTime()}.json";
            var service = new SecretService(
                "testPassword", testDataFileLocation);

            var list = await service.ListAsync();

            Assert.IsNotNull(list);

            var testDataFile = new FileInfo(testDataFileLocation);

            if (testDataFile.Exists)
            {
                testDataFile.Delete();
            }
        }
예제 #28
0
        public async Task ShouldDeleteSecretWhenDeleteSecretCalled()
        {
            //Given
            _swarmClient.DeleteSecret(Arg.Any <string>()).Returns(x => Task.CompletedTask);
            var secretService    = new SecretService(_swarmClient, _loggerFactory);
            var secretController = new SecretController(secretService);

            //When
            var response = await secretController.DeleteSecret(_any.Create <string>());

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(204, result.StatusCode);
            await _swarmClient.Received(1).DeleteSecret(Arg.Any <string>());
        }
예제 #29
0
        public async Task ShouldReturnInternalServerErrorWhenGetSecretsCalledAndErrorOccour()
        {
            //Given
            _swarmClient.When(x => {
                x.GetSecrets();
            }).Do(_ => { throw new Exception(); });
            var secretService    = new SecretService(_swarmClient, _loggerFactory);
            var secretController = new SecretController(secretService);

            //When
            var response = await secretController.GetSecret("");

            var result = response as ContentResult;

            //Then
            Assert.NotNull(result);
            Assert.Equal(500, result.StatusCode);
        }
예제 #30
0
 public FilesController(
     UserManager <DeveloperUser> userManager,
     SignInManager <DeveloperUser> signInManager,
     ILoggerFactory loggerFactory,
     DeveloperDbContext dbContext,
     OSSApiService ossApiService,
     StorageService storageService,
     AppsContainer appsContainer,
     SecretService secretService)
 {
     _userManager    = userManager;
     _signInManager  = signInManager;
     _logger         = loggerFactory.CreateLogger <FilesController>();
     _dbContext      = dbContext;
     _ossApiService  = ossApiService;
     _storageService = storageService;
     _appsContainer  = appsContainer;
     _secretService  = secretService;
 }