diff --git a/CHANGELOG.md b/CHANGELOG.md index 765a9f0e..c6592b24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ before starting to add changes. Use example [placed in the end of the page](#exa ## [Unreleased] +- [PR-101](https://github.com/OS2Forms/os2forms/pull/101) + - Added support for `os2web_key` in Digital post + - Switched from saving settings in key value store to config, i.e + the module needs to be reconfigured. + - Added support for `os2web_key` in Fasit handler. + - Switched from saving settings in key value store to config, i.e + the module needs to be reconfigured. - [PR-179](https://github.com/OS2Forms/os2forms/pull/179) Remove unused and abandoned package `webmozart/path-util`. diff --git a/composer.json b/composer.json index 81bfb75c..f6d9b016 100644 --- a/composer.json +++ b/composer.json @@ -58,7 +58,8 @@ "itk-dev/serviceplatformen": "^1.5", "mglaman/composer-drupal-lenient": "^1.0", "os2web/os2web_audit": "^1.0", - "os2web/os2web_datalookup": "^2.0", + "os2web/os2web_datalookup": "dev-feature/os2web_key as 2.1.0", + "os2web/os2web_key": "^1.0", "os2web/os2web_nemlogin": "^1.0", "os2web/os2web_simplesaml": "dev-master", "php-http/guzzle7-adapter": "^1.0", @@ -78,6 +79,10 @@ "wsdltophp/packagegenerator": "^4.0" }, "repositories": { + "os2web/os2web_datalookup": { + "type": "vcs", + "url": "https://github.com/itk-dev/os2web_datalookup" + }, "drupal": { "type": "composer", "url": "https://packages.drupal.org/8" diff --git a/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php b/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php index a9acd083..00df83a3 100644 --- a/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php +++ b/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php @@ -3,8 +3,10 @@ namespace Drupal\os2forms_dawa\Plugin\os2web\DataLookup; use Drupal\Component\Utility\NestedArray; +use Drupal\Core\File\FileSystem; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Drupal\key\KeyRepositoryInterface; use Drupal\os2forms_dawa\Entity\DatafordelerMatrikula; use Drupal\os2web_audit\Service\Logger; use Drupal\os2web_datalookup\Plugin\os2web\DataLookup\DataLookupBase; @@ -30,20 +32,31 @@ public function __construct( $plugin_definition, protected ClientInterface $httpClient, Logger $auditLogger, + KeyRepositoryInterface $keyRepository, + FileSystem $fileSystem, ) { - parent::__construct($configuration, $plugin_id, $plugin_definition, $auditLogger); + parent::__construct($configuration, $plugin_id, $plugin_definition, $auditLogger, $keyRepository, $fileSystem); } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + /** @var \Drupal\os2web_audit\Service\Logger $auditLogger */ + $auditLogger = $container->get('os2web_audit.logger'); + /** @var \Drupal\key\KeyRepositoryInterface $keyRepository */ + $keyRepository = $container->get('key.repository'); + /** @var \Drupal\Core\File\FileSystem $fileSystem */ + $fileSystem = $container->get('file_system'); + return new static( $configuration, $plugin_id, $plugin_definition, $container->get('http_client'), - $container->get('os2web_audit.logger'), + $auditLogger, + $keyRepository, + $fileSystem, ); } diff --git a/modules/os2forms_digital_post/README.md b/modules/os2forms_digital_post/README.md index a487b13e..999d87c7 100644 --- a/modules/os2forms_digital_post/README.md +++ b/modules/os2forms_digital_post/README.md @@ -31,6 +31,11 @@ examples](modules/os2forms_digital_post_examples/README.md). Go to `/admin/os2forms_digital_post/settings` to set up global settings for digital post. +### Key + +We use [os2web_key](https://github.com/OS2web/os2web_key) to provide the certificate for sending digital post, and the +key must be of type "[Certificate](https://github.com/os2web/os2web_key?tab=readme-ov-file#certificate)". + ### Queue The actual sending of digital post is handled by jobs in an [Advanced diff --git a/modules/os2forms_digital_post/os2forms_digital_post.info.yml b/modules/os2forms_digital_post/os2forms_digital_post.info.yml index 71a17688..0e1408cc 100644 --- a/modules/os2forms_digital_post/os2forms_digital_post.info.yml +++ b/modules/os2forms_digital_post/os2forms_digital_post.info.yml @@ -7,6 +7,7 @@ dependencies: - 'beskedfordeler:beskedfordeler' - 'drupal:advancedqueue' - 'os2web_datalookup:os2web_datalookup' + - 'os2web_key:os2web_key' - 'webform:webform' - 'webform:webform_submission_log' - 'os2web:os2web_audit' diff --git a/modules/os2forms_digital_post/os2forms_digital_post.install b/modules/os2forms_digital_post/os2forms_digital_post.install index 760743cb..48768e21 100644 --- a/modules/os2forms_digital_post/os2forms_digital_post.install +++ b/modules/os2forms_digital_post/os2forms_digital_post.install @@ -17,3 +17,12 @@ use Drupal\os2forms_digital_post\Helper\BeskedfordelerHelper; function os2forms_digital_post_schema() { return Drupal::service(BeskedfordelerHelper::class)->schema(); } + +/** + * Install OS2Web key module. + */ +function os2forms_digital_post_update_9001(): void { + \Drupal::service('module_installer')->install([ + 'os2web_key', + ], TRUE); +} diff --git a/modules/os2forms_digital_post/os2forms_digital_post.services.yml b/modules/os2forms_digital_post/os2forms_digital_post.services.yml index c13fb96f..745b88d2 100644 --- a/modules/os2forms_digital_post/os2forms_digital_post.services.yml +++ b/modules/os2forms_digital_post/os2forms_digital_post.services.yml @@ -9,7 +9,8 @@ services: Drupal\os2forms_digital_post\Helper\Settings: arguments: - - "@keyvalue" + - "@config.factory" + - "@key.repository" Drupal\os2forms_digital_post\Helper\CertificateLocatorHelper: arguments: @@ -30,11 +31,12 @@ services: Drupal\os2forms_digital_post\Helper\DigitalPostHelper: arguments: - "@Drupal\\os2forms_digital_post\\Helper\\Settings" - - "@Drupal\\os2forms_digital_post\\Helper\\CertificateLocatorHelper" + - "@Drupal\\os2web_key\\KeyHelper" - "@plugin.manager.os2web_datalookup" - "@Drupal\\os2forms_digital_post\\Helper\\MeMoHelper" - "@Drupal\\os2forms_digital_post\\Helper\\ForsendelseHelper" - "@Drupal\\os2forms_digital_post\\Helper\\BeskedfordelerHelper" + - "@Drupal\\os2forms_digital_post\\Helper\\CertificateLocatorHelper" - "@logger.channel.os2forms_digital_post" - "@logger.channel.os2forms_digital_post_submission" - "@os2web_audit.logger" diff --git a/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php b/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php index 201581c5..490e0f5a 100644 --- a/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php +++ b/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php @@ -19,7 +19,7 @@ /** * Test commands for digital post. */ -class DigitalPostTestCommands extends DrushCommands { +final class DigitalPostTestCommands extends DrushCommands { use AutowireTrait; /** @@ -151,7 +151,9 @@ private function dumpDigitalPostSettings(SymfonyStyle $io): void { Yaml::encode([ 'testMode' => $this->digitalPostSettings->getTestMode(), 'sender' => $this->digitalPostSettings->getSender(), - 'certificate' => $this->digitalPostSettings->getCertificate(), + 'certificate' => [ + 'key' => $this->digitalPostSettings->getKey(), + ], 'processing' => $this->digitalPostSettings->getProcessing(), ]), '', diff --git a/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php b/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php index cbef5ad4..446dc8f3 100644 --- a/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php +++ b/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php @@ -8,6 +8,7 @@ use Drupal\os2forms_digital_post\Helper\BeskedfordelerHelper; use Drupal\os2forms_digital_post\Helper\WebformHelperSF1601; use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Event subscriber for PostStatusBeskedModtagEvent. @@ -23,6 +24,7 @@ public function __construct( private readonly BeskedfordelerHelper $beskedfordelerHelper, private readonly MessageHelper $messageHelper, private readonly WebformHelperSF1601 $webformHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] LoggerInterface $logger, ) { parent::__construct($logger); diff --git a/modules/os2forms_digital_post/src/Exception/InvalidSettingException.php b/modules/os2forms_digital_post/src/Exception/InvalidSettingException.php deleted file mode 100644 index c3d34af6..00000000 --- a/modules/os2forms_digital_post/src/Exception/InvalidSettingException.php +++ /dev/null @@ -1,10 +0,0 @@ -queueStorage = $entityTypeManager->getStorage('advancedqueue_queue'); } @@ -44,12 +47,23 @@ public function __construct( */ public static function create(ContainerInterface $container) { return new static( + $container->get('config.factory'), + $container->get('entity_type.manager'), $container->get(Settings::class), - $container->get(CertificateLocatorHelper::class), - $container->get('entity_type.manager') ); } + /** + * {@inheritdoc} + * + * @phpstan-return string[] + */ + protected function getEditableConfigNames() { + return [ + Settings::CONFIG_NAME, + ]; + } + /** * {@inheritdoc} */ @@ -63,15 +77,26 @@ public function getFormId() { * @phpstan-param array $form * @phpstan-return array */ - public function buildForm(array $form, FormStateInterface $form_state) { - $form['test_mode'] = [ + public function buildForm(array $form, FormStateInterface $form_state): array { + $form = parent::buildForm($form, $form_state); + + $form['message'] = [ + '#theme' => 'status_messages', + '#message_list' => [ + 'status' => [ + $this->t('Use drush os2forms-digital-post:test:send to test sending digital post.'), + ], + ], + ]; + + $form[Settings::TEST_MODE] = [ '#type' => 'checkbox', '#title' => $this->t('Test mode'), - '#default_value' => $this->settings->getTestMode(), + '#default_value' => $this->settings->getEditableValue(Settings::TEST_MODE), + '#description' => $this->createDescription(Settings::TEST_MODE), ]; - $sender = $this->settings->getSender(); - $form['sender'] = [ + $form[Settings::SENDER] = [ '#type' => 'fieldset', '#title' => $this->t('Sender'), '#tree' => TRUE, @@ -82,126 +107,184 @@ public function buildForm(array $form, FormStateInterface $form_state) { '#options' => [ 'CVR' => $this->t('CVR'), ], - '#default_value' => $sender[Settings::SENDER_IDENTIFIER_TYPE] ?? 'CVR', + '#default_value' => $this->settings->getEditableValue([Settings::SENDER, Settings::SENDER_IDENTIFIER_TYPE]) ?? 'CVR', '#required' => TRUE, + '#description' => $this->createDescription([Settings::SENDER, Settings::SENDER_IDENTIFIER_TYPE]), ], Settings::SENDER_IDENTIFIER => [ '#type' => 'textfield', '#title' => $this->t('Identifier'), - '#default_value' => $sender[Settings::SENDER_IDENTIFIER] ?? NULL, + '#default_value' => $this->settings->getEditableValue([Settings::SENDER, Settings::SENDER_IDENTIFIER]), '#required' => TRUE, + '#description' => $this->createDescription([Settings::SENDER, Settings::SENDER_IDENTIFIER]), ], Settings::FORSENDELSES_TYPE_IDENTIFIKATOR => [ '#type' => 'textfield', '#title' => $this->t('Forsendelsestypeidentifikator'), - '#default_value' => $sender[Settings::FORSENDELSES_TYPE_IDENTIFIKATOR] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::SENDER, Settings::FORSENDELSES_TYPE_IDENTIFIKATOR, + ]), '#required' => TRUE, + '#description' => $this->createDescription([Settings::SENDER, Settings::FORSENDELSES_TYPE_IDENTIFIKATOR]), ], ]; - $certificate = $this->settings->getCertificate(); - $form['certificate'] = [ + $form[Settings::CERTIFICATE] = [ '#type' => 'fieldset', '#title' => $this->t('Certificate'), '#tree' => TRUE, + ]; - 'locator_type' => [ - '#type' => 'select', - '#title' => $this->t('Certificate locator type'), - '#options' => [ - 'azure_key_vault' => $this->t('Azure key vault'), - 'file_system' => $this->t('File system'), - ], - '#default_value' => $certificate['locator_type'] ?? NULL, + $form[Settings::CERTIFICATE][Settings::CERTIFICATE_PROVIDER] = [ + '#type' => 'select', + '#title' => $this->t('Provider'), + '#options' => [ + Settings::PROVIDER_TYPE_FORM => $this->t('Form'), + Settings::PROVIDER_TYPE_KEY => $this->t('Key'), ], + '#default_value' => $this->settings->getEditableValue([Settings::CERTIFICATE, Settings::CERTIFICATE_PROVIDER]) ?? Settings::PROVIDER_TYPE_FORM, + '#description' => $this->t('Specifies which provider to use'), ]; - $form['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE] = [ + '#type' => 'select', + '#title' => $this->t('Certificate locator type'), + '#options' => [ + CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT => $this->t('Azure key vault'), + CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM => $this->t('File system'), + ], + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_TYPE, + ]) ?? NULL, + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM]], + ], + '#description' => $this->t('Specifies which locator to use'), + ]; + + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT] = [ '#type' => 'fieldset', '#title' => $this->t('Azure key vault'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; $settings = [ - 'tenant_id' => ['title' => $this->t('Tenant id')], - 'application_id' => ['title' => $this->t('Application id')], - 'client_secret' => ['title' => $this->t('Client secret')], - 'name' => ['title' => $this->t('Name')], - 'secret' => ['title' => $this->t('Secret')], - 'version' => ['title' => $this->t('Version')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_TENANT_ID => ['title' => $this->t('Tenant id')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_APPLICATION_ID => ['title' => $this->t('Application id')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_CLIENT_SECRET => ['title' => $this->t('Client secret')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_NAME => ['title' => $this->t('Name')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_SECRET => ['title' => $this->t('Secret')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_VERSION => ['title' => $this->t('Version')], ]; foreach ($settings as $key => $info) { - $form['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] = [ '#type' => 'textfield', '#title' => $info['title'], - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT, + $key, + ]) ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; } - $form['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM] = [ '#type' => 'fieldset', '#title' => $this->t('File system'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], - 'path' => [ + CertificateLocatorHelper::LOCATOR_FILE_SYSTEM_PATH => [ '#type' => 'textfield', '#title' => $this->t('Path'), - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM, + CertificateLocatorHelper::LOCATOR_FILE_SYSTEM_PATH, + ]) ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], ], ]; - $form['certificate']['passphrase'] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_PASSPHRASE] = [ '#type' => 'textfield', '#title' => $this->t('Passphrase'), - '#default_value' => $certificate['passphrase'] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_PASSPHRASE, + ]) ?? '', + '#states' => [ + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ], + ], ]; - $processing = $this->settings->getProcessing(); - $form['processing'] = [ + $form[Settings::CERTIFICATE][Settings::PROVIDER_TYPE_KEY] = [ + '#type' => 'key_select', + '#key_filters' => [ + 'type' => 'os2web_key_certificate', + ], + '#key_description' => FALSE, + '#title' => $this->t('Key'), + '#default_value' => $this->settings->getEditableValue([Settings::CERTIFICATE, Settings::PROVIDER_TYPE_KEY]), + '#description' => $this->createDescription([Settings::CERTIFICATE, Settings::PROVIDER_TYPE_KEY]), + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_KEY]], + 'required' => [':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_KEY]], + ], + ]; + + $form[Settings::PROCESSING] = [ '#type' => 'fieldset', '#title' => $this->t('Processing'), '#tree' => TRUE, ]; - $defaultValue = $processing['queue'] ?? 'os2forms_digital_post'; - $form['processing']['queue'] = [ + $queue = $this->settings->getEditableValue([Settings::PROCESSING, Settings::QUEUE]); + $form[Settings::PROCESSING][Settings::QUEUE] = [ '#type' => 'select', '#title' => $this->t('Queue'), '#options' => array_map( static fn(EntityInterface $queue) => $queue->label(), $this->queueStorage->loadMultiple() ), - '#default_value' => $defaultValue, - '#description' => $this->t("Queue for digital post jobs. The queue must be run via Drupal's cron or via drush advancedqueue:queue:process @queue(in a cron job).", [ - '@queue' => $defaultValue, - ':queue_url' => '/admin/config/system/queues/jobs/' . urlencode($defaultValue), - ]), - ]; - - $form['actions']['#type'] = 'actions'; - - $form['actions']['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Save settings'), - ]; - - $form['actions']['testCertificate'] = [ - '#type' => 'submit', - '#name' => 'testCertificate', - '#value' => $this->t('Test certificate'), + '#required' => TRUE, + '#default_value' => $queue, + '#description' => $this->createDescription([Settings::PROCESSING, Settings::QUEUE], + $queue + ? $this->t("Queue for digital post jobs. The queue must be run via Drupal's cron or via drush advancedqueue:queue:process @queue (in a cron job).", [ + '@queue' => $queue, + ':queue_url' => Url::fromRoute('view.advancedqueue_jobs.page_1', [ + 'arg_0' => $queue, + ])->toString(TRUE)->getGeneratedUrl(), + ]) + : $this->t("Queue for digital post jobs. The queue must be processed via Drupal's cron or drush advancedqueue:queue:process (in a cron job)."), + ), ]; return $form; @@ -212,19 +295,19 @@ public function buildForm(array $form, FormStateInterface $form_state) { * * @phpstan-param array $form */ - public function validateForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { - return; - } - - $values = $formState->getValues(); - if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values['certificate']['locator_type']) { - $path = $values['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL; - if (!file_exists($path)) { - $formState->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + public function validateForm(array &$form, FormStateInterface $form_state): void { + $values = $form_state->getValues(); + + if (Settings::PROVIDER_TYPE_FORM === $values[Settings::CERTIFICATE][Settings::CERTIFICATE_PROVIDER]) { + if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE]) { + $path = $values[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM][CertificateLocatorHelper::LOCATOR_FILE_SYSTEM_PATH] ?? NULL; + if (!file_exists($path)) { + $form_state->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + } } } + + parent::validateForm($form, $form_state); } /** @@ -232,39 +315,43 @@ public function validateForm(array &$form, FormStateInterface $formState): void * * @phpstan-param array $form */ - public function submitForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { - $this->testCertificate(); - return; + public function submitForm(array &$form, FormStateInterface $form_state): void { + $config = $this->config(Settings::CONFIG_NAME); + foreach ([ + Settings::TEST_MODE, + Settings::SENDER, + Settings::CERTIFICATE, + Settings::PROCESSING, + ] as $key) { + $config->set($key, $form_state->getValue($key)); } + $config->save(); - try { - $settings['test_mode'] = (bool) $formState->getValue('test_mode'); - $settings['sender'] = $formState->getValue('sender'); - $settings['certificate'] = $formState->getValue('certificate'); - $settings['processing'] = $formState->getValue('processing'); - $this->settings->setSettings($settings); - $this->messenger()->addStatus($this->t('Settings saved')); - } - catch (OptionsResolverException $exception) { - $this->messenger()->addError($this->t('Settings not saved (@message)', ['@message' => $exception->getMessage()])); - } + parent::submitForm($form, $form_state); } /** - * Test certificate. + * Create form field description with information on any runtime override. + * + * @param string|array $key + * The key. + * @param \Drupal\Core\StringTranslation\TranslatableMarkup|null $description + * The actual field description. + * + * @return string + * The full description. + * + * @phpstan-param string|string[] $key */ - private function testCertificate(): void { - try { - $certificateLocator = $this->certificateLocatorHelper->getCertificateLocator(); - $certificateLocator->getCertificates(); - $this->messenger()->addStatus($this->t('Certificate succesfully tested')); - } - catch (\Throwable $throwable) { - $message = $this->t('Error testing certificate: %message', ['%message' => $throwable->getMessage()]); - $this->messenger()->addError($message); + private function createDescription(string|array $key, ?TranslatableMarkup $description = NULL): string { + if ($value = $this->settings->getOverride($key)) { + if (!empty($description)) { + $description .= '
'; + } + $description .= $this->t('Note: overridden on runtime with the value @value.', ['@value' => var_export($value['runtime'], TRUE)]); } + + return (string) $description; } } diff --git a/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php b/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php index d9fb96a3..c2f2b990 100644 --- a/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php +++ b/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php @@ -12,6 +12,7 @@ use Drupal\webform_attachment\Element\WebformAttachmentBase; use ItkDev\Serviceplatformen\Service\SF1601\Serializer; use Oio\Fjernprint\ForsendelseI; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Abstract message helper. @@ -23,7 +24,9 @@ abstract class AbstractMessageHelper { */ public function __construct( readonly protected Settings $settings, + #[Autowire(service: 'plugin.manager.element_info')] readonly protected ElementInfoManager $elementInfoManager, + #[Autowire(service: 'webform.token_manager')] readonly protected WebformTokenManagerInterface $webformTokenManager, ) { } diff --git a/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php b/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php index 5b93da5e..c256dc17 100644 --- a/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php +++ b/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php @@ -9,6 +9,7 @@ use Drupal\webform\WebformSubmissionInterface; use Psr\Log\LoggerAwareTrait; use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Beskedfordeler helper. @@ -24,6 +25,7 @@ class BeskedfordelerHelper { public function __construct( private readonly Connection $database, private readonly MeMoHelper $meMoHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] LoggerInterface $logger, ) { $this->setLogger($logger); diff --git a/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php b/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php index 10e6ac57..01fde400 100644 --- a/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php +++ b/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php @@ -16,8 +16,17 @@ * Certificate locator helper. */ class CertificateLocatorHelper { + public const LOCATOR_TYPE = 'locator_type'; public const LOCATOR_TYPE_AZURE_KEY_VAULT = 'azure_key_vault'; public const LOCATOR_TYPE_FILE_SYSTEM = 'file_system'; + public const LOCATOR_PASSPHRASE = 'passphrase'; + public const LOCATOR_AZURE_KEY_VAULT_TENANT_ID = 'tenant_id'; + public const LOCATOR_AZURE_KEY_VAULT_APPLICATION_ID = 'application_id'; + public const LOCATOR_AZURE_KEY_VAULT_CLIENT_SECRET = 'client_secret'; + public const LOCATOR_AZURE_KEY_VAULT_NAME = 'name'; + public const LOCATOR_AZURE_KEY_VAULT_SECRET = 'secret'; + public const LOCATOR_AZURE_KEY_VAULT_VERSION = 'version'; + public const LOCATOR_FILE_SYSTEM_PATH = 'path'; /** * {@inheritdoc} @@ -31,12 +40,12 @@ public function __construct( * Get certificate locator. */ public function getCertificateLocator(): CertificateLocatorInterface { - $certificateSettings = $this->settings->getCertificate(); + $certificateSettings = $this->settings->getEditableValue(Settings::CERTIFICATE); $locatorType = $certificateSettings['locator_type']; $options = $certificateSettings[$locatorType]; $options += [ - 'passphrase' => $certificateSettings['passphrase'] ?: '', + 'passphrase' => $certificateSettings['passphrase'], ]; if (self::LOCATOR_TYPE_AZURE_KEY_VAULT === $locatorType) { diff --git a/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php b/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php index 8681cf35..44198074 100644 --- a/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php +++ b/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php @@ -11,12 +11,14 @@ use Drupal\os2web_datalookup\Plugin\DataLookupManager; use Drupal\os2web_datalookup\Plugin\os2web\DataLookup\DataLookupCompanyInterface; use Drupal\os2web_datalookup\Plugin\os2web\DataLookup\DataLookupCprInterface; +use Drupal\os2web_key\KeyHelper; use Drupal\webform\WebformSubmissionInterface; use ItkDev\Serviceplatformen\Service\SF1601\SF1601; use ItkDev\Serviceplatformen\Service\SF1601\Serializer; use Oio\Fjernprint\ForsendelseI; use Psr\Log\LoggerInterface; use Psr\Log\LoggerTrait; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Webform helper. @@ -29,13 +31,18 @@ final class DigitalPostHelper implements LoggerInterface { */ public function __construct( private readonly Settings $settings, - private readonly CertificateLocatorHelper $certificateLocatorHelper, + private readonly KeyHelper $keyHelper, + #[Autowire(service: 'plugin.manager.os2web_datalookup')] private readonly DataLookupManager $dataLookupManager, private readonly MeMoHelper $meMoHelper, private readonly ForsendelseHelper $forsendelseHelper, private readonly BeskedfordelerHelper $beskedfordelerHelper, + private readonly CertificateLocatorHelper $certificateLocatorHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] private readonly LoggerChannelInterface $logger, + #[Autowire(service: 'logger.channel.os2forms_digital_post_submission')] private readonly LoggerChannelInterface $submissionLogger, + #[Autowire(service: 'os2web_audit.logger')] private readonly Logger $auditLogger, ) { } @@ -59,11 +66,23 @@ public function __construct( */ public function sendDigitalPost(string $type, Message $message, ?ForsendelseI $forsendelse, ?WebformSubmissionInterface $submission = NULL): array { $senderSettings = $this->settings->getSender(); + + if (Settings::PROVIDER_TYPE_FORM === $this->settings->getCertificateProvider()) { + $certificateLocator = $this->certificateLocatorHelper->getCertificateLocator(); + } + else { + $certificateLocator = new KeyCertificateLocator( + $this->settings->getCertificateKey(), + $this->keyHelper + ); + } + $options = [ 'test_mode' => (bool) $this->settings->getTestMode(), 'authority_cvr' => $senderSettings[Settings::SENDER_IDENTIFIER], - 'certificate_locator' => $this->certificateLocatorHelper->getCertificateLocator(), + 'certificate_locator' => $certificateLocator, ]; + $service = new SF1601($options); $transactionId = Serializer::createUuid(); diff --git a/modules/os2forms_digital_post/src/Helper/KeyCertificateLocator.php b/modules/os2forms_digital_post/src/Helper/KeyCertificateLocator.php new file mode 100644 index 00000000..8d8f0a41 --- /dev/null +++ b/modules/os2forms_digital_post/src/Helper/KeyCertificateLocator.php @@ -0,0 +1,59 @@ + + */ + private array $certificates; + + /** + * Constructor. + */ + public function __construct( + private readonly KeyInterface $key, + private readonly KeyHelper $keyHelper, + ) { + parent::__construct(); + } + + /** + * {@inheritdoc} + * + * @phpstan-return array + */ + public function getCertificates(): array { + if (!isset($this->certificates)) { + $this->certificates = $this->keyHelper->getCertificates($this->key); + } + + return $this->certificates; + } + + /** + * {@inheritdoc} + */ + public function getCertificate(): string { + return $this->key->getKeyValue(); + } + + /** + * {@inheritdoc} + */ + public function getAbsolutePathToCertificate(): string { + throw new CertificateLocatorException(__METHOD__ . ' should not be used.'); + } + +} diff --git a/modules/os2forms_digital_post/src/Helper/Settings.php b/modules/os2forms_digital_post/src/Helper/Settings.php index e64be738..fc7ab385 100644 --- a/modules/os2forms_digital_post/src/Helper/Settings.php +++ b/modules/os2forms_digital_post/src/Helper/Settings.php @@ -2,45 +2,66 @@ namespace Drupal\os2forms_digital_post\Helper; -use Drupal\Core\KeyValueStore\KeyValueFactoryInterface; -use Drupal\Core\KeyValueStore\KeyValueStoreInterface; -use Drupal\os2forms_digital_post\Exception\InvalidSettingException; -use Symfony\Component\OptionsResolver\OptionsResolver; +use Drupal\Core\Config\Config; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Config\ImmutableConfig; +use Drupal\key\KeyInterface; +use Drupal\key\KeyRepositoryInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * General settings for os2forms_digital_post. */ final class Settings { + public const CONFIG_NAME = 'os2forms_digital_post.settings'; + + public const TEST_MODE = 'test_mode'; + + public const SENDER = 'sender'; public const SENDER_IDENTIFIER_TYPE = 'sender_identifier_type'; public const SENDER_IDENTIFIER = 'sender_identifier'; public const FORSENDELSES_TYPE_IDENTIFIKATOR = 'forsendelses_type_identifikator'; + public const CERTIFICATE = 'certificate'; + public const KEY = 'key'; + public const CERTIFICATE_PROVIDER = 'certificate_provider'; + public const PROVIDER_TYPE_FORM = 'form'; + public const PROVIDER_TYPE_KEY = 'key'; + + public const PROCESSING = 'processing'; + public const QUEUE = 'queue'; + /** - * The store. + * The runtime (immutable) config. * - * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface + * @var \Drupal\Core\Config\ImmutableConfig */ - private KeyValueStoreInterface $store; + private ImmutableConfig $runtimeConfig; /** - * The key prefix. + * The (mutable) config. * - * @var string + * @var \Drupal\Core\Config\Config */ - private $collection = 'os2forms_digital_post.'; + private Config $editableConfig; /** - * Constructor. + * The constructor. */ - public function __construct(KeyValueFactoryInterface $keyValueFactory) { - $this->store = $keyValueFactory->get($this->collection); + public function __construct( + ConfigFactoryInterface $configFactory, + #[Autowire(service: 'key.repository')] + private readonly KeyRepositoryInterface $keyRepository, + ) { + $this->runtimeConfig = $configFactory->get(self::CONFIG_NAME); + $this->editableConfig = $configFactory->getEditable(self::CONFIG_NAME); } /** * Get test mode. */ public function getTestMode(): bool { - return (bool) $this->get('test_mode', TRUE); + return (bool) $this->get(self::TEST_MODE, TRUE); } /** @@ -49,18 +70,32 @@ public function getTestMode(): bool { * @phpstan-return array */ public function getSender(): array { - $value = $this->get('sender'); + $value = $this->get(self::SENDER); + return is_array($value) ? $value : []; } + /** + * Get certificate provider. + */ + public function getCertificateProvider(): ?string { + return $this->get([self::CERTIFICATE, self::CERTIFICATE_PROVIDER]); + } + + /** + * Get key. + */ + public function getKey(): ?string { + return $this->get([self::CERTIFICATE, self::KEY]); + } + /** * Get certificate. - * - * @phpstan-return array */ - public function getCertificate(): array { - $value = $this->get('certificate'); - return is_array($value) ? $value : []; + public function getCertificateKey(): ?KeyInterface { + return $this->keyRepository->getKey( + $this->getKey(), + ); } /** @@ -69,57 +104,82 @@ public function getCertificate(): array { * @phpstan-return array */ public function getProcessing(): array { - $value = $this->get('processing'); + $value = $this->get(self::PROCESSING); + return is_array($value) ? $value : []; } /** - * Get a setting value. + * Get editable value. * - * @param string $key + * @param string|array $key * The key. - * @param mixed|null $default - * The default value. * * @return mixed - * The setting value. + * The editable value. */ - private function get(string $key, $default = NULL) { - $resolver = $this->getSettingsResolver(); - if (!$resolver->isDefined($key)) { - throw new InvalidSettingException(sprintf('Setting %s is not defined', $key)); + public function getEditableValue(string|array $key): mixed { + if (is_array($key)) { + $key = implode('.', $key); } - - return $this->store->get($key, $default); + return $this->editableConfig->get($key); } /** - * Set settings. + * Get runtime value override if any. * - * @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface + * @param string|array $key + * The key. * - * @phpstan-param array $settings + * @return array|null + * - 'runtime': the runtime value + * - 'editable': the editable (raw) value */ - public function setSettings(array $settings): self { - $settings = $this->getSettingsResolver()->resolve($settings); - foreach ($settings as $key => $value) { - $this->store->set($key, $value); + public function getOverride(string|array $key): ?array { + $runtimeValue = $this->getRuntimeValue($key); + $editableValue = $this->getEditableValue($key); + + // Note: We deliberately use "Equal" (==) rather than "Identical" (===) + // to compare values (cf. https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison). + if ($runtimeValue == $editableValue) { + return NULL; } - return $this; + return [ + 'runtime' => $runtimeValue, + 'editable' => $editableValue, + ]; } /** - * Get settings resolver. + * Get a setting value. + * + * @param string|array $key + * The key. + * @param mixed $default + * The default value. + * + * @return mixed + * The setting value. */ - private function getSettingsResolver(): OptionsResolver { - return (new OptionsResolver()) - ->setDefaults([ - 'test_mode' => TRUE, - 'sender' => [], - 'certificate' => [], - 'processing' => [], - ]); + private function get(string|array $key, mixed $default = NULL) { + return $this->getRuntimeValue($key) ?? $default; + } + + /** + * Get runtime value with any overrides applied. + * + * @param string|array $key + * The key. + * + * @return mixed + * The runtime value. + */ + public function getRuntimeValue(string|array $key): mixed { + if (is_array($key)) { + $key = implode('.', $key); + } + return $this->runtimeConfig->get($key); } } diff --git a/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php b/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php index 3c2c724e..60fae6a2 100644 --- a/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php +++ b/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php @@ -21,6 +21,7 @@ use ItkDev\Serviceplatformen\Service\SF1601\SF1601; use Psr\Log\LoggerInterface; use Psr\Log\LoggerTrait; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Webform helper. @@ -51,11 +52,14 @@ final class WebformHelperSF1601 implements LoggerInterface { public function __construct( private readonly Settings $settings, EntityTypeManagerInterface $entityTypeManager, + #[Autowire(service: 'plugin.manager.os2web_datalookup')] private readonly DataLookupManager $dataLookupManager, private readonly MeMoHelper $meMoHelper, private readonly ForsendelseHelper $forsendelseHelper, private readonly BeskedfordelerHelper $beskedfordelerHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] private readonly LoggerChannelInterface $logger, + #[Autowire(service: 'logger.channel.os2forms_digital_post_submission')] private readonly LoggerChannelInterface $submissionLogger, private readonly DigitalPostHelper $digitalPostHelper, ) { diff --git a/modules/os2forms_fasit/os2forms_fasit.info.yml b/modules/os2forms_fasit/os2forms_fasit.info.yml index 43309b4d..fe55c94a 100644 --- a/modules/os2forms_fasit/os2forms_fasit.info.yml +++ b/modules/os2forms_fasit/os2forms_fasit.info.yml @@ -6,6 +6,7 @@ core_version_requirement: ^9 || ^10 dependencies: - drupal:webform - drupal:advancedqueue + - key:key - os2forms:os2forms_attachment - os2web:os2web_audit configure: os2forms_fasit.admin.settings diff --git a/modules/os2forms_fasit/os2forms_fasit.install b/modules/os2forms_fasit/os2forms_fasit.install new file mode 100644 index 00000000..f862bafb --- /dev/null +++ b/modules/os2forms_fasit/os2forms_fasit.install @@ -0,0 +1,15 @@ +install([ + 'key', + ], TRUE); +} diff --git a/modules/os2forms_fasit/os2forms_fasit.services.yml b/modules/os2forms_fasit/os2forms_fasit.services.yml index 4397c83f..e70008fb 100644 --- a/modules/os2forms_fasit/os2forms_fasit.services.yml +++ b/modules/os2forms_fasit/os2forms_fasit.services.yml @@ -1,16 +1,13 @@ services: Drupal\os2forms_fasit\Helper\Settings: + autowire: true arguments: - - "@keyvalue" + $keyRepository: "@key.repository" Drupal\os2forms_fasit\Helper\CertificateLocatorHelper: - arguments: - - "@Drupal\\os2forms_fasit\\Helper\\Settings" + autowire: true Drupal\os2forms_fasit\Helper\FasitHelper: + autowire: true arguments: - - '@http_client' - - '@entity_type.manager' - - "@Drupal\\os2forms_fasit\\Helper\\Settings" - - "@Drupal\\os2forms_fasit\\Helper\\CertificateLocatorHelper" - - "@os2web_audit.logger" + $auditLogger: "@os2web_audit.logger" diff --git a/modules/os2forms_fasit/src/Drush/Commands/FasitTestCommand.php b/modules/os2forms_fasit/src/Drush/Commands/FasitTestCommand.php new file mode 100644 index 00000000..9d1fb281 --- /dev/null +++ b/modules/os2forms_fasit/src/Drush/Commands/FasitTestCommand.php @@ -0,0 +1,41 @@ +helper->pingApi(); + $this->io()->success('Successfully connected to Fasit API'); + } + catch (\Throwable $t) { + $this->io()->error($t->getMessage()); + } + + } + +} diff --git a/modules/os2forms_fasit/src/Form/SettingsForm.php b/modules/os2forms_fasit/src/Form/SettingsForm.php index d0fe119e..2cfed651 100644 --- a/modules/os2forms_fasit/src/Form/SettingsForm.php +++ b/modules/os2forms_fasit/src/Form/SettingsForm.php @@ -2,41 +2,65 @@ namespace Drupal\os2forms_fasit\Form; -use Drupal\Core\Form\FormBase; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\os2forms_fasit\Helper\CertificateLocatorHelper; -use Drupal\os2forms_fasit\Helper\Settings; +use Drupal\os2forms_fasit\Helper\FasitHelper; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\OptionsResolver\Exception\ExceptionInterface as OptionsResolverException; /** - * Organisation settings form. + * Fasit settings form. */ -final class SettingsForm extends FormBase { +final class SettingsForm extends ConfigFormBase { use StringTranslationTrait; + public const CONFIG_NAME = 'os2forms_fasit.settings'; public const FASIT_API_BASE_URL = 'fasit_api_base_url'; public const FASIT_API_TENANT = 'fasit_api_tenant'; public const FASIT_API_VERSION = 'fasit_api_version'; public const CERTIFICATE = 'certificate'; + public const KEY = 'key'; + public const CERTIFICATE_PROVIDER = 'certificate_provider'; + public const PROVIDER_TYPE_FORM = 'form'; + public const PROVIDER_TYPE_KEY = 'key'; + + public const ACTION_PING_API = 'action_ping_api'; /** - * Constructor. + * {@inheritdoc} */ - public function __construct(private readonly Settings $settings, private readonly CertificateLocatorHelper $certificateLocatorHelper) { + public function __construct( + ConfigFactoryInterface $config_factory, + private readonly FasitHelper $helper, + ) { + parent::__construct($config_factory); } /** * {@inheritdoc} + * + * @phpstan-return self */ - public static function create(ContainerInterface $container): SettingsForm { + public static function create(ContainerInterface $container): self { return new static( - $container->get(Settings::class), - $container->get(CertificateLocatorHelper::class) + $container->get('config.factory'), + $container->get(FasitHelper::class) ); } + /** + * {@inheritdoc} + * + * @phpstan-return array + */ + protected function getEditableConfigNames() { + return [ + self::CONFIG_NAME, + ]; + } + /** * {@inheritdoc} */ @@ -51,57 +75,74 @@ public function getFormId() { * @phpstan-return array */ public function buildForm(array $form, FormStateInterface $form_state): array { + $form = parent::buildForm($form, $form_state); + $config = $this->config(self::CONFIG_NAME); - $fasitApiBaseUrl = $this->settings->getFasitApiBaseUrl(); $form[self::FASIT_API_BASE_URL] = [ '#type' => 'textfield', '#title' => $this->t('Fasit API base url'), '#required' => TRUE, - '#default_value' => !empty($fasitApiBaseUrl) ? $fasitApiBaseUrl : NULL, + '#default_value' => $config->get(self::FASIT_API_BASE_URL), '#description' => $this->t('Specifies which base url to use. This is disclosed by Schultz'), ]; - $fasitApiTenant = $this->settings->getFasitApiTenant(); $form[self::FASIT_API_TENANT] = [ '#type' => 'textfield', '#title' => $this->t('Fasit API tenant'), '#required' => TRUE, - '#default_value' => !empty($fasitApiTenant) ? $fasitApiTenant : NULL, + '#default_value' => $config->get(self::FASIT_API_TENANT), '#description' => $this->t('Specifies which tenant to use. This is disclosed by Schultz'), ]; - $fasitApiVersion = $this->settings->getFasitApiVersion(); $form[self::FASIT_API_VERSION] = [ '#type' => 'textfield', '#title' => $this->t('Fasit API version'), '#required' => TRUE, - '#default_value' => !empty($fasitApiVersion) ? $fasitApiVersion : NULL, + '#default_value' => $config->get(self::FASIT_API_VERSION), '#description' => $this->t('Specifies which api version to use. Should probably be v2'), ]; - $certificate = $this->settings->getCertificate(); + $certificateConfig = $config->get(self::CERTIFICATE) ?? []; $form[self::CERTIFICATE] = [ '#type' => 'fieldset', '#title' => $this->t('Certificate'), '#tree' => TRUE, - CertificateLocatorHelper::LOCATOR_TYPE => [ + self::CERTIFICATE_PROVIDER => [ '#type' => 'select', - '#title' => $this->t('Certificate locator type'), + '#title' => $this->t('Provider'), '#options' => [ - CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT => $this->t('Azure key vault'), - CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM => $this->t('File system'), + self::PROVIDER_TYPE_FORM => $this->t('Form'), + self::PROVIDER_TYPE_KEY => $this->t('Key'), ], - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE] ?? NULL, + '#default_value' => $certificateConfig[self::CERTIFICATE_PROVIDER] ?? self::PROVIDER_TYPE_FORM, + '#description' => $this->t('Specifies which provider to use'), ], ]; + $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE] = [ + '#type' => 'select', + '#title' => $this->t('Certificate locator type'), + '#options' => [ + CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT => $this->t('Azure key vault'), + CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM => $this->t('File system'), + ], + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_TYPE] ?? NULL, + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM]], + ], + '#description' => $this->t('Specifies which locator to use'), + ]; + $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT] = [ '#type' => 'fieldset', '#title' => $this->t('Azure key vault'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; @@ -118,9 +159,12 @@ public function buildForm(array $form, FormStateInterface $form_state): array { $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] = [ '#type' => 'textfield', '#title' => $info['title'], - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] ?? NULL, + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; } @@ -129,15 +173,21 @@ public function buildForm(array $form, FormStateInterface $form_state): array { '#type' => 'fieldset', '#title' => $this->t('File system'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], 'path' => [ '#type' => 'textfield', '#title' => $this->t('Path'), - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL, + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], ], ]; @@ -145,20 +195,36 @@ public function buildForm(array $form, FormStateInterface $form_state): array { $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_PASSPHRASE] = [ '#type' => 'textfield', '#title' => $this->t('Passphrase'), - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_PASSPHRASE] ?? NULL, + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_PASSPHRASE] ?? NULL, + '#states' => [ + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ], + ], ]; - $form['actions']['#type'] = 'actions'; - - $form['actions']['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Save settings'), + $form[self::CERTIFICATE][self::PROVIDER_TYPE_KEY] = [ + '#type' => 'key_select', + '#title' => $this->t('Key'), + '#default_value' => $certificateConfig[self::PROVIDER_TYPE_KEY] ?? NULL, + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_KEY]], + 'required' => [':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_KEY]], + ], ]; - $form['actions']['testCertificate'] = [ - '#type' => 'submit', - '#name' => 'testCertificate', - '#value' => $this->t('Test certificate'), + $form['actions']['ping_api'] = [ + '#type' => 'container', + + self::ACTION_PING_API => [ + '#type' => 'submit', + '#name' => self::ACTION_PING_API, + '#value' => $this->t('Ping API'), + ], + + 'message' => [ + '#markup' => $this->t('Note: Pinging the API will use saved config.'), + ], ]; return $form; @@ -169,20 +235,23 @@ public function buildForm(array $form, FormStateInterface $form_state): array { * * @phpstan-param array $form */ - public function validateForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { + public function validateForm(array &$form, FormStateInterface $form_state): void { + if (self::ACTION_PING_API === ($form_state->getTriggeringElement()['#name'] ?? NULL)) { return; } - $values = $formState->getValues(); + $values = $form_state->getValues(); - if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE]) { - $path = $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL; - if (!file_exists($path)) { - $formState->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + if (self::PROVIDER_TYPE_FORM === $values[self::CERTIFICATE][self::CERTIFICATE_PROVIDER]) { + if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE]) { + $path = $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL; + if (!file_exists($path)) { + $form_state->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + } } } + + parent::validateForm($form, $form_state); } /** @@ -190,44 +259,30 @@ public function validateForm(array &$form, FormStateInterface $formState): void * * @phpstan-param array $form */ - public function submitForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { - $this->testCertificate(); + public function submitForm(array &$form, FormStateInterface $form_state): void { + if (self::ACTION_PING_API === ($form_state->getTriggeringElement()['#name'] ?? NULL)) { + try { + $this->helper->pingApi(); + $this->messenger()->addStatus($this->t('Pinged API successfully.')); + } + catch (\Throwable $t) { + $this->messenger()->addError($this->t('Pinging API failed: @message', ['@message' => $t->getMessage()])); + } return; } - try { - $settings[self::CERTIFICATE] = $formState->getValue(self::CERTIFICATE); - $settings[self::FASIT_API_BASE_URL] = $formState->getValue(self::FASIT_API_BASE_URL); - $settings[self::FASIT_API_TENANT] = $formState->getValue(self::FASIT_API_TENANT); - $settings[self::FASIT_API_VERSION] = $formState->getValue(self::FASIT_API_VERSION); - - $this->settings->setSettings($settings); - $this->messenger()->addStatus($this->t('Settings saved')); + $config = $this->config(self::CONFIG_NAME); + foreach ([ + self::FASIT_API_BASE_URL, + self::FASIT_API_TENANT, + self::FASIT_API_VERSION, + self::CERTIFICATE, + ] as $key) { + $config->set($key, $form_state->getValue($key)); } - catch (OptionsResolverException $exception) { - $this->messenger()->addError($this->t('Settings not saved (@message)', ['@message' => $exception->getMessage()])); - - return; - } - - $this->messenger()->addStatus($this->t('Settings saved')); - } + $config->save(); - /** - * Test certificate. - */ - private function testCertificate(): void { - try { - $certificateLocator = $this->certificateLocatorHelper->getCertificateLocator(); - $certificateLocator->getCertificates(); - $this->messenger()->addStatus($this->t('Certificate successfully tested')); - } - catch (\Throwable $throwable) { - $message = $this->t('Error testing certificate: %message', ['%message' => $throwable->getMessage()]); - $this->messenger()->addError($message); - } + parent::submitForm($form, $form_state); } } diff --git a/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php b/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php index 3f244d1a..4d56a580 100644 --- a/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php +++ b/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php @@ -38,12 +38,12 @@ public function __construct(private readonly Settings $settings) { * Get certificate locator. */ public function getCertificateLocator(): CertificateLocatorInterface { - $certificateSettings = $this->settings->getCertificate(); + $config = $this->settings->getFasitCertificateConfig(); - $locatorType = $certificateSettings[self::LOCATOR_TYPE]; - $options = $certificateSettings[$locatorType]; + $locatorType = $config[self::LOCATOR_TYPE]; + $options = $config[$locatorType]; $options += [ - self::LOCATOR_PASSPHRASE => $certificateSettings[self::LOCATOR_PASSPHRASE] ?: '', + self::LOCATOR_PASSPHRASE => $config[self::LOCATOR_PASSPHRASE] ?: '', ]; if (self::LOCATOR_TYPE_AZURE_KEY_VAULT === $locatorType) { diff --git a/modules/os2forms_fasit/src/Helper/FasitHelper.php b/modules/os2forms_fasit/src/Helper/FasitHelper.php index 2bd84d65..12a5c51f 100644 --- a/modules/os2forms_fasit/src/Helper/FasitHelper.php +++ b/modules/os2forms_fasit/src/Helper/FasitHelper.php @@ -4,18 +4,21 @@ use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\Core\File\FileSystemInterface; use Drupal\os2forms_attachment\Element\AttachmentElement; use Drupal\os2forms_fasit\Exception\FasitResponseException; use Drupal\os2forms_fasit\Exception\FasitXMLGenerationException; use Drupal\os2forms_fasit\Exception\FileTypeException; use Drupal\os2forms_fasit\Exception\InvalidSettingException; use Drupal\os2forms_fasit\Exception\InvalidSubmissionException; +use Drupal\os2forms_fasit\Form\SettingsForm; use Drupal\os2forms_fasit\Plugin\WebformHandler\FasitWebformHandler; use Drupal\os2web_audit\Service\Logger; use Drupal\webform\Entity\WebformSubmission; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Utils; +use Psr\Http\Message\ResponseInterface; use Symfony\Component\HttpFoundation\Response; /** @@ -38,6 +41,7 @@ public function __construct( private readonly ClientInterface $client, private readonly EntityTypeManagerInterface $entityTypeManager, private readonly Settings $settings, + private readonly FileSystemInterface $fileSystem, private readonly CertificateLocatorHelper $certificateLocator, private readonly Logger $auditLogger, ) { @@ -206,8 +210,6 @@ private function uploadDocument(array $uploads, string $submissionId, array $han } } - [$certificateOptions, $tempCertFilename] = $this->getCertificateOptionsAndTempCertFilename(); - $body = $doc->saveXML(); if (!$body) { @@ -219,20 +221,14 @@ private function uploadDocument(array $uploads, string $submissionId, array $han 'Content-Type' => 'application/xml', ], 'body' => $body, - 'cert' => $certificateOptions, ]; // Attempt upload. try { - $response = $this->client->request('POST', $endpoint, $options); + $response = $this->post($endpoint, $options); } catch (GuzzleException $e) { throw new FasitResponseException($e->getMessage(), $e->getCode()); - } finally { - // Remove the certificate from disk. - if (file_exists($tempCertFilename)) { - unlink($tempCertFilename); - } } if (Response::HTTP_OK !== $response->getStatusCode()) { @@ -262,26 +258,6 @@ private function checkHandlerConfiguration(array $handlerConfiguration, string $ } } - /** - * Gets certificate options and temp certificate filename. - * - * @throws \Drupal\os2forms_fasit\Exception\CertificateLocatorException - * Certificate locator exception. - * - * @phpstan-return array - */ - private function getCertificateOptionsAndTempCertFilename(): array { - $certificateLocator = $this->certificateLocator->getCertificateLocator(); - $localCertFilename = tempnam(sys_get_temp_dir(), 'cert'); - file_put_contents($localCertFilename, $certificateLocator->getCertificate()); - $certificateOptions = - $certificateLocator->hasPassphrase() ? - [$localCertFilename, $certificateLocator->getPassphrase()] - : $localCertFilename; - - return [$certificateOptions, $localCertFilename]; - } - /** * Uploads attachment to Fasit. * @@ -345,8 +321,6 @@ private function uploadFile(string $originalFilename, string $tempFilename, stri self::FASIT_API_METHOD_UPLOAD ); - [$certificateOptions, $tempCertFilename] = $this->getCertificateOptionsAndTempCertFilename(); - // Attempt upload. try { $options = [ @@ -356,18 +330,13 @@ private function uploadFile(string $originalFilename, string $tempFilename, stri 'X-Title' => pathinfo($originalFilename, PATHINFO_FILENAME), ], 'body' => Utils::tryFopen($tempFilename, 'r'), - 'cert' => $certificateOptions, ]; - $response = $this->client->request('POST', $endpoint, $options); + $response = $this->post($endpoint, $options); } catch (GuzzleException $e) { throw new FasitResponseException($e->getMessage(), $e->getCode()); } finally { - // Remove the certificate from disk. - if (file_exists($tempCertFilename)) { - unlink($tempCertFilename); - } // Remove the attachment from disk. if (file_exists($tempFilename)) { unlink($tempFilename); @@ -510,4 +479,96 @@ private function getSubmission(string $submissionId): EntityInterface { return $storage->load($submissionId); } + /** + * Send POST request to Fasit API. + * + * @param string $endpoint + * The API endpoint. + * @param array $options + * The request options. + * + * @return \Psr\Http\Message\ResponseInterface + * The response. + * + * @throws \GuzzleHttp\Exception\GuzzleException + * A Guzzle exception. + */ + private function post(string $endpoint, array $options): ResponseInterface { + try { + $config = $this->settings->getFasitCertificateConfig(); + + // Key => string + // Azure => file without passphrase + // Filesystem => file with potential passphrase. + $provider = $config['certificate_provider']; + + if (SettingsForm::PROVIDER_TYPE_KEY === $provider) { + $certificate = $this->settings->getKeyValue(); + $certPath = $this->fileSystem->tempnam($this->fileSystem->getTempDirectory(), 'os2forms_fasit_cert'); + // `tempnam` has created a file, so we must replace when saving. + $this->fileSystem->saveData($certificate, $certPath, FileSystemInterface::EXISTS_REPLACE); + $options['cert'] = $certPath; + } + elseif (SettingsForm::PROVIDER_TYPE_FORM === $provider) { + [$certificateOptions] = $this->getCertificateOptionsAndTempCertFilename(); + $options['cert'] = $certificateOptions; + } + else { + throw new InvalidSettingException('Invalid certificate configuration'); + } + + return $this->client->request('POST', $endpoint, $options); + } finally { + // Remove the certificate from disk. + if (isset($certPath) && file_exists($certPath)) { + unlink($certPath); + } + } + } + + /** + * Ping the Fasit API and expect a 400 Bad Request response. + * + * @throws \Throwable + */ + public function pingApi(): void { + $endpoint = sprintf('%s/%s/%s/documents/%s', + $this->settings->getFasitApiBaseUrl(), + $this->settings->getFasitApiTenant(), + $this->settings->getFasitApiVersion(), + self::FASIT_API_METHOD_UPLOAD + ); + + try { + $this->post($endpoint, []); + } + catch (\Throwable $t) { + // Throw if it's not a 400 Bad Request exception. + if (!($t instanceof GuzzleException) + || Response::HTTP_BAD_REQUEST !== $t->getCode()) { + throw $t; + } + } + } + + /** + * Gets certificate options and temp certificate filename. + * + * @throws \Drupal\os2forms_fasit\Exception\CertificateLocatorException + * Certificate locator exception. + * + * @phpstan-return array + */ + private function getCertificateOptionsAndTempCertFilename(): array { + $certificateLocator = $this->certificateLocator->getCertificateLocator(); + $localCertFilename = tempnam(sys_get_temp_dir(), 'cert'); + file_put_contents($localCertFilename, $certificateLocator->getCertificate()); + $certificateOptions = + $certificateLocator->hasPassphrase() ? + [$localCertFilename, $certificateLocator->getPassphrase()] + : $localCertFilename; + + return [$certificateOptions, $localCertFilename]; + } + } diff --git a/modules/os2forms_fasit/src/Helper/Settings.php b/modules/os2forms_fasit/src/Helper/Settings.php index de065fc6..09410299 100644 --- a/modules/os2forms_fasit/src/Helper/Settings.php +++ b/modules/os2forms_fasit/src/Helper/Settings.php @@ -2,115 +2,111 @@ namespace Drupal\os2forms_fasit\Helper; -use Drupal\Core\KeyValueStore\KeyValueFactoryInterface; -use Drupal\Core\KeyValueStore\KeyValueStoreInterface; -use Drupal\os2forms_fasit\Exception\InvalidSettingException; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Config\ImmutableConfig; +use Drupal\key\KeyRepositoryInterface; use Drupal\os2forms_fasit\Form\SettingsForm; -use Symfony\Component\OptionsResolver\OptionsResolver; /** * General settings for os2forms_fasit. */ final class Settings { /** - * The store. + * The config. * - * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface + * @var \Drupal\Core\Config\ImmutableConfig */ - private KeyValueStoreInterface $store; + private ImmutableConfig $config; /** - * The key value collection name. - * - * @var string + * The constructor. */ - private $collection = 'os2forms_fasit'; + public function __construct( + ConfigFactoryInterface $configFactory, + private readonly KeyRepositoryInterface $keyRepository, + ) { + $this->config = $configFactory->get(SettingsForm::CONFIG_NAME); + } /** - * The constructor. + * Get fasit api base url. */ - public function __construct(KeyValueFactoryInterface $keyValueFactory) { - $this->store = $keyValueFactory->get($this->collection); + public function getFasitApiBaseUrl(): ?string { + return $this->get(SettingsForm::FASIT_API_BASE_URL); } /** - * Get fasit api base url. + * Get fasit api tenant. */ - public function getFasitApiBaseUrl(): string { - return $this->get(SettingsForm::FASIT_API_BASE_URL, ''); + public function getFasitApiTenant(): ?string { + return $this->get(SettingsForm::FASIT_API_TENANT); } /** - * Get fasit api base url. + * Get fasit api version. */ - public function getFasitApiTenant(): string { - return $this->get(SettingsForm::FASIT_API_TENANT, ''); + public function getFasitApiVersion(): ?string { + return $this->get(SettingsForm::FASIT_API_VERSION); } /** - * Get fasit api base url. + * Get Fasit configuration selector. */ - public function getFasitApiVersion(): string { - return $this->get(SettingsForm::FASIT_API_VERSION, ''); + public function getFasitCertificateConfig(): ?array { + return $this->get(SettingsForm::CERTIFICATE); } /** - * Get certificate. - * - * @phpstan-return array + * Get Fasit certificate provider. */ - public function getCertificate(): array { - $value = $this->get(SettingsForm::CERTIFICATE); - return is_array($value) ? $value : []; + public function getFasitCertificateProvider(): string { + $config = $this->getFasitCertificateConfig(); + + return $config[SettingsForm::CERTIFICATE_PROVIDER] ?? SettingsForm::PROVIDER_TYPE_FORM; } /** - * Get a setting value. - * - * @param string $key - * The key. - * @param mixed|null $default - * The default value. - * - * @return mixed - * The setting value. + * Get Fasit certificate locator. */ - private function get(string $key, $default = NULL) { - $resolver = $this->getSettingsResolver(); - if (!$resolver->isDefined($key)) { - throw new InvalidSettingException(sprintf('Setting %s is not defined', $key)); - } + public function getFasitCertificateLocator(): string { + $config = $this->getFasitCertificateConfig(); - return $this->store->get($key, $default); + return $config[CertificateLocatorHelper::LOCATOR_TYPE] ?? CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM; } /** - * Set settings. - * - * @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface - * - * @phpstan-param array $settings + * Get Fasit key certificate configuration. + */ + public function getFasitCertificateKey(): ?string { + $config = $this->getFasitCertificateConfig(); + + return $config[SettingsForm::PROVIDER_TYPE_KEY] ?? NULL; + } + + /** + * Get certificate. */ - public function setSettings(array $settings): self { - $settings = $this->getSettingsResolver()->resolve($settings); - foreach ($settings as $key => $value) { - $this->store->set($key, $value); - } + public function getKeyValue(): ?string { + $key = $this->keyRepository->getKey( + $this->getFasitCertificateKey(), + ); - return $this; + return $key?->getKeyValue(); } /** - * Get settings resolver. + * Get a setting value. + * + * @param string $key + * The key. + * @param mixed|null $default + * The default value. + * + * @return mixed + * The setting value. */ - private function getSettingsResolver(): OptionsResolver { - return (new OptionsResolver()) - ->setDefaults([ - SettingsForm::FASIT_API_BASE_URL => '', - SettingsForm::FASIT_API_TENANT => '', - SettingsForm::FASIT_API_VERSION => '', - SettingsForm::CERTIFICATE => [], - ]); + private function get(string $key, $default = NULL): mixed { + return $this->config->get($key) ?? $default; } } diff --git a/os2forms.install b/os2forms.install index 2079b530..b6085142 100644 --- a/os2forms.install +++ b/os2forms.install @@ -228,3 +228,12 @@ function _os2form_install_init_area_terms() { function os2forms_update_103001() { \Drupal::service('module_installer')->install(['os2web_audit']); } + +/** + * Implements hook_update_N(). + * + * Enable os2web_key module. + */ +function os2forms_update_103002() { + \Drupal::service('module_installer')->install(['os2web_key']); +} diff --git a/scripts/code-analysis b/scripts/code-analysis index 9fec0f46..ace9e282 100755 --- a/scripts/code-analysis +++ b/scripts/code-analysis @@ -16,9 +16,21 @@ if [ ! -f "$drupal_dir/composer.json" ]; then composer --no-interaction create-project drupal/recommended-project:^10 "$drupal_dir" fi # Copy our code into the modules folder -mkdir -p "$drupal_dir/$module_path" + +# Clean up +rm -fr "${drupal_dir:?}/$module_path" + # https://stackoverflow.com/a/15373763 -rsync --archive --compress . --filter=':- .gitignore' --exclude "$drupal_dir" --exclude .git "$drupal_dir/$module_path" +# rsync --archive --compress . --filter=':- .gitignore' --exclude "$drupal_dir" --exclude .git "$drupal_dir/$module_path" + +# The rsync command in not available in itkdev/php8.1-fpm + +git config --global --add safe.directory /app +# Copy module files into module path +for f in $(git ls-files); do + mkdir -p "$drupal_dir/$module_path/$(dirname "$f")" + cp "$f" "$drupal_dir/$module_path/$f" +done drupal_composer config minimum-stability dev @@ -37,4 +49,4 @@ drupal_composer config extra.merge-plugin.include "$module_path/composer.json" drupal_composer require --dev symfony/phpunit-bridge # Run PHPStan -(cd "$drupal_dir" && vendor/bin/phpstan --configuration="$module_path/phpstan.neon") +(cd "$drupal_dir/$module_path" && ../../../../vendor/bin/phpstan)