Categories
MicroProfile Project setup

MicroProfile support for Jessie

Introduction

In some previous blog, I introduced Jessie, a tool for creating maven based applications which contain the skeleton for applications using Java EE, DeltaSpike, PrimeFaces, and Octopus (the declarative security framework for Java EE)

Although most people just copy and paste from an existing application, I find it very handy that I can generate very easily some as I create quite some demo type applications.

The last few months, besides Java EE applications, I’m also creating more and more Eclipse MicroProfile based demos. So in the last few weeks, I added support for MicroProfile into Jessie. It generates a demo app which uses the MicroProfile Specifications and specific support for the different server implementations.

MicroProfile 1.2

Version 1.2 is not the latest version of the specification. It is released end of September 2017 but is supported by quite a number of implementations as you can see on this overview page.

Besides the basic buildings blocks JAX-RS, JSON-P, and CDI, it contains

Configuration

This specification defines how configuration values can be read from different sources to customize your application.

Fault tolerance

It defines some various options for resilient micro-services like retry policies, bulkheads, circuit breakers, and fallback options.

JWT Authentication

This first version defines the basics of authentication and authorization information propagation to the micro-service using JWT. Inspired on OAuth2 and OpenId Connect, it is possible to define user information and the roles it has in a self-contained way so that no external parties need to be consulted.

Health Metrics

It defines the way how developers can expose some ‘telemetry’ data in a uniform way. It has support for things like the number of invocations, statistics on the execution time of endpoints, and so on.

Health Checks

The health checks are on a different level as the metrics. Which the checks we can verify if our service is still performing well. Or that we should kill it and start a new one. Besides standard checks (using memory, CPU, etc …) you can define your own checks very easily.

Application Generation

In this first version, the generation is still at a basic level. The online version of Jessie can be found here.

After you have selected the ‘MicroProfile’ technology stack, added some basic information about the maven artifact name, you can select one of the 4 implementations that support MicroProfile 1.2 completely

– WildFly swarm – 2017.12.1
– Liberty 17.0.0.3
– KumuluzEE 2.5.2
– Payara micro 5.181

The app contains examples of all specifications mentioned above (the JWT auth code is not always completely working due to small issues in configuration and calling the endpoint) and can be seen in action from the index.html overview page.

Conclusion

In this second official release of Jessie, you can now also generate MicroProfile 1.2 applications. You can choose one of the 4 supported implementations and all the required code for generating a fat jar application is in place.

In a future version of Jessie, newer releases of MicroProfile will be supported, the small known issues will be handled and selection of the included specifications will be possible.

have fun.

Categories
Atbash Overview

Atbash repositories overview

Now that I’m working a bit more than 6 months on the Atbash repositories, it is time to give you some overview of them.

For the moment, almost all of them are geared towards Java EE 7 and Java 7.

The idea is to create a MicroProfile compatible experience on Java EE 7. As much as possible of course. Since MicroProfile is based on Java 8, it is not always easy (or possible) to have an identical experience.

But the idea is to give the developers the possibility to have a “smooth” migration from Java EE 7 to MicroProfile by having all or the most important specifications, available on those servers.

Utility repository

Github

This contains some code used in multiple other Atbash repositories. It is not directly related to the goal but can have some usages in any project.

utils-se

– BASE64 encoder and decoder
– Utility class related to searching classes and resources on different class loaders (Current Thread, class loader of utility class or System class loader) and instantiating classes with advanced argument matching.
– Reading library or framework version from manifest file
– Check to see if an application is running within a CDI container
– Utilities related to verification and handling proxies (like determining original class)

– Reflection utilities useable in unit testing (so that we can read and set private properties without the need for setters and getters which would only be needed for testing)

utils-cdi

– Programmatic retrieval of CDI Beans, also for an optional bean (bean defined by Producer method which may or may not be present)
– Retrieval of a bean defined by Producer method involving generic types (issue due to type erasure)

– Fake bean manager useable within unit tests to supply some Mock Cdi bean instances when using programmatic CDI bean retrieval.

utils-jsf

– Creating a method expression based on the expression value
– Retrieving property values from JSF components (taking into account expressions and static values)
– Custom component finding which starts at the parent itself but then extends to the parent until found or view root is reached.

Atbash JSON (Java SE)

GitHub

Alternative JSON-B implementation (not following the specs!) to convert Java instances to JSON and vice versa. The code is adapted from the JSON smart framework (no longer maintained) for the use cases within Atbash (see Atbash JWT support) and extended to have customizations.

JWT Support (Java SE + CDI)

GitHub

The code in this repository is to support JWT (JSON Web Token, signed but also encrypted) as they appear in protocols like OAuth2 and OpenId Connect.

To support this encoding and decoding, there is also a unified handling of cryptographic keys. It is capable of reading them from a PEM file, a Java Keystore, a JWK and a JWKSet. Various encrypted formats for the Private Key are supported.

But the idea goes a bit further than just support OpenId Connect JWTs. Instead of exchanging data as JSON, why not exchange them as JWT. That way, we are not only transferring information but also make some guarantees like sender verification and end to end protection as we can detect changes through the signing.

Atbash Config (Java SE + CDI)

GitHub

The Atbash config is a Java 7 port of the MicroProfile Config specification and the Apache Geronimo implementation.

But there are also some extensions created like
– Support for custom named configuration files.
– Support for Stages so that based on a system property, values can be overridden in environments like Test environment.
– Support for custom formatted date values
– Logging of configuration values at startup of the application.
– Support for YAML format.

There is also a Config provider for testing available where the configuration values are stored in a HashMap.

Atbash Config server (MicroProfile Product)

GitHub

Allows defining the configuration values for MicroProfile application in a central place. These applications can retrieve the values using a JAX-RS endpoint.

There is also a client implementation available which, when added to the application, retrieves the values automatically, based on the configured endpoint of the config server.

Jerry (JSF)

GitHub

Jerry defines a JSF Renderer interceptor which allows you to perform various tasks on any JSF component.

It is the basis for a more advanced validation mechanism for JSF and the declarative security features of Octopus for JSF components.

Valerie (JSF, Bean Validation)

GitHub

Using the interceptor mechanism of Jerry, Valerie places the validation constraints of the Java properties (like not null, length etc) automatically on the JSF components it uses.
This way it allows to have the visual aspects of these constraints on the JSF component HTML representation and JSF validation without the need to put these constraints as JSF attribute values.

Octopus (Java SE, Java FX, CDI, JSF, JAX-RS)

GitHub

Octopus is a large framework consisting of small artifacts that bring you every aspect of authentication and authorization for Java EE and MicroProfile applications.

  • Permission-based framework
  • Secures URL, JSF components, and CDI and EJB method calls
  • Support for Java SE, JavaFX, JAX-RS and JSF
  • Integrates with OAuth2, OpenId Connect, LDAP, database, JWT, KeyCloak, CAS, …
  • Custom OpenId Connect solution within a microservices environment
  • Compatible with (and using) Microprofile (Config, Rest Client, MP-JWT, …), Java EE Security API, …
  • Very flexible, can be easily integrated within your application
  • Tightly integrated with CDI
  • Type-safe definition of permissions
  • Declarative declaration of JSF security (with tags, not using rendered attribute)
  • A custom voter can be created for more complex security requirements

Dependencies overview

The following Neo4J graph gives you an overview of the dependencies between these repositories and the relation with other libraries. Octopus is left out of the image because it would complicate it too much.

Have fun

Categories
Configuration MicroProfile

Atbash Configuration Server

Introduction

MicroProfile Config specification defines how configuration values can be picked up by the application. It has the concept of a Configuration source and converters to supply the values you need.

By default, only a ConfigSource for a classpath defined file and environment and system variables are defined.

But since we have the concepts in place, we can create our custom ConfigSource to retrieve the configuration from a central server.

Configuration Server

Instead of putting the configuration of each application within the application itself, we can store it in a central location.

It is very convenient to have an overview of the configuration of all your application at one place. Which makes updating it also very simple.

The first version of the Atbash Configuration Server exposes the configuration of an application through a JAX-RS endpoint.

The URL

/config/{application}

will give you the configuration values as a JSON structure for the specified application.

{
   "pets":"dog,cat",
   "dateValue":"2017-11-15",
   "value2":"500",
   "classname":"be.atbash.config.examples.se.testclasses.ConvTestTypeWStringCt",
   "value1":"Classpath Value",
   "value3":"true",
   "dateValueFmt":"16-11-2017,dd-MM-yyyy"
}

Creating the Configuration server

The configuration server is available within the directory  <server> of the repository https://github.com/atbashEE/atbash-config-server

You can build the server in 3 flavors

1. Java EE war.

With the maven command, mvn package -Pee7-servera WAR file is created which can be run by any Java EE 7 compliant server (Java 8 required)

2. WildFly Swarm executable JAR

The Configuration server can also be wrapped within a WildFly swarm application with the mvn package -Pwildfly-swarmcommand.

3. WebSphere Liberty executable JAR

There is also a profile defined to create a WebSphere Liberty JAR file, use the mvn package -Plibertycommand.

More servers will be supported when they have support for Config Spec 1.2.

Configuration of Server

Define within a config-server.properties or config-sever.yaml file on the classpath the following configuration information.

– rootDirectory: Root directory containing the configuration files for the application. See further for a directory structure.

– applications: List of known applications.

example (as yaml)

rootDirectory : /Users/rubus/atbash/config-server/server/demo
applications : ["app1", "app2"]

Possible directory structure

/demo
├── /app1
│  ├── app1.properties
│  └── app1-test.properties
└── /app2
   └── app2.properties

A subdirectory for each application so that the configuration values are nicely separated for each application.

All the features of Atbash config (like stage, yaml support, date support, etc) are available.

Client configuration

A ConfigSource implementation is available which integrates the result of the call to the JAX-RS endpoint into the configuration of the application.

In this first version, Atbash configuration extension is required (which makes it a bit more work) but this requirement will be removed in the next version.

Add the Maven artifact to your dependencies

    <dependency>
        <groupId>be.atbash.config</groupId>
        <artifactId>atbash-config-client</artifactId>
        <version>${atbash-config.version}</version>
    </dependency>

Define the base name of the configuration file which contains the configuration of the Config server.

Create a class implementing the be.atbash.config.spi.BaseConfigurationName interface and defining this class for usage with the ServiceLoader mechanism of Java.

Define the class name within src/main/resources/META-INF/services/be.atbash.config.spi.BaseConfigurationName

be.atbash.config.examples.DemoBaseName

Define the configuration within the specified properties file.

config.server.url=http://localhost:8181
config.server.app=app1
config.server.stage=test

* config.server.url: The _root_ of the Config server endpoint.

* config.server.app: The name of your application

* config.server.stage: (optional) Indication of the stage of the application to retrieve specific values.

We can use all the regular features of Configuration or Atbash config to specify the stage value, like environment or system properties.

The client can be used in a Java SE, Java EE or a MicroProfile environment.

Conclusion

With the Atbash Configuration server, you can store the configuration values for all your applications at a central location. The values can be picked up by a JAX-RS call through the Client ConfigSource.

The server can be run by WildFly Swarm, Liberty or a regular Java EE 7 server. The client can be used for all environments capable of using the MicroProfile Configuration spec (including Java SE and Java EE)

A future version will bring you some more features and makes it easier to set things up.

Have fun.

Categories
JavaFX Security

Declarative Security permissions for Java FX FXML Views

Introduction

Using declarative permissions is the preferred way to have security constraints on GUI elements, separately from business logic and fine-grained because we are using individual permission/access rights.
With JavaServer Faces, you can add custom tags, but also within JavaFX FXML views you can do something similar. And recently I found the time to create a POC for an idea that I had some years ago.

Declarative Permissions

When defining indications within the view of your application, GUI elements can be active or not visible depend ending on the permissions the user has. By placing them within your view markup you have 2 major benefits:

  • The ‘definition’ when an element should be visible is done on the element itself and thus it is very clear on which element it operates
  • It isn’t mingled with your other business code.

Also, using permissions is much better and easier to work with than roles. When each feature is assigned specific permissions which the user needs to have, no application redeploy is needed when a feature can now be used by more users. You just have to assign the permission to the users.
Roles are assigned to users and thus when a single feature needs to be accessible by a group of people, you can’t assign the role to them as it would give them also access to other features. And thus you end up changing the code.

JavaFX FXML

With the FXML views, you can define how the view is presented to the end users. Just as with JavaServer Pages tags, it is also possible to create your own custom components to tailor the system to your needs.
Adding additional information to the standard components is also possible by means of the userData tag.

<Button mnemonicParsing="false" onAction="#permission" text="Only admin permission">
  <userData>
    <RequiresPermissions value="admin"/>
  </userData>
</Button>

You can add there information which can be used by your code later on. You can even add multiple data sets by using the JavaFX Collections.

Here in our case we add an instance of the Octopus JavaFX RequiresPermissions class and specify that the user needs the permission admin before the button will be visible.

In order to make this work, you need also to import the class (just as within regular java code)

<?import be.atbash.ee.security.octopus.javafx.authz.tag.RequiresPermissions?>

Processing the view

In order to remove the component from the view when the user hasn’t the required permissions, we need to scan the view just before it is ‘rendered’ to the screen.
This can be easily achieved by the excellent framework afterburner which was a method getView() defined within the FXMLView class.

Octopus defines a child class, be.atbash.ee.security.octopus.javafx.SecureFXMLView, which performs the following steps when the view is retrieved

  • Scan all view nodes
  • Verifies if there is an instance of the RequiresPermissions within the userData section
  • Checks if the user has the permission or not.
  • If (s)he has not, sets the node to not visible (node.setVisible(false) )

Octopus Java FX support

Next, to the processing of the view, Octopus has now also support for JavaFX views by helping the developer in creating a Login screen and the integration with the Octopus Core classes which can perform the required steps for authentication and authorization.

This support is built on top of the afterburner framework which makes developing JavaFX applications easy.

You can start the application by using the start method from the be.atbash.ee.security.octopus.javafx.SecureFXMLApplication class.

SecureFXMLApplication.start(stage, new LoginView(), new UserPageView());

The loginView itself must extend from be.atbash.ee.security.octopus.javafx.LoginFXMLView and contain components with ids user, password and loginButton.

The start() method must also a receive an instance of the first real page which will be shown after the user is authenticated. This is a FXML view where the java class extends from be.atbash.ee.security.octopus.javafx.SecureFXMLView. These views are scanned for their contents within the userData section and component are hidden when the user doesn’t have the required privileges.

Page navigation can be performed by be.atbash.ee.security.octopus.javafx.SecureFXMLApplication#showPage and this method also perform the hiding of components based on the authorization info of this view.

Demo

The Atbash Octopus framework code has a demo application to show this feature in action. It can be found at GitHub .

For those who want to have a quick idea how it looks like, I recorded also a short video which demonstrates the demo

Conclusion

Declarative permissions can also be used on JavaFX FXML views, just as you can do this with JavaServer Faces. Instead of custom tags who defines the required permissions, you have to define the permission requirements within the userData section which is available within each JavaFX component.
This is only a POC and the functionality will be extended in future versions of Atbash Octopus (as the rewrite of the Octopus framework is currently still in Alpha)

Have fun with it

Categories
Project setup

Generating (Maven) Projects

Introduction

The first thing we do when starting a new application is setting up our project. A lot of people use Maven for this, and you have various options how you can do this.
Since I create a lot of projects for testing out various features of the Atbash projects or for trying things out (I have around 300 projects on my computer today) I was searching for some help to do this.

Application setup

When trying things out, I need to have some minimal project setup. Not only do I need the Maven pom file with the required dependencies, I also need some files like configuration or a login file for Octopus.

I do not need to have tools to generate me the JPA entities, JSF Screens or JAX-RS endpoints. Creating a few of them is not difficult with the current IDE’s and that automatic generation is mostly too opinionated so that it is not usable in production systems either.

So what are the options to have this minimal project setup

Copy and Paste

You can always copy such a minimal project you have already created and made some modifications to

  • Change the groupId and artifactId of the pom file
  • Update the dependencies
  • Update the configuration file to match your new dependencies and use case you want to test out.
  • Change the java package with your java code
  • Add or remove code depending on the feature for this use case.

This is a valid procedure and in most cases the most efficient one. You don’t need to learn any new tool, extend it with your features (Like Octopus in my case) but of course, it is not the most fun way of doing things.

JBoss Forge

JBoss Forge https://forge.jboss.org/ is a tool specifically designed to get your application up and running fast. It not only generates the project for you but also can help you in generating those well-structured classes like JPA entities, JAX-RS endpoints, and screens with JSF or Angular(JS).

I used it in the past and it can be a valuable tool but it is not the right thing for what I want.
Although you can generate your maven project, you need a script and/or a custom add-on for the features that I want (specific dependencies within the pom.xml file and some configuration and java files)

It also has a lot of options to generate code for you, but again this is sometimes opinionated and not what you or your company wants to use.

Other tools

Since there are various other tools on the internet, the topic seems to be important for a lot of people. Similar tools which I found are generjee and factorEE.
Not all of them are maintained anymore or do focus on the wrong things (for my use case) like generating code.
I also find a CLI very important in this case since it allows you to create an application very rapidly (and recreate it based on the same configuration)

Jessie

So, due to the lack of the right tool for me, I created one of my own called Jessie (Java EE Start project as it was geared at that time towards Java EE). Last year with the release of CDI 2.0, I did a rewrite of it using the Java SE CDI container and included the usage of ThymeLeaf as templating mechanism so that it became easier to generate files which can be customized.

In the OpenSource spirit of Atbash, I placed the code on Github  and created a front end for it.
You can play with it on the OpenShift V3 instance  or can download the code that just needs a few parameters within a YAML config file and the CLI version generates your project.

The first version has support for Java EE and additional frameworks like DeltaSpike, PrimeFaces, and Octopus, the security framework.

Since I’m also involved with MicroProfile lately, a version for MicroProfile and the support for the different vendor implementation like LibertyIO, WildFly Swarm, Payara Micro etc will be created later on.

Conclusion

When setting up a new project, the most efficient solution is creating it from scratch or start from a similar existing project and make the required adaptations.
Another useful tool is JBoss Forge, mainly when you are interested in generating some code.

Jessie has been created a few years ago as a toy and now available on GitHub and it was a good learning opportunity for CDI 2.0, templating with ThymeLeaf and creating a tool which runs in multiple environments (CLI, Java FX, Web/JSF)

Maybe it is also helpful for you.

Have fun.

Categories
JAX-RS Security

Http Signatures for End-To-End protection

Introduction

In a distributed system, it is not enough to know who called you, but you also need to make sure the data which you receive are not altered in transit.
The use of tokens (like Bearer JWT tokens according to the OpenId Connect or MicroProfile JWT Auth specifications) can be captured and briefly used to send fake request to your endpoints.
And SSL (like using HTTPS connections) cannot guarantee that your message isn’t read or altered by someone due to the possibilities of SSL Proxy termination or even Man In The Middle Intermediates who fakes correct SSL.

Encryption or protection

The solution is that your processes somehow make sure that the communication between them is ‘safe’. If the processes themselves (your client and your server application) perform these tasks and not some network layer (SSL, in fact, doesn’t fit in any OSI based network layer) of your (virtual) machine.

When your process is performing these tasks, it is possible to create a security context between the 2 processes and then each process can ensure or detect that the message is unaltered or can’t be read, regardless of any Proxy or Man In The Middle.

Whether you need encryption of the message (because you have confidential data) or signing (sensitive data) depends on the data. But at least you need the signing of the message so that we can guarantee the message is actually sent by someone we trust and isn’t altered.

Http Signatures

There is a standard created to have a mechanism to implement this kind of End To End Protection. It is called ‘HTTP Signatures’ and designed by the IETF. https://tools.ietf.org/id/draft-cavage-http-signatures-09.html

It is very HTTP friendly as it adds an additional header to the request. Within this header, enough information is placed so that the target process can verify if the message was altered or not.

This header is called Signature

Signature : keyId="rsa-key-1",algorithm="rsa-sha256",headers="(request-target) date digest content-length",signature="Base64(RSA-SHA256(signing string))"

The specification defines the structure and framework how the header should be created and the verification process must be performed but leaves a lot of freedom to the developer to tailor this protection to his/her needs.

The idea is that there is a signature calculated based on some parameters which are mostly just other headers. And by calculating them on the receiving side, we can verify if these values are changed.

These parameters are described within the headers parameter, and in the example, the following headers are used (request-target) date digest content-length

The values of these headers are concatenated (there exist a few rules about how to do it) and for this string, the cryptographic hash is calculated the signature.
The calculation is done using the value specified by the algorithm parameter (rsa-sha256 in our example above) and from the key with id rsa-key-1 is used for this in our example.
There are a number of crypto algorithms allowed, but RSA keys are the most popular ones.
This signature value is a binary, so a BASE64 encoded value is placed within the header.

In theory, all headers can be used but some of them are more interesting than other ones.
For example

  • (request-target) is a pseudo header value containing the concatenation of the http method and the path of the URL. If you like to include also the hostname (which can be interesting if you want to make sure that a request for the test environments never hits production, you can add the host header in the set of headers which needs to be used for the calculation of the signature value.
  • date header contains the timestamp when the request is created. This allows is to reject ‘old’ requests.
  • digest is very interesting when there is a payload send to the endpoint (like with put and post). This header contains then the hash value of the payload and is a key point in the end to end protection we are discussing here.

On the receiving side, the headers which are specified within the signature parameter are checked. Like

  • date is verified to be within a skew value from the system time
  • digest is verified to see if the header value is the same as the calculated hash value from the payload.

And of course, the signature is verified. Here we decode the signature value with the public key defined in the keyId parameter, using the algorithm specified.
And that value should match the calculated value from the headers.

Using Http Signatures

I have created a Proof Of Concept how this can be integrated with JAX-RS, client and server side.

For the server side, it is quite simple since you can add filters and interceptors easily by annotating them with @Provider. By just then indicating if this interceptor and filters should need to do their work, verification of the HTTP Signature, you are set to go.

@Path("/order")
@RestSignatureCheck
public class OrderController {

On the client side, you can register the required filters and WriterInterceptor manually with the Client. Something like this

Client client = ClientBuilder.newClient();
client.register(SignatureClientRequestFilter.class);
client.register(SignatureWriterInterceptor.class);

One thing is on the roadmap is to integrate it with the MicroProfile Rest Client way of working so that you can register the Signatures Feature and you’re done.

The initial code can be found on Github.

Conclusion

With the Http Signatures specification, you can add a header which can be used to verify if the message is changed or not. This is a nice non-intrusive way of having an End-To-End protection implement which can complement the SSL features to be sure that no intermediary party changes the message.

Have fun.

Categories
JSF

A renderer interceptor concept for Java ServerFaces

Introduction

A renderer is an important concept within JSF. It is responsible for creating the HTML output of a page from the Component tree but also processing the response from the browser is their responsibility.

It takes the values from the attributes of a component to do their job. So developers mostly don’t interact directly with them, unless you are writing custom components and write a renderer yourself.

But sometimes it could be handy if we could create some kind of interceptor for the renderers methods so that we could have

  • Generic logic for component-based security
  • Retrieve validation info (like required, max size) from Beans so that information isn’t defined multiple times.

That is what Jerry and Valerie provide for you.

Origin

The first RendererInterceptor is committed some 10 years ago within the MyFaces-Extensions-CDI project (ExtVal). A set of useful extensions for Java EE programs covering CDI, Bean Validation, and JSF.

With the RendererInterceptor you have a before and after method for every major method in a Renderer which is decode, encodeBegin, encodeChildren, encodeEnd and getConvertedValue.

About 3 years ago, I extracted the RendererInterceptor concept from ExtVal to become Jerry and rewrote it to have a deep integration with CDI and target it exclusively to JSF 2.x. The Validation extensions parts for Bean Validation were bundled into Valerie.

That way, the most powerful code from ExtVal could be used standalone and Jerry could become the heart of the Declarative Permissions based framework Octopus for the JSF component security.

Now, a new rewrite is performed to bring it within the Atbash project family and restrict its usage to Java EE 7 (and later) using the CDI 1.1 features. This is the new release version 0.9.0.

The ComponentInitializer is greatly enhanced which I will explain in this blog.

ComponentInitializer

The ComponentInitializer is a specialized form of a RendererInterceptor and can change the JSF component just before it is encoded (HTML is generated) by the Renderer.

This can be handy if you want to perform some cross-cutting concern, so for all JSF components or all components of a certain type (input type) without the need to actually know all these JSF components or even adjust the renderers.

Classic examples are

  • Change the rendered attribute based on the presence of an inner tag to have declarative Component security (This is what Octopus does)
  • Change the look of components, like setting the background color of all required input fields.
  • Retrieve information from bean properties (like @NotNull) and set the required property. That way information is only required on the model classes and doesn’t need to be duplicated on the JSF components (This is what Valerie does)
@ApplicationScoped
public class RequiredInitializer implements ComponentInitializer {

   @Override
   public void configureComponent(FacesContext facesContext, UIComponent uiComponent, Map<String, Object> metaData) {
      InputText inputText = (InputText) uiComponent;

      String style = inputText.getStyle();
      if (style == null) {
         style = "";
      }

      if (inputText.isRequired()) {
         style = style + " background-color: #B04A4A;");

      } else {
         style = style.replace("background-color: #B04A4A;","");

      }
      inputText.setStyle(style);
   }

   @Override
   public boolean isSupportedComponent(UIComponent uiComponent) {
      return uiComponent instanceof InputText;
   }
}

 

The above example sets the background color of all input fields if they are required. This is just an example and probably you should implement such a functionality using styleClasses so that color can be defined outside the code in CSS.
All CDI beans implementing the ComponentInitializer interface are picked up automatically and applied to the correct JSF components based on the return value of the isSupportedComponent() method.

Due to the enhanced functionality within this version, a ComponentInitializer can be executed multiple times and thus we need to ‘undo’ our changed style in case the component is not required.

Just as in the previous release, by default, the ComponentInitializer is executed only once. When due to AJAX request, for example, the component is rendered again, the ComponentInitializer isn’t executed anymore. This is done to minimize the overhead of the feature.

However, when the component is in some kind of repeatable parent component, the Initializer is executed multiple times. The repeatable constructs detected are <ui:repeat> and UIData constructs like <h:datatable>.
This is required because the information can be different for each row like the case where the input field required property depends on the row (required=”#{_row.field.required}”)
This logic is added in this release and important to know when you upgrade from an older version.

RepeatableComponentInitializer

The new RepeatableComponentInitializer construction in this release is always executed, regardless of the ‘location’ of the component.

A use-case for this situation is the fact that a PrimeFaces table footer is always present, although no pagination is shown (resulting in a thin colored line). With a RepeatableComponentInitializer you can remove this footer (or upgrade to the upcoming 6.2 version where this is fixed by PrimeFaces code.

Setting up

You just need to add the Jerry (and/or Valerie) maven dependency to your JSF application.

<dependency>
   <groupId>be.atbash.ee.jsf</groupId>
   <artifactId>jerry</artifactId>
   <version>${atbash.jerry.version}</version>
</dependency>

And you are ready to go.

Some more information can be found in the user manuals for Jerry and Valerie.

When you have an application using an older version of Jerry and/or Valerie (0.4.1 and older) you can use the code within the Atbash migrator project to help you convert the import statements, dependencies and JSF namespaces to the new Atbash values.

Conclusion

With the RendererInterceptor you can perform all kind of useful code in a generic way, without knowing or changing the Renderers. The new release has a greatly improved ComponentInitializer execution (detecting repeated structures like <ui:repeat> and <h:dataTable>), the new RepeatableComponentInitializer concept and is part of the ever-growing Atbash projects.

Have fun.

 

Categories
Configuration

Implicit converters for MicroProfile Config

Introduction

Last month (January 2018), an update of the MicroProfile Config specification, version 1.2, was released which makes it easier to convert the configuration values to class instances.
It adds the concept of implicit/automatic converters and removes the requirement for creating specific converters in many cases.
The first implementations are already available and Atbash Configuration is now also updated.
This blog describes what the implicit/automatic converters are and how you can use them.

Converters

The configuration values we define are Strings because they are defined as a set of Characters in the configuration files. Using the configuration could be limited to a system which is capable of reading those Strings and that the developers need to convert these values to the proper instance (like Integer, Boolean or application specific classes) themselves.
But in that case, each developer will write his own set of converters and in the case of Integers and Booleans, for example, they are all the same.
So the framework itself can take care of these converters. And since we have then already the concept of a convert, it is easy to foresee an SPI which allows the creation of custom Converters by the developer for their application specific classes.
These basic converters for Integer and Boolean for example where present since the first release of the spec. Just as the SPI to add your own converters.

Implicit Converters

But the creation of all those custom converters can be minimized further. Since our application specific classes can be created from a String, they probably have some means of instantiating them through a method which takes a String parameter
– The constructor
– A static method with names like valueOf or parse.
So with the new implicit/automatic converters feature, when we have some class like this
public class ClassWithStringConstructor {
    private String value;

    public ClassWithStringConstructor (String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}
and have a parameter
some.key = Atbash

We can retrieve an instance of the class, with the value using

config.getValue("some.key", ClassWithStringConstructor.class)

or when we are in a CDI enabled context, we can also use injection

@Inject
@ConfigProperty("some.key")
private ClassWithStringConstructor parameterValue;

Collection type parameters

Another nice addition to this 1.2 release, is the use of collection type parameters. The ability to have multiple parameter values, like a list of values which is converted to an Array, List or Set.
It is quite common that a configuration value is, in fact, a list of value.
pets = dog,cat
previously, the developer needed to split the String and use the individual parts separately (although this is a very simple task with String.split() ), can be done automatically.
config.getValue("pets", String[].class)

With injection, we can automatically convert it to a List or a Set.

@Inject
@ConfigProperty(name = "pets")
private List<String> pets;

The List and Set variants can’t be used in a programmatic way (using config.getValue) since the second parameter doesn’t accept parameterized types (like List<String>).

When you have a value which contains a comma it in, you need to escape it
a,b,c\\,d

which results in 3 configuration values, where the last one is c,d.

Implicit combined with Collection.

We can even combine the collection type feature with the implicit/automatic converter feature. If we instead specify the class name like ClassWithStringConstructor instead of String, the configuration framework will use the appropriate way of converting.
config.getValue("pets", ClassWithStringConstructor[].class)

or

@Inject
@ConfigProperty(name = "pets")
private List<ClassWithStringConstructor> pets;

Octopus Config

As you could read in a previous blog, Octopus Config is a Java 7 port from Geronimo config. The support for the implicit/automatic converters and collections (like the arrays, List, and set) is taken from them.
Octopus Config itself is also updated so that the YAML usage supports the Collection type parameters. The example above with the pets can be written in the YAML equivalent format as
pets: [dog , cat]

The release 0.9.1 contains also some small other features are listed here. Most notable features are

– Improved Class converters based on different classloaders.
– Test artefact.
– Logging in Java SE environment
– Improvement information in logging with @ModuleConfigName
– Compatibility with another MicroProfile Config implementation on Java 8.

Conclusion

With the addition of the implicit/automatic converters, the need for writing custom converters can be dropped and conversion will take place by convention.
The Octopus Config version v0.9.1 is updated to incorporate these features together with some small other improvements and fixes.
Have fun.
Categories
Testing

Programmatic CDI access and Unit testing

Introduction

There are situations where you need to access the CDI system programmatically, instead of using annotations like @Inject

  • You want to retrieve a CDI bean within a context (class) which isn’t CDI-aware.
  • It is easier to retrieve an optional or multiple beans programmatically instead of using Instance.

Since CDI 1.1 (Java EE 6), this can be easily achieved by using

CDI.current();

The programmatic access is most useful if you are creating a library/framework or some reusable piece of functionality. But I guess everyone who creates more than 1 application is in the situation where things can be reused.

This blog shows the equivalent programmatic constructs but most importantly, how you can unit test your bean in those cases (no CDI container needed!)

Optional CDI bean

An optional bean is interesting in the situation where you define some basic functionality but in case the developer defines a CDI bean implementing the interface, that custom developer logic is executed.

public interface SomeInterface {}
// with classic injection
@Inject
private Instance<SomeInterface> optional;

   // Within a method
   if (!optional.isUnsatisfied()) {
      optional.get();
   }
// programmatic
// Within method
Instance<SomeInterface> instance = CDI.current().select(SomeInterface.class);
instance.isUnsatisfied() ? null : instance.get();

Multiple beans

Within a Chain of Responsibility pattern or the situation where you can have multiple add-ons which perform some logic in a certain situation, are the ideal situations for having multiple CDI beans implementing an interface.

// with classic injection
@Inject
private Instance<SomeInterface> addonInstances;

   // Within a method
   List<SomeInterface> addons = new ArrayList<>();
   addonInstances.iterator().forEachRemaining(
      addons::add
   );

// programmatic
// Within a method
List<SomeInterface> addons = new ArrayList<>();
for (SomeInterface addon : CDI.current().select(SomeInterface.class)) {
   result.add(addon);
}

Sending Events

One of the nice features of CDI is the ability to sends events between consumers and producers without the need of registering the consumers with the producer for example.

Producing the Event can be done using

// with classic injection
@Inject
private Event<Payload> payloadEvent;

   // Within a method
   payloadEvent.fire(new Payload());
// programmatic
// within a method
CDI.current().getBeanManager().fireEvent(new Payload());

Unit Testing

Now that you have used some CDI bean retrievals in a programmatic fashion, what happens when you execute a unit test?

java.lang.IllegalStateException: Unable to access CDI

When running with plain Java, without any CDI container, you get this message because the API doesn’t contain an implementation, only the specification of the behavior.

You can of course switch to integration testing, where you launch a proper CDI container. But you can, of course, stay with your basic unit testing and have a simple, minimalistic Cdi container implementation (which is by the way not very difficult to create)

Suppose we have following code

public SomeInterface readOptionalInstance() {
   Instance<SomeInterface> instance = CDI.current().select(SomeInterface.class);
   return instance.isUnsatisfied() ? null : instance.get();
}

And we like to test this piece of code then the optional bean is not defined with something like this

@Test
public void readOptionalInstance_NotPresent() {
   Assert.assertNull(viewBean.readOptionalInstance());
}

We need a simple CDI implementation. This is provided by the be.atbash.util.BeanManagerFake class, available in the tests artifact of atbash utils-cdi.

<dependency>
   <groupId>be.atbash.utils</groupId>
   <artifactId>utils-cdi</artifactId>
   <version>0.9.0</version>
   <classifier>tests</classifier>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-core</artifactId>
   <version>2.13.0</version>
   <scope>test</scope>
</dependency>

The CDI fake container (as in not real implementation, maybe not the correct term in the test concepts Dummy/Fake/Stub/Spy) is using Mockito underneath, so that is also a dependency we need to add to the project.

The test can then be adapted as follow

private BeanManagerFake beanManagerFake = new BeanManagerFake();

@After
public void cleanup() {
   beanManagerFake.deregistration();
}

@Test
public void readOptionalInstance_NotPresent() {
   beanManagerFake.endRegistration();
   Assert.assertNull(viewBean.readOptionalInstance());
}

We can instantiate the BeanManagerFake as a regular bean. Important here is the deregistration method after the test is finished. It is the idea to keep the fake CDI container between tests alive but only clear the contents. In the current version, the container is also unset which makes it necessary that the beanManagerFake variable is an instance variable (and not a class variable)

With the endRegistration method, we signal that all configuration of the CDI container has taken place and that the operational modus can start. It can give some instances of interfaces if needed as in our test example.

Here we didn’t register anything, so we get a null back.

This is updated test class which contains also a test in the case we specify an instance in the CDI container.

@RunWith(MockitoJUnitRunner.class)
public class ViewBeanTest {

   private ViewBean viewBean = new ViewBean();

   @Mock
   private SomeInterface mockClass;

   private BeanManagerFake beanManagerFake = new BeanManagerFake();

   @After
   public void cleanup() {
      beanManagerFake.deregistration();
   }

   @Test
   public void readOptionalInstance_NotPresent() {
      beanManagerFake.endRegistration();
      Assert.assertNull(viewBean.readOptionalInstance());
   }

   @Test
   public void readOptionalInstance_Present() {
      beanManagerFake.registerBean(mockClass, SomeInterface.class);
      beanManagerFake.endRegistration();
      Assert.assertNotNull(viewBean.readOptionalInstance());
      Assert.assertTrue(viewBean.readOptionalInstance() == mockClass)
   }
}

You can see that we can define a mock (with the @Mock of Mockito) as a bean within the CDI container with the registered bean. We supply the instance and the type to which this instance must be bound. Within CDI, an instance can be bound to multiple class instances like the class itself, the interface, Object.class etc …) This is also possible with BeanManagerFake as the second parameter of the registerBean method is a varargs with all the class values.

And if you run the above test, you will see they are all green, so we, in fact, get the exact instance of the CDI bean (here the mock) back as the return value of the method.

Of course, when you have very complex Cdi constructions, it is better to test them in a real CDI container. But if the focus is on the business logic, the simple CDI container for testing will do.

Code

The code of BeanManagerFake is available in the Atbash utils GitHub repository and artifacts are on Maven Central.

Conclusion

Using the programmatic interfaces of the CDI container is easier in those cases where you need to retrieve optional or multiple CDI beans. And of course in the context where the dependency injection isn’t available. And with the help of the BeanManagerFake, a simple CDI container for testing, Unit tests are possible which make is easier then to set up a full blown integration test with a container.

Have fun.

Categories
Security

Key derivation functions

Introduction

Although initially intended for creating better secret keys, Key derivation functions are probably better for storing hashed passwords. This post tells you more about what a Key derivation function does, how you can use it for storing hashed passwords and how you can use it in the Octopus framework.

What is it?

For the symmetric encryption you need the secret key, an array of bytes basically. A password can also be converted to a byte array so a password can be used. Then the key doesn’t need to be stored and when the user types in the password, the message can be encrypted or decrypted.

But of course, passwords are not a really good candidate as the key for an encryption.
– passwords consist of characters which have all more or less the same bit pattern. So the ‘random’ spread of bits through-out the byte array is not good.
– password are mostly short, so your key is probably too small.

So that is where the Key derivation functions come into the picture. They take a password or passphrase (a sentence used as a password) and can generate a byte array out of this. It has the following characteristics
– It needs a salt, a byte array, to be able to do his work. So salting is mandatory.
– When the same password/passphrase and salt are presented to the Key Derivation function, it results in the same byte array outcome (so it is deterministic, no random outcome)
– It is a one-way procedure. So from the output buts, the original password / passphrase can’t be reconstructed.
– The output, the number of bits generated, is configurable (important because key sizes for encryption must have some minimum lengths)
– The functions are intentionally slow to counter any brute-force attack. And iterations can be applied to make it even more difficult.

You can read more background info on this wiki page

for hashed passwords

In the previous section, you can read why those Key derivation functions are very good for generating a secret key (for symmetric encryption). The properties are designed specifically for that purpose.

But very rapidly, they saw an alternative use for these functions, create hashed passwords. The reason why are easy to see
– When offered the same input, the same output is generated
– The input can’t be reconstructed from the output.

But they have a few other properties which make it a better candidate for storing passwords then the classic hashing functions.
– The computation requires a salt, so generating an output byte array is not possible without it. This in contrast to a classic hash algorithm where we add the salt to the password to overcome the use of rainbow tables.
– The computation of Key Derivation functions are slow, those of hash algorithms are fast. And performing the hashing function multiple times is not a good idea because of the increase in collisions.

Algorithms

So we are now at the point that we can say that Key Derivation functions are better for storing hashed passwords. So how can we get started with it in our Java programs?

There are different algorithms developed (just like there are different hash algorithms) like argon2, sCript, bCript or PBKDF2.
Only one is available by default on the JVM, PBKDF2, although most people say argon2 is the best algorithm. So let us see how we can use that one on the JVM.

Since Key derivation functions are something completely different then hash algorithms, these aren’t available from java.security.MessageDigest class. But there is another standard java class available which give you an instance of the algorithm, javax.crypto.SecretKeyFactory

The following snippets generate the BASE64 encoded output for a certain password. It also generates a salt value.

String password = "atbash";

String keyAlgorithmName = "PBKDF2WithHmacSHA256";
SecretKeyFactory keyFactory;
keyFactory = SecretKeyFactory.getInstance(keyAlgorithmName);

char[] chars = password.toCharArray();

byte[] salt = new byte[32];
new SecureRandom().nextBytes(salt);

int hashIterations = 1024;

int keySizeBytes = 32;

byte[] encoded = keyFactory.generateSecret(
        new PBEKeySpec(chars, salt, hashIterations, keySizeBytes * 8)).getEncoded();

String hashed = Base64.getEncoder().encodeToString(encoded);

System.out.println(hashed);

So using them us quite easily.

Octopus support

Also within Octopus, there is support added for the PBKDF2 algorithm within version 0.9.7.1. And since the way you use it is so similar then classic Hash algorithms, the only thing you need to do is set the algorithm name in the configuration file.

hashAlgorithmName=PBKDF2WithHmacSHA256

See also the chapter in the Octopus Cookbook

Conclusion

Key derivation functions are designed for creating a key which can be used in Symmetric encryption algorithms based on a password.

But it turns out that they are also very well suited to stored hashed passwords. So try them out and use them in your next project with or without the Octopus security framework.

Have fun.

 

This website uses cookies. By continuing to use this site, you accept our use of cookies.  Learn more