-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSecrets.php
More file actions
164 lines (143 loc) · 6 KB
/
Secrets.php
File metadata and controls
164 lines (143 loc) · 6 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
<?php declare(strict_types=1);
namespace Bref\Secrets;
use AsyncAws\Ssm\SsmClient;
use Closure;
use Dotenv\Dotenv;
use JsonException;
use RuntimeException;
class Secrets
{
/**
* Decrypt environment variables that are encrypted with AWS SSM.
*
* @param SsmClient|null $ssmClient To allow mocking in tests.
* @throws JsonException
*/
public static function loadSecretEnvironmentVariables(?SsmClient $ssmClient = null): void
{
$envVars = self::getEnvVars();
// Only consider environment variables that start with "bref-ssm:"
$envVarsToDecrypt = array_filter($envVars, function (string $value): bool {
return str_starts_with($value, 'bref-ssm:');
});
if (empty($envVarsToDecrypt)) {
return;
}
// Extract the SSM parameter names by removing the "bref-ssm:" prefix
$ssmNames = array_map(function (string $value): string {
return substr($value, strlen('bref-ssm:'));
}, $envVarsToDecrypt);
$actuallyCalledSsm = false;
$parameters = self::readParametersFromCacheOr(function () use ($ssmClient, $ssmNames, &$actuallyCalledSsm) {
$actuallyCalledSsm = true;
return self::retrieveParametersFromSsm($ssmClient, array_values($ssmNames));
});
foreach ($parameters as $parameterName => $parameterValue) {
$envVar = array_search($parameterName, $ssmNames, true);
$_SERVER[$envVar] = $_ENV[$envVar] = $parameterValue;
putenv("$envVar=$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) {
$stderr = fopen('php://stderr', 'ab');
fwrite($stderr, '[Bref] Loaded these environment variables from SSM: ' . 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 every time.
*
* @param Closure(): array<string, string> $paramResolver
* @return array<string, string> Map of parameter name -> value
* @throws JsonException
*/
private static function readParametersFromCacheOr(Closure $paramResolver): array
{
// Check in cache first
$cacheFile = sys_get_temp_dir() . '/bref-ssm-parameters.php';
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[] $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;
}
private static function getEnvironment(): ?string
{
if ($environment = getenv('BREF_ENV')){
return $environment;
}
return getenv('APP_ENV') ?: null;
}
private static function getEnvironmentPath(): ?string
{
if ($environment = getenv('BREF_ENV_PATH')){
return $environment;
}
return getenv('LAMBDA_TASK_ROOT') ?: getcwd();
}
private static function getEnvFile(): string
{
$env = self::getEnvironment();
$envFilePath = self::getEnvironmentPath()."/.env.{$env}";
return $env && file_exists($envFilePath) ? ".env.{$env}" : '.env';
}
private static function getEnvVars(): array
{
$env = getenv(null, true);
return array_merge(
is_array($env) ? $env : [],
Dotenv::createUnsafeImmutable(
self::getEnvironmentPath(),
self::getEnvFile()
)->safeLoad());
}
}