diff --git a/.github/workflows/local-profile.yml b/.github/workflows/local-profile.yml index 73d2d395..9ddee5c3 100644 --- a/.github/workflows/local-profile.yml +++ b/.github/workflows/local-profile.yml @@ -71,6 +71,7 @@ jobs: - run: php tests/local/admin-file-sync-profile.php - run: php tests/local/admin-file-writer.php timeout-minutes: 2 + - run: php tests/local/gateway-access-proposal.php - run: php -l local-bot.php supervision: if: github.event_name != 'workflow_dispatch' || !inputs.native_smoke @@ -98,6 +99,8 @@ jobs: timeout-minutes: 2 - run: php tests/local/access-file-sync.php vendor/autoload.php timeout-minutes: 2 + - run: php tests/local/gateway-access-integration.php vendor/autoload.php + timeout-minutes: 2 - run: php -d memory_limit=128M tests/local/access-admission.php vendor/autoload.php timeout-minutes: 2 - run: php tests/local/admin-verification-refresh.php vendor/autoload.php @@ -166,6 +169,7 @@ jobs: - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/admin-cache-sync.php vendor/autoload.php - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/admin-file-sync.php vendor/autoload.php - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/access-file-sync.php vendor/autoload.php + - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/gateway-access-integration.php vendor/autoload.php - run: php -d memory_limit=128M -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/access-admission.php vendor/autoload.php timeout-minutes: 2 - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/admin-verification-refresh.php vendor/autoload.php diff --git a/docs/gateway-access-proposals.md b/docs/gateway-access-proposals.md new file mode 100644 index 00000000..66303da9 --- /dev/null +++ b/docs/gateway-access-proposals.md @@ -0,0 +1,35 @@ +# Gateway access proposal mode (not an activation guide) + +This optional bot adapter submits the existing authenticated Verified-role +projection as one atomic approved/whitelist request. It does not grant +access, allocate a gateway revision, change bans, start a process, or send +a network command. An inbox receipt is **not** a receipt from the gateway. + +For a PortableProfile with one enabled server, use its existing +`region_group` and `follow_front_door: true` binding. When a matching +Civ13 host consumer exists, `access_file_sync.gateway_proposals: true` +selects the adapter; the existing access sync mode, target policies and +verified mapping requirements still apply. The server's canonical +approved/whitelist target paths are used for policy validation only. The +adapter does not read or write those text files or fall back to them. +In publish mode the bot skips its legacy regional approved copies for the +opted-in group. Preview does not submit a proposal and leaves legacy copying +unchanged. + +The destination is fixed: `/front-door/access-inbox/proposal.json`. +Operators must separate this inbox from the authoritative snapshot's directory +and restrict both using OS permissions: only the authorized bot instance may +replace proposals, only the gateway host may commit revisions, and neither +should accept data from a region or a public endpoint. The request contains +exactly `group`, `approved`, and `whitelist`; it deliberately contains no +bot-controlled revision or command/target names. An explicitly allowed empty +list is represented by a newline, not a missing or empty file. + +The bot requires both `gateway_verified_access` and +`gateway_verified_access_inbox` to be `true` in the bound group config. The +paired [Civ13 draft #7102](https://github.com/Civ13/Civ13/pull/7102) includes +an inbox consumer and access readers for Persistence and Barracks/Battle TDM +groups with a dedicated relay gateway. Keep the bot option disabled until the +matching host and region code and inbox permissions for the selected group have +been reviewed. Ban authority is handled separately. Local tests use synthetic +TDM and Persistence groups and do not exercise live authentication or admission. diff --git a/src/Civ13/AccessFileSync.php b/src/Civ13/AccessFileSync.php index b0146157..4064c583 100644 --- a/src/Civ13/AccessFileSync.php +++ b/src/Civ13/AccessFileSync.php @@ -3,6 +3,7 @@ namespace Civ13; use Civ13\Server\AccessListWriter; +use Civ13\Server\GatewayAccessProposal; use React\Promise\PromiseInterface; use function React\Promise\all; use function React\Promise\resolve; @@ -19,7 +20,7 @@ final class AccessFileSync private array $capturedRecords = []; private \Closure $clock; private \Closure $writer; - private ?AccessListWriter $publisher = null; + private AccessListWriter|GatewayAccessProposal|null $publisher = null; private array $preview = ['state' => 'unavailable']; private readonly array $settings; private readonly object $server; @@ -71,7 +72,14 @@ public static function validateConfiguration(array $settings, string $guildId, a throw new \InvalidArgumentException('Explicit separate Verified policy and server SQL destination required'); } } - new AccessListWriter($settings['targets'], $settings['max_bytes']); // Constructor is pure. + // Keep existing explicit target/empty policy validation; gateway mode never opens these legacy files. + new AccessListWriter($settings['targets'], $settings['max_bytes']); + if (array_key_exists('gateway_group_config', $settings)) { + $binding = GatewayAccessProposal::binding($settings['gateway_group_config']); + if (str_replace('\\', '/', $settings['server_basedir']) !== $binding['gateway']) { + throw new \InvalidArgumentException('Access sync must follow the dedicated gateway'); + } + } } public function lastPreview(): array @@ -110,7 +118,12 @@ private function __construct( $this->guildId=$app->civ13_guild_id; $this->roleIds=$app->role_ids; $this->clock=\Closure::fromCallable($clock ?? time(...)); - if ($settings['mode']==='publish' && $writer===null) { $this->publisher=new AccessListWriter($settings['targets'],$settings['max_bytes']); } + if ($settings['mode']==='publish' && $writer===null) { + $config = $settings['gateway_group_config'] ?? null; + $this->publisher = $config === null + ? new AccessListWriter($settings['targets'], $settings['max_bytes']) + : new GatewayAccessProposal($config, GatewayAccessProposal::binding($config), $settings['targets'], $settings['max_bytes']); + } $this->writer=\Closure::fromCallable($writer ?? $this->publisher ?? static fn (): array => ['state'=>'unchanged']); $this->coordinator=new AdminSyncCoordinator(true, function (): PromiseInterface { diff --git a/src/Civ13/Civ13.php b/src/Civ13/Civ13.php index 6cf3c785..6ecce4be 100644 --- a/src/Civ13/Civ13.php +++ b/src/Civ13/Civ13.php @@ -1010,7 +1010,8 @@ private function publishRegionApprovedLists(Verifier $verifier): void $directories = []; foreach ($this->enabled_gameservers as $gameserver) { $group = $gameserver->regionGroupFile(); - if ($group === '') { + if ($group === '' || (($this->options['access_file_sync']['mode'] ?? null) === 'publish' + && $group === ($this->options['access_file_sync']['gateway_group_config'] ?? null))) { continue; } $directories[] = rtrim(str_replace('\\', '/', $gameserver->basedir), '/'); diff --git a/src/Civ13/PortableProfile.php b/src/Civ13/PortableProfile.php index 4b1becea..f5c40648 100644 --- a/src/Civ13/PortableProfile.php +++ b/src/Civ13/PortableProfile.php @@ -208,12 +208,24 @@ private static function accessFileSyncOptions(array $profile, array $options): a // An unconfigured existing profile may boot; attach refuses before any listener/I/O. if (array_keys($settings) === ['enabled']) { return ['enabled' => true]; } $keys = array_keys($settings); sort($keys); - if ($keys !== ['debounce_seconds','enabled','max_bytes','mode','refresh_timeout_seconds','targets'] + if (!in_array($keys, [['debounce_seconds','enabled','max_bytes','mode','refresh_timeout_seconds','targets'], + ['debounce_seconds','enabled','gateway_proposals','max_bytes','mode','refresh_timeout_seconds','targets']], true) || ($options['verification_read_only'] ?? null) !== true || count($profile['servers'] ?? []) !== 1) { throw new \InvalidArgumentException('Explicit bounded read-only access synchronization required'); } $key = array_key_first($profile['servers']); $server = $profile['servers'][$key]; if (($server['enabled'] ?? null) !== true) { throw new \InvalidArgumentException('Access server must be explicitly enabled'); } + $gateway = $settings['gateway_proposals'] ?? false; + if (array_key_exists('gateway_proposals', $settings) && !is_bool($settings['gateway_proposals'])) { + throw new \InvalidArgumentException('Boolean gateway proposal flag required'); + } + unset($settings['gateway_proposals']); + if ($gateway) { + if (($server['follow_front_door'] ?? null) !== true || !is_string($server['region_group'] ?? null)) { + throw new \InvalidArgumentException('Gateway proposals require a followed shard group'); + } + $settings['gateway_group_config'] = $server['region_group']; + } $settings['server_key'] = $key; $settings['server_basedir'] = $server['basedir']; AccessFileSync::validateConfiguration($settings, $options['civ13_guild_id'] ?? '', $options['role_ids'] ?? [], $options['admin_file_sync']['enabled'] ?? false); return $settings; diff --git a/src/Civ13/Server/GatewayAccessProposal.php b/src/Civ13/Server/GatewayAccessProposal.php new file mode 100644 index 00000000..0e4f2143 --- /dev/null +++ b/src/Civ13/Server/GatewayAccessProposal.php @@ -0,0 +1,102 @@ + 'not_attempted']; + + public function __construct(private readonly string $config, private readonly array $binding, private readonly array $targets, private readonly int $maxBytes) {} + + public static function binding(string $config): array + { + if (!PortableProfile::absoluteAdminFile($config) || is_link($config) || !is_file($config)) { + throw new \InvalidArgumentException('Explicit local gateway group configuration required'); + } + $bytes = @file_get_contents($config, false, null, 0, 1_048_577); + $group = is_string($bytes) && strlen($bytes) <= 1_048_576 + ? json_decode(preg_replace('/^\xEF\xBB\xBF/', '', $bytes), true, 32) : null; + if (!is_array($group) || ($group['gateway_verified_access'] ?? null) !== true + || ($group['gateway_verified_access_inbox'] ?? null) !== true + || !is_string($group['group'] ?? null) || !preg_match('/^[a-z0-9_-]{1,32}$/D', $group['group']) + || !PortableProfile::absoluteAdminFile($group['root'] ?? null) + || !is_int($group['relay_port'] ?? null) || $group['relay_port'] < 1 || $group['relay_port'] > 65535 + || !is_string($group['gate'] ?? null) || !preg_match('/^[a-z0-9_-]{1,32}$/D', $group['gate']) + || !is_array($group['regions'] ?? null)) { + throw new \InvalidArgumentException('Gateway verified access must be enabled in the bound shard group'); + } + $gates = array_values(array_filter($group['regions'], static fn ($region): bool => is_array($region) && ($region['id'] ?? null) === $group['gate'])); + if (count($gates) !== 1 || ($gates[0]['kind'] ?? null) !== 'GATEWAY') { + throw new \InvalidArgumentException('Dedicated gateway required'); + } + $root = rtrim(str_replace('\\', '/', $group['root']), '/'); + $directory = $root.'/front-door/access-inbox'; + clearstatcache(true); + $resolved = realpath($directory); + if (!is_dir($directory) || $resolved === false || !self::samePath($directory, $resolved) + || is_link($directory) || is_link(dirname($directory))) { + throw new \InvalidArgumentException('Provision a protected local gateway access inbox first'); + } + return ['group' => $group['group'], 'directory' => $directory, 'gateway' => $root.'/'.$group['gate']]; + } + + private static function samePath(string $a, string $b): bool + { + $a = str_replace('\\', '/', $a); $b = str_replace('\\', '/', $b); + return PHP_OS_FAMILY === 'Windows' ? strcasecmp($a, $b) === 0 : $a === $b; + } + + public function lastReceipt(): array { return $this->receipt; } + + public function __invoke(string $wire, int $generation, callable $canCommit): array + { + $stage = null; + $stream = null; + try { + $data = AccessListProjection::decode($wire); + if ($data['unmapped_role_holders'] !== 0) { return $this->receipt = ['state' => 'blocked', 'reason' => 'unmapped-role-holders']; } + if ($generation < 0 || $canCommit() !== true) { return $this->receipt = ['state' => 'superseded']; } + foreach ($data['outputs'] as $kind => $content) { + if (strlen($content) > $this->maxBytes || ($content === "\n" && !$this->targets[$kind]['allow_empty'])) { + return $this->receipt = ['state' => 'blocked', 'reason' => 'output-policy']; + } + } + $payload = json_encode(['group' => $this->binding['group']] + $data['outputs'], JSON_THROW_ON_ERROR)."\n"; + if (strlen($payload) > self::MAX_WIRE || self::binding($this->config) !== $this->binding) { + return $this->receipt = ['state' => 'blocked', 'reason' => 'gateway-binding-or-budget']; + } + $dir = $this->binding['directory']; + $path = $dir.'/proposal.json'; + $candidate = $dir.'/.proposal-'.bin2hex(random_bytes(16)).'.tmp'; + $stream = @fopen($candidate, 'x+b'); + if ($stream === false) { throw new \RuntimeException('stage-open'); } + $stage = $candidate; + if (fwrite($stream, $payload) !== strlen($payload) || !fflush($stream) || !fsync($stream) || !rewind($stream) + || stream_get_contents($stream, self::MAX_WIRE + 1) !== $payload) { throw new \RuntimeException('stage-verify'); } + if (!fclose($stream)) { throw new \RuntimeException('stage-close'); } + $stream = null; + if ($canCommit() !== true) { return $this->receipt = ['state' => 'superseded']; } + // The guard may have observed a group reconfiguration; validate the + // protected binding and destination immediately before replacement. + clearstatcache(true, $path); + if (self::binding($this->config) !== $this->binding || is_link($path) || (file_exists($path) && !is_file($path))) { + return $this->receipt = ['state' => 'blocked', 'reason' => 'gateway-destination-changed']; + } + if (!@rename($stage, $path)) { throw new \RuntimeException('replace-refused'); } + $stage = null; + $this->receipt = ['state' => 'submitted']; + return ['state' => 'updated', 'stage' => 'gateway-inbox']; + } catch (\Throwable) { + return $this->receipt = ['state' => 'blocked', 'reason' => 'gateway-proposal-refused']; + } finally { + if (is_resource($stream)) { fclose($stream); } + if ($stage !== null) { @unlink($stage); } + } + } +} diff --git a/tests/local/gateway-access-integration.php b/tests/local/gateway-access-integration.php new file mode 100644 index 00000000..a39e4b82 --- /dev/null +++ b/tests/local/gateway-access-integration.php @@ -0,0 +1,87 @@ +setValue($this, true); } + public function hostedRecords(): array { return [['ss13'=>'legacytest','discord'=>'990000000000000001']]; } +} +function gatewayIntegrationRemove(string $path): void { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $item) { + $item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname()); + } + rmdir($path); +} +function gatewayLegacyOwner(array $settings, string $group, string $gateway, string $otherGroup, string $other): \Civ13\Civ13 { + $owner=(new ReflectionClass(\Civ13\Civ13::class))->newInstanceWithoutConstructor(); + $owner->verifier=new GatewayLegacyVerifier(); + $owner->logger=new \Psr\Log\NullLogger(); + $owner->options=['access_file_sync'=>$settings]; + $owner->enabled_gameservers=[ + new class($group,$gateway) { public function __construct(private string $group, public string $basedir) {} public function regionGroupFile(): string { return $this->group; } }, + new class($otherGroup,$other) { public function __construct(private string $group, public string $basedir) {} public function regionGroupFile(): string { return $this->group; } }, + ]; + return $owner; +} +$root=sys_get_temp_dir().'/bot-gateway-composition-'.bin2hex(random_bytes(8)); mkdir($root); $root=realpath($root); +$service=null; +try { + foreach (['gateway/SQL','first/SQL','front-door/access-inbox','front-door/SQL','other/SQL'] as $dir) { mkdir("$root/$dir",0700,true); } + $group=['group'=>'sample','root'=>$root,'relay_port'=>2714,'gate'=>'gateway','gateway_verified_access'=>true,'gateway_verified_access_inbox'=>true, + 'regions'=>[['id'=>'gateway','kind'=>'GATEWAY'],['id'=>'first','kind'=>'BATTLE']]]; + $groupFile="$root/group.json"; file_put_contents($groupFile,json_encode($group,JSON_THROW_ON_ERROR)); + $otherGroup="$root/other.json"; file_put_contents($otherGroup,json_encode(['root'=>$root,'regions'=>[['id'=>'other']]],JSON_THROW_ON_ERROR)); + [$app,$settings,$f,$unused]=fixture(); + foreach ($settings['targets'] as $kind=>&$target) { $target['path']="$root/gateway/SQL/$kind.txt"; } unset($target); + unset($settings['server_key'],$settings['server_basedir']); $settings['gateway_proposals']=true; + $server=['enabled'=>true,'basedir'=>"$root/first",'ip'=>'127.0.0.1','port'=>1714,'name'=>'Synthetic','host'=>'127.0.0.1', + 'region_group'=>$groupFile,'follow_front_door'=>true]; + foreach (['discussion','playercount','ooc','lobby','asay','ic','transit','adminlog','debug','garbage','runtime','attack'] as $field) { $server[$field]=''; } + $profile=['schema'=>'civilizationbot.portable.v1','root'=>$root,'env_file'=>"$root/unused-synthetic.env",'state_dir'=>$root,'gitdir'=>$root, + 'servers'=>['test1714'=>$server], 'http_port'=>1715, 'verification_source'=>['mode'=>'read-only','url'=>'https://civ13.com/verified'], + 'options'=>['civ13_guild_id'=>$app->civ13_guild_id,'role_ids'=>$app->role_ids,'channel_ids'=>[]], 'access_file_sync'=>$settings]; + $profileFile="$root/profile.json"; file_put_contents($profileFile,json_encode($profile,JSON_THROW_ON_ERROR)); + $loaded=\Civ13\PortableProfile::load($profileFile); + check($loaded['servers']['test1714']['basedir']==="$root/gateway", 'actual profile follows dedicated gateway'); + $options=\Civ13\PortableProfile::runtimeOptions($loaded); $mapped=$options['access_file_sync']; + check(($mapped['gateway_group_config'] ?? null)===$groupFile && $mapped['mode']==='publish', 'profile binds publisher to intended group'); + $app->enabled_gameservers['test1714']->basedir="$root/gateway"; $app->options=$options; + $legacy="$root/gateway/SQL/approved.txt"; $authority="$root/front-door/SQL/verified-access.json"; + file_put_contents($legacy,"legacy sentinel\n"); file_put_contents($authority,"authority sentinel\n"); + $service=\Civ13\AccessFileSync::attach($app,$mapped,null,fn()=>$f->now); fire($f); + $proposal="$root/front-door/access-inbox/proposal.json"; + $one=json_decode(file_get_contents($proposal),true,32,JSON_THROW_ON_ERROR); + check($one===['group'=>'sample','approved'=>"faketest=990000000000000001\n",'whitelist'=>"faketest=990000000000000001\n"], 'real composition publishes first complete scoped projection'); + $app->verifier->verified=[['ss13'=>'Second.Test','discord'=>'990000000000000001']]; $service->verificationChanged(); fire($f); + $two=json_decode(file_get_contents($proposal),true,32,JSON_THROW_ON_ERROR); + check($two===['group'=>'sample','approved'=>"secondtest=990000000000000001\n",'whitelist'=>"secondtest=990000000000000001\n"], 'real composition replaces prior projection on refresh'); + check(file_get_contents($legacy)==="legacy sentinel\n" && file_get_contents($authority)==="authority sentinel\n", 'publisher does not directly change legacy or authority files'); + $service->stop(); $service=null; + $group['gateway_verified_access_inbox']=false; file_put_contents($groupFile,json_encode($group,JSON_THROW_ON_ERROR)); + $refused=false; try { \Civ13\PortableProfile::load($profileFile); } catch (InvalidArgumentException) { $refused=true; } + check($refused && json_decode(file_get_contents($proposal),true,32,JSON_THROW_ON_ERROR)===$two, 'profile refuses disabled inbox and preserves existing proposal'); + $group['gateway_verified_access_inbox']=true; file_put_contents($groupFile,json_encode($group,JSON_THROW_ON_ERROR)); + + $first="$root/first/SQL/approved.txt"; $other="$root/other/SQL/approved.txt"; + foreach (['publish','preview','legacy','disabled'] as $mode) { + foreach ([$legacy,$first,$other] as $file) { file_put_contents($file,"old sentinel\n"); } + $route=match($mode) { + 'publish'=>['mode'=>'publish','gateway_group_config'=>$groupFile], + 'preview'=>['mode'=>'preview','gateway_group_config'=>$groupFile], + 'legacy'=>['mode'=>'publish'], + default=>['enabled'=>false], + }; + $owner=gatewayLegacyOwner($route,$groupFile,"$root/gateway",$otherGroup,"$root/other"); + $owner->hostedVerificationRefreshed($owner->verifier); + $expected="legacytest=990000000000000001\n"; + $groupExpected=$mode==='publish' ? "old sentinel\n" : $expected; + check(file_get_contents($legacy)===$groupExpected && file_get_contents($first)===$groupExpected, "$mode routing for opted group"); + check(file_get_contents($other)===$expected, "$mode preserves independent legacy group"); + } + echo "PASS ".($checks-$gatewayChecksStart)." gateway profile, real composition, repeat replacement and legacy routing controls\n"; +} finally { + $service?->stop(); + gatewayIntegrationRemove($root); +} diff --git a/tests/local/gateway-access-proposal.php b/tests/local/gateway-access-proposal.php new file mode 100644 index 00000000..32156e0c --- /dev/null +++ b/tests/local/gateway-access-proposal.php @@ -0,0 +1,78 @@ +['BARRACKS','BATTLE'], 'earth'=>['MAINLAND','CONTINENT']] as $group=>$kinds) { + $dir = "$root/$group/front-door/access-inbox"; + mkdir($dir,0700,true); + mkdir("$root/$group/front-door/SQL",0700,true); + mkdir("$root/$group/gateway/SQL",0700,true); + mkdir("$root/$group/first/SQL",0700,true); + $sentinels = ["$root/$group/front-door/SQL/verified-access.json", "$root/$group/gateway/SQL/approved.txt", "$root/$group/first/SQL/approved.txt"]; + foreach ($sentinels as $path) { file_put_contents($path, "unchanged sentinel\n"); } + $config = [ + 'group'=>$group, 'root'=>"$root/$group", 'relay_port'=>$group==='tdm' ? 2714 : 3714, + 'gate'=>'gateway', 'gateway_verified_access'=>true, 'gateway_verified_access_inbox'=>true, + 'regions'=>[['id'=>'gateway','kind'=>'GATEWAY'],['id'=>'first','kind'=>$kinds[0]],['id'=>'second','kind'=>$kinds[1]]], + ]; + $file = "$root/$group.json"; + foreach ([null, false] as $disabled) { + $invalid = $config; + if ($disabled === null) { unset($invalid['gateway_verified_access_inbox']); } + else { $invalid['gateway_verified_access_inbox'] = $disabled; } + file_put_contents($file,json_encode($invalid,JSON_THROW_ON_ERROR)); + try { GatewayAccessProposal::binding($file); throw new RuntimeException('Disabled inbox accepted'); } + catch (InvalidArgumentException) { } + } + file_put_contents($file,json_encode($config,JSON_THROW_ON_ERROR)); + $binding = GatewayAccessProposal::binding($file); + $writer = new GatewayAccessProposal($file,$binding,['approved'=>['allow_empty'=>true],'whitelist'=>['allow_empty'=>true]],4096); + $empty = json_encode(['outputs'=>['approved'=>"\n",'whitelist'=>"\n"],'unmapped_role_holders'=>0],JSON_THROW_ON_ERROR); + check(($writer($empty,1,static fn()=>true)['state'] ?? null)==='updated', 'complete pair submitted'); + check(json_decode(file_get_contents($dir.'/proposal.json'),true,32,JSON_THROW_ON_ERROR)===['group'=>$group,'approved'=>"\n",'whitelist'=>"\n"], 'exact empty pair and scope'); + $outputs = ['approved'=>"alpha=990000000000000001\n",'whitelist'=>"bravo=990000000000000002\n"]; + $fresh = json_encode(['outputs'=>$outputs,'unmapped_role_holders'=>0],JSON_THROW_ON_ERROR); + check(($writer($fresh,2,static fn()=>true)['state'] ?? null)==='updated', 'existing proposal replaced'); + $before = file_get_contents($dir.'/proposal.json'); + check(json_decode($before,true,32,JSON_THROW_ON_ERROR)===['group'=>$group]+$outputs, 'replacement retains complete pair and scope'); + check(($writer->lastReceipt()['state'] ?? null)==='submitted' && glob($dir.'/.proposal-*')===[], 'replacement receipt and stage cleanup'); + $calls=0; + check(($writer($empty,3,static function () use (&$calls): bool { return ++$calls===1; })['state'] ?? null)==='superseded', 'late generation fence'); + check(file_get_contents($dir.'/proposal.json')===$before && glob($dir.'/.proposal-*')===[], 'late refusal preserves prior pair and deletes stage'); + $calls=0; + $disabled=$config; $disabled['gateway_verified_access_inbox']=false; + $result=$writer($empty,4,static function () use (&$calls,$file,$disabled): bool { + if (++$calls===2) { file_put_contents($file,json_encode($disabled,JSON_THROW_ON_ERROR)); } + return true; + }); + check(($result['state'] ?? null)==='blocked', 'disabled inbox during final guard refused'); + check(file_get_contents($dir.'/proposal.json')===$before && glob($dir.'/.proposal-*')===[], 'disabled inbox preserves prior pair and removes stage'); + file_put_contents($file,json_encode($config,JSON_THROW_ON_ERROR)); + check(($writer(str_replace('":0','":1',$empty),5,static fn()=>true)['state'] ?? null)==='blocked', 'unmapped role holder refused'); + $wrong = $config; $wrong['group'] = $group === 'tdm' ? 'earth' : 'tdm'; + file_put_contents($file,json_encode($wrong,JSON_THROW_ON_ERROR)); + check(($writer($empty,6,static fn()=>true)['state'] ?? null)==='blocked', 'wrong group refused'); + check(file_get_contents($dir.'/proposal.json')===$before,'prior scoped pair preserved'); + foreach ($sentinels as $path) { check(file_get_contents($path)==="unchanged sentinel\n", 'no legacy or authority direct write'); } + } + echo "Gateway proposals: replacement and synthetic TDM/Persistence scope checks passed\n"; +} finally { deleteTree($root); }