Ejemplo n.º 1
0
        public void SecretProvider_ValidParameters()
        {
            var secretProvider = new SecretProvider(translationkeySecretIdentifier, subscriptionKeySecretIdentifier, applicationId);

            var secret = secretProvider.GetSubscriptionKey();

            Assert.IsFalse(String.IsNullOrEmpty(secret));
        }
Ejemplo n.º 2
0
        public void SecretProvider_InvalidSecret()
        {
            const string invalidKey = "invalid";

            var secretProvider = new SecretProvider(invalidKey, invalidKey, applicationId);

            var secret = secretProvider.GetSubscriptionKey();
        }
Ejemplo n.º 3
0
        public void SecretProvider_ValidSecretInvalidAppId()
        {
            const string invalidKey = "invalid";

            var secretProvider = new SecretProvider(translationkeySecretIdentifier, subscriptionKeySecretIdentifier, invalidKey);

            var secret = secretProvider.GetTranslationKey();
        }
Ejemplo n.º 4
0
 public ValueCrypter(SecretProvider secretProvider)
 {
     rijndael            = new RijndaelManaged();
     this.secretProvider = secretProvider;
     byte[] key, iv;
     GenerateKeyFromPassword(rijndael.KeySize, out key, rijndael.BlockSize, out iv);
     rijndael.Key = key;
     rijndael.IV  = iv;
 }
Ejemplo n.º 5
0
        public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped <IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
            services.AddSingleton <IDataLoaderContextAccessor, DataLoaderContextAccessor>();
            services.AddSingleton <DataLoaderDocumentListener>();
            services.AddScoped <IInitializer, Initializer>();
            services.AddHostedService <CacheLoader>();
            services.AddScoped <AppSchema>();

            services.AddGraphQL(options =>
            {
                options.ExposeExceptions = true;
                options.EnableMetrics    = true;
            })
            .AddWebSockets()
            .AddDataLoader()
            .AddGraphTypes(ServiceLifetime.Scoped);

            var secretProvider = new SecretProvider();

            var port     = Environment.GetEnvironmentVariable("PORT");
            var server   = Environment.GetEnvironmentVariable("SERVER");
            var user     = Environment.GetEnvironmentVariable("USER");
            var database = Environment.GetEnvironmentVariable("DATABASE");

            var password = string.Empty;

            if (WebHostEnvironment.IsStaging())
            {
                password = secretProvider.GetSecret("dev_slipway_db");
            }
            else if (WebHostEnvironment.IsProduction())
            {
                password = secretProvider.GetSecret("sqlserver");
            }
            else
            {
                password = "******";
            }

            var str = $"Server={server},{port};Database={database};User Id={user};Password={password}";

#if DEBUG
            str = $"Server=localhost,1433;Database=Slipways;User Id=sa;Password=foo123bar!";
#endif
            services.AddSlipwaysData(str, ServiceLifetime.Transient);

            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }
Ejemplo n.º 6
0
        private static IHostBuilder CreateHostBuilder(string[] args)
        => Host.CreateDefaultBuilder(args).ConfigureServices((hostContext, services) =>
        {
            var configuration = hostContext.Configuration;

            services.AddSingleton <IMqttServerOptions, MqttServerOptions>();
            services.AddSingleton <IMqttServerFactory, MqttFactory>();
            services.AddSingleton <IMqttServerStorage, MqttStorage>();
            services.AddSingleton <IMqttServerSubscriptionInterceptor, MqttServerSubscriptionInterceptor>();

            services
            .AddSingleton <IMqttServerApplicationMessageInterceptor, MqttServerApplicationMessageInterceptor
                           >();

            services.AddSingleton <IMqttServerConnectionValidator, MqttServerConnectionValidator>();
            services.AddSingleton <IServerBuilder, ServerBuilder>();
            services.AddSingleton <IMqttRepository, MqttRepository>();

            ISecretProvider secretProvider = new SecretProvider();
            services.AddSingleton(secretProvider);

            var stage            = Environment.GetEnvironmentVariable("STAGE") ?? "";
            var connectionString = string.Empty;

            if (stage == "Development")
            {
                connectionString = configuration.GetConnectionString("postgres");
            }
            else
            {
                var db           = secretProvider.GetSecret("database");
                var host         = secretProvider.GetSecret("host");
                var username     = secretProvider.GetSecret("username");
                var port         = secretProvider.GetSecret("port");
                var pw           = secretProvider.GetSecret("postgres_db_password");
                connectionString = $"Host={host};Port={port};Username={username};Password={pw};Database={db};";
            }
            services.AddDbContext <DataContext>(options =>
            {
                options.UseNpgsql(connectionString);
                options.EnableSensitiveDataLogging();
                options.EnableDetailedErrors();
                options.EnableServiceProviderCaching();
            });

            services.AddHostedService <MqttService>();
        })
        .ConfigureLogging(
            logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
            logging.SetMinimumLevel(LogLevel.Trace);
        })
        .UseNLog();
Ejemplo n.º 7
0
        public void ShouldNotFindConfigInCollection()
        {
            var collection = new SecretConfigCollection
            {
                Items = new [] { new SecretConfig {
                                     Name = "test", Region = "us-east-2", SecretId = "a secret"
                                 } }
            };

            var    systemUnderTest = new SecretProvider(collection, manager.Object);
            Action act             = () => systemUnderTest.GetAwsSecret("fail");

            act.Should().Throw <SecretException>();
        }
Ejemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString      = "yyyy-MM-ddTHH:mm:ss";
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddAutoMapper(typeof(Program).Assembly);
            services.AddScoped <IRepositoryWrapper, RepositoryWrapper>();
            services.AddScoped <IValueRepository, ValueRepository>();
            services.AddScoped <ITimeRepository, TimeRepository>();
            services.AddScoped <ISensorRepository, SensorRepository>();
            services.AddScoped <IStatisticProvider, StatisticProvider>();
            services.AddScoped <Median>();
            services.AddScoped <ArethmeticMean>();
            //if (Environment.IsDevelopment())
            //{
            //    services.AddDbContext<DataContext>(options =>
            //    {
            //        options.UseSqlite(Configuration.GetConnectionString("Default"));
            //    });
            //}
            //else
            //{

            var secretProvider = new SecretProvider();
            var password       = secretProvider.GetSecret("sqlserver");
            var conString      = secretProvider.GetSecret("CON_STRING");

            if (Environment.IsDevelopment())
            {
                password  = "******";
                conString = "Server=localhost,1433;Database=Air;User Id=sa;Password="******"{conString}{password}");
            });
            //}
        }
Ejemplo n.º 9
0
        public void ShouldGetSecret()
        {
            const string configName = "test";
            var          collection = new SecretConfigCollection
            {
                Items = new [] { new SecretConfig {
                                     Name = configName, Region = "us-east-2", SecretId = "a secret"
                                 } }
            };

            var systemUnderTest = new SecretProvider(collection, manager.Object);
            var actual          = systemUnderTest.GetAwsSecret(configName);

            actual.Should().NotBeNull();
            actual.Should().BeAssignableTo <CachingSecret>();
        }
Ejemplo n.º 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddControllersAsServices();;
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Platooning MQTT Broker", Version = "v1"
                });
            });


            services.AddSingleton <IMqttServerOptions, MqttServerOptions>();
            services.AddSingleton <IMqttServerFactory, MqttFactory>();
            services.AddSingleton <IMqttServerStorage, MqttStorage>();
            services.AddSingleton <IMqttServerSubscriptionInterceptor, MqttServerSubscriptionInterceptor>();
            services.AddSingleton <IMqttServerApplicationMessageInterceptor, MqttServerApplicationMessageInterceptor>();
            services.AddSingleton <IMqttServerConnectionValidator, MqttServerConnectionValidator>();
            services.AddSingleton <IServerBuilder, ServerBuilder>();
            services.AddTransient <IMqttRepository, MqttRepository>();
            ISecretProvider sp = new SecretProvider();

            services.AddSingleton(sp);
            var stage            = Environment.GetEnvironmentVariable("STAGE") ?? "Development";
            var connectionString = string.Empty;

            if (stage == "Development")
            {
                connectionString = Configuration.GetConnectionString("postgres");
            }
            else
            {
                var db       = sp.GetSecret("database");
                var host     = sp.GetSecret("host");
                var username = sp.GetSecret("username");
                var port     = sp.GetSecret("port");
                var pw       = sp.GetSecret("postgres_db_password");
                connectionString = $"Host={host};Port={port};Username={username};Password={pw};Database={db};";
            }

            services.AddDbContext <DataContext>(options =>
            {
                options.UseNpgsql(connectionString, b => b.MigrationsAssembly("Mqtt.Context"));
            }, ServiceLifetime.Transient);
            services.AddTransient <Func <DataContext> >(options => () => options.GetService <DataContext>());

            services.AddHostedService <MqttService>();
        }
Ejemplo n.º 11
0
        public static CookAppUser CreateInstance(string userName, string password, string mobile, string email)
        {
            var now  = DateTime.Now;
            var user = new CookAppUser
            {
                UserName  = userName,
                Password  = SecretProvider.EncryptToMD5(password),
                Mobile    = mobile,
                Email     = email,
                CreatedBy = userName,
                CreatedOn = now,
                UpdatedBy = userName,
                UpdatedOn = now
            };

            user.GenerateId();
            return(user);
        }
Ejemplo n.º 12
0
        public static User CreateInstance(string userName, string mobile, string email, string password, string nickName, string operatedBy, UserPartition partition = UserPartition.JianPing, UserChannel channel = UserChannel.JianPingApp)
        {
            var now = DateTime.Now;

            return(new User
            {
                Mobile = mobile,
                Channel = channel,
                CreatedBy = operatedBy,
                CreatedOn = now,
                Email = email,
                NickName = nickName,
                Partition = partition,
                Password = SecretProvider.EncryptToMD5(password),
                UpdatedBy = operatedBy,
                UpdatedOn = now,
                UserName = userName,
                IsSuspend = false
            });
        }
Ejemplo n.º 13
0
        private static IHostBuilder CreateHostBuilder(string[] args)
        => Host.CreateDefaultBuilder(args)
        .UseSerilog()
        .ConfigureServices((hostContext, services) =>
        {
            var configuration = hostContext.Configuration;
            services.AddSingleton <IMqttServerOptions, MqttServerOptions>();
            services.AddSingleton <IMqttServerFactory, MqttFactory>();
            services.AddSingleton <IMqttServerStorage, MqttStorage>();
            services.AddSingleton <IMqttServerSubscriptionInterceptor, MqttServerSubscriptionInterceptor>();
            services.AddSingleton <IMqttServerApplicationMessageInterceptor, MqttServerApplicationMessageInterceptor>();
            services.AddSingleton <IMqttServerConnectionValidator, MqttServerConnectionValidator>();
            services.AddSingleton <IServerBuilder, ServerBuilder>();
            services.AddScoped <IMqttRepository, MqttRepository>();
            ISecretProvider sp = new SecretProvider();
            services.AddSingleton(sp);
            var stage = Environment.GetEnvironmentVariable("STAGE") ?? "Development";
            string connectionString;
            if (stage == "Development")
            {
                connectionString = configuration.GetConnectionString("postgres");
            }
            else
            {
                var db           = sp.GetSecret("database");
                var host         = sp.GetSecret("host");
                var username     = sp.GetSecret("username");
                var port         = sp.GetSecret("port");
                var pw           = sp.GetSecret("postgres_db_password");
                connectionString = $"Host={host};Port={port};Username={username};Password={pw};Database={db};";
            }
            services.AddDbContext <DataContext>(options =>
                                                options.UseNpgsql(connectionString, b => b.MigrationsAssembly("Mqtt.Context")));

            services.AddHostedService <MqttService>();
        });
Ejemplo n.º 14
0
        public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddMemoryCache();
            services.AddHostedService <CacheLoader>();

            services.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>();

            var sendGridUser    = Environment.GetEnvironmentVariable("SEND_GRID_USER");
            var graphQLEndpoint = Environment.GetEnvironmentVariable("GRAPH_QL_ENDPOINT");
            var apiEndpoint     = Environment.GetEnvironmentVariable("API_ENDPOINT");
            var apiPort         = Environment.GetEnvironmentVariable("API_PORT");

            var secretProvider = new SecretProvider();
            var key            = secretProvider.GetSecret("send_grid_key");

            if (Env.IsDevelopment())
            {
                key = Environment.GetEnvironmentVariable("SEND_GRID_KEY");
            }

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddTransient(_ => new AuthMessageSenderOptions
            {
                SendGridKey  = key,
                SendGridUser = sendGridUser
            });

            services.AddAutoMapper(typeof(Program).Assembly);

            services.AddScoped(_ => new GraphQLClient(graphQLEndpoint));
            services.AddScoped <ISecretProvider, SecretProvider>();
            services.AddScoped <IStoreWrapper, StoreWrapper>();
            services.AddScoped <ISlipwayStore, SlipwayStore>();
            services.AddScoped <IExtraStore, ExtraStore>();
            services.AddScoped <IManufacturerStore, ManufacturerStore>();
            services.AddScoped <IWaterStore, WaterStore>();
            services.AddScoped <IServiceStore, ServiceStore>();
            services.AddScoped <IPortStore, PortStore>();
            services.AddScoped <WaterViewModel>();
            services.AddScoped <IGraphQLService, GraphQLService>();

            services.AddTransient(_ => new ApplicationInfo {
                ApiEndpoint = $"{apiEndpoint}:{apiPort}", GraphQlEndpoint = graphQLEndpoint
            });

            services.AddHttpClient <ISlipwayService, SlipwayService>("slipwayClient", options =>
            {
                options.BaseAddress = new Uri($"{apiEndpoint}:{apiPort}");
            });
            services.AddHttpClient <IServiceService, ServiceService>("serviceClient", options =>
            {
                options.BaseAddress = new Uri($"{apiEndpoint}:{apiPort}");
            });
            services.AddHttpClient <IExtraService, ExtraService>("extraClient", options =>
            {
                options.BaseAddress = new Uri($"{apiEndpoint}:{apiPort}");
            });
            services.AddHttpClient <IWaterService, WaterService>("waterClient", options =>
            {
                options.BaseAddress = new Uri($"{apiEndpoint}:{apiPort}");
            });
            services.AddHttpClient <IManufacturerService, ManufacturerService>("manufacturerClient", options =>
            {
                options.BaseAddress = new Uri($"{apiEndpoint}:{apiPort}");
            });
            services.AddHttpClient <IPortService, PortService>("portClient", options =>
            {
                options.BaseAddress = new Uri($"{apiEndpoint}:{apiPort}");
            });

            if (!Env.IsDevelopment())
            {
                services.AddDataProtection()
                .SetApplicationName("slipways-web")
                .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/app/keys/"));
            }

            services.AddRazorPages()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Slipways");
                if (!Env.IsDevelopment())
                {
                    options.Conventions.AuthorizeAreaFolder("Admin", "/Slipway");
                    options.Conventions.AuthorizeAreaFolder("Admin", "/Water");
                    options.Conventions.AuthorizeAreaFolder("Admin", "/Service");
                    options.Conventions.AuthorizeAreaFolder("Admin", "/Port");
                }
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString      = "yyyy-MM-ddTHH:mm:ss";
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders =
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            var password = string.Empty;

            if (Env.IsProduction())
            {
                password = secretProvider.GetSecret("sqlserver");
            }
            else if (Env.IsStaging())
            {
                password = secretProvider.GetSecret("dev_slipway_db");
            }
            else
            {
                password = "******";
            }

            var server = Environment.GetEnvironmentVariable("SERVER");
            var user   = Environment.GetEnvironmentVariable("USER");
            var db     = Environment.GetEnvironmentVariable("DATABASE");
            var port   = Environment.GetEnvironmentVariable("PORT");

            var str = $"Server={server},{port};Database={db};User Id={user};Password={password}";

            services.AddDbContext <ApplicationDbContext>(_ => _.UseSqlServer(str));
        }
Ejemplo n.º 15
0
 public void GenerateGooiosSessionKey()
 {
     GooiosSessionKey = SecretProvider.EncryptToMD5($"{UserId}#{OpenId}${Guid.NewGuid().ToString()}>{CreatedOn.ToString()}");
 }
Ejemplo n.º 16
0
        public CookAppUserDto VerifyCookAppUserByPassword(string userName, string password)
        {
            var obj = _cookappUserRepo.GetFiltered(o => o.UserName == userName && o.Password == SecretProvider.EncryptToMD5(password)).FirstOrDefault();

            if (obj == null)
            {
                return(null);
            }
            return(MapperProvider.Mapper.Map <CookAppUserDto>(obj));
        }
Ejemplo n.º 17
0
 public MainWindow()
 {
     InitializeComponent();
     PopulateComboBoxWithTranscriptions();
     secretProvider = new SecretProvider(translationkeySecretIdentifier, subscriptionKeySecretIdentifier, applicationId);
 }
Ejemplo n.º 18
0
        public bool CheckPassword(string password)
        {
            var encryptPassword = SecretProvider.EncryptToMD5(password);

            return(encryptPassword == this.Password);
        }
Ejemplo n.º 19
0
 public static ICrypter Default(SecretProvider secretProvider)
 {
     return(new ValueCrypter(secretProvider));
 }
        public Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken)
        {
            if (!IsHmacEnabled)
            {
                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, "0")
                };

                context.Principal = new ClaimsPrincipal(
                    new[] {
                    new ClaimsIdentity(claims, SignatureProvider.SignatureScheme)
                });
                return(Task.FromResult(0));
            }

            var request       = context.Request;
            var authorization = request.Headers.Authorization;

            if (authorization == null || authorization.Scheme != SignatureProvider.SignatureScheme)
            {
                return(Task.FromResult(0));
            }
            if (string.IsNullOrWhiteSpace(authorization.Parameter))
            {
                context.ErrorResult = new AuthenticationFailureResult("Authorization token missing from header", request);
                return(Task.FromResult(0));
            }
            if (!request.Headers.Contains(SignatureProvider.UserIDHeader))
            {
                context.ErrorResult = new AuthenticationFailureResult(string.Format("User ID header {0} missing", SignatureProvider.UserIDHeader), request);
                return(Task.FromResult(0));
            }
            var userId = request.Headers.GetValues(SignatureProvider.UserIDHeader).FirstOrDefault();

            if (string.IsNullOrEmpty(userId))
            {
                context.ErrorResult = new AuthenticationFailureResult(string.Format("User ID missing from header value {0}", SignatureProvider.UserIDHeader), request);
                return(Task.FromResult(0));
            }

            var key = SecretProvider.GetSignatureSecretKey(userId);

            if (string.IsNullOrEmpty(key))
            {
                context.ErrorResult = new AuthenticationFailureResult("Unknown User ID", request);
                return(Task.FromResult(0));
            }

            var uri           = request.RequestUri.ToString().ToLowerInvariant();
            var stripProtocol = SecretProvider.GetProtocolStripList().Any(site => uri.Contains(site));
            var success       = SignatureProvider.HasValidSignature(request, userId, key, TimeOutPeriod, stripProtocol);

            //success = true;

            if (!success)
            {
                var sig        = SignatureProvider.CreateSignature(request, key, stripProtocol);
                var diagnostic = string.Format("Diagnostic info follows. Signature: {0}, attached sig: {1}, method: {2}, URI: {3}, content: {4}, Request time stamp:{5}, Server time stamp:{6}, User: {7}, Auth: {8}",
                                               sig,
                                               request.Headers.Authorization.Parameter,
                                               request.Method,
                                               request.RequestUri,
                                               request.Content != null ? request.Content.ReadAsStringAsync().Result : "",
                                               request.Headers.Date == null ? "" : request.Headers.Date.Value.ToUniversalTime().ToString("r"),
                                               DateTime.Now.ToUniversalTime().ToString("r"),
                                               request.Headers.GetValues(SignatureProvider.UserIDHeader).FirstOrDefault(),
                                               request.Headers.Authorization.Scheme);
                context.ErrorResult = new AuthenticationFailureResult("Invalid or expired signature. " + diagnostic, request);
            }
            else
            {
                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, userId)
                };

                context.Principal = new ClaimsPrincipal(
                    new[] {
                    new ClaimsIdentity(claims, SignatureProvider.SignatureScheme)
                });
            }

            //Place user id in context for later use
            context.ActionContext.Request.Properties.Add(UserIdField, userId);

            return(Task.FromResult(0));
        }