mirror of
https://github.com/shlinkio/shlink.git
synced 2026-03-12 01:54:41 +08:00
Support loading env vars from secret files
This commit is contained in:
@@ -4,7 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace Shlinkio\Shlink\Core\Config;
|
||||
|
||||
use function file_get_contents;
|
||||
use function is_file;
|
||||
use function Shlinkio\Shlink\Config\env;
|
||||
use function Shlinkio\Shlink\Config\parseEnvVar;
|
||||
use function sprintf;
|
||||
|
||||
enum EnvVars: string
|
||||
{
|
||||
@@ -77,7 +81,24 @@ enum EnvVars: string
|
||||
|
||||
public function loadFromEnv(mixed $default = null): mixed
|
||||
{
|
||||
return env($this->value, $default);
|
||||
return env($this->value) ?? $this->loadFromFileEnv() ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an equivalent environment variable exists with the `_FILE` suffix. If so, it loads its value as a file,
|
||||
* reads it, and returns its contents.
|
||||
* This is useful when loading Shlink with docker compose and using secrets.
|
||||
* See https://docs.docker.com/compose/use-secrets/
|
||||
*/
|
||||
private function loadFromFileEnv(): string|int|bool|null
|
||||
{
|
||||
$file = env(sprintf('%s_FILE', $this->value));
|
||||
if ($file === null || ! is_file($file)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$content = file_get_contents($file);
|
||||
return $content ? parseEnvVar($content) : null;
|
||||
}
|
||||
|
||||
public function existsInEnv(): bool
|
||||
|
||||
@@ -17,12 +17,16 @@ class EnvVarsTest extends TestCase
|
||||
{
|
||||
putenv(EnvVars::BASE_PATH->value . '=the_base_path');
|
||||
putenv(EnvVars::DB_NAME->value . '=shlink');
|
||||
|
||||
$envFilePath = __DIR__ . '/../DB_PASSWORD.env';
|
||||
putenv(EnvVars::DB_PASSWORD->value . '_FILE=' . $envFilePath);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
putenv(EnvVars::BASE_PATH->value . '=');
|
||||
putenv(EnvVars::DB_NAME->value . '=');
|
||||
putenv(EnvVars::DB_PASSWORD->value . '_FILE=');
|
||||
}
|
||||
|
||||
#[Test, DataProvider('provideExistingEnvVars')]
|
||||
@@ -54,4 +58,10 @@ class EnvVarsTest extends TestCase
|
||||
yield 'DB_DRIVER without default' => [EnvVars::DB_DRIVER, null, null];
|
||||
yield 'DB_DRIVER with default' => [EnvVars::DB_DRIVER, 'foobar', 'foobar'];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function fallsBackToReadEnvVarsFromFile(): void
|
||||
{
|
||||
self::assertEquals('this_is_the_password', EnvVars::DB_PASSWORD->loadFromEnv());
|
||||
}
|
||||
}
|
||||
|
||||
1
module/Core/test/DB_PASSWORD.env
Normal file
1
module/Core/test/DB_PASSWORD.env
Normal file
@@ -0,0 +1 @@
|
||||
this_is_the_password
|
||||
Reference in New Issue
Block a user