44require "aws-sdk-secretsmanager"
55require "concurrent-ruby"
66require "json"
7+ require "active_support/core_ext/object/blank.rb"
8+ require "base64"
79
810module SecretsManager
911 class SecretNotFound < StandardError ; end ;
@@ -23,13 +25,15 @@ def reset
2325
2426 def set ( path , value , ttl = 86400 )
2527 @_cache [ path ] = { expires_at : ( Time . now + ttl ) , value : value }
28+
2629 return self
2730 end
2831
2932 def find ( path )
3033 fetched = @_cache [ path ]
3134 return unless fetched
3235 return unless !fetched [ :expires_at ] . nil? && ( fetched [ :expires_at ] ) > Time . now
36+
3337 fetched [ :value ]
3438 end
3539 end
@@ -43,34 +47,36 @@ def initialize(client: nil)
4347 end
4448
4549 def secret_env
46- ENV [ ' AWS_SECRETS_ENV' ] || ENV [ ' RACK_ENV' ] || ' development'
50+ ENV [ " AWS_SECRETS_ENV" ] || ENV [ " RACK_ENV" ] || " development"
4751 end
4852
4953 def client
5054 return @aws_client if @aws_client
5155
5256 @_client ||= Aws ::SecretsManager ::Client . new ( {
53- region : ENV . fetch ( ' AWS_SECRETS_REGION' , ' us-east-1' ) ,
54- credentials : Aws ::Credentials . new ( ENV [ ' AWS_SECRETS_KEY' ] , ENV [ ' AWS_SECRETS_SECRET' ] )
57+ region : ENV . fetch ( " AWS_SECRETS_REGION" , " us-east-1" ) ,
58+ credentials : Aws ::Credentials . new ( ENV [ " AWS_SECRETS_KEY" ] , ENV [ " AWS_SECRETS_SECRET" ] )
5559 } )
5660 end
5761
5862 def fetch ( secret_path )
5963 if secret_path . start_with? ( "global" )
6064 resolved_path = secret_path
6165 else
62- resolved_path = secret_env + '/' + secret_path
66+ resolved_path = secret_env + "/" + secret_path
6367 end
6468
6569 cached_value = cache . find ( resolved_path )
6670 return cached_value if cached_value
6771
6872 response = client . get_secret_value ( secret_id : resolved_path )
6973 return nil unless response && response . secret_string
70- object = JSON . parse ( response . secret_string , symbolize_names : true )
7174
75+ object = JSON . parse ( response . secret_string , symbolize_names : true )
7276 value = parse_value ( object )
77+
7378 cache . set ( resolved_path , value , parse_ttl ( object ) )
79+
7480 return value
7581 rescue Aws ::SecretsManager ::Errors ::ResourceNotFoundException => e
7682 raise SecretsManager ::SecretNotFound , "Could not find secret with path #{ resolved_path } "
@@ -81,6 +87,7 @@ def [](path)
8187 end
8288
8389 private
90+
8491 def parse_ttl ( data )
8592 ## Default to one day cache TTL
8693 return 86400 unless data [ :ttl ] . present?
@@ -106,6 +113,5 @@ def parse_value(data)
106113
107114 return value
108115 end
109-
110116 end
111- end
117+ end
0 commit comments