Rails 7 allows access to nested encrypted secrets by method calls


Since Rails 5.2 was released, we can make use of the Credentials API to manage our secrets.

Check out our previous blog on Rails credentials to learn more about the working of the API.

Example

Consider config/credentials.yml.enc contains the following configuration:

aws:
  access_key_id: 123
  secret_access_key: 345
github:
  app_id: 123
  app_secret: 345
secret_key_base:

Before

Earlier we could only access the top-level key using the dot (.) syntax (i.e., Using a method call).

The nested keys had to be accessed using the [] syntax.

# Using the [] syntax
> Rails.application.credentials[:aws]
#=> { :access_key_id => 123, :secret_access_key => 345 }

# Using the dot(.) syntax for top-level key
> Rails.application.credentials.aws
#=> { :access_key_id => 123, :secret_access_key => 345 }

# Using the dot(.) syntax for top-level key and [] syntax for nested key
> Rails.application.credentials.aws[:access_key_id]
#=> 123

# Using the dot(.) syntax for nested key
> Rails.application.credentials.aws.access_key_id
#=> NoMethodError (undefined method `access_key_id' for {:access_key_id=>123, :secret_access_key=>345}:Hash)

After

As we can see in the last example, trying to access a nested key using the dot syntax raises a NoMethodError.

Rails 7 adds the ability to access nested secrets using the dot syntax (i.e., Using a method call).

Now it is possible to access the nested key access_key_id as follows:

# Using the dot (.) syntax for nested key
> Rails.application.credentials.aws.access_key_id
#=> 123