diff options
Diffstat (limited to 'lib/public/SetupCheck')
-rw-r--r-- | lib/public/SetupCheck/CheckServerResponseTrait.php | 162 | ||||
-rw-r--r-- | lib/public/SetupCheck/ISetupCheck.php | 36 | ||||
-rw-r--r-- | lib/public/SetupCheck/ISetupCheckManager.php | 21 | ||||
-rw-r--r-- | lib/public/SetupCheck/SetupResult.php | 188 |
4 files changed, 407 insertions, 0 deletions
diff --git a/lib/public/SetupCheck/CheckServerResponseTrait.php b/lib/public/SetupCheck/CheckServerResponseTrait.php new file mode 100644 index 00000000000..29a2215aa67 --- /dev/null +++ b/lib/public/SetupCheck/CheckServerResponseTrait.php @@ -0,0 +1,162 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCP\SetupCheck; + +use Generator; +use OCP\Http\Client\IClientService; +use OCP\Http\Client\IResponse; +use OCP\IConfig; +use OCP\IURLGenerator; +use OCP\L10N\IFactory; +use Psr\Log\LoggerInterface; + +/** + * Common trait for setup checks that need to use requests to the same server and check the response + * @since 31.0.0 + */ +trait CheckServerResponseTrait { + protected IConfig $config; + protected IURLGenerator $urlGenerator; + protected IClientService $clientService; + protected LoggerInterface $logger; + + /** + * Common helper string in case a check could not fetch any results + * @since 31.0.0 + */ + protected function serverConfigHelp(): string { + $l10n = \OCP\Server::get(IFactory::class)->get('lib'); + return $l10n->t('To allow this check to run you have to make sure that your Web server can connect to itself. Therefore it must be able to resolve and connect to at least one of its `trusted_domains` or the `overwrite.cli.url`. This failure may be the result of a server-side DNS mismatch or outbound firewall rule.'); + } + + /** + * Get all possible URLs that need to be checked for a local request test. + * This takes all `trusted_domains` and the CLI overwrite URL into account. + * + * @param string $url The absolute path (absolute URL without host but with web-root) to test starting with a / + * @param bool $isRootRequest Set to remove the web-root from URL and host (e.g. when requesting a path in the domain root like '/.well-known') + * @return list<string> List of possible absolute URLs + * @since 31.0.0 + */ + protected function getTestUrls(string $url, bool $isRootRequest = false): array { + $url = '/' . ltrim($url, '/'); + + $webroot = rtrim($this->urlGenerator->getWebroot(), '/'); + if ($isRootRequest === false && $webroot !== '' && str_starts_with($url, $webroot)) { + // The URL contains the web-root but also the base url does so, + // so we need to remove the web-root from the URL. + $url = substr($url, strlen($webroot)); + } + + // Base URLs to test + $baseUrls = []; + + // Try overwrite.cli.url first, it’s supposed to be how the server contacts itself + $cliUrl = $this->config->getSystemValueString('overwrite.cli.url', ''); + if ($cliUrl !== '') { + // The CLI URL already contains the web-root, so we need to normalize it if requested + $baseUrls[] = $this->normalizeUrl( + $cliUrl, + $isRootRequest + ); + } + + // Try URL generator second + // The base URL also contains the webroot so also normalize it + $baseUrls[] = $this->normalizeUrl( + $this->urlGenerator->getBaseUrl(), + $isRootRequest + ); + + /* Last resort: trusted domains */ + $trustedDomains = $this->config->getSystemValue('trusted_domains', []); + foreach ($trustedDomains as $host) { + if (str_contains($host, '*')) { + /* Ignore domains with a wildcard */ + continue; + } + $baseUrls[] = $this->normalizeUrl("https://$host$webroot", $isRootRequest); + $baseUrls[] = $this->normalizeUrl("http://$host$webroot", $isRootRequest); + } + + return array_map(fn (string $host) => $host . $url, array_values(array_unique($baseUrls))); + } + + /** + * Run a HTTP request to check header + * @param string $method The HTTP method to use + * @param string $url The absolute path (URL with webroot but without host) to check, can be the output of `IURLGenerator` + * @param bool $isRootRequest If set the webroot is removed from URLs to make the request target the host's root. Example usage are the /.well-known URLs in the root path. + * @param array{ignoreSSL?: bool, httpErrors?: bool, options?: array} $options HTTP client related options, like + * [ + * // Ignore invalid SSL certificates (e.g. self signed) + * 'ignoreSSL' => true, + * // Ignore requests with HTTP errors (will not yield if request has a 4xx or 5xx response) + * 'httpErrors' => true, + * // Additional options for the HTTP client (see `IClient`) + * 'options' => [], + * ] + * + * @return Generator<int, IResponse> + * @since 31.0.0 + */ + protected function runRequest(string $method, string $url, array $options = [], bool $isRootRequest = false): Generator { + $options = array_merge(['ignoreSSL' => true, 'httpErrors' => true], $options); + + $client = $this->clientService->newClient(); + $requestOptions = $this->getRequestOptions($options['ignoreSSL'], $options['httpErrors']); + $requestOptions = array_merge($requestOptions, $options['options'] ?? []); + + foreach ($this->getTestUrls($url, $isRootRequest) as $testURL) { + try { + yield $client->request($method, $testURL, $requestOptions); + } catch (\Throwable $e) { + $this->logger->debug('Can not connect to local server for running setup checks', ['exception' => $e, 'url' => $testURL]); + } + } + } + + /** + * Get HTTP client options + * @param bool $ignoreSSL If set SSL errors are ignored (e.g. self-signed certificates) + * @since 31.0.0 + */ + private function getRequestOptions(bool $ignoreSSL, bool $httpErrors): array { + $requestOptions = [ + 'connect_timeout' => 10, + 'http_errors' => $httpErrors, + 'nextcloud' => [ + 'allow_local_address' => true, + ], + ]; + if ($ignoreSSL) { + $requestOptions['verify'] = false; + } + return $requestOptions; + } + + /** + * Strip a trailing slash and remove the webroot if requested. + * @param string $url The URL to normalize. Should be an absolute URL containing scheme, host and optionally web-root. + * @param bool $removeWebroot If set the web-root is removed from the URL and an absolute URL with only the scheme and host (optional port) is returned + * @since 31.0.0 + */ + private function normalizeUrl(string $url, bool $removeWebroot): string { + if ($removeWebroot) { + $segments = parse_url($url); + if (!isset($segments['scheme']) || !isset($segments['host'])) { + throw new \InvalidArgumentException('URL is missing scheme or host'); + } + + $port = isset($segments['port']) ? (':' . $segments['port']) : ''; + return $segments['scheme'] . '://' . $segments['host'] . $port; + } + return rtrim($url, '/'); + } +} diff --git a/lib/public/SetupCheck/ISetupCheck.php b/lib/public/SetupCheck/ISetupCheck.php new file mode 100644 index 00000000000..e458510818f --- /dev/null +++ b/lib/public/SetupCheck/ISetupCheck.php @@ -0,0 +1,36 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + +namespace OCP\SetupCheck; + +/** + * This interface needs to be implemented if you want to provide custom + * setup checks in your application. The results of these checks will them + * be displayed in the admin overview. + * + * @since 28.0.0 + */ +interface ISetupCheck { + /** + * @since 28.0.0 + * @return string Category id, one of security/system/accounts, or a custom one which will be merged in system + */ + public function getCategory(): string; + + /** + * @since 28.0.0 + * @return string Translated name to display to the user + */ + public function getName(): string; + + /** + * @since 28.0.0 + */ + public function run(): SetupResult; +} diff --git a/lib/public/SetupCheck/ISetupCheckManager.php b/lib/public/SetupCheck/ISetupCheckManager.php new file mode 100644 index 00000000000..6245be3933a --- /dev/null +++ b/lib/public/SetupCheck/ISetupCheckManager.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + +namespace OCP\SetupCheck; + +/** + * @since 28.0.0 + */ +interface ISetupCheckManager { + /** + * @since 28.0.0 + * @return array<string,array<string,SetupResult>> Result of each check, first level key is category, second level key is title + */ + public function runAll(): array; +} diff --git a/lib/public/SetupCheck/SetupResult.php b/lib/public/SetupCheck/SetupResult.php new file mode 100644 index 00000000000..7d64b838087 --- /dev/null +++ b/lib/public/SetupCheck/SetupResult.php @@ -0,0 +1,188 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + +namespace OCP\SetupCheck; + +use OCP\RichObjectStrings\IValidator; + +/** + * @brief This class is used for storing the result of a setup check + * + * @since 28.0.0 + */ +class SetupResult implements \JsonSerializable { + /** + * @since 28.0.0 + */ + public const SUCCESS = 'success'; + + /** + * @since 28.0.0 + */ + public const INFO = 'info'; + + /** + * @since 28.0.0 + */ + public const WARNING = 'warning'; + + /** + * @since 28.0.0 + */ + public const ERROR = 'error'; + + /** + * @param string $name Translated name to display to the user + */ + private ?string $name = null; + + /** + * @brief Private constructor, use success()/info()/warning()/error() instead + * @param self::SUCCESS|self::INFO|self::WARNING|self::ERROR $severity + * @param array<string, array<string, string>> $descriptionParameters + * @throws \OCP\RichObjectStrings\InvalidObjectExeption + * @since 28.0.0 + * @since 28.0.2 Optional parameter ?array $descriptionParameters + * @since 28.0.2 throws \OCP\RichObjectStrings\InvalidObjectExeption + */ + private function __construct( + private string $severity, + private ?string $description = null, + private ?array $descriptionParameters = null, + private ?string $linkToDoc = null, + ) { + if ($description !== null && $descriptionParameters !== null) { + \OCP\Server::get(IValidator::class)->validate($description, $descriptionParameters); + } + } + + /** + * @brief Create a success result object + * @param ?string $description Translated detailed description to display to the user + * @param ?string $linkToDoc URI of related relevent documentation, be it from Nextcloud or another project + * @throws \OCP\RichObjectStrings\InvalidObjectExeption + * @since 28.0.0 + * @since 28.0.2 Optional parameter ?array $descriptionParameters + * @since 28.0.2 throws \OCP\RichObjectStrings\InvalidObjectExeption + */ + public static function success(?string $description = null, ?string $linkToDoc = null, ?array $descriptionParameters = null): self { + return new self(self::SUCCESS, $description, $descriptionParameters, $linkToDoc); + } + + /** + * @brief Create an info result object + * @param ?string $description Translated detailed description to display to the user + * @param ?string $linkToDoc URI of related relevent documentation, be it from Nextcloud or another project + * @throws \OCP\RichObjectStrings\InvalidObjectExeption + * @since 28.0.0 + * @since 28.0.2 Optional parameter ?array $descriptionParameters + * @since 28.0.2 throws \OCP\RichObjectStrings\InvalidObjectExeption + */ + public static function info(?string $description = null, ?string $linkToDoc = null, ?array $descriptionParameters = null): self { + return new self(self::INFO, $description, $descriptionParameters, $linkToDoc); + } + + /** + * @brief Create a warning result object + * @param ?string $description Translated detailed description to display to the user + * @param ?string $linkToDoc URI of related relevent documentation, be it from Nextcloud or another project + * @throws \OCP\RichObjectStrings\InvalidObjectExeption + * @since 28.0.0 + * @since 28.0.2 Optional parameter ?array $descriptionParameters + * @since 28.0.2 throws \OCP\RichObjectStrings\InvalidObjectExeption + */ + public static function warning(?string $description = null, ?string $linkToDoc = null, ?array $descriptionParameters = null): self { + return new self(self::WARNING, $description, $descriptionParameters, $linkToDoc); + } + + /** + * @brief Create an error result object + * @param ?string $description Translated detailed description to display to the user + * @param ?string $linkToDoc URI of related relevent documentation, be it from Nextcloud or another project + * @throws \OCP\RichObjectStrings\InvalidObjectExeption + * @since 28.0.0 + * @since 28.0.2 Optional parameter ?array $descriptionParameters + * @since 28.0.2 throws \OCP\RichObjectStrings\InvalidObjectExeption + */ + public static function error(?string $description = null, ?string $linkToDoc = null, ?array $descriptionParameters = null): self { + return new self(self::ERROR, $description, $descriptionParameters, $linkToDoc); + } + + /** + * @brief Get the severity for the setup check result + * + * @return self::SUCCESS|self::INFO|self::WARNING|self::ERROR + * @since 28.0.0 + */ + public function getSeverity(): string { + return $this->severity; + } + + /** + * @brief Get the description for the setup check result + * + * @since 28.0.0 + */ + public function getDescription(): ?string { + return $this->description; + } + + /** + * @brief Get the description parameters for the setup check result + * + * If this returns null, description must not be treated as rich text + * + * @since 28.0.2 + */ + public function getDescriptionParameters(): ?array { + return $this->descriptionParameters; + } + + /** + * @brief Get the name for the setup check + * + * @since 28.0.0 + */ + public function getName(): ?string { + return $this->name; + } + + /** + * @brief Set the name from the setup check + * + * @since 28.0.0 + */ + public function setName(string $name): void { + $this->name = $name; + } + + /** + * @brief Get a link to the doc for the explanation. + * + * @since 28.0.0 + */ + public function getLinkToDoc(): ?string { + return $this->linkToDoc; + } + + /** + * @brief Get an array representation of the result for API responses + * + * @since 28.0.0 + */ + public function jsonSerialize(): array { + return [ + 'name' => $this->name, + 'severity' => $this->severity, + 'description' => $this->description, + 'descriptionParameters' => $this->descriptionParameters, + 'linkToDoc' => $this->linkToDoc, + ]; + } +} |