Search code examples
javaspringencryptionspring-cloud-config

Spring Config Test with ApplicationContextInitializer - how to decrypt?


I have a test running against my Spring Config server to verify the application is working. I did some manual tests and everything works just fine with a basic launch of the Spring Confg Boot application, but I want a unit test to prove the solution and be able to test my development keystore and whatnot.

I added a custom ApplicationContextInitializer implementation to load the data from application-test.yml at startup of the execution. Everything works when the data is not encrypted; however, when I add an encrypted property, it does not decrypt it.

The implementation I used is:

public class TestYamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
    try {
      Resource resource = applicationContext.getResource(CLASSPATH_URI);
      YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
      PropertySource<?> testProperties = sourceLoader.load("yamlTestProperties", resource, null);
      applicationContext.getEnvironment().getPropertySources().addFirst(testProperties);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

The application-test.yml is:

my:
  encrypted:
    parameter: '{cipher}AQB8C/1v9J+jPQZG...'

server:
  port: 0

spring:
  profiles:
    active: native

encrypt:
  key-store:
    location: classpath*:/security/development-test.jks
    alias: DevelopmentTest
    secret: SomeSecretPassword123
    password: SomeStorePassword123

My test is annotated with @ContextConfiguration (initializers = TestYamlFileApplicationContextInitializer.class) to kick it off.

The test runs a basic check using:

@Autowired
Environment env;

@Test
public void testStuff() {
  String theProp = env.getProperty("my.encrypted.parameter");
  System.err.println(theProp);
}

The output is: {cipher}AQB8C/1v9J+jPQZG...

There are no exceptions listed.

What piece of the puzzle am I missing?


Solution

  • Looks like this an open issue at Spring. https://jira.spring.io/browse/SPR-12420. One possible solution has been provided at SO post Process Spring Boot externalized property values