Esempio n. 1
0
        internal static LoggerConfiguration ConfigureLoki(this LoggerConfiguration configuration, LokiOptions lokiOptions, bool dynamicLevel)
        {
            if (lokiOptions is null || lokiOptions.Enabled is false)
            {
                return(configuration);
            }

            if (string.IsNullOrEmpty(lokiOptions.Endpoint))
            {
                throw new TitanException("Loki cannot be null or empty.");
            }


            LokiCredentials credentials;

            if (lokiOptions.Credentials is null)
            {
                credentials = new NoAuthCredentials(lokiOptions.Endpoint);
            }
            else
            {
                credentials = new BasicAuthCredentials(lokiOptions.Endpoint, lokiOptions.Credentials.Username, lokiOptions.Credentials.Password);
            }

            configuration.WriteTo.TitanLoki(credentials, null, null, TitanLibHelper.GetLogLevel(lokiOptions.LogLevelRestriction),
                                            lokiOptions.BatchSizeLimit, lokiOptions.Period.ToTimeSpan(), lokiOptions.QueueLimit, dynamicLevel);
            return(configuration);
        }
        public void WriteSolution_HasCredentials_FileSavedAndTokenOnlyCredentialSavedOk()
        {
            // Arrange
            SetSolutionFilePath(@"c:\mysolutionfile.foo");
            var expectedFilePath = @"c:\.sonarlint\mysolutionfile.sqconfig";

            // Currently we can only handle saving basic auth credentials
            BasicAuthCredentials creds = new BasicAuthCredentials("user1", "".ToSecureString());

            var boundProject = new BoundSonarQubeProject
            {
                ProjectKey  = "mykey",
                ServerUri   = new Uri("http://localhost:9000"),
                Credentials = creds
            };

            // Act
            var actualFilePath = testSubject.WriteSolutionBinding(boundProject);

            // Assert
            actualFilePath.Should().Be(expectedFilePath);
            fileMock.Verify(x => x.WriteAllText(expectedFilePath, It.IsAny <string>()), Times.Once);
            var savedCredentials = configurableStore.ReadCredentials(new Uri("http://localhost:9000"));

            savedCredentials.Should().NotBeNull();
            savedCredentials.Username.Should().Be("user1");
            savedCredentials.Password.Should().Be("");
        }
        public void WriteSolution_HasCredentials_FileSavedAndCredentialsSavedOk()
        {
            // Arrange
            SetSolutionFilePath(@"c:\mysolutionfile.foo");
            var expectedFilePath = @"c:\.sonarlint\mysolutionfile.slconfig";

            // Currently we can only handle saving basic auth credentials
            BasicAuthCredentials creds = new BasicAuthCredentials("user1", "1234".ToSecureString());

            var boundProject = new BoundSonarQubeProject
            {
                ProjectKey  = "mykey",
                ServerUri   = new Uri("http://localhost:9000"),
                Credentials = creds
            };

            // Step 1 - file write should be queued but not written
            var actualFilePath = testSubject.WriteSolutionBinding(boundProject);

            actualFilePath.Should().Be(expectedFilePath);
            configurableSccFileSystem.AssertQueuedOperationCount(1);
            fileMock.Verify(x => x.WriteAllText(It.IsAny <string>(), It.IsAny <string>()), Times.Never);

            // Step 2 - execute the queued write
            configurableSccFileSystem.WritePendingNoErrorsExpected(); // write the queued changes

            actualFilePath.Should().Be(expectedFilePath);
            fileMock.Verify(x => x.WriteAllText(expectedFilePath, It.IsAny <string>()), Times.Once);
            var savedCredentials = configurableStore.ReadCredentials(new Uri("http://localhost:9000"));

            savedCredentials.Should().NotBeNull();
            savedCredentials.Username.Should().Be("user1");
            savedCredentials.Password.Should().Be("1234");
        }
Esempio n. 4
0
        private static void SetupLoki(LoggerConfiguration log, IConfiguration cfg)
        {
            var dat = cfg.GetSection("Serilog:Loki").Get <LokiConfigurationData>();

            if (dat == null)
            {
                return;
            }

            LokiCredentials credentials;

            if (string.IsNullOrWhiteSpace(dat.Username))
            {
                credentials = new NoAuthCredentials(dat.Address);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(dat.Password))
                {
                    throw new InvalidDataException("No password specified.");
                }

                credentials = new BasicAuthCredentials(dat.Address, dat.Username, dat.Password);
            }

            log.WriteTo.LokiHttp(credentials, new DefaultLogLabelProvider(new[]
            {
                new LokiLabel("App", "SS14.Changelog"),
                new LokiLabel("Server", dat.Name)
            }));
        }
Esempio n. 5
0
        public async Task MessageCanBeAddressedToSpecificEndpointUriWithOverridingCredentials()
        {
            var          overridingCredentials = new BasicAuthCredentials("override", "overridepw");
            var          mockTransportService  = GivenMockTransportService();
            const string messageContent        = "Hello, world!";

            using (var bus = await GivenConfiguredBus(mockTransportService.Object))
            {
                var options = new SendOptions
                {
                    Credentials = overridingCredentials
                };
                await bus.Send(messageContent, OtherEndpointUri, options);
            }

            // Only one call to ITransportService.SendMessage
            mockTransportService.Verify(
                ts => ts.SendMessage(
                    It.IsAny <Message>(),
                    It.IsAny <IEndpointCredentials>(),
                    It.IsAny <CancellationToken>()),
                Times.Once());

            // Specifically, only one call to ITransportService.SendMessage for this message
            // addressed to the expected destination with the specified override credentials
            mockTransportService.Verify(
                ts => ts.SendMessage(
                    It.Is <Message>(m => m.Content == messageContent &&
                                    m.Headers.Destination == OtherEndpointUri),
                    overridingCredentials,
                    It.IsAny <CancellationToken>()),
                Times.Once());
        }
        private void PostLoggingEvent(LoggingEvent[] loggingEvents)
        {
            var formatter  = new LokiBatchFormatter(labels);
            var httpClient = new LokiHttpClient(TrustSelfCignedCerts);

            if (httpClient is LokiHttpClient c)
            {
                LokiCredentials credentials;

                if (!string.IsNullOrEmpty(BasicAuthUserName) && !string.IsNullOrEmpty(BasicAuthPassword))
                {
                    credentials = new BasicAuthCredentials(ServiceUrl, BasicAuthUserName, BasicAuthPassword);
                }
                else
                {
                    credentials = new NoAuthCredentials(ServiceUrl);
                }

                c.SetAuthCredentials(credentials);
            }

            using (MemoryStream ms = new MemoryStream())
                using (var sc = new StreamWriter(ms))
                {
                    formatter.Format(loggingEvents, sc);
                    sc.Flush();
                    ms.Position = 0;
                    var content    = new StreamContent(ms);
                    var contentStr = content.ReadAsStringAsync().Result; // TO VERIFY
                    httpClient.PostAsync(LokiRouteBuilder.BuildPostUri(ServiceUrl), content);
                }
        }
Esempio n. 7
0
        public void TestInitialize()
        {
            sourceControlledFileSystem = new Mock <ISourceControlledFileSystem>();
            credentialsLoader          = new Mock <ISolutionBindingCredentialsLoader>();
            solutionBindingFileLoader  = new Mock <ISolutionBindingFileLoader>();
            onSaveCallback             = new Mock <Action <string> >();

            testSubject = new SolutionBindingDataWriter(sourceControlledFileSystem.Object,
                                                        solutionBindingFileLoader.Object,
                                                        credentialsLoader.Object);

            mockCredentials = new BasicAuthCredentials("user", "pwd".ToSecureString());

            boundSonarQubeProject = new BoundSonarQubeProject(
                new Uri("http://xxx.www.zzz/yyy:9000"),
                "MyProject Key",
                "projectName",
                mockCredentials);

            sourceControlledFileSystem
            .Setup(x => x.QueueFileWrites(new List <string> {
                MockFilePath
            }, It.IsAny <Func <bool> >()))
            .Callback((IEnumerable <string> filePath, Func <bool> method) => method());
        }
        public void SolutionBindingSerializer_WriteSolutionBinding_ReadSolutionBinding()
        {
            // Setup
            SolutionBindingSerializer testSubject = this.CreateTestSubject();
            var serverUri  = new Uri("http://xxx.www.zzz/yyy:9000");
            var creds      = new BasicAuthCredentials("user", "pwd".ConvertToSecureString());
            var projectKey = "MyProject Key";
            var written    = new BoundSonarQubeProject(serverUri, projectKey, creds);

            // Act (write)
            string output = testSubject.WriteSolutionBinding(written);

            this.sourceControlledFileSystem.WritePendingNoErrorsExpected();
            Assert.IsNotNull(output, "Expected a real file");
            this.TestContext.AddResultFile(output);
            Assert.IsTrue(File.Exists(output), "Expected a real file");

            // Verify
            this.store.AssertHasCredentials(serverUri);

            // Act (read)
            BoundSonarQubeProject read = testSubject.ReadSolutionBinding();

            // Verify
            var newCreds = read.Credentials as BasicAuthCredentials;

            Assert.AreNotEqual(creds, newCreds, "Different credential instance were expected");
            Assert.AreEqual(creds.UserName, newCreds.UserName);
            Assert.AreEqual(creds.Password.ConvertToUnsecureString(), newCreds.Password.ConvertToUnsecureString());
            Assert.AreEqual(written.ServerUri, read.ServerUri);
            this.outputPane.AssertOutputStrings(0);
        }
Esempio n. 9
0
        /// <summary>
        /// Will add/edit the binding information for next time usage
        /// </summary>
        private BindingConfiguration QueueWriteBindingInformation()
        {
            Debug.Assert(InternalState.QualityProfiles != null, "Initialize was expected to be called first");

            var configurationPersister = host.GetService <IConfigurationPersister>();

            configurationPersister.AssertLocalServiceIsNotNull();

            BasicAuthCredentials credentials = bindingArgs.Connection.UserName == null ? null : new BasicAuthCredentials(bindingArgs.Connection.UserName, bindingArgs.Connection.Password);

            Dictionary <Language, ApplicableQualityProfile> map = new Dictionary <Language, ApplicableQualityProfile>();

            foreach (var keyValue in InternalState.QualityProfiles)
            {
                map[keyValue.Key] = new ApplicableQualityProfile
                {
                    ProfileKey       = keyValue.Value.Key,
                    ProfileTimestamp = keyValue.Value.TimeStamp
                };
            }

            var bound = new BoundSonarQubeProject(bindingArgs.Connection.ServerUri,
                                                  bindingArgs.ProjectKey,
                                                  bindingArgs.ProjectName,
                                                  credentials,
                                                  bindingArgs.Connection.Organization);

            bound.Profiles = map;

            return(configurationPersister.Persist(bound, bindingMode));
        }
        public void SolutionBindingSerializer_WriteSolutionBinding_ReadSolutionBinding()
        {
            // Arrange
            SolutionBindingSerializer testSubject = this.CreateTestSubject();
            var serverUri  = new Uri("http://xxx.www.zzz/yyy:9000");
            var creds      = new BasicAuthCredentials("user", "pwd".ToSecureString());
            var projectKey = "MyProject Key";
            var written    = new BoundSonarQubeProject(serverUri, projectKey, "projectName", creds);

            // Act (write)
            string output = testSubject.WriteSolutionBinding(written);

            this.sourceControlledFileSystem.WritePendingNoErrorsExpected();
            output.Should().NotBeNull("Expected a real file");
            this.TestContext.AddResultFile(output);
            File.Exists(output).Should().BeTrue("Expected a real file");

            // Assert
            this.store.data.Should().ContainKey(serverUri);

            // Act (read)
            BoundSonarQubeProject read = testSubject.ReadSolutionBinding();

            // Assert
            var newCreds = read.Credentials as BasicAuthCredentials;

            newCreds.Should().NotBe(creds, "Different credential instance were expected");
            newCreds.UserName.Should().Be(creds.UserName);
            newCreds.Password.ToUnsecureString().Should().Be(creds.Password.ToUnsecureString());
            read.ServerUri.Should().Be(written.ServerUri);
            this.outputPane.AssertOutputStrings(0);
        }
Esempio n. 11
0
        /// <summary>
        /// Will bend add/edit the binding information for next time usage
        /// </summary>
        private void PendBindingInformation(ConnectionInformation connInfo)
        {
            Debug.Assert(this.qualityProfileMap != null, "Initialize was expected to be called first");

            var bindingSerializer = this.serviceProvider.GetService <IConfigurationProvider>();

            bindingSerializer.AssertLocalServiceIsNotNull();

            BasicAuthCredentials credentials = connection.UserName == null ? null : new BasicAuthCredentials(connInfo.UserName, connInfo.Password);

            Dictionary <Language, ApplicableQualityProfile> map = new Dictionary <Language, ApplicableQualityProfile>();

            foreach (var keyValue in this.qualityProfileMap)
            {
                map[keyValue.Key] = new ApplicableQualityProfile
                {
                    ProfileKey       = keyValue.Value.Key,
                    ProfileTimestamp = keyValue.Value.TimeStamp
                };
            }

            var bound = new BoundSonarQubeProject(connInfo.ServerUri, this.ProjectKey, credentials,
                                                  connInfo.Organization);

            bound.Profiles = map;

            var config = new BindingConfiguration(bound, this.bindingMode);

            bindingSerializer.WriteConfiguration(config);
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes endpoints in the supplied <paramref name="configuration"/> based on the
        /// properties of the specified <paramref name="configSection"/>
        /// </summary>
        /// <param name="configuration">The configuration to initialize</param>
        /// <param name="configSection">The configuration section containing the endpoint
        /// properties</param>
        protected virtual void InitializeEndpoints(TConfiguration configuration, PlatibusConfigurationSection configSection)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (configSection == null)
            {
                throw new ArgumentNullException(nameof(configSection));
            }

            IEnumerable <EndpointElement> endpoints = configSection.Endpoints;

            foreach (var endpointConfig in endpoints)
            {
                IEndpointCredentials credentials = null;
                switch (endpointConfig.CredentialType)
                {
                case ClientCredentialType.Basic:
                    var un = endpointConfig.Username;
                    var pw = endpointConfig.Password;
                    credentials = new BasicAuthCredentials(un, pw);
                    break;

                case ClientCredentialType.Windows:
                case ClientCredentialType.NTLM:
                    credentials = new DefaultCredentials();
                    break;
                }

                var endpoint = new Endpoint(endpointConfig.Address, credentials);
                configuration.AddEndpoint(endpointConfig.Name, endpoint);
            }
        }
        private static void ApplyBasicAuth(HttpRequestMessage request, BasicAuthCredentials credentials)
        {
            var basicAuthStr       = $"{credentials.UserName}:{credentials.Password}";
            var encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(basicAuthStr));

            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedCredentials);
        }
        public void SolutionBindingSerializer_WriteSolutionBinding_AddConfigFileToSolutionItemsFolder()
        {
            // Arrange
            SolutionBindingSerializer testSubject = this.CreateTestSubject();
            var         serverUri       = new Uri("http://xxx.www.zzz/yyy:9000");
            var         creds           = new BasicAuthCredentials("user", "pwd".ToSecureString());
            var         projectKey      = "MyProject Key";
            var         toWrite         = new BoundSonarQubeProject(serverUri, projectKey, "projectName", creds);
            ProjectMock solutionProject = (ProjectMock)this.projectSystemHelper.SolutionItemsProject;

            // Act
            string output = testSubject.WriteSolutionBinding(toWrite);

            // Assert that not actually done anything until the pending files were written
            this.store.data.Should().NotContainKey(serverUri);
            solutionProject.Files.ContainsKey(output).Should().BeFalse("Not expected to be added to solution items folder just yet");

            // Act (write pending)
            this.sourceControlledFileSystem.WritePendingNoErrorsExpected();

            // Assert
            this.store.data.Should().ContainKey(serverUri);
            solutionProject.Files.ContainsKey(output).Should().BeTrue("File {0} was not added to project", output);

            // Act (write again)
            string output2 = testSubject.WriteSolutionBinding(toWrite);

            this.sourceControlledFileSystem.WritePendingNoErrorsExpected();

            // Assert
            output2.Should().Be(output, "Should be the same file");
            this.store.data.Should().ContainKey(serverUri);
            solutionProject.Files.ContainsKey(output).Should().BeTrue("File {0} should remain in the project", output);
        }
Esempio n. 15
0
        private HttpStatusCode CreateUser(BasicAuthCredentials user)
        {
            MembershipCreateStatus createStatus;

            TraceLog.TraceFunction();  // log function entrance

            try
            {   // create new user account using the membership provider
                MembershipUser mu = Membership.CreateUser(user.Name, user.Password, user.Email, null, null, true, user.ID, out createStatus);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    return(HttpStatusCode.Created);
                }
                if (createStatus == MembershipCreateStatus.DuplicateUserName)
                {
                    return(HttpStatusCode.Conflict);
                }
                if (createStatus == MembershipCreateStatus.InvalidUserName ||
                    createStatus == MembershipCreateStatus.InvalidEmail ||
                    createStatus == MembershipCreateStatus.InvalidPassword)
                {
                    return(HttpStatusCode.NotAcceptable);
                }
            }
            catch (Exception)
            { }

            TraceLog.TraceError("Failed to create new user account: " + user.Name);
            return(HttpStatusCode.Conflict);
        }
Esempio n. 16
0
        public DockerInstance(string host, int port, string userName, string password)
        {
            Host = host;
            Port = port;
            var credentials = new BasicAuthCredentials(userName, password);

            this.client = new DockerClientConfiguration(new Uri($"http://{host}:{port}"), credentials).CreateClient();
        }
        protected override void ProcessRecord()
        {
            var output = new BasicAuthCredentials(_encodeService,
                                                  UserName,
                                                  Password);

            WriteObject(output);
        }
Esempio n. 18
0
        public void Save_ServerUriIsNull_CredentialsNotSaved()
        {
            var credentials = new BasicAuthCredentials("user", "password".ToSecureString());

            testSubject.Save(credentials, null);

            store.Verify(x => x.WriteCredentials(It.IsAny <Uri>(), It.IsAny <Credential>()), Times.Never);
        }
        public void Visit(BasicAuthCredentials credentials)
        {
            var authorization = new AuthenticationHeaderValue("Basic",
                                                              Convert.ToBase64String(
                                                                  Encoding.UTF8.GetBytes(
                                                                      credentials.Username + ":" + credentials.Password)));

            _client.DefaultRequestHeaders.Authorization = authorization;
        }
Esempio n. 20
0
        /// <summary>
        /// Sets the service credentials to use a Basic username and password
        /// when accessing a protected resource. The username and password
        /// is sent in the HTTP Authorization header as plain text and is not
        /// protected unless sent over HTTPS.
        /// </summary>
        /// <param name="token">The OAuth token</param>
        /// <param name="tokenSecret">The OAuth token secret</param>
        public void AuthenticateAs(string username, string password)
        {
            var credentials = new BasicAuthCredentials();

            credentials.Username = username;
            credentials.Password = password;

            _client.Credentials = credentials;
        }
        public void SolutionBindingSerializer_WriteSolutionBinding_ReadSolutionBinding_OnRealStore()
        {
            // Arrange
            var testSubject = new SolutionBindingSerializer(this.serviceProvider);
            var serverUri   = new Uri("http://xxx.www.zzz/yyy:9000");
            var projectKey  = "MyProject Key";

            this.store.DeleteCredentials(serverUri);

            // Case 1: has credentials
            var creds   = new BasicAuthCredentials("user", "pwd".ToSecureString());
            var written = new BoundSonarQubeProject(serverUri, projectKey, "projectName", creds);

            // Act (write + read)
            BoundSonarQubeProject read = null;

            try
            {
                testSubject.WriteSolutionBinding(written);
                this.sourceControlledFileSystem.WritePendingNoErrorsExpected();
                read = testSubject.ReadSolutionBinding();
            }
            finally
            {
                this.store.DeleteCredentials(serverUri);
            }

            // Assert
            var newCreds = read.Credentials as BasicAuthCredentials;

            newCreds.Should().NotBe(creds, "Different credential instance were expected");
            newCreds.UserName.Should().Be(creds.UserName);
            newCreds?.Password.ToUnsecureString().Should().Be(creds.Password.ToUnsecureString());
            read.ServerUri.Should().Be(written.ServerUri);
            this.outputPane.AssertOutputStrings(0);

            // Case 2: has not credentials (anonymous)
            creds   = null;
            written = new BoundSonarQubeProject(serverUri, projectKey, "projectName", creds);

            // Act (write + read)
            read = null;
            try
            {
                testSubject.WriteSolutionBinding(written);
                read = testSubject.ReadSolutionBinding();
            }
            finally
            {
                this.store.DeleteCredentials(serverUri);
            }

            // Assert
            read.Credentials.Should().BeNull();
            read.ServerUri.Should().Be(written.ServerUri);
            this.outputPane.AssertOutputStrings(0);
        }
Esempio n. 22
0
        private bool SetupLoki()
        {
            _config.RegisterCVar("loki.enabled", false);
            _config.RegisterCVar("loki.name", "");
            _config.RegisterCVar("loki.address", "");
            _config.RegisterCVar("loki.username", "");
            _config.RegisterCVar("loki.password", "");

            var enabled = _config.GetCVar <bool>("loki.enabled");

            if (!enabled)
            {
                return(true);
            }

            var serverName = _config.GetCVar <string>("loki.name");
            var address    = _config.GetCVar <string>("loki.address");
            var username   = _config.GetCVar <string>("loki.username");
            var password   = _config.GetCVar <string>("loki.password");

            if (string.IsNullOrWhiteSpace(serverName))
            {
                Logger.FatalS("loki", "Misconfiguration: Server name is not specified/empty.");
                return(false);
            }

            if (string.IsNullOrWhiteSpace(address))
            {
                Logger.FatalS("loki", "Misconfiguration: Loki address is not specified/empty.");
                return(false);
            }

            LokiCredentials credentials;

            if (string.IsNullOrWhiteSpace(username))
            {
                credentials = new NoAuthCredentials(address);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(password))
                {
                    Logger.FatalS("loki", "Misconfiguration: Loki password is not specified/empty but username is.");
                    return(false);
                }

                credentials = new BasicAuthCredentials(address, username, password);
            }

            Logger.DebugS("loki", "Loki enabled for server {ServerName} loki address {LokiAddress}.", serverName,
                          address);

            var handler = new LokiLogHandler(serverName, credentials);

            _log.RootSawmill.AddHandler(handler);
            return(true);
        }
Esempio n. 23
0
        public HttpResponseMessageWrapper <User> UpdateUser(HttpRequestMessage req, Guid id)
        {
            Operation      operation = null;
            HttpStatusCode code      = AuthenticateUser(req);

            if (code != HttpStatusCode.OK)
            {   // user not authenticated
                return(ReturnResult <User>(req, operation, code));
            }

            // verify body contains two sets of user data - the original values and the new values
            List <BasicAuthCredentials> userCreds = null;

            code = ProcessRequestBody <List <BasicAuthCredentials> >(req, out userCreds, out operation);
            if (code != HttpStatusCode.OK)  // error encountered processing body
            {
                return(ReturnResult <User>(req, operation, code));
            }

            // get the original and new items out of the message body
            BasicAuthCredentials originalUserData = userCreds[0];
            BasicAuthCredentials newUserData      = userCreds[1];

            // make sure the item ID's match
            if (originalUserData.ID != newUserData.ID || originalUserData.ID != id)
            {
                return(ReturnResult <User>(req, operation, HttpStatusCode.BadRequest));
            }

            try
            {   // TODO: should we allow changing of username?
                // check to make sure the old password passed in the message is valid
                if (!Membership.ValidateUser(CurrentUser.Name, originalUserData.Password))
                {
                    return(ReturnResult <User>(req, operation, HttpStatusCode.Forbidden));
                }

                MembershipUser mu = Membership.GetUser(originalUserData.Name);
                if (!mu.Email.Equals(newUserData.Email, StringComparison.OrdinalIgnoreCase))
                {
                    mu.Email = newUserData.Email;
                    Membership.UpdateUser(mu);
                }
                if (originalUserData.Password != newUserData.Password)
                {
                    mu.ChangePassword(originalUserData.Password, newUserData.Password);
                }

                User currentUser = this.StorageContext.Users.Single <User>(u => u.ID == CurrentUser.ID);
                return(ReturnResult <User>(req, operation, currentUser, HttpStatusCode.Accepted));
            }
            catch (Exception)
            {
                return(ReturnResult <User>(req, operation, HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 24
0
        public async Task connect(String host, int port, String user, String local_path, String remote_path, String password, TLS_MODE tls_mode, bool use_compression, String container)
        {
            cancel = new CancellationTokenSource();
            SetLocalPath(local_path);
            compress      = use_compression;
            this.tls_mode = tls_mode;
            if (String.IsNullOrWhiteSpace(remote_path))
            {
                remote_path = "";
            }
            else if (remote_path.EndsWith("/") == false && remote_path.EndsWith("\\") == false)
            {
                remote_path += "/";
            }
            this.remote_path = remote_path;
            this.container   = container;
            if (host.IndexOf("://") == -1)
            {
                host = "tcp://" + host;
            }
            host += ":" + port;
            Credentials creds     = new AnonymousCredentials();
            var         pswd_info = new FileInfo(password);

            if (pswd_info.Exists)
            {
                if (pswd_info.Attributes.HasFlag(FileAttributes.ReparsePoint))
                {
                    throw new Exception("Sysmlinks will crash this;0");
                }
                creds        = new CertificateCredentials(new X509Certificate2(password, ""));                              //warning sym links will throw an error here
                ca_cert_path = user;
                ((CertificateCredentials)creds).ServerCertificateValidationCallback += ServerCertificateValidationCallback; //not sure why cannot do this for basic auth
            }
            else if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(password))
            {
                creds = new BasicAuthCredentials(user, password, tls_mode != TLS_MODE.None);
            }
            var config = new DockerClientConfiguration(new Uri(host), creds);

            client = config.CreateClient();
            try {
                var stats = await client.Containers.InspectContainerAsync(container);

                if (!stats.State.Running)
                {
                    MainWindow.ShowMessage("Container is not running", "Unable to connect");
                }
                else
                {
                    connected = true;
                }
            } catch (Exception e) {
                HandleException(e);
            }
        }
        protected override async Task <Outcome <ActorToken> > OnGetAccessTokenAsync(CancellationToken cancellationToken)
        {
            try
            {
                var accessTokenOutcome = await base.OnGetAccessTokenAsync(cancellationToken);

                if (!accessTokenOutcome)
                {
                    return(accessTokenOutcome);
                }

                // try getting a cached exchanged token ...
                var accessToken   = accessTokenOutcome.Value;
                var cachedOutcome = await getCachedIdentityTokenAsync(accessToken);

                if (cachedOutcome)
                {
                    return(cachedOutcome);
                }

                // exchange token for
                var clientCredentials = await OnGetClientCredentials();

                var credentials = new BasicAuthCredentials(clientCredentials.Identity, clientCredentials.Secret);

                var bearerToken   = accessTokenOutcome.Value as BearerToken;
                var isBearerToken = bearerToken is { };
                var subjectToken  = isBearerToken
                    ? bearerToken.Value
                    : accessTokenOutcome.Value.ToString();
                var txOutcome = await _tokenExchangeService.ExchangeAccessTokenAsync(
                    credentials,
                    subjectToken,
                    cancellationToken);

                if (!txOutcome || !ActorToken.TryParse(txOutcome.Value.AccessToken, out var actorToken))
                {
                    return(Outcome <ActorToken> .Fail(txOutcome.Exception));
                }

                var exchangedToken = isBearerToken
                    ? new BearerToken(actorToken.Identity, false)
                    : actorToken;

                // cache exchanged token and return it ...
                await cacheTokenExchangeAsync(accessToken, exchangedToken);

                return(Outcome <ActorToken> .Success(exchangedToken));
            }
            catch (Exception ex)
            {
                Logger.Error(new Exception($"Claims transformation failure: {ex.Message}", ex));
                throw;
            }
        }
Esempio n. 26
0
        public TokenManager(BotCredentials apiCredentials)
        {
            Credentials = apiCredentials ?? throw new ArgumentNullException(nameof(apiCredentials));

            // Set up credentials to use with the api instance.
            BasicAuthCredentials basicAuthCreds = new BasicAuthCredentials(
                username: Credentials.ClientId,
                password: Credentials.ClientSecret);

            Api = new ApiCaller(ApiUrl, Credentials.UserAgent, basicAuthCreds);
        }
    public void CreateToken_Ctor()
    {
        //Arrange
        var credentials = new BasicAuthCredentials("fred", "letmein");

        //Act
        var token = credentials.CreateToken();

        //Assert
        token.Should().Be(expectedToken);
    }
Esempio n. 28
0
        protected HttpStatusCode AuthenticateUser(HttpRequestMessage req)
        {
            TraceLog.TraceFunction();

            // this should work if auth cookie has been provided
            MembershipUser mu = Membership.GetUser();

            if (mu != null && Membership.Provider is UserMembershipProvider)
            {   // get user id from authenticated identity (cookie)
                this.currentUser = UserMembershipProvider.AsUser(mu);
                return(HttpStatusCode.OK);
            }

            BasicAuthCredentials credentials = GetUserFromMessageHeaders(req);

            if (credentials == null)
            {
                if (HttpContext.Current.Request.Headers[authRequestHeader] != null)
                {   // cookie is no longer valid, return 401 Unauthorized
                    TraceLog.TraceError("Cookie is expired or invalid");
                    return(HttpStatusCode.Unauthorized);
                }

                // auth headers not found, return 400 Bad Request
                TraceLog.TraceError("Bad request: no user information found");
                return(HttpStatusCode.BadRequest);
            }

            try
            {   // authenticate the user
                if (Membership.ValidateUser(credentials.Name, credentials.Password) == false)
                {
                    TraceLog.TraceError("Invalid username or password for user " + credentials.Name);
                    return(HttpStatusCode.Forbidden);
                }

                mu = Membership.GetUser(credentials.Name, true);
                this.currentUser = UserMembershipProvider.AsUser(mu);

                if (Membership.Provider is UserMembershipProvider)
                {   // add auth cookie to response (cookie includes user id)
                    HttpCookie authCookie = UserMembershipProvider.CreateAuthCookie(this.currentUser);
                    HttpContext.Current.Response.Cookies.Add(authCookie);
                }

                TraceLog.TraceInfo(String.Format("User {0} successfully logged in", credentials.Name));
                return(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {   // username not found - return 404 Not Found
                TraceLog.TraceException(String.Format("Username not found: {0}", credentials.Name), ex);
                return(HttpStatusCode.NotFound);
            }
        }
Esempio n. 29
0
        public void Save_CredentialsAreBasicAuth_CredentialsSavedWithUnsecuredString()
        {
            var credentials = new BasicAuthCredentials("user", "password".ToSecureString());

            testSubject.Save(credentials, mockUri);

            store.Verify(x =>
                         x.WriteCredentials(
                             It.Is <TargetUri>(t => t.ActualUri == mockUri),
                             It.Is <Credential>(c => c.Username == "user" && c.Password == "password")),
                         Times.Once);
        }
Esempio n. 30
0
        public void CorrectHeaderGenerated()
        {
            var test1 = new
                        BasicAuthCredentials("TestUser", "TestPassword");

            Assert.AreEqual(test1.AsAuthHeader(), new AuthenticationHeaderValue(Basic, "VGVzdFVzZXI6VGVzdFBhc3N3b3Jk"), "Auth header output is not as expected.");

            var test2 = new
                        BasicAuthCredentials("GeddyLee", "playsPrettyGoodBass");

            Assert.AreEqual(test2.AsAuthHeader(), new AuthenticationHeaderValue(Basic, "R2VkZHlMZWU6cGxheXNQcmV0dHlHb29kQmFzcw=="), "Auth header output is not as expected.");
        }
Esempio n. 31
0
        private HttpStatusCode CreateUser(BasicAuthCredentials user)
        {
            MembershipCreateStatus createStatus;
            TraceLog.TraceFunction();  // log function entrance

            try
            {   // create new user account using the membership provider
                MembershipUser mu = Membership.CreateUser(user.Name, user.Password, user.Email, null, null, true, user.ID, out createStatus);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    return HttpStatusCode.Created;
                }
                if (createStatus == MembershipCreateStatus.DuplicateUserName)
                {
                    return HttpStatusCode.Conflict;
                }
                if (createStatus == MembershipCreateStatus.InvalidUserName ||
                    createStatus == MembershipCreateStatus.InvalidEmail ||
                    createStatus == MembershipCreateStatus.InvalidPassword)
                {
                    return HttpStatusCode.NotAcceptable;
                }
            }
            catch (Exception)
            { }

            TraceLog.TraceError("Failed to create new user account: " + user.Name);
            return HttpStatusCode.Conflict;
        }