brefphp / secrets-loader

Load secret values from SSM into environment variables
https://bref.sh/docs/environment/variables.html#secrets
MIT License
13 stars 7 forks source link

Multiple envs vars mapped to same SSM parameter can fail #10

Open drjamesj opened 7 months ago

drjamesj commented 7 months ago

Ran into an edge case today where my project has multiple environment variables referencing the same SSM parameter.

For example:

  environment:
    DB_HOST_1: bref-ssm:/my-secret
    DB_HOST_2: bref-ssm:/my-secret

In this case, during parsing, only one of the values is replaced and the other was not being replaced. After a bit of headscratching I believe the suspect code is:

        foreach ($parameters as $parameterName => $parameterValue) {
            $envVar = array_search($parameterName, $ssmNames, true);
            $_SERVER[$envVar] = $_ENV[$envVar] = $parameterValue;
            putenv("$envVar=$parameterValue");
        }

When we expect only one occurrence of the SSM parameter in the list of $envVarsToDecrypt, array_search is sufficient. But it only returns the first matching key and so results in subsequent variables not being replaced with their SSM value. The solution is to iterate through all envVars that match this SSM parameter.

On the same note, I also found that there is some small inefficiency with retrieving the paramters from SSM, because the duplicates are not removed. Some kind of array_unique could be useful there.

Will try and find the time for a PR at some point.

selfsimilar commented 4 months ago

I wrote a fix for this about six months ago, but it still hasn't been merged. https://github.com/brefphp/secrets-loader/pull/9