Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IOPAB-73: Fix AssetBuilder not able to validate asset digest #100

Merged
merged 1 commit into from
Apr 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
IOPAB-73: Fix AssetBuilder not able to validate asset digest
Included in CiviCRM 5.58.0
PR: civicrm#25305
  • Loading branch information
olayiwola-compucorp committed Apr 12, 2023
commit 8050e9049d4594c9326824baffd6190751fbe093
58 changes: 11 additions & 47 deletions Civi/Core/AssetBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
/**
* Class AssetBuilder
* @package Civi\Core
* @service asset_builder
*
* The AssetBuilder is used to manage semi-dynamic assets.
* In normal production use, these assets are built on first
Expand Down Expand Up @@ -70,7 +71,7 @@
* secure it (e.g. alternative digest() calculations), but the
* current implementation is KISS.
*/
class AssetBuilder {
class AssetBuilder extends \Civi\Core\Service\AutoService {

/**
* @return array
Expand Down Expand Up @@ -137,9 +138,14 @@ public function getUrl($name, $params = []) {
}
else {
return \CRM_Utils_System::url('civicrm/asset/builder', [
// The 'an' and 'ad' provide hints for cache lifespan and debugging/inspection.
'an' => $name,
'ap' => $this->encode($params),
'ad' => $this->digest($name, $params),
'aj' => \Civi::service('crypto.jwt')->encode([
'asset' => [$name, $params],
'exp' => 86400 * (floor(\CRM_Utils_Time::time() / 86400) + 2),
// Caching-friendly TTL -- We want the URL to be stable for a decent amount of time.
], ['SIGN', 'WEAK_SIGN']),
], TRUE, NULL, FALSE);
}
}
Expand Down Expand Up @@ -280,7 +286,6 @@ protected function getCacheUrl($fileName = NULL) {
* @return string
*/
protected function digest($name, $params) {
// WISHLIST: For secure digest, generate+persist privatekey & call hash_hmac.
ksort($params);
$digest = md5(
$name .
Expand All @@ -291,40 +296,6 @@ protected function digest($name, $params) {
return $digest;
}

/**
* Encode $params in a format that's optimized for shorter URLs.
*
* @param array $params
* @return string
*/
protected function encode($params) {
if (empty($params)) {
return '';
}

$str = json_encode($params);
if (function_exists('gzdeflate')) {
$str = gzdeflate($str);
}
return base64_encode($str);
}

/**
* @param string $str
* @return array
*/
protected function decode($str) {
if ($str === NULL || $str === FALSE || $str === '') {
return [];
}

$str = base64_decode($str);
if (function_exists('gzdeflate')) {
$str = gzinflate($str);
}
return json_decode($str, TRUE);
}

/**
* @return bool
*/
Expand Down Expand Up @@ -371,16 +342,9 @@ public static function pageRender($get) {
/** @var Assetbuilder $assets */
$assets = \Civi::service('asset_builder');

$expectDigest = $assets->digest($get['an'], $assets->decode($get['ap']));
if ($expectDigest !== $get['ad']) {
return [
'statusCode' => 500,
'mimeType' => 'text/plain',
'content' => 'Invalid digest',
];
}

return $assets->render($get['an'], $assets->decode($get['ap']));
$obj = \Civi::service('crypto.jwt')->decode($get['aj'], ['SIGN', 'WEAK_SIGN']);
$arr = json_decode(json_encode($obj), TRUE);
return $assets->render($arr['asset'][0], $arr['asset'][1]);
}
catch (UnknownAssetException $e) {
return [
Expand Down
25 changes: 25 additions & 0 deletions Civi/Core/Compiler/AutoServiceScannerPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Civi\Core\Compiler;

use Civi\Core\ClassScanner;
use Civi\Core\Service\AutoServiceInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* Scan the source-tree for implementations of `AutoServiceInterface`. Load them.
*
* Note: This will scan the core codebase as well as active extensions. For fully automatic
* support in an extension, the extension must enable the mixin `scan-classes@1`.
*/
class AutoServiceScannerPass implements CompilerPassInterface {

public function process(ContainerBuilder $container) {
$autoServices = ClassScanner::get(['interface' => AutoServiceInterface::class]);
foreach ($autoServices as $autoService) {
$autoService::buildContainer($container);
}
}

}
3 changes: 3 additions & 0 deletions Civi/Core/Container.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
<?php
namespace Civi\Core;

use Civi\Core\Compiler\AutoServiceScannerPass;
use Civi\Core\Event\EventScanner;
use Civi\Core\Lock\LockManager;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;

Expand Down Expand Up @@ -96,6 +98,7 @@ public function createContainer() {
//$container->set(self::SELF, $this);

$container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
$container->addCompilerPass(new AutoServiceScannerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1000);

$container->setDefinition(self::SELF, new Definition(
'Civi\Core\Container',
Expand Down
199 changes: 199 additions & 0 deletions Civi/Core/Service/AutoDefinition.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
<?php

namespace Civi\Core\Service;

use Civi\Api4\Service\Spec\Provider\Generic\SpecProviderInterface;
use Civi\Api4\Utils\ReflectionUtils;
use Civi\Core\HookInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AutoDefinition {

/**
* Identify any/all service-definitions for the given class.
*
* If the class defines any static factory methods, then there may be multiple definitions.
*
* @param string $className
* The name of the class to scan. Look for `@inject` and `@service` annotations.
* @return \Symfony\Component\DependencyInjection\Definition[]
* Ex: ['my.service' => new Definition('My\Class')]
*/
public static function scan(string $className): array {
$class = new \ReflectionClass($className);
$result = [];

$classDoc = ReflectionUtils::parseDocBlock($class->getDocComment());
if (!empty($classDoc['service'])) {
$serviceName = static::pickName($classDoc, $class->getName());
$def = static::createBaseline($class, $classDoc);
self::applyConstructor($def, $class);
$result[$serviceName] = $def;
}

foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_STATIC) as $method) {
/** @var \ReflectionMethod $method */
$methodDoc = ReflectionUtils::parseDocBlock($method->getDocComment());
if (!empty($methodDoc['service'])) {
$serviceName = static::pickName($methodDoc, $class->getName() . '::' . $method->getName());
$returnClass = isset($methodDoc['return'][0]) ? new \ReflectionClass($methodDoc['return'][0]) : $class;
$def = static::createBaseline($returnClass, $methodDoc);
$def->setFactory($class->getName() . '::' . $method->getName());
$def->setArguments(static::toReferences($methodDoc['inject'] ?? ''));
$result[$serviceName] = $def;
}
}

if (count($result) === 0) {
error_log("WARNING: Class {$class->getName()} was expected to have a service definition, but it did not. Perhaps it needs service name.");
}

return $result;
}

/**
* Create a basic definition for an unnamed service.
*
* @param string $className
* The name of the class to scan. Look for `@inject` and `@service` annotations.
* @return \Symfony\Component\DependencyInjection\Definition
*/
public static function create(string $className): Definition {
$class = new \ReflectionClass($className);
$classDoc = ReflectionUtils::parseDocBlock($class->getDocComment());
$def = static::createBaseline($class, $classDoc);
static::applyConstructor($def, $class);
return $def;
}

protected static function pickName(array $docBlock, string $internalDefault): string {
if (is_string($docBlock['service'])) {
return $docBlock['service'];
}
if (!empty($docBlock['internal']) && $internalDefault) {
return $internalDefault;
}
throw new \RuntimeException("Error: Failed to determine service name ($internalDefault). Please specify '@service NAME' or '@internal'.");
}

protected static function createBaseline(\ReflectionClass $class, ?array $docBlock = []): Definition {
$class = is_string($class) ? new \ReflectionClass($class) : $class;
$def = new Definition($class->getName());
$def->setPublic(TRUE);
self::applyTags($def, $class, $docBlock);
self::applyObjectProperties($def, $class);
self::applyObjectMethods($def, $class);
return $def;
}

protected static function toReferences(string $injectExpr): array {
return array_map(
function (string $part) {
return new Reference($part);
},
static::splitSymbols($injectExpr)
);
}

protected static function splitSymbols(string $expr): array {
if ($expr === '') {
return [];
}
$extraTags = explode(',', $expr);
return array_map('trim', $extraTags);
}

/**
* @param \Symfony\Component\DependencyInjection\Definition $def
* @param \ReflectionClass $class
* @param array $docBlock
*/
protected static function applyTags(Definition $def, \ReflectionClass $class, array $docBlock): void {
if (!empty($docBlock['internal'])) {
$def->addTag('internal');
}
if ($class->implementsInterface(HookInterface::class) || $class->implementsInterface(EventSubscriberInterface::class)) {
$def->addTag('event_subscriber');
}
if ($class->implementsInterface(SpecProviderInterface::class)) {
$def->addTag('spec_provider');
}

if (!empty($classDoc['serviceTags'])) {
foreach (static::splitSymbols($classDoc['serviceTags']) as $extraTag) {
$def->addTag($extraTag);
}
}
}

/**
* @param \Symfony\Component\DependencyInjection\Definition $def
* @param \ReflectionClass $class
*/
protected static function applyConstructor(Definition $def, \ReflectionClass $class): void {
if ($construct = $class->getConstructor()) {
$constructAnno = ReflectionUtils::parseDocBlock($construct->getDocComment() ?? '');
if (!empty($constructAnno['inject'])) {
$def->setArguments(static::toReferences($constructAnno['inject']));
}
}
}

/**
* Scan for any methods with `@inject`. They should be invoked via `$def->addMethodCall()`.
*
* @param \Symfony\Component\DependencyInjection\Definition $def
* @param \ReflectionClass $class
*/
protected static function applyObjectMethods(Definition $def, \ReflectionClass $class): void {
foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
/** @var \ReflectionMethod $method */
if ($method->isStatic()) {
continue;
}

$anno = ReflectionUtils::parseDocBlock($method->getDocComment());
if (!empty($anno['inject'])) {
$def->addMethodCall($method->getName(), static::toReferences($anno['inject']));
}
}
}

/**
* Scan for any properties with `@inject`. They should be configured via `$def->setProperty()`
* or via `injectPrivateProperty()`.
*
* @param \Symfony\Component\DependencyInjection\Definition $def
* @param \ReflectionClass $class
* @throws \Exception
*/
protected static function applyObjectProperties(Definition $def, \ReflectionClass $class): void {
foreach ($class->getProperties() as $property) {
/** @var \ReflectionProperty $property */
if ($property->isStatic()) {
continue;
}

$propDoc = ReflectionUtils::getCodeDocs($property);
if (!empty($propDoc['inject'])) {
if ($propDoc['inject'] === TRUE) {
$propDoc['inject'] = $property->getName();
}
if ($property->isPublic()) {
$def->setProperty($property->getName(), new Reference($propDoc['inject']));
}
elseif ($class->hasMethod('injectPrivateProperty')) {
$def->addMethodCall('injectPrivateProperty', [$property->getName(), new Reference($propDoc['inject'])]);
}
else {
throw new \Exception(sprintf('Property %s::$%s is marked private. To inject services into private properties, you must implement method "injectPrivateProperty($key, $value)".',
$class->getName(), $property->getName()
));
}
}
}
}

}
41 changes: 41 additions & 0 deletions Civi/Core/Service/AutoService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
namespace Civi\Core\Service;

/**
* AutoService is a base-class for defining a service (in the service-container).
* Classes which extend AutoService will have these characteristics:
*
* - The class is scanned automatically (if you enable `scan-classes@1`).
* - The class is auto-registered as a service in Civi's container.
* - The service is given a default name (derived from the class name).
* - The service may subscribe to events (via `HookInterface` or `EventSubscriberInterface`).
*
* Additionally, the class will be scanned for various annotations:
*
* - Class annotations:
* - `@service <service.name>`: Customize the service name.
* - `@serviceTags <tag1,tag2>`: Declare additional tags for the service.
* - Property annotations
* - `@inject [<service.name>]`: Inject another service automatically (by assigning this property).
* If the '<service.name>' is blank, then it loads an eponymous service.
* - Method annotations
* - (TODO) `@inject <service.name>`: Inject another service automatically (by calling the setter-method).
*
* Note: Like other services in the container, AutoService cannot meaningfully subscribe to
* early/boot-critical events such as `hook_entityTypes` or `hook_container`. However, you may
* get a similar effect by customizing the `buildContainer()` method.
*/
abstract class AutoService implements AutoServiceInterface {

use AutoServiceTrait;

}
Loading