Spring Cloud Contract Setting `stubsMode` at runtime - configuration

We're using Spring Cloud Contract for testing our services. I was wondering if there is some way to set the stubsMode at runtime, as opposed to being an option on the annotation:
#AutoConfigureStubRunner(ids = {...}, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
If the annotation is the only way to set this option, we'll need to have two separate classes, one for local and one for remote.

You can use the properties. We describe it in the docs. Just pass the system prop stubrunner.stubs-mode=local or an env var STUBRUNNER_STUBS_MODE=LOCAL

Related

Passing sensitive information to cloud functions

Is there an "official" solution for passing sensitive information, such as API keys, to Google Cloud Functions? In particular it would be nice to avoid passing this information as arguments to the function since it will be the same for every invocation. AWS Lambda has a built-in solution using encrypted environment variables for this. Is there some similar approach for Google Cloud Functions?
I could imagine using a cloud storage bucket or cloud datastore for this, but that feels very manual.
If you're using Cloud Functions with Firebase, you're looking for environment configuration.
With that, you deploy configuration data from the Firebase CLI:
firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
And then read it in your functions with:
functions.config().someservice.id
You can use Google Secret Manager.
https://cloud.google.com/secret-manager/docs
See this article for an example:
https://dev.to/googlecloud/using-secrets-in-google-cloud-functions-5aem
The other answers are outdated, since firebase-functions v3.18.0 the recommended way is to use secrets (like env but passed explicitly to specific functions and without .env but a remote config) : https://firebase.google.com/docs/functions/config-env?hl=en#secret-manager
Before environment variable support was released in firebase-functions v3.18.0, using functions.config() was the recommended approach for environment configuration. This approach is still supported, but we recommend all new projects use environment variables instead, as they are simpler to use and improve the portability of your code.
You can use it like this:
firebase functions:secrets:set MY_SECRET
And answer a value to the CLI.
And then in your function:
exports.processPayment = functions
// Make the secret available to this function
.runWith({ secrets: ["MY_SECRET"] })
.onCall((data, context) => {
// Now you have access to process.env.MY_SECRET
});
Few options that you can go about this:
GCP Runtime Configuration. Set up a schema that can be only accessed by your service account and put your secret there. You do that prior to your deployment. Your app should be able to use Runtime Configuration API to access these. You can use this nifty library: https://www.npmjs.com/package/#google-cloud/rcloadenv
Generate a JS on the fly including that information as part of your cloud function build/deploy and include that file as part of you cloud function.
Use Google KMS to store the keys and access it with KMS's API
As for now, there's no way to do this.
https://issuetracker.google.com/issues/35907643

Restlet custom configuration properties files

Frameworks like Spring, Struts facilitates for property file reading. For instance MessageResources in Struts. I want to know whether there are such property files which are in built supported by Restlet framework itself. If there is one, then I will not need to re invent the wheel and be able to use it straight.My application configuration values will be included in that file. I am new to Restlet, I couldn't find any soulution. Any way to do this?
There is no support like this in Restlet. That said you can leverage client protocols to load these properties files from difference locations:
Protocol.FILE - from filesystem directly
Protocol.CLAP - from classpath
Protocol.OBAP - from OSGi bundle
Here is a sample:
ClientResource cr = new ClientResource("clap://someproperties.properties");
Properties props = new Properties();
props.load(cr.get().getStream());
You need to specify this protocol when defining your component:
Component component = new Component();
(...)
component.getServers().add(Protocol.HTTP, 8182);
component.getClients().add(Protocol.CLAP);

How to pass configuration parameters to SimpleInjector packaging?

So SimpleInjector now has a packaging nuget that you can use to isolate different aspects of root composition.
Say I have a configurable composition root in a library that is reused by multiple projects in an application. For example, in an Azure solution I might have a Web role and a Worker role which share a large set of the same dependencies for the most part, but with slightly different configuration options depending on the consumer. When I compose the root, I can pass in a plain old RootCompositionSettings object with properties that tell SimpleInjector how to register dependencies.
However, I am not sure how (or if) I can pass these settings to an IPackage instance. Is it possible to pass custom settings to a SimpleInjector package, and if so, how?
I see that the standard practices for registering packages is to invoke either
container.RegisterPackages(); // scans all loaded assemblies for IPackage
// or
container.RegisterPackages(IEnumerable<Assembly>) // specific assemblies only
...so how can we pass parameters into the packaging instance(s)? Is there some way to do it via the container?
The trick here is to pass the information on with the container to the package. You can do this by using the container's Items dictionary, that is much like ASP.NET's HttpContext.Items collection. This can be done as follows:
using SimpleInjector.Advanced;
container.SetItem(typeof(RootCompositionSettings), settings);
container.RegisterPackages();
Now inside your packages, you can do the following:
var settings =
(RootCompositionSettings)container.GetItem(typeof(RootCompositionSettings));
Please note that:
SetItem and GetItem are extension methods that are located in the SimpleInjector.Advanced namespace. Those methods allow you to access the (internal) Items dictionary.
You can pass in any key you like. Passing in typeof(RootCompositionSettings) is just convenient in this case, but not required.
If you need to call the settings in more places, it might be useful to create a more specific extension method that allows you to access the setting instance, but that's up to you.
Another option is to not use the IPackage interface and the SimpleInjector.Packaging library at all. In most cases it doesn't really add anything and you could simply define a public static method in the assembly that does the same as a package does. For instance:
public static class BusinessLayerBootstrapper
{
public static void Bootstrap(Container container, ScopedLifestyle scopedLifestyle,
RootCompositionSettings settings)
{
// Here the same logic as what you would write in your package.
}
}
Most applications are not that dynamic that you need to load assemblies dynamically and the startup project usually has a hard reference to all the other assemblies. In that case it is perfectly sane to simply call a static method.
And even if you have the requirement of dynamically loading assemblies and allowing them to register their stuff in the container, it's quite trivial to build your own IPackage abstraction instead:\
// Your own IPackage interface
public interface IPackage
{
void RegisterServices(Container container, RootCompositionSettings settings);
}
// Your own extension method
public static void RegisterPackages(this Container container,
RootCompositionSettings settings)
{
var packages =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetExportedTypes()
where typeof(IPackage).IsAssignableFrom(type)
where !type.IsAbstract
select (IPackage)Activator.CreateInstance(type);
packages.ToList().ForEach(p => p.RegisterServices(container, settings));
}
In fact, except for some extra validations and filtering out dynamic assemblies, the SimpleInjector.Packaging project is not much more than this.

Resolving a dependency while supplying values for downstream dependencies

I've been running into endless problems attempting to use Windsor with Web API and injecting HttpRequestMessage into downstream dependencies of a controller. Since I've tried all the matching answers on Stackoverflow, I'd like to ask the question in a different way:
In Castle Windsor, how can I resolve a component instance while supplying a value for a downstream dependency? That is, the supplied value is required by a component that is required by the component being resolved.
For context, I'm trying to inject HttpRequestMessage so that I can use it to resolve the request context (primarily to resolve an absolute URL).
Edit I'd also like to point out that I don't currently have a dependency on Web Host / System.Web and I'd rather not change that.
A proper approach is to
Create IMyDesiredRouteParameterProvider
Implement it. Get the current request inside it and get the url
Register it and inject it in the desired dependent class via constructor.
I made myself such an implementation and I can say that this way it works fine. You can make Web.Infrastructure assembly and put the implementation there. Or put both the interface and the implementation there if you are going to reference it from another web module.
using System;
using System.Web;
namespace RouteParameterProvider
{
interface IMyRouteParameterProvider
{
string GetRouteParameter();
}
public class ControllerActionMethodRouteParameterProvider : IMyRouteParameterProvider
{
public string GetRouteParameter()
{
string Parameter = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"] as string;
if (string.IsNullOrEmpty(Parameter))
{
throw new InvalidOperationException();
}
return Parameter;
}
}
}
You can get every possible thing that the Request Context contains from :
HttpContext.Current.Request.RequestContext
And it will be better if you rethink your design decision :
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
Containers are to be initialized at runtime and then used to resolve.
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
It sounds like you want to register an item with the container at runtime, post-startup. In general, this is not a good practice--registration should be a discrete event that happens when the app is fired up, and the container's state should not be changed during runtime.
Dependency Injection is about resolving service components, not runtime state--state is generally passed via methods (method injection). In this case it sounds like your LinkGenerator component needs access to the ambient state of the request.
I'm not that familiar with HttpRequestMessage, but this answer seems to show that it is possible to retreive it from HttpContext.Current. You could make this a method on your LinkGenerator class, or wrap this call in a separate component that gets injected into LinkGenerator (HttpRequestMessageProvider?). The latter would be my preferred method, as it allows LinkGenerator to be more testable.
Given the lack of a clean way of doing this and Web API not providing information as to the hosted endpoint beyond per-request context objects, I ended up injecting the base url from configuration.
Is this library by Mark Seemann the answer? In the description he writes explicitly :
This approach enables the use of Dependency Injection (DI) because the
request can be injected into the services which require it.
Then gives an example :
// Inside an ApiController
var uri = this.Url.GetLink(a=> a.GetById(1337));
By which you can then pass the URL down the road in the service that you have injected in the controller.
UPDATE :
Mark Seemann wrote about the same exact problem here:
"Because HttpRequestMessage provides the context you may need to
compose dependency graphs, the best extensibility point is the
extensibility point which provides an HttpRequestMessage every time a
graph should be composed. This extensibility point is the
IHttpControllerActivator interface:..."
This way you can pass request context information to a component deep in the object graph by getting from the HttpRequestMessage and passing it to the DI container.
Just take a look at the interface of IHttpControllerActivator.
The WEB API framework gets the IHttpControllerActivator through DependencyResolver. You probably already replaced it by your CastleWindsorDependencyResolver. Now you have to implement and register your HttpControllerActivator and register it.
When the WEB API framework gets IHttpControllerActivator from DependencyResolver (your Castle Windsor DR) and calls IHttpControllerActivator.Create() it will pass you the HttpRequestMessage. You can get your info from there and pass it to the your CastleDR before you call Resolve(typeof(MyController)) which will resolve the whole object graph - that means you will have MyHttpContextInfo to inject in your XYZComponent deep in the resolution stack.
This way tou are passing the arguments in the last possible moment but it is still possible. In Castle Windsor I make such passing of arguments though CreationContext.AdditionalArguments["myArgument"];.

What is the best way to pass configurations to OSGI components?

I have a set of parameters that should be configured by the user. But they are just too much to send them through RESTful services or something similar. Besides there may be another set of configurations of same parameters.
Assume that my configurations are: p1, p2, p3, ... p10
I want to make possible having more than set of initialization of these configurations such as:
(p1=x, p2=y, ... p10=1)
(p1=a, p2=b, ... p10=10)
To do that I currently implement my OSGI component with metatype=true and configurationFactory = true options so that each instance of my component will have a set of configurations initialized. Then, I process the instances in a manager component.
So the question what do you suggest for passing configurations to OSGI components from user?
Thanks
If this is really about configurations you should use the OSGi ConfigurationAdmin service. A console like the Apache Felix WebConsole can then be used to edit configurations.
If the values (or some values) can be different for each RESTful call to your application and they don't fit in a URL, you can make a POST request instead of a GET, and pass the values in the body of the request, in a suitable format.