Skip to content

Commit f945118

Browse files
committed
Redact API keys overwritten via env variables to prevent leakage to undesired users
1 parent ab811b1 commit f945118

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/Form/Type/APIKeyType.php

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,45 @@
2828
use Symfony\Component\Form\FormInterface;
2929
use Symfony\Component\Form\FormView;
3030
use Symfony\Component\OptionsResolver\OptionsResolver;
31+
use Symfony\Contracts\Translation\TranslatorInterface;
3132

3233
class APIKeyType extends AbstractType
3334
{
35+
public function __construct(private readonly TranslatorInterface $translator)
36+
{
37+
}
38+
3439
public function getParent(): string
3540
{
3641
return PasswordType::class;
3742
}
3843

3944
public function buildView(FormView $view, FormInterface $form, array $options): void
4045
{
41-
//Ensure that the field is never empty
42-
$view->vars['value'] = $form->getViewData();
46+
$viewData = $form->getViewData();
47+
48+
//If the field is disabled, show the redacted API key
49+
if ($options['disabled'] ?? false) {
50+
if ($viewData === null || $viewData === '') {
51+
$view->vars['value'] = $viewData;
52+
} else {
53+
54+
$view->vars['value'] = self::redact((string)$viewData) . ' (' . $this ->translator->trans("form.apikey.redacted") . ')';
55+
}
56+
} else { //Otherwise, show the actual value
57+
$view->vars['value'] = $viewData;
58+
}
59+
}
60+
61+
public static function redact(string $apiKey): string
62+
{
63+
//Show only the last 2 characters of the API key if it is long enough (more than 16 characters)
64+
//Replace all other characters with dots
65+
if (strlen($apiKey) > 16) {
66+
return str_repeat('*', strlen($apiKey) - 2) . substr($apiKey, -2);
67+
}
68+
69+
return str_repeat('*', strlen($apiKey));
4370
}
4471

4572
public function configureOptions(OptionsResolver $resolver): void

translations/messages.en.xlf

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13051,5 +13051,11 @@ Please note, that you can not impersonate a disabled user. If you try you will g
1305113051
<target>Info provider settings</target>
1305213052
</segment>
1305313053
</unit>
13054+
<unit id="VgSodKY" name="form.apikey.redacted">
13055+
<segment>
13056+
<source>form.apikey.redacted</source>
13057+
<target>Redacted for security reasons</target>
13058+
</segment>
13059+
</unit>
1305413060
</file>
1305513061
</xliff>

0 commit comments

Comments
 (0)