diff --git a/.gitignore b/.gitignore index 2e73df093dfd4..a3e6f7872ca17 100644 --- a/.gitignore +++ b/.gitignore @@ -45,6 +45,7 @@ !/apps/twofactor_backupcodes !/apps/user_status !/apps/weather_status +!/apps/webhook_listeners !/apps/workflowengine /apps/files_external/3rdparty/irodsphp/PHPUnitTest /apps/files_external/3rdparty/irodsphp/web diff --git a/apps/dav/composer/composer/autoload_static.php b/apps/dav/composer/composer/autoload_static.php index caa6cc8d5e6c3..94961e04837bc 100644 --- a/apps/dav/composer/composer/autoload_static.php +++ b/apps/dav/composer/composer/autoload_static.php @@ -150,13 +150,13 @@ class ComposerStaticInitDAV 'OCA\\DAV\\CardDAV\\MultiGetExportPlugin' => __DIR__ . '/..' . '/../lib/CardDAV/MultiGetExportPlugin.php', 'OCA\\DAV\\CardDAV\\PhotoCache' => __DIR__ . '/..' . '/../lib/CardDAV/PhotoCache.php', 'OCA\\DAV\\CardDAV\\Plugin' => __DIR__ . '/..' . '/../lib/CardDAV/Plugin.php', + 'OCA\\DAV\\CardDAV\\Security\\CardDavRateLimitingPlugin' => __DIR__ . '/..' . '/../lib/CardDAV/Security/CardDavRateLimitingPlugin.php', 'OCA\\DAV\\CardDAV\\Sharing\\Backend' => __DIR__ . '/..' . '/../lib/CardDAV/Sharing/Backend.php', 'OCA\\DAV\\CardDAV\\Sharing\\Service' => __DIR__ . '/..' . '/../lib/CardDAV/Sharing/Service.php', 'OCA\\DAV\\CardDAV\\SyncService' => __DIR__ . '/..' . '/../lib/CardDAV/SyncService.php', 'OCA\\DAV\\CardDAV\\SystemAddressbook' => __DIR__ . '/..' . '/../lib/CardDAV/SystemAddressbook.php', 'OCA\\DAV\\CardDAV\\UserAddressBooks' => __DIR__ . '/..' . '/../lib/CardDAV/UserAddressBooks.php', 'OCA\\DAV\\CardDAV\\Xml\\Groups' => __DIR__ . '/..' . '/../lib/CardDAV/Xml/Groups.php', - 'OCA\\DAV\\CardDAV\\Security\\CardDavRateLimitingPlugin' => __DIR__ . '/..' . '/../lib/CardDAV/Security/CardDavRateLimitingPlugin.php', 'OCA\\DAV\\Command\\CreateAddressBook' => __DIR__ . '/..' . '/../lib/Command/CreateAddressBook.php', 'OCA\\DAV\\Command\\CreateCalendar' => __DIR__ . '/..' . '/../lib/Command/CreateCalendar.php', 'OCA\\DAV\\Command\\DeleteCalendar' => __DIR__ . '/..' . '/../lib/Command/DeleteCalendar.php', diff --git a/apps/webhook_listeners/appinfo/info.xml b/apps/webhook_listeners/appinfo/info.xml new file mode 100644 index 0000000000000..a8cec901ec3ed --- /dev/null +++ b/apps/webhook_listeners/appinfo/info.xml @@ -0,0 +1,33 @@ + + + webhook_listeners + Nextcloud webhook support + Nextcloud webhook support + Nextcloud webhook support + 1.0.0-dev + agpl + Côme Chilliet + WebhookListeners + + + + + + customization + https://github.com/nextcloud/server + https://github.com/nextcloud/server/issues + https://github.com/nextcloud/server.git + + + + + + + OCA\WebhookListeners\Command\ListWebhooks + + + + OCA\WebhookListeners\Settings\Admin + + diff --git a/apps/webhook_listeners/composer/autoload.php b/apps/webhook_listeners/composer/autoload.php new file mode 100644 index 0000000000000..fa45003779ed7 --- /dev/null +++ b/apps/webhook_listeners/composer/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders keyed by their corresponding vendor directories. + * + * @return array + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/apps/webhook_listeners/composer/composer/InstalledVersions.php b/apps/webhook_listeners/composer/composer/InstalledVersions.php new file mode 100644 index 0000000000000..51e734a774b3e --- /dev/null +++ b/apps/webhook_listeners/composer/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/apps/webhook_listeners/composer/composer/LICENSE b/apps/webhook_listeners/composer/composer/LICENSE new file mode 100644 index 0000000000000..f27399a042d95 --- /dev/null +++ b/apps/webhook_listeners/composer/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/apps/webhook_listeners/composer/composer/autoload_classmap.php b/apps/webhook_listeners/composer/composer/autoload_classmap.php new file mode 100644 index 0000000000000..0501a86df2ce8 --- /dev/null +++ b/apps/webhook_listeners/composer/composer/autoload_classmap.php @@ -0,0 +1,22 @@ + $vendorDir . '/composer/InstalledVersions.php', + 'OCA\\WebhookListeners\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', + 'OCA\\WebhookListeners\\BackgroundJobs\\WebhookCall' => $baseDir . '/../lib/BackgroundJobs/WebhookCall.php', + 'OCA\\WebhookListeners\\Command\\ListWebhooks' => $baseDir . '/../lib/Command/ListWebhooks.php', + 'OCA\\WebhookListeners\\Controller\\WebhooksController' => $baseDir . '/../lib/Controller/WebhooksController.php', + 'OCA\\WebhookListeners\\Db\\AuthMethod' => $baseDir . '/../lib/Db/AuthMethod.php', + 'OCA\\WebhookListeners\\Db\\WebhookListener' => $baseDir . '/../lib/Db/WebhookListener.php', + 'OCA\\WebhookListeners\\Db\\WebhookListenerMapper' => $baseDir . '/../lib/Db/WebhookListenerMapper.php', + 'OCA\\WebhookListeners\\Listener\\WebhooksEventListener' => $baseDir . '/../lib/Listener/WebhooksEventListener.php', + 'OCA\\WebhookListeners\\Migration\\Version1000Date20240527153425' => $baseDir . '/../lib/Migration/Version1000Date20240527153425.php', + 'OCA\\WebhookListeners\\ResponseDefinitions' => $baseDir . '/../lib/ResponseDefinitions.php', + 'OCA\\WebhookListeners\\Service\\PHPMongoQuery' => $baseDir . '/../lib/Service/PHPMongoQuery.php', + 'OCA\\WebhookListeners\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php', +); diff --git a/apps/webhook_listeners/composer/composer/autoload_namespaces.php b/apps/webhook_listeners/composer/composer/autoload_namespaces.php new file mode 100644 index 0000000000000..3f5c929625125 --- /dev/null +++ b/apps/webhook_listeners/composer/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/../lib'), +); diff --git a/apps/webhook_listeners/composer/composer/autoload_real.php b/apps/webhook_listeners/composer/composer/autoload_real.php new file mode 100644 index 0000000000000..336058c2e24cd --- /dev/null +++ b/apps/webhook_listeners/composer/composer/autoload_real.php @@ -0,0 +1,37 @@ +setClassMapAuthoritative(true); + $loader->register(true); + + return $loader; + } +} diff --git a/apps/webhook_listeners/composer/composer/autoload_static.php b/apps/webhook_listeners/composer/composer/autoload_static.php new file mode 100644 index 0000000000000..43a9b4779d9c6 --- /dev/null +++ b/apps/webhook_listeners/composer/composer/autoload_static.php @@ -0,0 +1,48 @@ + + array ( + 'OCA\\WebhookListeners\\' => 21, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'OCA\\WebhookListeners\\' => + array ( + 0 => __DIR__ . '/..' . '/../lib', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'OCA\\WebhookListeners\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', + 'OCA\\WebhookListeners\\BackgroundJobs\\WebhookCall' => __DIR__ . '/..' . '/../lib/BackgroundJobs/WebhookCall.php', + 'OCA\\WebhookListeners\\Command\\ListWebhooks' => __DIR__ . '/..' . '/../lib/Command/ListWebhooks.php', + 'OCA\\WebhookListeners\\Controller\\WebhooksController' => __DIR__ . '/..' . '/../lib/Controller/WebhooksController.php', + 'OCA\\WebhookListeners\\Db\\AuthMethod' => __DIR__ . '/..' . '/../lib/Db/AuthMethod.php', + 'OCA\\WebhookListeners\\Db\\WebhookListener' => __DIR__ . '/..' . '/../lib/Db/WebhookListener.php', + 'OCA\\WebhookListeners\\Db\\WebhookListenerMapper' => __DIR__ . '/..' . '/../lib/Db/WebhookListenerMapper.php', + 'OCA\\WebhookListeners\\Listener\\WebhooksEventListener' => __DIR__ . '/..' . '/../lib/Listener/WebhooksEventListener.php', + 'OCA\\WebhookListeners\\Migration\\Version1000Date20240527153425' => __DIR__ . '/..' . '/../lib/Migration/Version1000Date20240527153425.php', + 'OCA\\WebhookListeners\\ResponseDefinitions' => __DIR__ . '/..' . '/../lib/ResponseDefinitions.php', + 'OCA\\WebhookListeners\\Service\\PHPMongoQuery' => __DIR__ . '/..' . '/../lib/Service/PHPMongoQuery.php', + 'OCA\\WebhookListeners\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitWebhookListeners::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitWebhookListeners::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitWebhookListeners::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/apps/webhook_listeners/composer/composer/installed.json b/apps/webhook_listeners/composer/composer/installed.json new file mode 100644 index 0000000000000..f20a6c47c6d4f --- /dev/null +++ b/apps/webhook_listeners/composer/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": false, + "dev-package-names": [] +} diff --git a/apps/webhook_listeners/composer/composer/installed.php b/apps/webhook_listeners/composer/composer/installed.php new file mode 100644 index 0000000000000..1a66c7f2416b6 --- /dev/null +++ b/apps/webhook_listeners/composer/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => 'b1797842784b250fb01ed5e3bf130705eb94751b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => 'b1797842784b250fb01ed5e3bf130705eb94751b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/apps/webhook_listeners/img/app-dark.svg b/apps/webhook_listeners/img/app-dark.svg new file mode 100644 index 0000000000000..148495ade91db --- /dev/null +++ b/apps/webhook_listeners/img/app-dark.svg @@ -0,0 +1 @@ + diff --git a/apps/webhook_listeners/img/app.svg b/apps/webhook_listeners/img/app.svg new file mode 100644 index 0000000000000..8d98fac4b695f --- /dev/null +++ b/apps/webhook_listeners/img/app.svg @@ -0,0 +1 @@ + diff --git a/apps/webhook_listeners/lib/AppInfo/Application.php b/apps/webhook_listeners/lib/AppInfo/Application.php new file mode 100644 index 0000000000000..d1ffa5db49ba9 --- /dev/null +++ b/apps/webhook_listeners/lib/AppInfo/Application.php @@ -0,0 +1,55 @@ +injectFn($this->registerRuleListeners(...)); + } + + private function registerRuleListeners( + IEventDispatcher $dispatcher, + ContainerInterface $container, + LoggerInterface $logger, + ): void { + /** @var WebhookListenerMapper */ + $mapper = $container->get(WebhookListenerMapper::class); + + /* Listen to all events with at least one webhook configured */ + $configuredEvents = $mapper->getAllConfiguredEvents(); + foreach ($configuredEvents as $eventName) { + $logger->debug("Listening to {$eventName}"); + $dispatcher->addServiceListener( + $eventName, + WebhooksEventListener::class, + -1, + ); + } + } +} diff --git a/apps/webhook_listeners/lib/BackgroundJobs/WebhookCall.php b/apps/webhook_listeners/lib/BackgroundJobs/WebhookCall.php new file mode 100644 index 0000000000000..9c9a4bb6dbe37 --- /dev/null +++ b/apps/webhook_listeners/lib/BackgroundJobs/WebhookCall.php @@ -0,0 +1,63 @@ +mapper->getById($webhookId); + $client = $this->clientService->newClient(); + $options = [ + 'verify' => $this->certificateManager->getAbsoluteBundlePath(), + 'headers' => $webhookListener->getHeaders() ?? [], + 'body' => json_encode($data), + ]; + try { + switch ($webhookListener->getAuthMethodEnum()) { + case AuthMethod::None: + break; + case AuthMethod::Header: + $authHeaders = $webhookListener->getAuthDataClear(); + $options['headers'] = array_merge($options['headers'], $authHeaders); + break; + } + $response = $client->request($webhookListener->getHttpMethod(), $webhookListener->getUri(), $options); + $statusCode = $response->getStatusCode(); + if ($statusCode >= 200 && $statusCode < 300) { + $this->logger->debug('Webhook returned status code '.$statusCode, ['body' => $response->getBody()]); + } else { + $this->logger->warning('Webhook returned unexpected status code '.$statusCode, ['body' => $response->getBody()]); + } + } catch (\Exception $e) { + $this->logger->error('Webhook call failed: '.$e->getMessage(), ['exception' => $e]); + } + } +} diff --git a/apps/webhook_listeners/lib/Command/ListWebhooks.php b/apps/webhook_listeners/lib/Command/ListWebhooks.php new file mode 100644 index 0000000000000..157097f3f1540 --- /dev/null +++ b/apps/webhook_listeners/lib/Command/ListWebhooks.php @@ -0,0 +1,43 @@ +setName('webhook_listeners:list') + ->setDescription('Lists configured webhook listeners'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int { + $webhookListeners = array_map( + fn (WebhookListener $listener): array => array_map( + fn (string|array|null $value): ?string => (is_array($value) ? json_encode($value) : $value), + $listener->jsonSerialize() + ), + $this->mapper->getAll() + ); + $this->writeTableInOutputFormat($input, $output, $webhookListeners); + return static::SUCCESS; + } +} diff --git a/apps/webhook_listeners/lib/Controller/WebhooksController.php b/apps/webhook_listeners/lib/Controller/WebhooksController.php new file mode 100644 index 0000000000000..1c4306eabb8a2 --- /dev/null +++ b/apps/webhook_listeners/lib/Controller/WebhooksController.php @@ -0,0 +1,259 @@ + + * @throws OCSException Other internal error + * + * 200: Webhook registrations returned + */ + #[ApiRoute(verb: 'GET', url: '/api/v1/webhooks')] + #[AuthorizedAdminSetting(settings:Admin::class)] + public function index(): DataResponse { + try { + $webhookListeners = $this->mapper->getAll(); + + return new DataResponse( + array_map( + fn (WebhookListener $listener): array => $listener->jsonSerialize(), + $webhookListeners + ) + ); + } catch (\Exception $e) { + $this->logger->error('Error when listing webhooks', ['exception' => $e]); + throw new OCSException('An internal error occurred', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } + + /** + * Get details on a registered webhook + * + * @param int $id id of the webhook + * + * @return DataResponse + * @throws OCSNotFoundException Webhook not found + * @throws OCSException Other internal error + * + * 200: Webhook registration returned + */ + #[ApiRoute(verb: 'GET', url: '/api/v1/webhooks/{id}')] + #[AuthorizedAdminSetting(settings:Admin::class)] + public function show(int $id): DataResponse { + try { + return new DataResponse($this->mapper->getById($id)->jsonSerialize()); + } catch (DoesNotExistException $e) { + throw new OCSNotFoundException($e->getMessage(), $e); + } catch (\Exception $e) { + $this->logger->error('Error when getting webhook', ['exception' => $e]); + throw new OCSException('An internal error occurred', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } + + /** + * Register a new webhook + * + * @param string $httpMethod HTTP method to use to contact the webhook + * @param string $uri Webhook URI endpoint + * @param string $event Event class name to listen to + * @param ?array $eventFilter Mongo filter to apply to the serialized data to decide if firing + * @param ?array $headers Array of headers to send + * @param "none"|"headers"|null $authMethod Authentication method to use + * @param ?array $authData Array of data for authentication + * + * @return DataResponse + * + * 200: Webhook registration returned + * + * @throws OCSBadRequestException Bad request + * @throws OCSForbiddenException Insufficient permissions + * @throws OCSException Other error + */ + #[ApiRoute(verb: 'POST', url: '/api/v1/webhooks')] + #[AuthorizedAdminSetting(settings:Admin::class)] + public function create( + string $httpMethod, + string $uri, + string $event, + ?array $eventFilter, + ?array $headers, + ?string $authMethod, + #[\SensitiveParameter] + ?array $authData, + ): DataResponse { + $appId = null; + if ($this->session->get('app_api') === true) { + $appId = $this->request->getHeader('EX-APP-ID'); + } + try { + $authMethod = AuthMethod::from($authMethod ?? AuthMethod::None->value); + } catch (\ValueError $e) { + throw new OCSBadRequestException('This auth method does not exist'); + } + try { + /* We can never reach here without a user in session */ + assert(is_string($this->userId)); + $webhookListener = $this->mapper->addWebhookListener( + $appId, + $this->userId, + $httpMethod, + $uri, + $event, + $eventFilter, + $headers, + $authMethod, + $authData, + ); + return new DataResponse($webhookListener->jsonSerialize()); + } catch (\UnexpectedValueException $e) { + throw new OCSBadRequestException($e->getMessage(), $e); + } catch (\DomainException $e) { + throw new OCSForbiddenException($e->getMessage(), $e); + } catch (\Exception $e) { + $this->logger->error('Error when inserting webhook', ['exception' => $e]); + throw new OCSException('An internal error occurred', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } + + /** + * Update an existing webhook registration + * + * @param int $id id of the webhook + * @param string $httpMethod HTTP method to use to contact the webhook + * @param string $uri Webhook URI endpoint + * @param string $event Event class name to listen to + * @param ?array $eventFilter Mongo filter to apply to the serialized data to decide if firing + * @param ?array $headers Array of headers to send + * @param "none"|"headers"|null $authMethod Authentication method to use + * @param ?array $authData Array of data for authentication + * + * @return DataResponse + * + * 200: Webhook registration returned + * + * @throws OCSBadRequestException Bad request + * @throws OCSForbiddenException Insufficient permissions + * @throws OCSException Other error + */ + #[ApiRoute(verb: 'POST', url: '/api/v1/webhooks/{id}')] + #[AuthorizedAdminSetting(settings:Admin::class)] + public function update( + int $id, + string $httpMethod, + string $uri, + string $event, + ?array $eventFilter, + ?array $headers, + ?string $authMethod, + #[\SensitiveParameter] + ?array $authData, + ): DataResponse { + $appId = null; + if ($this->session->get('app_api') === true) { + $appId = $this->request->getHeader('EX-APP-ID'); + } + try { + $authMethod = AuthMethod::from($authMethod ?? AuthMethod::None->value); + } catch (\ValueError $e) { + throw new OCSBadRequestException('This auth method does not exist'); + } + try { + /* We can never reach here without a user in session */ + assert(is_string($this->userId)); + $webhookListener = $this->mapper->updateWebhookListener( + $id, + $appId, + $this->userId, + $httpMethod, + $uri, + $event, + $eventFilter, + $headers, + $authMethod, + $authData, + ); + return new DataResponse($webhookListener->jsonSerialize()); + } catch (\UnexpectedValueException $e) { + throw new OCSBadRequestException($e->getMessage(), $e); + } catch (\DomainException $e) { + throw new OCSForbiddenException($e->getMessage(), $e); + } catch (\Exception $e) { + $this->logger->error('Error when updating flow with id ' . $id, ['exception' => $e]); + throw new OCSException('An internal error occurred', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } + + /** + * Remove an existing webhook registration + * + * @param int $id id of the webhook + * + * @return DataResponse + * + * 200: Boolean returned whether something was deleted FIXME + * + * @throws OCSBadRequestException Bad request + * @throws OCSForbiddenException Insufficient permissions + * @throws OCSException Other error + */ + #[ApiRoute(verb: 'DELETE', url: '/api/v1/webhooks/{id}')] + #[AuthorizedAdminSetting(settings:Admin::class)] + public function destroy(int $id): DataResponse { + try { + $deleted = $this->mapper->deleteById($id); + return new DataResponse($deleted); + } catch (\UnexpectedValueException $e) { + throw new OCSBadRequestException($e->getMessage(), $e); + } catch (\DomainException $e) { + throw new OCSForbiddenException($e->getMessage(), $e); + } catch (\Exception $e) { + $this->logger->error('Error when deleting flow with id ' . $id, ['exception' => $e]); + throw new OCSException('An internal error occurred', Http::STATUS_INTERNAL_SERVER_ERROR, $e); + } + } +} diff --git a/apps/webhook_listeners/lib/Db/AuthMethod.php b/apps/webhook_listeners/lib/Db/AuthMethod.php new file mode 100644 index 0000000000000..ab8bff76eb7f6 --- /dev/null +++ b/apps/webhook_listeners/lib/Db/AuthMethod.php @@ -0,0 +1,15 @@ +crypto = $crypto; + $this->addType('appId', 'string'); + $this->addType('userId', 'string'); + $this->addType('httpMethod', 'string'); + $this->addType('uri', 'string'); + $this->addType('event', 'string'); + $this->addType('eventFilter', 'json'); + $this->addType('headers', 'json'); + $this->addType('authMethod', 'string'); + $this->addType('authData', 'string'); + } + + public function getAuthMethodEnum(): AuthMethod { + return AuthMethod::from($this->getAuthMethod()); + } + + public function getAuthDataClear(): array { + $authData = $this->getAuthData(); + if ($authData === null) { + return []; + } + return json_decode($this->crypto->decrypt($authData), associative:true, flags:JSON_THROW_ON_ERROR); + } + + public function setAuthDataClear( + #[\SensitiveParameter] + ?array $data + ): void { + if ($data === null) { + if ($this->getAuthMethodEnum() === AuthMethod::Header) { + throw new \UnexpectedValueException('Header auth method needs an associative array of headers as auth data'); + } + $this->setAuthData(null); + return; + } + $this->setAuthData($this->crypto->encrypt(json_encode($data))); + } + + public function jsonSerialize(): array { + $fields = array_keys($this->getFieldTypes()); + return array_combine( + $fields, + array_map( + fn ($field) => $this->getter($field), + $fields + ) + ); + } +} diff --git a/apps/webhook_listeners/lib/Db/WebhookListenerMapper.php b/apps/webhook_listeners/lib/Db/WebhookListenerMapper.php new file mode 100644 index 0000000000000..97e01062f2f86 --- /dev/null +++ b/apps/webhook_listeners/lib/Db/WebhookListenerMapper.php @@ -0,0 +1,207 @@ + + */ +class WebhookListenerMapper extends QBMapper { + public const TABLE_NAME = 'webhook_listeners'; + + private const EVENTS_CACHE_KEY = 'eventsUsedInWebhooks'; + + private ?ICache $cache = null; + + public function __construct( + IDBConnection $db, + ICacheFactory $cacheFactory, + ) { + parent::__construct($db, self::TABLE_NAME, WebhookListener::class); + if ($cacheFactory->isAvailable()) { + $this->cache = $cacheFactory->createDistributed(); + } + } + + /** + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws Exception + */ + public function getById(int $id): WebhookListener { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); + + return $this->findEntity($qb); + } + + /** + * @throws Exception + * @return WebhookListener[] + */ + public function getAll(): array { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()); + + return $this->findEntities($qb); + } + + /** + * @throws Exception + */ + public function addWebhookListener( + ?string $appId, + string $userId, + string $httpMethod, + string $uri, + string $event, + ?array $eventFilter, + ?array $headers, + AuthMethod $authMethod, + #[\SensitiveParameter] + ?array $authData, + ): WebhookListener { + /* Remove any superfluous antislash */ + $event = ltrim($event, '\\'); + if (!class_exists($event) || !is_a($event, IWebhookCompatibleEvent::class, true)) { + throw new \UnexpectedValueException("$event is not an event class compatible with webhooks"); + } + $webhookListener = WebhookListener::fromParams( + [ + 'appId' => $appId, + 'userId' => $userId, + 'httpMethod' => $httpMethod, + 'uri' => $uri, + 'event' => $event, + 'eventFilter' => $eventFilter ?? [], + 'headers' => $headers, + 'authMethod' => $authMethod->value, + ] + ); + $webhookListener->setAuthDataClear($authData); + $this->cache?->remove(self::EVENTS_CACHE_KEY); + return $this->insert($webhookListener); + } + + /** + * @throws Exception + */ + public function updateWebhookListener( + int $id, + ?string $appId, + string $userId, + string $httpMethod, + string $uri, + string $event, + ?array $eventFilter, + ?array $headers, + AuthMethod $authMethod, + #[\SensitiveParameter] + ?array $authData, + ): WebhookListener { + /* Remove any superfluous antislash */ + $event = ltrim($event, '\\'); + if (!class_exists($event) || !is_a($event, IWebhookCompatibleEvent::class, true)) { + throw new \UnexpectedValueException("$event is not an event class compatible with webhooks"); + } + $webhookListener = WebhookListener::fromParams( + [ + 'id' => $id, + 'appId' => $appId, + 'userId' => $userId, + 'httpMethod' => $httpMethod, + 'uri' => $uri, + 'event' => $event, + 'eventFilter' => $eventFilter ?? [], + 'headers' => $headers, + 'authMethod' => $authMethod->value, + ] + ); + $webhookListener->setAuthDataClear($authData); + $this->cache?->remove(self::EVENTS_CACHE_KEY); + return $this->update($webhookListener); + } + + /** + * @throws Exception + */ + public function deleteById(int $id): bool { + $qb = $this->db->getQueryBuilder(); + + $qb->delete($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); + + return ($qb->executeStatement() > 0); + } + + /** + * @throws Exception + * @return list + */ + private function getAllConfiguredEventsFromDatabase(): array { + $qb = $this->db->getQueryBuilder(); + + $qb->selectDistinct('event') + ->from($this->getTableName()); + + $result = $qb->executeQuery(); + + $configuredEvents = []; + + while (($event = $result->fetchOne()) !== false) { + $configuredEvents[] = $event; + } + + return $configuredEvents; + } + + /** + * List all events with at least one webhook configured, with cache + * @throws Exception + * @return list + */ + public function getAllConfiguredEvents(): array { + $events = $this->cache?->get(self::EVENTS_CACHE_KEY); + if ($events !== null) { + return json_decode($events); + } + $events = $this->getAllConfiguredEventsFromDatabase(); + // cache for 5 minutes + $this->cache?->set(self::EVENTS_CACHE_KEY, json_encode($events), 300); + return $events; + } + + /** + * @throws Exception + */ + public function getByEvent(string $event): array { + $qb = $this->db->getQueryBuilder(); + + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('event', $qb->createNamedParameter($event, IQueryBuilder::PARAM_STR))); + + return $this->findEntities($qb); + } +} diff --git a/apps/webhook_listeners/lib/Listener/WebhooksEventListener.php b/apps/webhook_listeners/lib/Listener/WebhooksEventListener.php new file mode 100644 index 0000000000000..5ea4d531c9f0e --- /dev/null +++ b/apps/webhook_listeners/lib/Listener/WebhooksEventListener.php @@ -0,0 +1,71 @@ + + */ +class WebhooksEventListener implements IEventListener { + public function __construct( + private WebhookListenerMapper $mapper, + private IJobList $jobList, + private LoggerInterface $logger, + private IUserSession $userSession, + ) { + } + + public function handle(Event $event): void { + $webhookListeners = $this->mapper->getByEvent($event::class); + $user = $this->userSession->getUser(); + + foreach ($webhookListeners as $webhookListener) { + // TODO add group membership to be able to filter on it + $data = [ + 'event' => $this->serializeEvent($event), + 'user' => (is_null($user) ? null : JsonSerializer::serializeUser($user)), + 'time' => time(), + ]; + if ($this->filterMatch($webhookListener->getEventFilter(), $data)) { + $this->jobList->add( + WebhookCall::class, + [ + $data, + $webhookListener->getId(), + ] + ); + } + } + } + + private function serializeEvent(IWebhookCompatibleEvent $event): array { + $data = $event->getWebhookSerializable(); + $data['class'] = $event::class; + return $data; + } + + private function filterMatch(array $filter, array $data): bool { + if ($filter === []) { + return true; + } + return PHPMongoQuery::executeQuery($filter, $data); + } +} diff --git a/apps/webhook_listeners/lib/Migration/Version1000Date20240527153425.php b/apps/webhook_listeners/lib/Migration/Version1000Date20240527153425.php new file mode 100755 index 0000000000000..44f2476dd44c5 --- /dev/null +++ b/apps/webhook_listeners/lib/Migration/Version1000Date20240527153425.php @@ -0,0 +1,72 @@ +hasTable(WebhookListenerMapper::TABLE_NAME)) { + $table = $schema->createTable(WebhookListenerMapper::TABLE_NAME); + $table->addColumn('id', Types::BIGINT, [ + 'autoincrement' => true, + 'notnull' => true, + 'length' => 4, + ]); + $table->addColumn('app_id', Types::STRING, [ + 'notnull' => false, + 'length' => 64, + ]); + $table->addColumn('user_id', Types::STRING, [ + 'notnull' => true, + 'length' => 64, + ]); + $table->addColumn('http_method', Types::STRING, [ + 'notnull' => true, + 'length' => 32, + ]); + $table->addColumn('uri', Types::STRING, [ + 'notnull' => true, + 'length' => 4000, + ]); + $table->addColumn('event', Types::TEXT, [ + 'notnull' => true, + ]); + $table->addColumn('event_filter', Types::TEXT, [ + 'notnull' => false, + ]); + $table->addColumn('headers', Types::TEXT, [ + 'notnull' => false, + ]); + $table->addColumn('auth_method', Types::STRING, [ + 'notnull' => true, + 'length' => 16, + 'default' => '', + ]); + $table->addColumn('auth_data', Types::TEXT, [ + 'notnull' => false, + ]); + $table->setPrimaryKey(['id']); + return $schema; + } + return null; + } +} diff --git a/apps/webhook_listeners/lib/ResponseDefinitions.php b/apps/webhook_listeners/lib/ResponseDefinitions.php new file mode 100644 index 0000000000000..cb33f93e8ffda --- /dev/null +++ b/apps/webhook_listeners/lib/ResponseDefinitions.php @@ -0,0 +1,26 @@ +, + * headers?: array, + * authMethod: string, + * authData?: array, + * } + */ +class ResponseDefinitions { +} diff --git a/apps/webhook_listeners/lib/Service/PHPMongoQuery.php b/apps/webhook_listeners/lib/Service/PHPMongoQuery.php new file mode 100644 index 0000000000000..e8e52615008b3 --- /dev/null +++ b/apps/webhook_listeners/lib/Service/PHPMongoQuery.php @@ -0,0 +1,340 @@ +debug('executeQuery called', ['query' => $query, 'document' => $document, 'options' => $options]); + } + + if(!is_array($query)) { + return (bool)$query; + } + + return self::_executeQuery($query, $document, $options); + } + + /** + * Internal execute query + * + * This expects an array from the query and has an additional logical operator (for the root query object the logical operator is always $and so this is not required) + * + * @throws Exception + */ + private static function _executeQuery(array $query, array &$document, array $options = [], string $logicalOperator = '$and'): bool { + if($logicalOperator !== '$and' && (!count($query) || !isset($query[0]))) { + throw new Exception($logicalOperator.' requires nonempty array'); + } + if($options['_debug'] && $options['_shouldLog']) { + $options['logger']->debug('_executeQuery called', ['query' => $query, 'document' => $document, 'logicalOperator' => $logicalOperator]); + } + + // for the purpose of querying documents, we are going to specify that an indexed array is an array which + // only contains numeric keys, is sequential, the first key is zero, and not empty. This will allow us + // to detect an array of key->vals that have numeric IDs vs an array of queries (where keys were not specified) + $queryIsIndexedArray = !empty($query) && array_is_list($query); + + foreach($query as $k => $q) { + $pass = true; + if(is_string($k) && substr($k, 0, 1) === '$') { + // key is an operator at this level, except $not, which can be at any level + if($k === '$not') { + $pass = !self::_executeQuery($q, $document, $options); + } else { + $pass = self::_executeQuery($q, $document, $options, $k); + } + } elseif($logicalOperator === '$and') { // special case for $and + if($queryIsIndexedArray) { // $q is an array of query objects + $pass = self::_executeQuery($q, $document, $options); + } elseif(is_array($q)) { // query is array, run all queries on field. All queries must match. e.g { 'age': { $gt: 24, $lt: 52 } } + $pass = self::_executeQueryOnElement($q, $k, $document, $options); + } else { + // key value means equality + $pass = self::_executeOperatorOnElement('$e', $q, $k, $document, $options); + } + } else { // $q is array of query objects e.g '$or' => [{'fullName' => 'Nick'}] + $pass = self::_executeQuery($q, $document, $options, '$and'); + } + switch($logicalOperator) { + case '$and': // if any fail, query fails + if(!$pass) { + return false; + } + break; + case '$or': // if one succeeds, query succeeds + if($pass) { + return true; + } + break; + case '$nor': // if one succeeds, query fails + if($pass) { + return false; + } + break; + default: + if($options['_shouldLog']) { + $options['logger']->warning('_executeQuery could not find logical operator', ['query' => $query, 'document' => $document, 'logicalOperator' => $logicalOperator]); + } + return false; + } + } + switch($logicalOperator) { + case '$and': // all succeeded, query succeeds + return true; + case '$or': // all failed, query fails + return false; + case '$nor': // all failed, query succeeded + return true; + default: + if($options['_shouldLog']) { + $options['logger']->warning('_executeQuery could not find logical operator', ['query' => $query, 'document' => $document, 'logicalOperator' => $logicalOperator]); + } + return false; + } + } + + /** + * Execute a query object on an element + * + * @throws Exception + */ + private static function _executeQueryOnElement(array $query, string $element, array &$document, array $options = []): bool { + if($options['_debug'] && $options['_shouldLog']) { + $options['logger']->debug('_executeQueryOnElement called', ['query' => $query, 'element' => $element, 'document' => $document]); + } + // iterate through query operators + foreach($query as $op => $opVal) { + if(!self::_executeOperatorOnElement($op, $opVal, $element, $document, $options)) { + return false; + } + } + return true; + } + + /** + * Check if an operator is equal to a value + * + * Equality includes direct equality, regular expression match, and checking if the operator value is one of the values in an array value + * + * @param mixed $v + * @param mixed $operatorValue + */ + private static function _isEqual($v, $operatorValue): bool { + if (is_array($v) && is_array($operatorValue)) { + return $v == $operatorValue; + } + if(is_array($v)) { + return in_array($operatorValue, $v); + } + if(is_string($operatorValue) && preg_match('/^\/(.*?)\/([a-z]*)$/i', $operatorValue, $matches)) { + return (bool)preg_match('/'.$matches[1].'/'.$matches[2], $v); + } + return $operatorValue === $v; + } + + /** + * Execute a Mongo Operator on an element + * + * @param string $operator The operator to perform + * @param mixed $operatorValue The value to provide the operator + * @param string $element The target element. Can be an object path eg price.shoes + * @param array $document The document in which to find the element + * @param array $options Options + * @throws Exception Exceptions on invalid operators, invalid unknown operator callback, and invalid operator values + */ + private static function _executeOperatorOnElement(string $operator, $operatorValue, string $element, array &$document, array $options = []): bool { + if($options['_debug'] && $options['_shouldLog']) { + $options['logger']->debug('_executeOperatorOnElement called', ['operator' => $operator, 'operatorValue' => $operatorValue, 'element' => $element, 'document' => $document]); + } + + if($operator === '$not') { + return !self::_executeQueryOnElement($operatorValue, $element, $document, $options); + } + + $elementSpecifier = explode('.', $element); + $v = & $document; + $exists = true; + foreach($elementSpecifier as $index => $es) { + if(empty($v)) { + $exists = false; + break; + } + if(isset($v[0])) { + // value from document is an array, so we need to iterate through array and test the query on all elements of the array + // if any elements match, then return true + $newSpecifier = implode('.', array_slice($elementSpecifier, $index)); + foreach($v as $item) { + if(self::_executeOperatorOnElement($operator, $operatorValue, $newSpecifier, $item, $options)) { + return true; + } + } + return false; + } + if(isset($v[$es])) { + $v = & $v[$es]; + } else { + $exists = false; + break; + } + } + + switch($operator) { + case '$all': + if(!$exists) { + return false; + } + if(!is_array($operatorValue)) { + throw new Exception('$all requires array'); + } + if(count($operatorValue) === 0) { + return false; + } + if(!is_array($v)) { + if(count($operatorValue) === 1) { + return $v === $operatorValue[0]; + } + return false; + } + return count(array_intersect($v, $operatorValue)) === count($operatorValue); + case '$e': + if(!$exists) { + return false; + } + return self::_isEqual($v, $operatorValue); + case '$in': + if(!$exists) { + return false; + } + if(!is_array($operatorValue)) { + throw new Exception('$in requires array'); + } + if(count($operatorValue) === 0) { + return false; + } + if(is_array($v)) { + return count(array_intersect($v, $operatorValue)) > 0; + } + return in_array($v, $operatorValue); + case '$lt': return $exists && $v < $operatorValue; + case '$lte': return $exists && $v <= $operatorValue; + case '$gt': return $exists && $v > $operatorValue; + case '$gte': return $exists && $v >= $operatorValue; + case '$ne': return (!$exists && $operatorValue !== null) || ($exists && !self::_isEqual($v, $operatorValue)); + case '$nin': + if(!$exists) { + return true; + } + if(!is_array($operatorValue)) { + throw new Exception('$nin requires array'); + } + if(count($operatorValue) === 0) { + return true; + } + if(is_array($v)) { + return count(array_intersect($v, $operatorValue)) === 0; + } + return !in_array($v, $operatorValue); + + case '$exists': return ($operatorValue && $exists) || (!$operatorValue && !$exists); + case '$mod': + if(!$exists) { + return false; + } + if(!is_array($operatorValue)) { + throw new Exception('$mod requires array'); + } + if(count($operatorValue) !== 2) { + throw new Exception('$mod requires two parameters in array: divisor and remainder'); + } + return $v % $operatorValue[0] === $operatorValue[1]; + + default: + if(empty($options['unknownOperatorCallback']) || !is_callable($options['unknownOperatorCallback'])) { + throw new Exception('Operator '.$operator.' is unknown'); + } + + $res = call_user_func($options['unknownOperatorCallback'], $operator, $operatorValue, $element, $document); + if($res === null) { + throw new Exception('Operator '.$operator.' is unknown'); + } + if(!is_bool($res)) { + throw new Exception('Return value of unknownOperatorCallback must be boolean, actual value '.$res); + } + return $res; + } + throw new Exception('Didn\'t return in switch'); + } + + /** + * Get the fields this query depends on + * + * @param array query The query to analyse + * @return array An array of fields this query depends on + */ + public static function getDependentFields(array $query) { + $fields = []; + foreach($query as $k => $v) { + if(is_array($v)) { + $fields = array_merge($fields, static::getDependentFields($v)); + } + if(is_int($k) || $k[0] === '$') { + continue; + } + $fields[] = $k; + } + return array_unique($fields); + } +} diff --git a/apps/webhook_listeners/lib/Settings/Admin.php b/apps/webhook_listeners/lib/Settings/Admin.php new file mode 100644 index 0000000000000..5ef7656ca3e5e --- /dev/null +++ b/apps/webhook_listeners/lib/Settings/Admin.php @@ -0,0 +1,62 @@ + */ class($this->appName, '') extends TemplateResponse { + public function render(): string { + return ''; + } + }; + } + + public function getSection(): ?string { + return 'admindelegation'; + } + + /** + * @return int whether the form should be rather on the top or bottom of + * the admin section. The forms are arranged in ascending order of the + * priority values. It is required to return a value between 0 and 100. + * + * E.g.: 70 + */ + public function getPriority(): int { + return 0; + } + + public function getName(): string { + return $this->l10n->t('Webhooks'); + } + + public function getAuthorizedAppConfig(): array { + return []; + } +} diff --git a/apps/webhook_listeners/openapi.json b/apps/webhook_listeners/openapi.json new file mode 100644 index 0000000000000..8488ce8e11758 --- /dev/null +++ b/apps/webhook_listeners/openapi.json @@ -0,0 +1,767 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "webhook_listeners", + "version": "0.0.1", + "description": "Nextcloud webhook support", + "license": { + "name": "agpl" + } + }, + "components": { + "securitySchemes": { + "basic_auth": { + "type": "http", + "scheme": "basic" + }, + "bearer_auth": { + "type": "http", + "scheme": "bearer" + } + }, + "schemas": { + "OCSMeta": { + "type": "object", + "required": [ + "status", + "statuscode" + ], + "properties": { + "status": { + "type": "string" + }, + "statuscode": { + "type": "integer" + }, + "message": { + "type": "string" + }, + "totalitems": { + "type": "string" + }, + "itemsperpage": { + "type": "string" + } + } + }, + "WebhookInfo": { + "type": "object", + "required": [ + "id", + "userId", + "httpMethod", + "uri", + "authMethod" + ], + "properties": { + "id": { + "type": "string" + }, + "userId": { + "type": "string" + }, + "httpMethod": { + "type": "string" + }, + "uri": { + "type": "string" + }, + "event": { + "type": "string" + }, + "eventFilter": { + "type": "object", + "additionalProperties": { + "type": "object" + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "authMethod": { + "type": "string" + }, + "authData": { + "type": "object", + "additionalProperties": { + "type": "object" + } + } + } + } + } + }, + "paths": { + "/ocs/v2.php/apps/webhook_listeners/api/v1/webhooks": { + "get": { + "operationId": "webhooks-index", + "summary": "List registered webhooks", + "description": "This endpoint requires admin access", + "tags": [ + "webhooks" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Webhook registrations returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WebhookInfo" + } + } + } + } + } + } + } + } + } + } + }, + "post": { + "operationId": "webhooks-create", + "summary": "Register a new webhook", + "description": "This endpoint requires admin access", + "tags": [ + "webhooks" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "httpMethod", + "in": "query", + "description": "HTTP method to use to contact the webhook", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "uri", + "in": "query", + "description": "Webhook URI endpoint", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "event", + "in": "query", + "description": "Event class name to listen to", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "eventFilter", + "in": "query", + "description": "Mongo filter to apply to the serialized data to decide if firing", + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "headers", + "in": "query", + "description": "Array of headers to send", + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "authMethod", + "in": "query", + "description": "Authentication method to use", + "schema": { + "type": "string", + "nullable": true, + "enum": [ + "none", + "headers" + ] + } + }, + { + "name": "authData", + "in": "query", + "description": "Array of data for authentication", + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Webhook registration returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/WebhookInfo" + } + } + } + } + } + } + } + }, + "400": { + "description": "Bad request", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "403": { + "description": "Insufficient permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/webhook_listeners/api/v1/webhooks/{id}": { + "get": { + "operationId": "webhooks-show", + "summary": "Get details on a registered webhook", + "description": "This endpoint requires admin access", + "tags": [ + "webhooks" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "description": "id of the webhook", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Webhook registration returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/WebhookInfo" + } + } + } + } + } + } + } + }, + "404": { + "description": "Webhook not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + }, + "post": { + "operationId": "webhooks-update", + "summary": "Update an existing webhook registration", + "description": "This endpoint requires admin access", + "tags": [ + "webhooks" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "httpMethod", + "in": "query", + "description": "HTTP method to use to contact the webhook", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "uri", + "in": "query", + "description": "Webhook URI endpoint", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "event", + "in": "query", + "description": "Event class name to listen to", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "eventFilter", + "in": "query", + "description": "Mongo filter to apply to the serialized data to decide if firing", + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "headers", + "in": "query", + "description": "Array of headers to send", + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "authMethod", + "in": "query", + "description": "Authentication method to use", + "schema": { + "type": "string", + "nullable": true, + "enum": [ + "none", + "headers" + ] + } + }, + { + "name": "authData", + "in": "query", + "description": "Array of data for authentication", + "schema": { + "type": "string", + "nullable": true + } + }, + { + "name": "id", + "in": "path", + "description": "id of the webhook", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Webhook registration returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/WebhookInfo" + } + } + } + } + } + } + } + }, + "400": { + "description": "Bad request", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "403": { + "description": "Insufficient permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + }, + "delete": { + "operationId": "webhooks-destroy", + "summary": "Remove an existing webhook registration", + "description": "This endpoint requires admin access", + "tags": [ + "webhooks" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "description": "id of the webhook", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Boolean returned whether something was deleted FIXME", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "400": { + "description": "Bad request", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "403": { + "description": "Insufficient permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + } + }, + "tags": [] +} \ No newline at end of file diff --git a/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php b/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php new file mode 100644 index 0000000000000..b385cff1228f4 --- /dev/null +++ b/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php @@ -0,0 +1,103 @@ +connection = \OCP\Server::get(IDBConnection::class); + $this->cacheFactory = \OCP\Server::get(ICacheFactory::class); + $this->pruneTables(); + + $this->mapper = new WebhookListenerMapper( + $this->connection, + $this->cacheFactory, + ); + } + + protected function tearDown(): void { + $this->pruneTables(); + parent::tearDown(); + } + + protected function pruneTables() { + $query = $this->connection->getQueryBuilder(); + $query->delete(WebhookListenerMapper::TABLE_NAME)->executeStatement(); + } + + public function testInsertListenerWithNotSupportedEvent() { + $this->expectException(\UnexpectedValueException::class); + $listener1 = $this->mapper->addWebhookListener( + null, + 'bob', + 'POST', + 'https://webhook.example.com/endpoint', + UserCreatedEvent::class, + null, + null, + AuthMethod::None, + null, + ); + } + + public function testInsertListenerAndGetIt() { + $listener1 = $this->mapper->addWebhookListener( + null, + 'bob', + 'POST', + 'https://webhook.example.com/endpoint', + NodeWrittenEvent::class, + null, + null, + AuthMethod::None, + null, + ); + + $listener2 = $this->mapper->getById($listener1->getId()); + + $listener1->resetUpdatedFields(); + $this->assertEquals($listener1, $listener2); + } + + public function testInsertListenerAndGetItWithAuthData() { + $listener1 = $this->mapper->addWebhookListener( + null, + 'bob', + 'POST', + 'https://webhook.example.com/endpoint', + NodeWrittenEvent::class, + null, + null, + AuthMethod::Header, + ['secretHeader' => 'header'], + ); + + $listener2 = $this->mapper->getById($listener1->getId()); + + $listener1->resetUpdatedFields(); + $this->assertEquals($listener1, $listener2); + } +} diff --git a/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php b/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php new file mode 100644 index 0000000000000..071330a79e319 --- /dev/null +++ b/apps/webhook_listeners/tests/Service/PHPMongoQueryTest.php @@ -0,0 +1,47 @@ + [ + 'class' => NodeWrittenEvent::class, + 'node' => [ + 'id' => 23, + 'path' => '/tmp/file.txt', + ], + ], + 'user' => [ + 'uid' => 'bob', + ], + ]; + return [ + [[], [], true], + [[], $event, true], + [['event.class' => NodeWrittenEvent::class], $event, true], + [['event.class' => NodeWrittenEvent::class, 'user.uid' => 'bob'], $event, true], + [['event.node.path' => '/.txt$/'], $event, true], + [['event.node.id' => ['$gte' => 22]], $event, true], + [['event.class' => 'SomethingElse'], $event, false], + ]; + } + + /** + * @dataProvider dataExecuteQuery + */ + public function testExecuteQuery(array $query, array $document, bool $matches) { + $this->assertEquals($matches, PHPMongoQuery::executeQuery($query, $document)); + } +} diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 8e1408e121ef6..dbd9ebc66ab58 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -281,6 +281,8 @@ 'OCP\\EventDispatcher\\GenericEvent' => $baseDir . '/lib/public/EventDispatcher/GenericEvent.php', 'OCP\\EventDispatcher\\IEventDispatcher' => $baseDir . '/lib/public/EventDispatcher/IEventDispatcher.php', 'OCP\\EventDispatcher\\IEventListener' => $baseDir . '/lib/public/EventDispatcher/IEventListener.php', + 'OCP\\EventDispatcher\\IWebhookCompatibleEvent' => $baseDir . '/lib/public/EventDispatcher/IWebhookCompatibleEvent.php', + 'OCP\\EventDispatcher\\JsonSerializer' => $baseDir . '/lib/public/EventDispatcher/JsonSerializer.php', 'OCP\\Exceptions\\AbortedEventException' => $baseDir . '/lib/public/Exceptions/AbortedEventException.php', 'OCP\\Exceptions\\AppConfigException' => $baseDir . '/lib/public/Exceptions/AppConfigException.php', 'OCP\\Exceptions\\AppConfigIncorrectTypeException' => $baseDir . '/lib/public/Exceptions/AppConfigIncorrectTypeException.php', diff --git a/lib/composer/composer/autoload_psr4.php b/lib/composer/composer/autoload_psr4.php index 74e48cf69ae28..7bf40f7a6b581 100644 --- a/lib/composer/composer/autoload_psr4.php +++ b/lib/composer/composer/autoload_psr4.php @@ -9,5 +9,6 @@ 'OC\\Core\\' => array($baseDir . '/core'), 'OC\\' => array($baseDir . '/lib/private'), 'OCP\\' => array($baseDir . '/lib/public'), + 'Bamarni\\Composer\\Bin\\' => array($vendorDir . '/bamarni/composer-bin-plugin/src'), '' => array($baseDir . '/lib/private/legacy'), ); diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index d6939ae36ce8b..9f3b289cdfc5a 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -322,6 +322,8 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OCP\\EventDispatcher\\GenericEvent' => __DIR__ . '/../../..' . '/lib/public/EventDispatcher/GenericEvent.php', 'OCP\\EventDispatcher\\IEventDispatcher' => __DIR__ . '/../../..' . '/lib/public/EventDispatcher/IEventDispatcher.php', 'OCP\\EventDispatcher\\IEventListener' => __DIR__ . '/../../..' . '/lib/public/EventDispatcher/IEventListener.php', + 'OCP\\EventDispatcher\\IWebhookCompatibleEvent' => __DIR__ . '/../../..' . '/lib/public/EventDispatcher/IWebhookCompatibleEvent.php', + 'OCP\\EventDispatcher\\JsonSerializer' => __DIR__ . '/../../..' . '/lib/public/EventDispatcher/JsonSerializer.php', 'OCP\\Exceptions\\AbortedEventException' => __DIR__ . '/../../..' . '/lib/public/Exceptions/AbortedEventException.php', 'OCP\\Exceptions\\AppConfigException' => __DIR__ . '/../../..' . '/lib/public/Exceptions/AppConfigException.php', 'OCP\\Exceptions\\AppConfigIncorrectTypeException' => __DIR__ . '/../../..' . '/lib/public/Exceptions/AppConfigIncorrectTypeException.php', diff --git a/lib/public/EventDispatcher/IWebhookCompatibleEvent.php b/lib/public/EventDispatcher/IWebhookCompatibleEvent.php new file mode 100644 index 0000000000000..b13c35c187bbc --- /dev/null +++ b/lib/public/EventDispatcher/IWebhookCompatibleEvent.php @@ -0,0 +1,24 @@ + $node->getId(), + 'path' => $node->getPath(), + ]; + } + + /** + * @since 30.0.0 + */ + public static function serializeUser(IUser $user): array { + return [ + 'uid' => $user->getUID(), + 'displayName' => $user->getDisplayName(), + ]; + } +} diff --git a/lib/public/Files/Events/Node/AbstractNodeEvent.php b/lib/public/Files/Events/Node/AbstractNodeEvent.php index 1b290578ab940..64b0e3a3aa511 100644 --- a/lib/public/Files/Events/Node/AbstractNodeEvent.php +++ b/lib/public/Files/Events/Node/AbstractNodeEvent.php @@ -9,12 +9,14 @@ namespace OCP\Files\Events\Node; use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IWebhookCompatibleEvent; +use OCP\EventDispatcher\JsonSerializer; use OCP\Files\Node; /** * @since 20.0.0 */ -abstract class AbstractNodeEvent extends Event { +abstract class AbstractNodeEvent extends Event implements IWebhookCompatibleEvent { /** * @since 20.0.0 */ @@ -29,4 +31,13 @@ public function __construct( public function getNode(): Node { return $this->node; } + + /** + * @since 30.0.0 + */ + public function getWebhookSerializable(): array { + return [ + 'node' => JsonSerializer::serializeFileInfo($this->node), + ]; + } } diff --git a/lib/public/Files/Events/Node/AbstractNodesEvent.php b/lib/public/Files/Events/Node/AbstractNodesEvent.php index a5b058f18f55e..7941a9e596a80 100644 --- a/lib/public/Files/Events/Node/AbstractNodesEvent.php +++ b/lib/public/Files/Events/Node/AbstractNodesEvent.php @@ -9,12 +9,14 @@ namespace OCP\Files\Events\Node; use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IWebhookCompatibleEvent; +use OCP\EventDispatcher\JsonSerializer; use OCP\Files\Node; /** * @since 20.0.0 */ -abstract class AbstractNodesEvent extends Event { +abstract class AbstractNodesEvent extends Event implements IWebhookCompatibleEvent { /** * @since 20.0.0 */ @@ -37,4 +39,14 @@ public function getSource(): Node { public function getTarget(): Node { return $this->target; } + + /** + * @since 30.0.0 + */ + public function getWebhookSerializable(): array { + return [ + 'source' => JsonSerializer::serializeFileInfo($this->source), + 'target' => JsonSerializer::serializeFileInfo($this->target), + ]; + } } diff --git a/psalm.xml b/psalm.xml index 2f1e226b5cf7a..f2aed4b382b2e 100644 --- a/psalm.xml +++ b/psalm.xml @@ -45,6 +45,7 @@ + diff --git a/tests/enable_all.php b/tests/enable_all.php index b95f00f767e65..db01de6ec4110 100644 --- a/tests/enable_all.php +++ b/tests/enable_all.php @@ -24,3 +24,4 @@ function enableApp($app) { enableApp('federation'); enableApp('federatedfilesharing'); enableApp('admin_audit'); +enableApp('webhook_listeners');