diff --git a/src/Secrets.php b/src/Secrets.php index 91cd76c..d7ee270 100644 --- a/src/Secrets.php +++ b/src/Secrets.php @@ -101,28 +101,40 @@ private static function retrieveParametersFromSsm(?SsmClient $ssmClient, array $ $parameters = []; $parametersNotFound = []; - // The API only accepts up to 10 parameters at a time, so we batch the calls + // The API only accepts up to 10 parameters at a time, so we batch the calls. + // async-aws sends a request as soon as it is created: create every batch before reading any, + // so the batches run in parallel instead of one after the other. + $results = []; foreach (array_chunk($ssmNames, 10) as $batchOfSsmNames) { + $results[] = $ssm->getParameters([ + 'Names' => $batchOfSsmNames, + 'WithDecryption' => true, + ]); + } + + // Every result is read, even after one failed: async-aws throws a failure nobody read when the result is destructed + $failure = null; + foreach ($results as $result) { try { - $result = $ssm->getParameters([ - 'Names' => $batchOfSsmNames, - 'WithDecryption' => true, - ]); foreach ($result->getParameters() as $parameter) { $parameters[$parameter->getName()] = $parameter->getValue(); } + $parametersNotFound = array_merge($parametersNotFound, $result->getInvalidParameters()); } 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; + $failure ??= $e; + } + } + + if ($failure !== null) { + if ($failure->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: {$failure->getMessage()}", + $failure->getCode(), + $failure, + ); } - $parametersNotFound = array_merge($parametersNotFound, $result->getInvalidParameters()); + throw $failure; } if (count($parametersNotFound) > 0) { diff --git a/tests/SecretsTest.php b/tests/SecretsTest.php index 9c85a10..a09816a 100644 --- a/tests/SecretsTest.php +++ b/tests/SecretsTest.php @@ -8,9 +8,12 @@ use AsyncAws\Ssm\ValueObject\Parameter; use Bref\Secrets\Secrets; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\HttpClient\Response\MockResponse; class SecretsTest extends TestCase { + /** @var array{Name: string, Value: string} */ private array $resultParams = [ 'Name' => '/some/parameter', 'Value' => 'foobar', @@ -103,6 +106,66 @@ public function test throws a clear error message on missing permissions putenv('SOME_VARIABLE'); } + public function test sends the batches of parameters in parallel(): void + { + // 11 parameters: two batches, as the API takes up to 10 at a time + $names = []; + for ($i = 1; $i <= 11; $i++) { + $names[] = "/some/parameter-$i"; + putenv("VAR_$i=bref-ssm:/some/parameter-$i"); + } + + $events = []; + $httpClient = new MockHttpClient(function (string $method, string $url, array $options) use (&$events): MockResponse { + $batch = json_decode($options['body'], true)['Names']; + $events[] = 'request'; + $body = (function () use (&$events, $batch) { + $events[] = 'read'; + yield json_encode([ + 'Parameters' => array_map(fn (string $name) => ['Name' => $name, 'Value' => "value of $name"], $batch), + 'InvalidParameters' => [], + ]); + })(); + + return new MockResponse($body, ['http_code' => 200, 'response_headers' => ['content-type' => 'application/x-amz-json-1.1']]); + }); + $ssmClient = new SsmClient(['region' => 'us-east-1', 'accessKeyId' => 'key', 'accessKeySecret' => 'secret'], null, $httpClient); + + Secrets::loadSecretEnvironmentVariables($ssmClient); + + // Both requests are sent before either response is read + $this->assertSame(['request', 'request', 'read', 'read'], $events); + foreach ($names as $i => $name) { + $this->assertSame("value of $name", getenv('VAR_' . ($i + 1))); + putenv('VAR_' . ($i + 1)); + } + } + + public function test throws a clear error message when every batch fails(): void + { + for ($i = 1; $i <= 11; $i++) { + putenv("VAR_$i=bref-ssm:/app/test-$i"); + } + + $ssmClient = $this->getMockBuilder(SsmClient::class) + ->disableOriginalConstructor() + ->getMock(); + // Both batches are sent, and both fail + $ssmClient->expects($this->exactly(2)) + ->method('getParameters') + ->willReturnCallback(fn () => ResultMockFactory::createFailing(GetParametersResult::class, 400, 'User: arn:aws:sts::123456:assumed-role/app-dev-us-east-1-lambdaRole/app-dev-hello is not authorized to perform: ssm:GetParameters')); + + $expected = preg_quote('Bref was not able to resolve secrets contained in environment variables from SSM because of a permissions issue with the SSM API.', '/'); + $this->expectExceptionMessageMatches("/^$expected/"); + try { + Secrets::loadSecretEnvironmentVariables($ssmClient); + } finally { + for ($i = 1; $i <= 11; $i++) { + putenv("VAR_$i"); + } + } + } + /** * @param array $resultParameters */