Skip to content
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
4 changes: 4 additions & 0 deletions .github/workflows/local-profile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions docs/gateway-access-proposals.md
Original file line number Diff line number Diff line change
@@ -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: `<group-root>/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.
19 changes: 16 additions & 3 deletions src/Civ13/AccessFileSync.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion src/Civ13/Civ13.php
Original file line number Diff line number Diff line change
Expand Up @@ -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), '/');
Expand Down
14 changes: 13 additions & 1 deletion src/Civ13/PortableProfile.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
102 changes: 102 additions & 0 deletions src/Civ13/Server/GatewayAccessProposal.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace Civ13\Server;

use Civ13\AccessListProjection;
use Civ13\PortableProfile;

/** Gateway host consumes this request; the bot never writes authority or allocates a revision. */
final class GatewayAccessProposal
{
private const MAX_WIRE = 8_388_608;

private array $receipt = ['state' => '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); }
}
}
}
Loading
Loading