Files

127 lines
10 KiB
PHP

<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$accounts = $method('accounts');
$as = static function (string $name) use ($module, $accounts): void {
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
throw new RuntimeException('Unknown fixture account');
};
$denied = static function (callable $call, string $reason): void {
try { $call(); throw new LogicException('Unexpected permission grant: ' . $reason); }
catch (NextFloorDenied $e) { check($e->getMessage() === $reason, 'Expected ' . $reason . ', got ' . $e->getMessage()); }
};
foreach ($accounts as $a) check($a['password'] !== $a['name'] . '-test-password' && password_verify($a['name'] . '-test-password', $a['password']), 'Passwords are hashed');
$form = $module->GetConfigurationForm();
check(!str_contains($form, 'password_hash') && !str_contains($form, '$2y$') && !str_contains($form, '$argon2'), 'Configuration never exposes password hashes');
check(str_contains($form, 'SelectObject') && str_contains($form, 'Büro 2'), 'Rights use actual plan and native object choices');
$as('empty');
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'An empty user sees no values');
$building = $method('visibleBuilding');
check(count($building['floors'][0]['rooms']) === 2 && count($building['floors'][0]['furniture']) === 1, 'All building geometry remains');
check($building['floors'][0]['rooms'][0]['climate_card'] === false && $building['floors'][0]['rooms'][1]['area_id'] === null, 'No live room binding leaks');
$denied(fn() => $method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]), 'admin_required');
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$as('reader');
$tree = $method('visibleTree', $method('objectTree'));
check(count($tree['variables']) === 9, 'Global readers see every variable and the schedule');
check(!in_array(888, array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'), true), 'All means the visualization, never unrelated Symcon variables');
check(!in_array(888, array_column($tree['objects'], 'object_id'), true), 'Users never receive unrelated native object branches');
foreach ($tree['variables'] as $v) check($v['attributes']['symcon_can_control'] === false, 'Every reader value is marked readonly');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
$as('office');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'Room control exposes its own native category and schedule only; links do not pull in private targets');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'cover.101']]); // alias uses the same native capability
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => ['light.101', 'light.201']]]), 'control_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.103']]), 'variable_readonly');
$method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.104']);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][1]['climate']['temperature'] === 'none', 'Foreign room climate is removed');
check($building['floors'][0]['placements'][1]['entity_id'] === 'none', 'Foreign placement link is removed even while its geometry stays');
$topology = $method('objectTree');
foreach ($topology['objects'] as &$node) if ($node['object_id'] === 103) $node['parent_id'] = 11;
unset($node);
$topology['objects'][] = ['object_id' => 11, 'parent_id' => 10, 'name' => 'Strom', 'path' => 'Gebäude / Büro 2 / Strom', 'object_type' => 0];
$as('office');
$withTopology = $method('visibleTree', $topology);
check(in_array(11, array_column($withTopology['objects'], 'object_id'), true), 'Utility discovery retains an authorized meter category');
check(!in_array(900, array_column($withTopology['objects'], 'object_id'), true), 'Unrelated instance branches remain private');
$as('device');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [102, 103], 'Single-device grant does not grant its whole room or native area');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][0]['climate_card'] === false, 'Device grant does not reveal room climate');
check(in_array('switch.102', $building['floors'][0]['rooms'][0]['panel'], true), 'Approved device is still reachable in its room under its actual native entity');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
// Shared variables and legacy bindings on a different item must not reappear outside the granted room.
$extended = fixtureBuilding();
$extended['floors'][0]['furniture'][] = ['id' => 'private', 'type' => 'wallbox', 'x' => 7, 'z' => 2, 'temp_entity2' => 'sensor.104', 'legacy_binding' => 'sensor.104', 'picture' => 'https://camera.invalid/live'];
$fixture['attributes']['Building'] = json_encode($extended);
$as('office'); $projected = $method('visibleBuilding')['floors'][0]['furniture'][1];
check($projected['temp_entity2'] === 'none' && $projected['legacy_binding'] === 'none' && !isset($projected['picture']), 'Unauthorized items never reuse otherwise approved values or live pictures');
$extended['floors'][0]['furniture'][0]['temp_entity2'] = 'sensor.104';
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
check($method('allowedEntity', 'sensor.104', false), 'Additional temperature bindings belong to an explicitly granted device');
$extended['floors'][0]['furniture'][0]['hydronic'] = ['status' => 'cover.104', 'circuits' => [['id' => 'c1', 'status' => 'cover.105']], 'stations' => [['id' => 's1', 'status' => 'cover.204']]];
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
foreach ([104, 105, 204] as $id) check($method('allowedEntity', 'sensor.' . $id, false), 'A granted device includes its plant, circuit and station status');
$as('empty');
$hiddenHydronic = $method('visibleBuilding')['floors'][0]['furniture'][0]['hydronic'];
check($hiddenHydronic['status'] === 'none' && $hiddenHydronic['circuits'][0]['status'] === 'none' && $hiddenHydronic['stations'][0]['status'] === 'none', 'Unauthorized hydronic statuses remain private');
$fixture['attributes']['Building'] = json_encode(fixtureBuilding());
$as('operator');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.201']]);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.888']), 'read_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.888']]), 'control_forbidden');
$as('native');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [201, 203], 'An explicit native instance grant follows its descendants, not its whole area');
$as('admin');
$method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]);
check(count($method('visibleTree', $method('objectTree'))['objects']) > 0, 'Admin retains the native editor tree');
check($method('visibleBuilding') === fixtureBuilding(), 'Admin project is unmodified');
ob_start(); $method('sendApiResult', ['payload' => str_repeat('x', 300000)], true); $manifest = json_decode((string) ob_get_clean(), true)['_nextfloor_transfer'];
$as('reader');
try { $method('readTransfer', $manifest['id'], 0); throw new LogicException('Cross-session transport read was accepted'); }
catch (RuntimeException $e) { check($e->getMessage() === 'transfer_not_found', 'Transfer ownership is enforced'); }
$method('releaseTransfer', $manifest['id']);
$as('admin');
check(strlen($method('readTransfer', $manifest['id'], 0)['data']) > 0, 'Another session cannot remove this snapshot');
$method('releaseTransfer', $manifest['id']);
$url = $module->OpenDesigner(); parse_str((string) parse_url(substr($url, 5), PHP_URL_QUERY), $query);
check(isset($query['ticket']) && !isset($query['token']), 'Console links use tickets, never a reusable admin token');
check($method('exchangeConsoleTicket', $query['ticket']), 'Console recovers admin access without an account');
check(!$method('exchangeConsoleTicket', $query['ticket']), 'Console tickets cannot be replayed');
check(!str_contains($module->GetVisualizationTile(), 'ticket=') && !str_contains($module->GetVisualizationTile(), 'token='), 'Tiles never embed admin capabilities');
// A saved rights/enable change and a native delete revoke a previously valid cookie.
$accountID = array_key_first(array_filter($accounts, static fn(array $a): bool => $a['name'] === 'officeview'));
$browserToken = str_repeat('b', 64);
$fixture['attributes']['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => $accountID, 'epoch' => $accounts[$accountID]['epoch'], 'csrf' => 'test', 'seen' => time(), 'expires' => time() + 3600]]);
$_COOKIE['NFSC_Session_12345'] = $browserToken;
check($method('resolveSession') !== null, 'Cookie starts valid');
$module->SaveAccessUser($accountID, 'officeview', 'user', false, false, false, '[]', '[]', '[]', '');
check($method('resolveSession') === null, 'Disabling or editing rights revokes the old cookie');
$module->DeleteAccessUser($accountID);
check(!isset($method('accounts')[$accountID]) && $method('resolveSession') === null, 'Deletion removes the account and its access');
echo "OK: hashed accounts, console recovery, one-use tickets, admin/reader/room/device scopes, alias-resistant access, private state and geometry separation, bulk preauthorization, archive guards and native readonly variables\n";