-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathSecrets.php
More file actions
205 lines (179 loc) · 8.7 KB
/
Copy pathSecrets.php
File metadata and controls
205 lines (179 loc) · 8.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
<?php declare(strict_types=1);
namespace Bref\Secrets;
use AsyncAws\SecretsManager\SecretsManagerClient;
use AsyncAws\Ssm\SsmClient;
use Closure;
use JsonException;
use RuntimeException;
class Secrets
{
/**
* Decrypt environment variables that are encrypted with AWS SSM.
*
* @param SsmClient|null $ssmClient To allow mocking in tests.
* @param SecretsManagerClient|null $secretsManagerClient To allow mocking in tests.
* @throws JsonException
*/
public static function loadSecretEnvironmentVariables(?SsmClient $ssmClient = null, ?SecretsManagerClient $secretsManagerClient = null): void
{
/** @var array<string,string>|string|false $envVars */
$envVars = getenv(local_only: true); // @phpstan-ignore-line PHPStan is wrong
if (! is_array($envVars)) {
return;
}
// Only consider environment variables that start with "bref-ssm:" or "bref-secretsmanager:"
$envVarsToDecrypt = array_filter($envVars, function (string $value): bool {
return str_starts_with($value, 'bref-ssm:') || str_starts_with($value, 'bref-secretsmanager:');
});
if (empty($envVarsToDecrypt)) {
return;
}
$ssmNames = [];
$secretsManagerNames = [];
// Extract the SSM and SecretsManager parameter names by removing the prefixes
foreach ($envVarsToDecrypt as $key => $envVar) {
if (str_starts_with($envVar, 'bref-ssm:')) {
$ssmNames[$key] = substr($envVar, strlen('bref-ssm:'));
}
if (str_starts_with($envVar, 'bref-secretsmanager:')) {
$secretsManagerNames[$key] = substr($envVar, strlen('bref-secretsmanager:'));
}
}
if (count($secretsManagerNames) > 0 && class_exists(SecretsManagerClient::class) === false) {
throw new RuntimeException('In order to load secrets from SecretsManager you must install "async-aws/secrets-manager" package');
}
$actuallyCalledSsm = false;
if (count($ssmNames) > 0) {
$ssmParameters = self::readParametersFromCacheOr('ssm', function () use ($ssmClient, $ssmNames, &$actuallyCalledSsm) {
$actuallyCalledSsm = true;
return self::retrieveParametersFromSsm($ssmClient, array_values($ssmNames));
});
foreach ($ssmParameters as $parameterName => $parameterValue) {
$envVar = array_search($parameterName, $ssmNames, true);
$_SERVER[$envVar] = $_ENV[$envVar] = $parameterValue;
putenv("$envVar=$parameterValue");
}
}
$actuallyCalledSecretsManager = false;
if (count($secretsManagerNames) > 0) {
$secretsManagerParameters = self::readParametersFromCacheOr('secretsmanager', function () use ($secretsManagerClient, $secretsManagerNames, &$actuallyCalledSecretsManager) {
$actuallyCalledSecretsManager = true;
return self::retrieveParametersFromSecretsManager($secretsManagerClient, $secretsManagerNames);
});
foreach ($secretsManagerParameters as $parameterName => $parameterValue) {
$_SERVER[$parameterName] = $_ENV[$parameterName] = $parameterValue;
putenv("$parameterName=$parameterValue");
}
}
// Only log once (when the cache was empty) else it might spam the logs in the function runtime
// (where the process restarts on every invocation)
if ($actuallyCalledSsm || $actuallyCalledSecretsManager) {
$stderr = fopen('php://stderr', 'ab');
fwrite($stderr, '[Bref] Loaded these environment variables from SSM/SecretsManager: ' . implode(', ', array_keys($envVarsToDecrypt)) . PHP_EOL);
}
}
/**
* Cache the parameters in a temp file.
* Why? Because on the function runtime, the PHP process might
* restart on every invocation (or on error), so we don't want to
* call SSM/SecretsManager every time.
*
* @param Closure(): array<string, string> $paramResolver
* @return array<string, string> Map of parameter name -> value
* @throws JsonException
*/
private static function readParametersFromCacheOr(string $paramType, Closure $paramResolver): array
{
// Check in cache first
$cacheFile = sprintf('%s/bref-%s-parameters.php', sys_get_temp_dir(), $paramType);
if (is_file($cacheFile)) {
$parameters = json_decode(file_get_contents($cacheFile), true, 512, JSON_THROW_ON_ERROR);
if (is_array($parameters)) {
return $parameters;
}
}
// Not in cache yet: we resolve it
$parameters = $paramResolver();
// Using json_encode instead of var_export due to possible security issues
file_put_contents($cacheFile, json_encode($parameters, JSON_THROW_ON_ERROR));
return $parameters;
}
/**
* @param string[] $secretNames
* @return array<string, string> Map of parameter name -> value
* @throws JsonException
*/
private static function retrieveParametersFromSecretsManager(
?SecretsManagerClient $secretsManagerClient,
array $secretNames
): array {
$secretsManager = $secretsManagerClient ?? new SecretsManagerClient([
'region' => $_ENV['AWS_REGION'] ?? $_ENV['AWS_DEFAULT_REGION'],
]);
/** @var array<string, string> $parameters Map of parameter name -> value */
$parameters = [];
foreach ($secretNames as $secretId) {
try {
$result = $secretsManager->getSecretValue([
'SecretId' => $secretId,
]);
$secretString = $result->getSecretString();
} catch (RuntimeException $e) {
if ($e->getCode() === 400) {
// Extra descriptive error message for the most common error
throw new RuntimeException(
"Bref was not able to resolve secrets contained in environment variables from SecretsManager because of a permissions issue with the SecretsManager API. Did you add IAM permissions in serverless.yml to allow Lambda to access SecretsManager? (docs: https://bref.sh/docs/environment/variables.html#at-deployment-time).\nFull exception message: {$e->getMessage()}",
$e->getCode(),
$e,
);
}
throw $e;
}
$secretValues = json_decode($secretString, true, 512, JSON_THROW_ON_ERROR);
foreach ($secretValues as $name => $value) {
$parameters[$name] = $value;
}
}
return $parameters;
}
/**
* @param string[] $ssmNames
* @return array<string, string> Map of parameter name -> value
*/
private static function retrieveParametersFromSsm(?SsmClient $ssmClient, array $ssmNames): array
{
$ssm = $ssmClient ?? new SsmClient([
'region' => $_ENV['AWS_REGION'] ?? $_ENV['AWS_DEFAULT_REGION'],
]);
/** @var array<string, string> $parameters Map of parameter name -> value */
$parameters = [];
$parametersNotFound = [];
// The API only accepts up to 10 parameters at a time, so we batch the calls
foreach (array_chunk($ssmNames, 10) as $batchOfSsmNames) {
try {
$result = $ssm->getParameters([
'Names' => $batchOfSsmNames,
'WithDecryption' => true,
]);
foreach ($result->getParameters() as $parameter) {
$parameters[$parameter->getName()] = $parameter->getValue();
}
} catch (RuntimeException $e) {
if ($e->getCode() === 400) {
// Extra descriptive error message for the most common error
throw new RuntimeException(
"Bref was not able to resolve secrets contained in environment variables from SSM because of a permissions issue with the SSM API. Did you add IAM permissions in serverless.yml to allow Lambda to access SSM? (docs: https://bref.sh/docs/environment/variables.html#at-deployment-time).\nFull exception message: {$e->getMessage()}",
$e->getCode(),
$e,
);
}
throw $e;
}
$parametersNotFound = array_merge($parametersNotFound, $result->getInvalidParameters());
}
if (count($parametersNotFound) > 0) {
throw new RuntimeException('The following SSM parameters could not be found: ' . implode(', ', $parametersNotFound));
}
return $parameters;
}
}