218 lines
11 KiB
PHP
218 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Database\Connection;
|
|
use LogicException;
|
|
|
|
/** Explicit host composition. Verification grants no application capability to an actor. */
|
|
final class StandaloneRuntime
|
|
{
|
|
public const FEATURES = ['capital-register', 'operational-orders', 'requisition-accounts', 'requisition-expiry',
|
|
'urgent-reviews', 'urgent-quotations', 'conflict-releases', 'private-audit', 'expense-allocations',
|
|
'agreement-order-limits', 'order-parts', 'import-tariffs', 'import-legal', 'import-dossier',
|
|
'import-bank-support', 'import-readiness', 'import-estimates', 'import-landed-costs', 'budget-distributions',
|
|
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle', 'finance-configuration'];
|
|
|
|
/** @var array{root:string,manifest:array<string,mixed>,paths:array<string,string>}|null */
|
|
private ?array $artifact = null;
|
|
|
|
/** @param array<string,mixed> $settings */
|
|
public function __construct(private readonly array $settings, private readonly StandaloneArtifact $verifier) {}
|
|
|
|
public function enabled(): bool
|
|
{
|
|
return ($this->settings['enabled'] ?? false) === true;
|
|
}
|
|
|
|
public function requested(string $feature): bool
|
|
{
|
|
return $this->enabled() && ($this->settings['features'][$feature] ?? false) === true;
|
|
}
|
|
|
|
public function syntheticOnly(): bool
|
|
{
|
|
$value = $this->enabled() ? ($this->settings['synthetic_only'] ?? true) : true;
|
|
if (! is_bool($value)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_DATA_CLASSIFICATION');
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
/** @return array<string,string>|null */
|
|
public function configure(Connection $db): ?array
|
|
{
|
|
if (! $this->enabled()) {
|
|
return null;
|
|
}
|
|
$this->assertInstallation($db);
|
|
StandaloneSchema::verify($db->getSchemaBuilder(), $this->settings['features'] ?? []);
|
|
|
|
return $this->artifact()['paths'];
|
|
}
|
|
|
|
/** Refuse a process that loaded an older package before selecting this composition. */
|
|
public function assertLoadedPackages(bool $allowMissing = false): void
|
|
{
|
|
$artifact = $this->artifact();
|
|
foreach ([...get_declared_classes(), ...get_declared_interfaces(), ...get_declared_traits()] as $class) {
|
|
if (! str_starts_with($class, 'Tempo\\Finance\\Budget\\') && ! str_starts_with($class, 'Tempo\\Purchasing\\')
|
|
&& ! str_starts_with($class, 'Tempo\\Finance\\Payables\\') && ! str_starts_with($class, 'Tempo\\Finance\\GeneralLedger\\')) {
|
|
continue;
|
|
}
|
|
$loaded = (new \ReflectionClass($class))->getFileName();
|
|
$root = realpath($artifact['root']);
|
|
if (! is_string($loaded) || $root === false || ! str_starts_with(realpath($loaded) ?: '', $root.DIRECTORY_SEPARATOR)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CLASS_LOCATION');
|
|
}
|
|
}
|
|
foreach ([
|
|
'Tempo\\Finance\\Budget\\BudgetControl' => 'budget-control/src/BudgetControl.php',
|
|
'Tempo\\Purchasing\\Internal\\InternalRequisitions' => 'purchasing/src/InternalRequisitions.php',
|
|
'Tempo\\Finance\\Payables\\Payables' => 'payables/src/Payables.php',
|
|
'Tempo\\Finance\\GeneralLedger\\LedgerSchema' => 'general-ledger/src/LedgerSchema.php',
|
|
] as $class => $file) {
|
|
if (! class_exists($class, false)) {
|
|
if ($allowMissing) {
|
|
continue;
|
|
}
|
|
throw new LogicException('COMPRAS_RUNTIME_CLASS_MISSING');
|
|
}
|
|
$loaded = (new \ReflectionClass($class))->getFileName();
|
|
if (! is_string($loaded) || realpath($loaded) !== realpath($artifact['root'].'/'.$file)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CLASS_LOCATION');
|
|
}
|
|
}
|
|
if (! $allowMissing) {
|
|
if ($this->requested('finance-configuration')) {
|
|
$configuration = 'Tempo\\Finance\\GeneralLedger\\LedgerConfiguration';
|
|
if (! class_exists($configuration, false) || (new \ReflectionClass($configuration))->getConstant('VERSION') !== 'COMMON-FINANCE-CONFIGURATION-v1') {
|
|
throw new LogicException('COMPRAS_RUNTIME_FINANCE_CONFIGURATION');
|
|
}
|
|
}
|
|
if ($this->requested('supplier-settlements')) {
|
|
$settlements = new \ReflectionClass('Tempo\\Finance\\Payables\\SupplierSettlements');
|
|
$payables = new \ReflectionClass('Tempo\\Finance\\Payables\\Payables');
|
|
if (! $settlements->hasConstant('HOST_POLICY') || $settlements->getConstant('HOST_POLICY') !== 'COMMON-SUPPLIER-SETTLEMENT-v1'
|
|
|| ! $payables->hasMethod('hostSettlements')) {
|
|
throw new LogicException('COMPRAS_RUNTIME_SETTLEMENT_POLICY');
|
|
}
|
|
}
|
|
if ($this->requested('general-ledger')) {
|
|
$journal = new \ReflectionClass('Tempo\\Finance\\GeneralLedger\\PayableJournal');
|
|
if (! $journal->hasConstant('HOST_POLICY') || $journal->getConstant('HOST_POLICY') !== 'COMMON-PAYABLE-JOURNAL-v1'
|
|
|| ! in_array('hostPolicy', array_map(fn ($parameter) => $parameter->getName(), $journal->getConstructor()?->getParameters() ?? []), true)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_JOURNAL_POLICY');
|
|
}
|
|
if ($this->requested('general-ledger-cycle') && (! $journal->hasConstant('CONFIGURED_CORRECTIONS_VERSION')
|
|
|| $journal->getConstant('CONFIGURED_CORRECTIONS_VERSION') !== 'COMMON-LEDGER-CONFIGURED-CORRECTION-v1')) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CORRECTION_POLICY');
|
|
}
|
|
}
|
|
$budget = new \ReflectionClass('Tempo\\Finance\\Budget\\BudgetControl');
|
|
foreach ([
|
|
'budget-distributions' => ['DISTRIBUTIONS_VERSION', CommonBudget::DISTRIBUTIONS_CONTRACT, ['recordDistribution', 'consumeDistribution', 'amendDistribution']],
|
|
'order-parts' => ['ORDER_PARTS_VERSION', CommonBudget::ORDER_PARTS_CONTRACT, ['commitOrderParts', 'consumeOrderParts', 'cancelOrderParts']],
|
|
'import-landed-costs' => ['LANDED_COSTS_VERSION', CommonBudget::LANDED_COSTS_CONTRACT, ['reserveLandedCosts', 'transitionLandedCosts']],
|
|
'import-estimates' => ['IMPORT_ESTIMATE_VERSION', CommonBudget::IMPORT_ESTIMATE_CONTRACT, ['reserveImportEstimate', 'releaseImportEstimate']],
|
|
'requisition-expiry' => ['REQUISITION_CYCLES_VERSION', CommonBudget::REQUISITION_CYCLES_CONTRACT, ['beginRequisitionCycle', 'closeRequisitionCycle']],
|
|
] as $feature => [$constant, $contract, $methods]) {
|
|
if (! $this->requested($feature)) {
|
|
continue;
|
|
}
|
|
if (! $budget->hasConstant($constant) || $budget->getConstant($constant) !== $contract) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY_CONTRACT:'.$feature);
|
|
}
|
|
foreach ($methods as $method) {
|
|
if (! $budget->hasMethod($method)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY_METHOD:'.$feature);
|
|
}
|
|
}
|
|
}
|
|
if ($this->requested('requisition-expiry')) {
|
|
$purchasing = new \ReflectionClass('Tempo\\Purchasing\\Internal\\InternalRequisitions');
|
|
if (! $purchasing->hasMethod('supportsExpiryCycles') || $purchasing->getMethod('supportsExpiryCycles')->invoke(null) !== true) {
|
|
throw new LogicException('COMPRAS_RUNTIME_PURCHASING_CYCLES');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @return array{root:string,manifest:array<string,mixed>,paths:array<string,string>} */
|
|
public function artifact(): array
|
|
{
|
|
if ($this->artifact !== null) {
|
|
return $this->artifact;
|
|
}
|
|
$root = $this->settings['root'] ?? null;
|
|
$pin = $this->settings['manifest_sha256'] ?? null;
|
|
$id = $this->settings['installation_id'] ?? null;
|
|
if (! $this->enabled() || ! is_string($root) || ! is_string($pin) || ! is_string($id)
|
|
|| ! preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D', $id)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CONFIGURATION');
|
|
}
|
|
$artifact = $this->verifier->verify($root, $pin);
|
|
$this->syntheticOnly();
|
|
$features = $this->settings['features'] ?? [];
|
|
if (! is_array($features)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_FEATURES');
|
|
}
|
|
foreach ($features as $feature => $enabled) {
|
|
if (! is_string($feature) || ! in_array($feature, self::FEATURES, true) || ! is_bool($enabled)
|
|
|| ($enabled && ! in_array($feature, $artifact['manifest']['capabilities'], true))) {
|
|
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE');
|
|
}
|
|
}
|
|
|
|
return $this->artifact = $artifact;
|
|
}
|
|
|
|
/** No query when the composition is off; no schema creation or repair during a request. */
|
|
public function feature(string $feature, Connection $db): bool
|
|
{
|
|
if (! $this->requested($feature)) {
|
|
return false;
|
|
}
|
|
$this->assertInstallation($db);
|
|
|
|
return true;
|
|
}
|
|
|
|
public function assertInstallation(Connection $db): void
|
|
{
|
|
$this->artifact();
|
|
$binding = self::databaseBinding($db);
|
|
if (! $db->getSchemaBuilder()->hasTable('compras_runtime_installations')) {
|
|
throw new LogicException('COMPRAS_RUNTIME_INSTALLATION_MISSING');
|
|
}
|
|
$receipt = $db->table('compras_runtime_installations')->where('id', $this->settings['installation_id'])->first();
|
|
if ($receipt === null || $receipt->product !== 'compras' || $receipt->contract !== StandaloneArtifact::CONTRACT
|
|
|| ! hash_equals($this->settings['manifest_sha256'], (string) $receipt->manifest_sha256)
|
|
|| ! hash_equals($binding, (string) $receipt->database_binding_sha256)) {
|
|
throw new LogicException('COMPRAS_RUNTIME_INSTALLATION_MISMATCH');
|
|
}
|
|
}
|
|
|
|
/** Database and runtime role are bound explicitly, without an SGF or test naming convention. */
|
|
public static function databaseBinding(Connection $db): string
|
|
{
|
|
if ($db->getDriverName() !== 'pgsql') {
|
|
throw new LogicException('COMPRAS_RUNTIME_DATABASE_DRIVER');
|
|
}
|
|
$identity = $db->selectOne('SELECT current_database() AS database_name, current_user AS role_name,
|
|
(SELECT oid::text FROM pg_database WHERE datname=current_database()) AS database_oid,
|
|
inet_server_addr()::text AS server_address, inet_server_port() AS server_port,
|
|
CASE WHEN rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls THEN 1 ELSE 0 END AS elevated
|
|
FROM pg_roles WHERE rolname=current_user');
|
|
if ($identity === null || (int) $identity->elevated !== 0 || $identity->server_address === null || $identity->server_port === null) {
|
|
throw new LogicException('COMPRAS_RUNTIME_DATABASE_IDENTITY');
|
|
}
|
|
|
|
return hash('sha256', json_encode([
|
|
'product' => 'compras', 'database' => $identity->database_name, 'oid' => $identity->database_oid,
|
|
'role' => $identity->role_name, 'address' => $identity->server_address, 'port' => (int) $identity->server_port,
|
|
], JSON_THROW_ON_ERROR));
|
|
}
|
|
}
|