找回密码
 立即注册
首页 业界区 业界 明明环境变量已经解密,为啥@ConfigurationProperties ...

明明环境变量已经解密,为啥@ConfigurationProperties 注入还是加密值?

恐肩 昨天 18:10
问题背景

在微服务的 application.properties 文件中有一个 test.container-name 配置。原始配置如下:
  1. test.container-name=Tomcat
复制代码
同时有一个 Java 类 TestConfigProperty 中通过 @ConfigurationProperties 注解注入这个配置属性到它的变量 containerName 中,代码如下:
  1. @ConfigurationProperties(prefix = "test")  
  2. @Component  
  3. public class TestConfigProperty {  
  4.     private String containerName;  
  5.   
  6.     public String getContainerName() {  
  7.         return containerName;  
  8.     }  
  9.   
  10.     public void setContainerName(String containerName) {  
  11.         this.containerName = containerName;  
  12.     }  
  13. }
复制代码
现在因为 test.container-name 配置包含敏感信息,不能直接配置原始的值,需要配置加密之后的值,在微服务启动的时候解密。现在是 test.container-name 配置引用了 TEST_CONTAINER_NAME 环境变量。配置如下:
  1. test.container-name=${TEST_CONTAINER_NAME}
复制代码
然后在环境变量中配置了加密之后的值。在本案例中为了简化,这里加密就用的 Base64 编码作为示例演示。如下图所示:
1.png

2.png

在项目中有框架提供了在微服务启动时对加密后的字符串解密的能力,实现的基本原理是提供了一个 DecryptEnvironmentPostProcessor 类扩展了 EnvironmentPostProcessor。
在它的 postProcessEnvironment() 方法中,判断环境变量配置的值是否是以 ENC_ 开头,如果是则进行解密。解密之后放到一个 MapPropertySource 里面,然后添加到所有的 PropertySource 的前面。示例代码如下:
  1. public class DecryptEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {  
  2.     private static final String DECRYPTED_SOURCE_NAME = "decryptedSystemEnvironment";  
  3.   
  4.     @Override  
  5.     public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {  
  6.         String systemEnvName = StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME;  
  7.         MapPropertySource systemEnvSource = (MapPropertySource) environment.getPropertySources().get(systemEnvName);  
  8.         Map<String, Object> decryptedMap = new HashMap<>();  
  9.         if (systemEnvSource == null) {  
  10.             return;  
  11.         }  
  12.         systemEnvSource.getSource().forEach((key, value) -> {  
  13.             if (value instanceof String strVal) {  
  14.                 // 这里进行了解密
  15.                 if (StringUtils.isNotEmpty(strVal) && strVal.startsWith("ENC_")) {  
  16.                     String plainText = new String(Base64.getDecoder().decode(strVal.substring(4)));  
  17.                     decryptedMap.put(key, plainText);  
  18.                 }  
  19.             }  
  20.         });  
  21.   
  22.         if (!decryptedMap.isEmpty()) {  
  23.             MapPropertySource decryptedSource = new MapPropertySource(DECRYPTED_SOURCE_NAME, decryptedMap);  
  24.             // 这里添加到所有的PropertySource的前面
  25.             environment.getPropertySources().addBefore(systemEnvName, decryptedSource);  
  26.         }  
  27.     }  
  28.   
  29.     @Override  
  30.     public int getOrder() {  
  31.         return Ordered.LOWEST_PRECEDENCE;  
  32.     }  
  33. }
复制代码
按照上述配置,通过调试发现类 TestConfigProperty 里面注入的还是加密之后的值,而并不是想要的解密之后的值。如下图所示:
3.png

查看 Environment 的 getPropertySources() 方法的返回值中,解密之后的环境变量属性配置确实是在未解密的环境变量属性配置之前,按照直观上的理解,那应该注入的是解密之后的值才对,但是实际结果却不是这样的。如下图所示:
4.png

问题原理

之前的文章这就是宽松的适配规则!里面讲了宽松适配的原理。在 Spring 的框架体系中是在 ConfigurationPropertiesBindingPostProcessor 中的 postProcessBeforeInitialization() 中实现对有 @ConfigurationProperties 注解修饰类的属性进行绑定的。
在它的内部实际上是通过调用 ConfigurationPropertiesBinder 的 bind() 来实现属性绑定的。代码如下:
  1. public class ConfigurationPropertiesBindingPostProcessor
  2.     implements BeanPostProcessor, PriorityOrdered, ApplicationContextAware, InitializingBean {
  3.     @Override
  4.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  5.         if (!hasBoundValueObject(beanName)) {
  6.             bind(ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName));
  7.         }
  8.         return bean;
  9.     }
  10.    
  11.     private void bind(ConfigurationPropertiesBean bean) {
  12.         if (bean == null) {
  13.             return;
  14.         }
  15.         Assert.state(bean.asBindTarget().getBindMethod() != BindMethod.VALUE_OBJECT,
  16.                 "Cannot bind @ConfigurationProperties for bean '" + bean.getName()
  17.                         + "'. Ensure that @ConstructorBinding has not been applied to regular bean");
  18.         try {
  19.             // 这里实际上是调用了ConfigurationPropertiesBinder的bind()方法
  20.             this.binder.bind(bean);
  21.         }
  22.         catch (Exception ex) {
  23.             throw new ConfigurationPropertiesBindException(bean, ex);
  24.         }
  25.     }
  26. }
复制代码
5.png

在 ConfigurationPropertiesBinder 的 bind() 方法又调用了 Binder 的 bind() 方法。如下图所示:
6.png

在调用  Binder 的 bind() 方法时,会把注解上配置的前缀传进去,在本案例中就是 test,并基于这个前缀创建一个 ConfigurationPropertyName 对象,然后最终调用到 bindObject() 方法。代码如下:
  1. public class Binder {
  2.     public <T> BindResult<T> bind(String name, Bindable<T> target, BindHandler handler) {
  3.         // 这里基于test前缀创建了ConfigurationPropertyName对象
  4.         return bind(ConfigurationPropertyName.of(name), target, handler);
  5.     }
  6.    
  7.     private <T> T bind(ConfigurationPropertyName name, Bindable<T> target, BindHandler handler, Context context,
  8.         boolean allowRecursiveBinding, boolean create) {
  9.         try {
  10.             Bindable<T> replacementTarget = handler.onStart(name, target, context);
  11.             if (replacementTarget == null) {
  12.                 return handleBindResult(name, target, handler, context, null, create);
  13.             }
  14.             target = replacementTarget;
  15.             // 调用bindObject()方法
  16.             Object bound = bindObject(name, target, handler, context, allowRecursiveBinding);
  17.             return handleBindResult(name, target, handler, context, bound, create);
  18.         }
  19.         catch (Exception ex) {
  20.             return handleBindError(name, target, handler, context, ex);
  21.         }
  22.     }
  23. }
复制代码
在  bindObject() 中首先调用 findProperty() 方法查找属性,因为当前只是前缀 test,因此肯定是找不到对应的属性配置的。 因此往下走会调用到 bindDataObject()方法。对于 JavaBean 来说,在 Binder 的 bindDataObject() 方法最终会调用到 JavaBeanBinder 的 bind() 方法。代码如下:
  1. public class Binder {
  2.     private <T> Object bindObject(ConfigurationPropertyName name, Bindable<T> target, BindHandler handler,
  3.             Context context, boolean allowRecursiveBinding) {
  4.             ConfigurationProperty property = findProperty(name, target, context);
  5.             if (property == null && context.depth != 0 && containsNoDescendantOf(context.getSources(), name)) {
  6.                 return null;
  7.             }
  8.             // 省略中间代码
  9.             
  10.             //调用bindDataObject()方法
  11.             return bindDataObject(name, target, handler, context, allowRecursiveBinding);
  12.         }
  13.     private Object bindDataObject(ConfigurationPropertyName name, Bindable<?> target, BindHandler handler,
  14.             Context context, boolean allowRecursiveBinding) {
  15.         if (isUnbindableBean(name, target, context)) {
  16.             return null;
  17.         }
  18.         Class<?> type = target.getType().resolve(Object.class);
  19.         BindMethod bindMethod = target.getBindMethod();
  20.         if (!allowRecursiveBinding && context.isBindingDataObject(type)) {
  21.             return null;
  22.         }
  23.         
  24.         // 注意这里的lambda表达式,在JavaBeanBinder的bind()方法最终又会调用到这个lambda表达式
  25.         DataObjectPropertyBinder propertyBinder = (propertyName, propertyTarget) -> bind(name.append(propertyName),
  26.                 propertyTarget, handler, context, false, false);
  27.                
  28.             // 这里会调用到JavaBeanBinder的bind()方法
  29.         return context.withDataObject(type, () -> fromDataObjectBinders(bindMethod,
  30.                 (dataObjectBinder) -> dataObjectBinder.bind(name, target, context, propertyBinder)));
  31.     }
  32. }
复制代码
在 JavaBeanBinder 的 bind() 方法中会获取这个对象的所有的 BeanProperty,然后又反调用回 Binder 中的lambda表达式了。代码如下:
  1. class JavaBeanBinder implements DataObjectBinder {
  2.     @Override
  3.     public <T> T bind(ConfigurationPropertyName name, Bindable<T> target, Context context,
  4.             DataObjectPropertyBinder propertyBinder) {
  5.         boolean hasKnownBindableProperties = target.getValue() != null && hasKnownBindableProperties(name, context);
  6.         Bean<T> bean = Bean.get(target, hasKnownBindableProperties);
  7.         if (bean == null) {
  8.             return null;
  9.         }
  10.         BeanSupplier<T> beanSupplier = bean.getSupplier(target);
  11.         boolean bound = bind(propertyBinder, bean, beanSupplier, context);
  12.         return (bound ? beanSupplier.get() : null);
  13.     }
  14.    
  15.     private <T> boolean bind(DataObjectPropertyBinder propertyBinder, Bean<T> bean, BeanSupplier<T> beanSupplier,
  16.         Context context) {
  17.         boolean bound = false;
  18.         for (BeanProperty beanProperty : bean.getProperties().values()) { // 获取这个对象上所有的BeanProperty属性
  19.             bound |= bind(beanSupplier, propertyBinder, beanProperty);
  20.             context.clearConfigurationProperty();
  21.         }
  22.         return bound;
  23.     }
  24.    
  25.     private <T> boolean bind(BeanSupplier<T> beanSupplier, DataObjectPropertyBinder propertyBinder,
  26.         BeanProperty property) {
  27.         String propertyName = determinePropertyName(property);
  28.         ResolvableType type = property.getType();
  29.         Supplier<Object> value = property.getValue(beanSupplier);
  30.         Annotation[] annotations = property.getAnnotations();
  31.         Object bound = propertyBinder.bindProperty(propertyName, //这个地方实际上又反调用回Binder中的lambda表达式了
  32.                 Bindable.of(type).withSuppliedValue(value).withAnnotations(annotations));
  33.         if (bound == null) {
  34.             return false;
  35.         }
  36.         if (property.isSettable()) {
  37.             property.setValue(beanSupplier, bound);
  38.         }
  39.         else if (value == null || !bound.equals(value.get())) {
  40.             throw new IllegalStateException("No setter found for property: " + property.getName());
  41.         }
  42.         return true;
  43.     }
  44. }
复制代码
BeanProperty 对象会将 JavaBean 中的属性统一为 Dash 格式。在本案例中属性名称是 containerName,统一之后就变成了 container-name。如下图所示:
7.png

在 Binder 中 lambda 表达式会将属性拼接到已有的 ConfigurationPropertyName 前缀上,在本案例中就变成了 test.container-name。然后又递归调用 bind() 方法,然后又调用 findProperty() 方法尝试从从对应的 ConfigurationPropertySource 中获取对应的配置中查找这个属性。
Spring 提供了 SpringIterableConfigurationPropertySource 作为 ConfigurationPropertySource 实现类, 它实际是对 PropertySource 的一个适配,内部有一个 propertySource 表示真正的配置。通过调试 contex.getSource() 方法的返回值,可以看到加密之后的 PropertySource 确实是在没有加密的前面。代码如下:
  1. DataObjectPropertyBinder propertyBinder = (propertyName, propertyTarget) -> bind(name.append(propertyName), //这里将属性名称拼接到test前缀上
  2.                 propertyTarget, handler, context, false, false);
  3.                
  4. private <T> ConfigurationProperty findProperty(ConfigurationPropertyName name, Bindable<T> target,
  5.     Context context) {
  6.     if (name.isEmpty() || target.hasBindRestriction(BindRestriction.NO_DIRECT_PROPERTY)) {
  7.         return null;
  8.     }
  9.     for (ConfigurationPropertySource source : context.getSources()) {
  10.         ConfigurationProperty property = source.getConfigurationProperty(name);
  11.         if (property != null) {
  12.             return property;
  13.         }
  14.     }
  15.     return null;
  16. }
复制代码
8.png

在 getConfigurationProperty() 方法中首先调用父类 SpringConfigurationPropertySource 的 getConfigurationProperty() 方法。在该方法中会调用 PropertyMapper 的 map() 方法对传入的 ConfigurationPropertyName 类型的 name 进行转换,然后根据转换后拿到的名称去 PropertySource 中获取对应的属性。
  1. class SpringConfigurationPropertySource implements ConfigurationPropertySource {
  2.     public ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) {
  3.         if (name == null) {
  4.             return null;
  5.         }
  6.         for (PropertyMapper mapper : this.mappers) {
  7.             try {
  8.                 for (String candidate : mapper.map(name)) { // 这里先通过PropertyMapper转换名称
  9.                     Object value = getPropertySource().getProperty(candidate); // 根据转换后的名称获取获取对应的属性
  10.                     if (value != null) {
  11.                         Origin origin = PropertySourceOrigin.get(this.propertySource, candidate);
  12.                         return ConfigurationProperty.of(this, name, value, origin);
  13.                     }
  14.                 }
  15.             }
  16.             catch (Exception ex) {
  17.                 // Ignore
  18.             }
  19.         }
  20.         return null;
  21.     }
  22. }
复制代码
在创建 SpringConfigurationPropertySource 对象时,会根据 PropertySource 是 MapPropertySource 还是 SystemEnvironmentPropertySource ,从而设置不同的 mappers 属性,对于 SystemEnvironmentPropertySource,它会多一个 SystemEnvironmentPropertyMapper 。代码如下:
  1. class SpringConfigurationPropertySource implements ConfigurationPropertySource {
  2.    private static final PropertyMapper[] DEFAULT_MAPPERS = { DefaultPropertyMapper.INSTANCE };
  3.    private static final PropertyMapper[] SYSTEM_ENVIRONMENT_MAPPERS = { SystemEnvironmentPropertyMapper.INSTANCE,
  4.     DefaultPropertyMapper.INSTANCE };
  5.    
  6.    static SpringConfigurationPropertySource from(PropertySource<?> source) {
  7.         Assert.notNull(source, "Source must not be null");
  8.         PropertyMapper[] mappers = getPropertyMappers(source);
  9.         if (isFullEnumerable(source)) {
  10.             return new SpringIterableConfigurationPropertySource((EnumerablePropertySource<?>) source, mappers);
  11.         }
  12.         return new SpringConfigurationPropertySource(source, mappers);
  13.     }
  14.    
  15.     private static PropertyMapper[] getPropertyMappers(PropertySource<?> source) {
  16.         // 这里判断了如果是SystemEnvironmentPropertySource则会返回SYSTEM_ENVIRONMENT_MAPPERS,里面包含了SystemEnvironmentPropertyMapper
  17.         if (source instanceof SystemEnvironmentPropertySource && hasSystemEnvironmentName(source)) {
  18.             return SYSTEM_ENVIRONMENT_MAPPERS;
  19.         }
  20.         return DEFAULT_MAPPERS;
  21.     }
  22. }
复制代码
对于 DefaultPropertyMapper 它的 map() 方法会直接返回 ConfigurationPropertyName 的名称,在本案例中就会直接返回 test.container-name。代码如下:
  1. final class DefaultPropertyMapper implements PropertyMapper {
  2.     @Override
  3.     public List<String> map(ConfigurationPropertyName configurationPropertyName) {
  4.         // Use a local copy in case another thread changes things
  5.         LastMapping<ConfigurationPropertyName, List<String>> last = this.lastMappedConfigurationPropertyName;
  6.         if (last != null && last.isFrom(configurationPropertyName)) {
  7.             return last.getMapping();
  8.         }
  9.         // 这里直接返回ConfigurationPropertyName的名称
  10.         String convertedName = configurationPropertyName.toString();
  11.         List<String> mapping = Collections.singletonList(convertedName);
  12.         this.lastMappedConfigurationPropertyName = new LastMapping<>(configurationPropertyName, mapping);
  13.         return mapping;
  14.     }
  15. }
复制代码
对于 SystemEnvironmentPropertyMapper 它会返回两个格式的名称,在本案例中就会返回 TEST_CONTAINERNAME 和 TEST_CONTAINER_NAME 两种格式。代码如下:
  1. final class SystemEnvironmentPropertyMapper implements PropertyMapper {
  2.     public static final PropertyMapper INSTANCE = new SystemEnvironmentPropertyMapper();
  3.     @Override
  4.     public List<String> map(ConfigurationPropertyName configurationPropertyName) {
  5.         String name = convertName(configurationPropertyName);
  6.         String legacyName = convertLegacyName(configurationPropertyName);
  7.         if (name.equals(legacyName)) {
  8.             return Collections.singletonList(name);
  9.         }
  10.         // 这里会返回两个格式的名称
  11.         return Arrays.asList(name, legacyName);
  12.     }
  13.     private String convertName(ConfigurationPropertyName name) {
  14.         return convertName(name, name.getNumberOfElements());
  15.     }
  16.     private String convertName(ConfigurationPropertyName name, int numberOfElements) {
  17.         StringBuilder result = new StringBuilder();
  18.         for (int i = 0; i < numberOfElements; i++) {
  19.             if (!result.isEmpty()) {
  20.                 result.append('_');
  21.             }
  22.             result.append(name.getElement(i, Form.UNIFORM).toUpperCase(Locale.ENGLISH));
  23.         }
  24.         return result.toString();
  25.     }
  26.     private String convertLegacyName(ConfigurationPropertyName name) {
  27.         StringBuilder result = new StringBuilder();
  28.         for (int i = 0; i < name.getNumberOfElements(); i++) {
  29.             if (!result.isEmpty()) {
  30.                 result.append('_');
  31.             }
  32.             result.append(convertLegacyNameElement(name.getElement(i, Form.ORIGINAL)));
  33.         }
  34.         return result.toString();
  35.     }
  36.     private Object convertLegacyNameElement(String element) {
  37.         return element.replace('-', '_').toUpperCase(Locale.ENGLISH);
  38.     }
  39. }
复制代码
在本案例中decryptedSystemEnvironment 的 PropertySource 类型是 MapPropertySource,存放的内容是 TEST_CONTAINER_NAME=Tomcat。它只有 DefaultPropertyMapper;
名称为 systemEnvironment 的 PropertySource 类型是 SystemEnvironmentPropertySource,存放的内容是 TEST_CONTAINER_NAME=ENC_VG9tY2F0。它有DefaultPropertyMapper 和 SystemEnvironmentPropertyMapper。
decryptedSystemEnvironment 在顺序上排在 systemEnvironment 前面。这个时候开始查找传入名称为 test.container-name 的 ConfigurationPropertyName,这个时候先从 decryptedSystemEnvironment 开始找,经过 DefaultPropertyMapper 转换之后拿到的属性名称是 test.container-name,配置里面没有这个配置;然后从 systemEnvironment 开始找,经过 SystemEnvironmentPropertyMapper 转换之后拿到的属性名称是TEST_CONTAINERNAME 和 TEST_CONTAINER_NAME,根据 TEST_CONTAINER_NAME 就拿到了 ENC_VG9tY2F0 。这就解释了为啥配置类注入的还是加密之后的值了。
问题解决

知道问题的原理了之后,问题就好解决了。一种方法是可以在 DecryptEnvironmentPostProcessor 类的 postProcessBeforeInitialization() 方法中把添加的 MapPropertySource 类型改为 SystemEnvironmentPropertySource 就可以了。代码如下:
  1. @Override  
  2. public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {  
  3.     String systemEnvName = StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME;  
  4.     MapPropertySource systemEnvSource = (MapPropertySource) environment.getPropertySources().get(systemEnvName);  
  5.     Map<String, Object> decryptedMap = new HashMap<>();  
  6.     if (systemEnvSource == null) {  
  7.         return;  
  8.     }  
  9.     systemEnvSource.getSource().forEach((key, value) -> {  
  10.         if (value instanceof String strVal) {  
  11.             if (StringUtils.isNotEmpty(strVal) && strVal.startsWith("ENC_")) {  
  12.                 String plainText = new String(Base64.getDecoder().decode(strVal.substring(4)));  
  13.                 decryptedMap.put(key, plainText);  
  14.             }  
  15.         }  
  16.     });  
  17.   
  18.     if (!decryptedMap.isEmpty()) {  
  19.                 // 这里原来添加的是MapPropertySource类型,现在调整为SystemEnvironmentPropertySource类型
  20.         // MapPropertySource decryptedSource = new MapPropertySource(DECRYPTED_SOURCE_NAME, decryptedMap);  
  21.         environment.getPropertySources().addBefore(systemEnvName, new SystemEnvironmentPropertySource(DECRYPTED_SOURCE_NAME, decryptedMap));  
  22.         System.out.println("");  
  23.     }  
  24. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册