Exemple #1
0
        public async void HandleEnvRequestAsync_ReturnsExpected()
        {
            var opts = new EnvEndpointOptions();

            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appSettings);
            var config = configurationBuilder.Build();
            var host   = new HostingEnvironment()
            {
                EnvironmentName = "EnvironmentName"
            };
            var mgmtOptions = TestHelpers.GetManagementOptions(opts);
            var ep          = new EnvEndpoint(opts, config, host);
            var middle      = new EnvEndpointMiddleware(null, ep, mgmtOptions);

            var context = CreateRequest("GET", "/env");
            await middle.HandleEnvRequestAsync(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(context.Response.Body, Encoding.UTF8);
            var json   = await reader.ReadLineAsync();

            var expected = "{\"activeProfiles\":[\"EnvironmentName\"],\"propertySources\":[{\"properties\":{\"management:endpoints:path\":{\"value\":\"/cloudfoundryapplication\"},\"management:endpoints:enabled\":{\"value\":\"true\"},\"Logging:LogLevel:Steeltoe\":{\"value\":\"Information\"},\"Logging:LogLevel:Pivotal\":{\"value\":\"Information\"},\"Logging:LogLevel:Default\":{\"value\":\"Warning\"},\"Logging:IncludeScopes\":{\"value\":\"false\"}},\"name\":\"MemoryConfigurationProvider\"}]}";

            Assert.Equal(expected, json);
        }
Exemple #2
0
        public void GetPropertySourceName_ReturnsExpected()
        {
            var opts    = new EnvEndpointOptions();
            var builder = new ConfigurationBuilder();

            builder.AddEnvironmentVariables();
            var config = builder.Build();
            var env    = HostingHelpers.GetHostingEnvironment();
            var ep     = new EnvEndpoint(opts, config, env);

            var provider = config.Providers.Single();
            var name     = ep.GetPropertySourceName(provider);

            Assert.Equal(provider.GetType().Name, name);

            builder = new ConfigurationBuilder();
            builder.AddJsonFile("foobar", true);
            config = builder.Build();

            ep = new EnvEndpoint(opts, config, env);

            provider = config.Providers.Single();
            name     = ep.GetPropertySourceName(provider);
            Assert.Equal("JsonConfigurationProvider: [foobar]", name);
        }
Exemple #3
0
        public void EnvEndpointMiddleware_PathAndVerbMatching_ReturnsExpected()
        {
            var opts = new EnvEndpointOptions();
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appSettings);
            var config = configurationBuilder.Build();
            var host   = new HostingEnvironment()
            {
                EnvironmentName = "EnvironmentName"
            };
            var ep   = new EnvEndpoint(opts, config, host);
            var mgmt = new CloudFoundryManagementOptions()
            {
                Path = "/"
            };

            mgmt.EndpointOptions.Add(opts);
            var middle = new EnvEndpointMiddleware(null, ep, new List <IManagementOptions> {
                mgmt
            });

            Assert.True(middle.RequestVerbAndPathMatch("GET", "/env"));
            Assert.False(middle.RequestVerbAndPathMatch("PUT", "/env"));
            Assert.False(middle.RequestVerbAndPathMatch("GET", "/badpath"));
        }
        /// <summary>
        /// Add Environment middleware to OWIN Pipeline
        /// </summary>
        /// <param name="builder">OWIN <see cref="IAppBuilder" /></param>
        /// <param name="config"><see cref="IConfiguration"/> of application for configuring env endpoint and inclusion in response</param>
        /// <param name="hostingEnvironment"><see cref="IHostingEnvironment"/> of the application</param>
        /// <param name="loggerFactory">For logging within the middleware</param>
        /// <returns>OWIN <see cref="IAppBuilder" /> with Env Endpoint added</returns>
        public static IAppBuilder UseEnvActuator(this IAppBuilder builder, IConfiguration config, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory = null)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

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

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

            IEnvOptions options     = new EnvEndpointOptions(config);
            var         mgmtOptions = ManagementOptions.Get(config);

            foreach (var mgmt in mgmtOptions)
            {
                if (!mgmt.EndpointOptions.Contains(options))
                {
                    mgmt.EndpointOptions.Add(options);
                }
            }

            var endpoint = new EnvEndpoint(options, config, hostingEnvironment, loggerFactory?.CreateLogger <EnvEndpoint>());
            var logger   = loggerFactory?.CreateLogger <EndpointOwinMiddleware <EnvironmentDescriptor> >();

            return(builder.Use <EndpointOwinMiddleware <EnvironmentDescriptor> >(endpoint, mgmtOptions, new List <HttpMethod> {
                HttpMethod.Get
            }, true, logger));
        }
Exemple #5
0
        public void GetPropertySourceDescriptor_ReturnsExpected()
        {
            var opts        = new EnvEndpointOptions();
            var appsettings = new Dictionary <string, string>()
            {
                ["management:endpoints:enabled"]            = "false",
                ["management:endpoints:path"]               = "/cloudfoundryapplication",
                ["management:endpoints:loggers:enabled"]    = "false",
                ["management:endpoints:heapdump:enabled"]   = "true",
                ["management:endpoints:heapdump:sensitive"] = "true",
                ["management:endpoints:cloudfoundry:validatecertificates"] = "true",
                ["management:endpoints:cloudfoundry:enabled"] = "true"
            };
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appsettings);
            var config = configurationBuilder.Build();

            var ep       = new EnvEndpoint(opts, config, new TestHosting());
            var provider = config.Providers.Single();
            var desc     = ep.GetPropertySourceDescriptor(provider, config);

            Assert.Equal("MemoryConfigurationProvider", desc.Name);
            var props = desc.Properties;

            Assert.NotNull(props);
            Assert.Equal(7, props.Count);
            Assert.Contains("management:endpoints:enabled", props.Keys);
            var prop = props["management:endpoints:enabled"];

            Assert.NotNull(prop);
            Assert.Equal("false", prop.Value);
            Assert.Null(prop.Origin);
        }
Exemple #6
0
        public void Sanitized_NonDefault_WhenSet()
        {
            var appsettings = new Dictionary <string, string>()
            {
                ["management:endpoints:env:keystosanitize:0"] = "credentials",
                ["password"] = "******"
            };

            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appsettings);
            var config = configurationBuilder.Build();
            var opts   = new EnvEndpointOptions(config);
            var ep     = new EnvEndpoint(opts, config, new TestHosting());
            var result = ep.DoInvoke(config);

            Assert.NotNull(result);

            var desc = result.PropertySources[0];

            Assert.Equal("MemoryConfigurationProvider", desc.Name);
            var props = desc.Properties;

            Assert.NotNull(props);
            Assert.Contains("password", props.Keys);
            Assert.NotNull(props["password"]);
            Assert.Equal("mysecret", props["password"].Value);
        }
Exemple #7
0
        /// <summary>
        /// Register the ENV endpoint, OWIN middleware and options
        /// </summary>
        /// <param name="container">Autofac DI <see cref="ContainerBuilder"/></param>
        /// <param name="config">Your application's <see cref="IConfiguration"/></param>
        /// <param name="hostingEnv">A class describing the app hosting environment - defaults to <see cref="GenericHostingEnvironment"/></param>
        public static void RegisterEnvActuator(this ContainerBuilder container, IConfiguration config, IHostingEnvironment hostingEnv = null)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

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

            container.Register(c =>
            {
                var envOptions  = new EnvEndpointOptions(config);
                var mgmtOptions = c.Resolve <IEnumerable <IManagementOptions> >();
                foreach (var mgmt in mgmtOptions)
                {
                    mgmt.EndpointOptions.Add(envOptions);
                }
                return(envOptions);
            }).As <IEnvOptions>().IfNotRegistered(typeof(IEnvOptions));

            container.RegisterInstance(hostingEnv ?? new GenericHostingEnvironment()
            {
                EnvironmentName = "Production"
            }).As <IHostingEnvironment>();
            container.RegisterType <EnvEndpoint>().As <IEndpoint <EnvironmentDescriptor> >().SingleInstance();
            container.RegisterType <EndpointOwinMiddleware <EnvironmentDescriptor> >().SingleInstance();
        }
        public void RoutesByPathAndVerb()
        {
            var options = new EnvEndpointOptions();

            Assert.True(options.ExactMatch);
            Assert.Equal("/actuator/env", options.GetContextPath(new ActuatorManagementOptions()));
            Assert.Equal("/cloudfoundryapplication/env", options.GetContextPath(new CloudFoundryManagementOptions()));
            Assert.Null(options.AllowedVerbs);
        }
Exemple #9
0
        public void Constructor_InitializesWithDefaults()
        {
            var opts = new EnvEndpointOptions();

            Assert.Equal("env", opts.Id);

            Assert.Equal(new string[] { "password", "secret", "key", "token", ".*credentials.*", "vcap_services" }, opts.KeysToSanitize);
            Assert.Equal(Permissions.RESTRICTED, opts.RequiredPermissions);
        }
Exemple #10
0
        public void GetPropertySourceDescriptor_ReturnsExpected()
        {
            var opts        = new EnvEndpointOptions();
            var appsettings = new Dictionary <string, string>()
            {
                ["management:endpoints:enabled"]            = "false",
                ["management:endpoints:path"]               = "/cloudfoundryapplication",
                ["management:endpoints:loggers:enabled"]    = "false",
                ["management:endpoints:heapdump:enabled"]   = "true",
                ["management:endpoints:heapdump:sensitive"] = "true",
                ["management:endpoints:cloudfoundry:validatecertificates"] = "true",
                ["management:endpoints:cloudfoundry:enabled"] = "true",
                ["common"]   = "appsettings",
                ["CharSize"] = "should not duplicate"
            };

            var otherAppsettings = new Dictionary <string, string>()
            {
                ["common"]   = "otherAppsettings",
                ["charSize"] = "should not duplicate"
            };

            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appsettings);
            configurationBuilder.AddInMemoryCollection(otherAppsettings);
            var config = configurationBuilder.Build();
            var env    = HostingHelpers.GetHostingEnvironment();
            var ep     = new EnvEndpoint(opts, config, env);

            var appsettingsProvider = config.Providers.ElementAt(0);
            var appsettingsDesc     = ep.GetPropertySourceDescriptor(appsettingsProvider);

            var otherAppsettingsProvider = config.Providers.ElementAt(1);
            var otherAppsettingsDesc     = ep.GetPropertySourceDescriptor(otherAppsettingsProvider);

            Assert.Equal("MemoryConfigurationProvider", appsettingsDesc.Name);
            var props = appsettingsDesc.Properties;

            Assert.NotNull(props);
            Assert.Equal(9, props.Count);
            Assert.Contains("management:endpoints:enabled", props.Keys);
            var prop = props["management:endpoints:enabled"];

            Assert.NotNull(prop);
            Assert.Equal("false", prop.Value);
            Assert.Null(prop.Origin);

            var otherProps                = otherAppsettingsDesc.Properties;
            var appsettingsCommonProp     = props["common"];
            var otherAppsettingCommonProp = otherProps["common"];

            Assert.Equal("appsettings", appsettingsCommonProp.Value);
            Assert.Equal("otherAppsettings", otherAppsettingCommonProp.Value);
        }
Exemple #11
0
        public static void UseEnvActuator(IConfiguration configuration, IHostingEnvironment hostingEnvironment = null, ILoggerFactory loggerFactory = null)
        {
            var options = new EnvEndpointOptions(configuration);

            _mgmtOptions.RegisterEndpointOptions(configuration, options);
            hostingEnvironment = hostingEnvironment ?? new DefaultHostingEnvironment("development");
            var ep      = new EnvEndpoint(options, configuration, hostingEnvironment, CreateLogger <EnvEndpoint>(loggerFactory));
            var handler = new EnvHandler(ep, SecurityServices, _mgmtOptions, CreateLogger <EnvHandler>(loggerFactory));

            ConfiguredHandlers.Add(handler);
        }
Exemple #12
0
        public void Constructor_ThrowsIfNulls()
        {
            IEnvOptions         options       = null;
            IConfiguration      configuration = null;
            IHostingEnvironment env           = null;

            Assert.Throws <ArgumentNullException>(() => new EnvEndpoint(options, configuration, env));

            options = new EnvEndpointOptions();
            Assert.Throws <ArgumentNullException>(() => new EnvEndpoint(options, configuration, env));

            configuration = new ConfigurationBuilder().Build();
            Assert.Throws <ArgumentNullException>(() => new EnvEndpoint(options, configuration, env));
        }
Exemple #13
0
        /// <summary>
        /// Adds the services used by the Env actuator
        /// </summary>
        /// <param name="services">Reference to the service collection</param>
        /// <param name="configuration">Reference to the configuration system</param>
        /// <returns>A reference to the service collection</returns>
        public static IServiceCollection AddEnvActuatorServices(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

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

            var options = new EnvEndpointOptions(configuration);

            services.TryAddSingleton <IEnvOptions>(options);
            services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IEndpointOptions), options));
            services.TryAddSingleton <EnvEndpoint>();

            return(services);
        }
Exemple #14
0
        public void EnvEndpointMiddleware_PathAndVerbMatching_ReturnsExpected()
        {
            var opts = new EnvEndpointOptions();
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            var config = configurationBuilder.Build();
            var host   = new GenericHostingEnvironment()
            {
                EnvironmentName = "EnvironmentName"
            };
            var ep   = new EnvEndpoint(opts, config, host);
            var mgmt = new CloudFoundryManagementOptions()
            {
                Path = "/"
            };
            var middle = new EndpointOwinMiddleware <EnvironmentDescriptor>(null, ep, new List <IManagementOptions> {
                mgmt
            });

            Assert.True(middle.RequestVerbAndPathMatch("GET", "/env"));
            Assert.False(middle.RequestVerbAndPathMatch("PUT", "/env"));
            Assert.False(middle.RequestVerbAndPathMatch("GET", "/badpath"));
        }
Exemple #15
0
        public void DoInvoke_ReturnsExpected()
        {
            var opts        = new EnvEndpointOptions();
            var appsettings = new Dictionary <string, string>()
            {
                ["management:endpoints:enabled"]          = "false",
                ["management:endpoints:path"]             = "/cloudfoundryapplication",
                ["management:endpoints:loggers:enabled"]  = "false",
                ["management:endpoints:heapdump:enabled"] = "true",
                ["management:endpoints:cloudfoundry:validatecertificates"] = "true",
                ["management:endpoints:cloudfoundry:enabled"] = "true"
            };
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appsettings);
            var config = configurationBuilder.Build();

            var ep     = new EnvEndpoint(opts, config, new TestHosting());
            var result = ep.DoInvoke(config);

            Assert.NotNull(result);
            Assert.Single(result.ActiveProfiles);
            Assert.Equal("EnvironmentName", result.ActiveProfiles[0]);
            Assert.Single(result.PropertySources);

            var desc = result.PropertySources[0];

            Assert.Equal("MemoryConfigurationProvider", desc.Name);
            var props = desc.Properties;

            Assert.NotNull(props);
            Assert.Equal(6, props.Count);
            Assert.Contains("management:endpoints:loggers:enabled", props.Keys);
            var prop = props["management:endpoints:loggers:enabled"];

            Assert.NotNull(prop);
            Assert.Equal("false", prop.Value);
            Assert.Null(prop.Origin);
        }
Exemple #16
0
        public void Sanitized_ReturnsExpected()
        {
            var opts        = new EnvEndpointOptions();
            var appsettings = new Dictionary <string, string>()
            {
                ["password"]         = "******",
                ["secret"]           = "mysecret",
                ["key"]              = "mysecret",
                ["token"]            = "mysecret",
                ["my_credentials"]   = "mysecret",
                ["credentials_of"]   = "mysecret",
                ["my_credentialsof"] = "mysecret",
                ["vcap_services"]    = "mysecret"
            };
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appsettings);
            var config = configurationBuilder.Build();

            var ep     = new EnvEndpoint(opts, config, new TestHosting());
            var result = ep.DoInvoke(config);

            Assert.NotNull(result);

            var desc = result.PropertySources[0];

            Assert.Equal("MemoryConfigurationProvider", desc.Name);
            var props = desc.Properties;

            Assert.NotNull(props);
            foreach (var key in appsettings.Keys)
            {
                Assert.Contains(key, props.Keys);
                Assert.NotNull(props[key]);
                Assert.Equal("******", props[key].Value);
                Assert.Null(props[key].Origin);
            }
        }