See the output from MockMvc.peform()

Lets say you have a unit test on a Spring MVC controller like this:

/**
 * Tests RESTController.getPostcode() with a false postcode and building number
 */
@Test
public void PostcodeAndBuilding_FalsePostcodeIsNotGot_Passes() throws Exception {

    mockMvc.perform(get("/postcode/" + test3PostcodeRequest + "/" + test3BuildingNumberRequest))
            .andExpect(status().isOk())
            .andExpect(content().contentType(contentType))
            .andExpect(jsonPath("$.status", is(404)));

}

The test is failing, so you want to grab the response for whatever reason.  The simply way of doing this is to return the response of the MockMvc.perform into an MvcResult and run getResponse and getContentAsString on it to turn it into a String:

/**
 * Tests RESTController.getPostcode() with a false postcode and building number
 */
@Test
public void PostcodeAndBuilding_FalsePostcodeIsNotGot_Passes() throws Exception {

    MvcResult result = mockMvc.perform(get("/postcode/" + test3PostcodeRequest + "/" + test3BuildingNumberRequest));
            //.andExpect(status().isOk())
            //.andExpect(content().contentType(contentType))
            //.andExpect(jsonPath("$.status", is(404)));

    String content = result.getResponse().getContentAsString();

}

You now have the content stored as String to do with what you wish.

Facebooktwittergoogle_plusredditmail

A Zero Byte SSL Key, is Never a Good Thing…

I’ve been working on a side project that exposes the Post Offices PAF data via a REST API.  While securing the site I was getting problems loading the Apache config, after a few seconds of investigation I spot a major problem…

A zero byte SSL key, is never a good thing:

root@jupiter:~/api.postcode.software_ssl# ls -la
total 12
drwxr-xr-x  2 root root 4096 Jan 21 17:23 .
drwx------ 10 root root 4096 Jan 22 11:18 ..
-rw-r--r--  1 root root 1119 Jan 21 17:23 api.postcode.software.csr
-rw-r--r--  1 root root    0 Jan 21 17:27 api.postcode.software.key

Time for a re-issue…

I wouldn’t be so annoyed if the key hadn’t only just been issued after a 12 hour wait.

I’ll post more on the project when its complete (as complete as a side project ever gets!) on this blog.

Facebooktwittergoogle_plusredditmail

Very Berry Smoothie Recipe

The recipe for the smoothie I’ve been having most mornings is:

  • Half a cup of blueberries
  • Half a cup of raspberries
  • Half a cup of strawberries
  • Half a cup of curly kale
  • Two desert spoons of plain yoghurt
  • A cup of almond milk

Blend in blender or smoothie maker for 60 seconds.  Chill before drinking.  Watch out for kale and strawberry seeds in-between your teeth after drinking!

Facebooktwittergoogle_plusredditmail

Creating a Root CA and Signing a Certificate for Development

I’ve recently been writing some services in Java using Spring where the service will be accessed over HTTP when live.  I obviously want to use this configuration in development but I don’t want to pay for a certificate.

I could write a null implementation of TrustManager, but this will be very different to live and is something that could possibly make its way through to live.

Instead, I’ll create a self-signed root CA and sign the SSL certificate for the service myself using the new root CA.

Install OpenSSL

Firstly you will need OpenSSL installed. I used the installation of OpenSSL on my MacBook Pro that comes with OS X.  On Ubuntu you install it using:

sudo apt-get install openssl

Windows users can grab OpenSSL from here.

Create the Root Key

Next you need to create the root key.

openssl genrsa -out rootCA.key 2048

If you would like to add a password to the root key, which is highly recommended, do the following:

openssl genrsa -des3 -out rootCA.key 2048

Using the above command will ask for a password to secure the key.  You will need to enter the password each time you use the key if you secure it.

Create a Root Certificate

The next step is to create a root certificate and self-sign the certificate using the root key generated earlier.

openssql req -x509 -new -nodes -key rootCA.key -sha256 -days 712 -out rootCA.pem

You will need to answer a few questions about the root CA.  Here’s how I answered the questions:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:Lancashire
Locality Name (eg, city) []:Blackpool
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Andy McCall Ltd
Organizational Unit Name (eg, section) []:Development
Common Name (eg, YOUR name) []:Andy McCall
Email Address []:certificates@andymccall.co.uk

We now have a root CA that we can use to sign things with.  If you are using Windows, install this CA into the local machine’s root certificate store using the Microsoft Management Console (MMC).  There’s a guide at SQLServerMart that is easy enough to follow for servers, there’s also a guide here for the desktop.  For other operating systems or platforms Google is your friend.

Create a Certificate

The next step is to create the certificate that will be used to secure the service over HTTPS.  There are a number of steps to do this

Create the key

The first step is to create a private key.

openssl genrsa -out service.key 2048

Generate a Certificate Signing Request

Using the key create a certificate signing request for your service:

openssl req -new -key service.key -out service.csr

You’ll be asked a host of questions again, the important bit of information here is the common name.  This will be how you will access your service.  In this example the service is called service.local and I’ve added service.local to my hosts file.  This would also work if you used a corporate DNS and you where securing myservice.mycorporation.myinternaldns.com or if you used an IP address.  It basically has to match the address you will access the service on.

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:Lancashire
Locality Name (eg, city) []:Blackpool
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Andy McCall Ltd
Organizational Unit Name (eg, section) []:Development
Common Name (eg, YOUR name) []:service.local
Email Address []:certificates@andymccall.co.uk

Do not use a challenge password with this certificate.

Sign the Certificate Signing Request Using the Root 

Now we sign the request to make to trust it:

openssl x509 -req -in service.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out service.crt -days 356 -sha256

We now have a signed certificate (service.crt) and a key file (service.key).  Under Linux servers and hardware devices, we can use these two keys together to secure our service.  Under Windows we need to import it into the certificate store first and to do that we need the files to be combined into a single Personal Information Exchange file.

Convert Certificate and Key into a Personal Information Exchange File

To import the certificate and key into the Windows certificate store we need to convert them to a Personal Information Exchange (.pfx) file.

openssl pkcs12 -export -out service.pfx -inkey service.key -in service.crt -certfile rootCA.pem

You don’t need to use an export password, but its obviously more secure if you do.  This will produce a single .pfx file that you can import into your OS.

Once the certificate is installed you can check to see if the certificate is valid:

Clicking on the Certification Path shows the chain of trust:

Finally, set your service to run under HTTPS and use the new certificate to secure the service.  Configure your endpoint within your application as service.local and you now have a correctly configured development environment that is live like.

Facebooktwittergoogle_plusredditmail

Disabling IPv6 via Chef on Windows

While there are lots of resources on the Internet for disabling IPv6 on Linux, there are very few that show how to disable IPv6 on Windows.  Here is a quick recipe that I put together that will disable IPv6 and restart if needed.

powershell_script "disable_ipv6" do
    guard_interpreter :powershell_script
    code "New-ItemProperty 'HKLM:\\SYSTEM\\CurrentControlSet\\services\\TCPIP6\\Parameters\\' -Name 'DisabledComponents' -Value '0xffffffff' -PropertyType 'DWord'"
    notifies :reboot_now, 'reboot[disable_ipv6_requires_reboot]', :immediately
    not_if "(Get-ItemProperty -Path 'HKLM:\\SYSTEM\\CurrentControlSet\\services\\TCPIP6\\Parameters' -Name DisabledComponents -ErrorAction SilentlyContinue).DisabledComponents -ne $null"
end

reboot 'disable_ipv6_requires_reboot' do
    action :nothing
    reason 'Disabling IPv6 requires a reboot to take effect.'
end

Before you use this, you should know that Microsoft do not recommend you disable IPv6.  You will experience a 5 second delay during the boot up process and Microsoft does not explicitly test this scenario.

Another interesting thing about this recipe is the condition used in the not_if.  I initially wanted to use Test-Path, but it turns out that Test-Path doesn’t work on registry values, it only works on registry paths.   I got around this using Get-ItemProperty and testing for a null value.

Facebooktwittergoogle_plusredditmail

Deploying Multiple files using Chef and Arrays

This post is one of a number of posts I’m making on nifty little tricks for Chef beginners.  These posts will try and detail solutions to common problems I found when learning Chef.  Hopefully I will save some people some time.

When I first started using Chef I would write the same lines of code over and over again to deploy files to a server.  This code would look something like the following:

cookbook_file "/etc/test/file1.txt"
   source "/my/files/file1.txt"
end

While this works for a few files it soon becomes unmanageable when you need to deploy more than a few.  The easiest way to keep your recipe nice and tidy is to create an array of the files and loop through the array performing the Chef action on the file that’s needed.  This will reduce the number of lines in your recipe and will be easier to maintain going forward.  This looks like this:

# Location of the files and templates within the cookbook
# the following location would translation to files/default/my/files
files_directory="/my/files"

# Location to deploy to
etc_directory="/etc/test"

# Array of the files that require to be deployed
file_array = [
'file1.txt',
'file1.txt',
'file1.txt',
'file1.txt']

# For each file in the array
file_array.each do |this_file|
   cookbook_file "#{etc_directory}/" + this_file do
      source "#{files_directory}/#{this_file}"
   end
end

The inner code works with cookbook_file, template or anything else you may need to do multiple times.

Facebooktwittergoogle_plusredditmail

Creating Directories Including Parents using Chef on Windows

I’ve recently been building some test environments on Microsoft Windows 2008 R2 using Chef. One thing that Chef misses is an easy way to create parent directories if needed when creating a directory.

The standard method of creating a directory will not work if D:\foo\bar doesn’t already exist:

directory "D:\\foo\\bar\\buzz" do
   action :create
end

You can create a parent directories by placing each element of a path into an array, then loop through the array creating each folder:

%w[ D:\\foo \\foo\\bar \\foo\\bar\\baz ].each do |path|
   directory path do
      action :create
   end
end

I already had my path declared in a variable for other uses. I didn’t want to store it twice and I didn’t want to create a block of Ruby to try and break the path up from the variable.

After some research I discovered that its easier to simply run the New-Item command in a PowerShell block:

# Location of the install and patch directory
install_directory="D:\\foo\\bar\\buzz"

# Create the directory, including parents
powershell_script "create_install_directoy_if_not_exists" do
   guard_interpreter :powershell_script
   code "New-Item -ItemType Directory -Path #{install_directory} -Force"
   not_if "Test-Path #{install_directory}"
end

This will create the directory, including parent directories if needed. On Windows this appears to be the easiest way of coping with missing parent directories.

Facebooktwittergoogle_plusredditmail

Bandwidth Usage…

I’ve been running on DD-WRT for a month or so I can start to get a feel for how much data I use.

Bandwidth Usage November 2016

Bandwidth Usage November 2016

Most of the time I use under 20GB a day.  The odd day I might pop over that amount.  You can clearly see when I buy a game on Steam – I think this particular 80GB download was for Call of Duty: Infinite Warfare.

Its clear that I will never go with a capped download.  I like the flexibility of being able to download as much as I want, even if I don’t use it.

Next up is getting OpenVPN working on them.

Facebooktwittergoogle_plusredditmail