107 lines
8.8 KiB
PHP
107 lines
8.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
// CLI-only, synthetic data. Never bootstrap the application or its .env.
|
|
function env(string $key, mixed $default = null): mixed { return $default; }
|
|
$project = realpath($argv[1] ?? '') ?: throw new RuntimeException('Project root required');
|
|
$payload = realpath($argv[2] ?? '') ?: throw new RuntimeException('Payload root required');
|
|
$runtime = $argv[3] ?? throw new RuntimeException('Empty synthetic runtime required');
|
|
if (file_exists($runtime)) { throw new RuntimeException('Synthetic runtime must not already exist'); }
|
|
mkdir($runtime, 0700, true);
|
|
foreach (array_keys(getenv()) as $key) { if (str_starts_with(strtoupper($key), 'IAM_')) { putenv($key); } }
|
|
foreach (['IAM_GROUP_ENABLED'=>'1','IAM_GROUP_OWNER_IDS'=>'1','IAM_KEFU_COMPANY_CODE'=>'zyt-im',
|
|
'IAM_RUNTIME_PATH'=>$runtime,'IAM_GROUP_DB_PATH'=>$runtime.'/group.sqlite'] as $key=>$value) { putenv($key.'='.$value); }
|
|
|
|
$appRoot=$runtime.'/application';$classPath='/server/app/service/group/';
|
|
mkdir($appRoot.$classPath,0700,true);mkdir($appRoot.'/integration',0700,true);
|
|
copy($project.'/integration/kefu-menu-catalog.json',$appRoot.'/integration/kefu-menu-catalog.json');
|
|
$checks=0;
|
|
function check(bool $ok,string $label):void { global $checks;$checks++;if(!$ok)throw new RuntimeException($label); }
|
|
foreach (['GroupService.php','KefuApplicationService.php','KefuMenuCatalog.php'] as $file) {
|
|
$raw=file_get_contents($payload.$classPath.$file);
|
|
check(!preg_match('/\bON\s+CONFLICT\b[\s\S]*?\bDO\s+UPDATE\b/i',$raw),'Unsupported UPSERT syntax: '.$file);
|
|
check(!preg_match('/\b(?:INSERT\s+OR\s+REPLACE|REPLACE\s+INTO)\b/i',$raw),'Destructive replacement SQL: '.$file);
|
|
copy($payload.$classPath.$file,$appRoot.$classPath.$file);
|
|
}
|
|
$loader=require $project.'/server/vendor/autoload.php';
|
|
$loader->addPsr4('app\\',$appRoot.'/server/app',true);
|
|
foreach (['GroupService.php','KefuApplicationService.php','KefuMenuCatalog.php'] as $file) { require_once $appRoot.$classPath.$file; }
|
|
|
|
use app\service\group\{GroupStore,GroupService,KefuMetadataClient,KefuApplicationService};
|
|
use app\service\shared\{SourceApiClient,SessionStore};
|
|
$source=new class extends SourceApiClient {
|
|
public function __construct(){}
|
|
public function sourceKey():string{return hash('sha256','sqlite-compatibility-fixture-only');}
|
|
public function request(string $method,string $path,array $data=[],string $token=''):array {
|
|
if ($method==='GET' && $path==='auth.admin/detail') { return ['id'=>$data['id']]; }
|
|
throw new RuntimeException('Unexpected source access');
|
|
}
|
|
};
|
|
$key=str_repeat('ab',32);$calls=0;$name='Synthetic report';$sort=1;
|
|
$transport=function(string $url,array $headers,string $body)use($key,&$calls,&$name,&$sort):array {
|
|
$calls++;$nonce='';foreach($headers as $header){if(str_starts_with($header,'X-Group-Nonce: '))$nonce=substr($header,15);}
|
|
$value=['version'=>1,'client_id'=>'kefu','generated_at'=>time(),'subjects'=>[],
|
|
'catalog'=>['permissions'=>[['code'=>'report:read','name'=>$name,'group'=>'Synthetic reports','page'=>'Report','kind'=>'page','source'=>'custom','enabled'=>true,'sort'=>$sort]]]];
|
|
$raw=json_encode($value,JSON_THROW_ON_ERROR);
|
|
return ['status'=>200,'body'=>$raw,'headers'=>['X-Group-Response-Signature'=>hash_hmac('sha256',"response\n$nonce\n".hash('sha256',$raw),hex2bin($key))]];
|
|
};
|
|
$metadata=new KefuMetadataClient('https://synthetic.invalid/api',$key,$transport);
|
|
$store=new GroupStore($source->sourceKey());
|
|
$store->execute('INSERT INTO company(id,code,name,parent_id,disable,create_time,update_time) VALUES(2,?,?,0,0,1,1)',['zyt-im','Synthetic company']);
|
|
$clock=1000;$group=new GroupService($source,new SessionStore($runtime.'/sessions'),$store,static function()use(&$clock):int{return $clock;},$metadata);
|
|
$owner=['id'=>1,'is_root'=>1,'permissions'=>['*'],'menus'=>[],'role_id'=>[],'disable'=>0];
|
|
$session=['source_token'=>'synthetic-only'];
|
|
$app=new KefuApplicationService($store,$source,$metadata);
|
|
$sync=static fn():array=>$app->sync(['client_id'=>'kefu'],1);
|
|
$menus=static fn():array=>$group->dispatchStructure('menu.lists',$owner,2,[],[]);
|
|
$first=$sync();check($first['status']==='ok'&&$first['roles_changed']===0,'Initial sync failed');
|
|
$node=$store->one('SELECT n.* FROM application_catalog_node m JOIN company_structure_node n ON n.id=m.node_id WHERE m.external_key=?',['action-report:read']);
|
|
$store->execute('INSERT INTO role_native_menu(source_role_id,menu_id,update_time) VALUES(7,?,1)',[$node['id']]);
|
|
$grants=$store->all('SELECT * FROM role_native_menu');
|
|
$ids=$store->all('SELECT * FROM application_catalog_node ORDER BY external_key');
|
|
$store->execute('UPDATE company_structure_node SET name=? WHERE id=?',['Group override',$node['id']]);
|
|
$name='Changed source name';$sort=9;$second=$sync();$third=$sync();
|
|
$current=$store->one('SELECT * FROM company_structure_node WHERE id=?',[$node['id']]);
|
|
check($current['name']==='Group override'&&(int)$current['sort']===9,'Override or source update lost');
|
|
check($third['created']===0&&$third['updated']===0,'Repeat sync not idempotent');
|
|
check($store->all('SELECT * FROM application_catalog_node ORDER BY external_key')===$ids,'Node identity changed');
|
|
check($store->all('SELECT * FROM role_native_menu')===$grants,'Repeat sync changed role grants');
|
|
check($store->one('SELECT value FROM group_meta WHERE name=?',['kefu.catalog.synced.2'])!==null,'Sync timestamp missing');
|
|
|
|
// Prove both the initial TTL insert and an existing TTL update are contained.
|
|
$store->execute("CREATE TRIGGER fail_attempt_insert BEFORE INSERT ON group_meta WHEN NEW.name='kefu.catalog.attempt.2' BEGIN SELECT RAISE(ABORT,'synthetic TTL insert failure'); END");
|
|
$beforeCalls=$calls;$beforeNodes=$store->all('SELECT * FROM company_structure_node ORDER BY id');
|
|
check(count($menus())>0,'TTL insert failure blocked old menu list');
|
|
check($calls===$beforeCalls,'Remote request started after TTL insert failure');
|
|
check($store->all('SELECT * FROM company_structure_node ORDER BY id')===$beforeNodes,'TTL failure changed menu data');
|
|
$store->execute('DROP TRIGGER fail_attempt_insert');
|
|
$store->execute('INSERT INTO group_meta(name,value) VALUES(?,?)',['kefu.catalog.attempt.2','0']);
|
|
$store->execute("CREATE TRIGGER fail_attempt_update BEFORE UPDATE ON group_meta WHEN NEW.name='kefu.catalog.attempt.2' BEGIN SELECT RAISE(ABORT,'synthetic TTL update failure'); END");
|
|
check(count($menus())>0&&$calls===$beforeCalls,'TTL update failure blocked list or called remote');
|
|
check($store->one('SELECT value FROM group_meta WHERE name=?',['kefu.catalog.attempt.2'])['value']==='0','Failed TTL update committed');
|
|
$store->execute('DROP TRIGGER fail_attempt_update');
|
|
$menus();$afterCalls=$calls;check($afterCalls===$beforeCalls+1,'Successful refresh did not sync');
|
|
$menus();check($calls===$afterCalls,'Refresh TTL did not bound calls');
|
|
$store->execute('ALTER TABLE company RENAME TO synthetic_company_hidden');
|
|
$app->refreshIfDue(2,1);
|
|
check($calls===$afterCalls,'Company lookup failure called remote');
|
|
$store->execute('ALTER TABLE synthetic_company_hidden RENAME TO company');
|
|
|
|
// Membership is organization metadata. Explicit re-enable updates the same row.
|
|
$member=static function(int $status,int $login)use($group,$owner,$session):array {
|
|
return $group->dispatch('group.member.save',$owner,$session,'',['company_id'=>2,'admin_id'=>2,'member_status'=>$status,'can_login'=>$login],[]);
|
|
};
|
|
$member(1,1);$row=$store->one('SELECT rowid,* FROM membership WHERE company_id=2 AND source_id=2');
|
|
$gid=$store->one('SELECT gid FROM subject WHERE source_id=2')['gid'];
|
|
$clock++;$member(0,0);$store->identity(2);
|
|
$disabled=$store->membership(2,2);check((int)$disabled['member_status']===0&&(int)$disabled['can_login']===0,'Identity refresh revived membership');
|
|
$clock++;$member(1,1);$enabled=$store->one('SELECT rowid,* FROM membership WHERE company_id=2 AND source_id=2');
|
|
check($enabled['rowid']===$row['rowid']&&(int)$enabled['member_status']===1&&(int)$enabled['can_login']===1&&(int)$enabled['update_time']===$clock,'Membership re-enable changed identity or status contract');
|
|
check($store->one('SELECT gid FROM subject WHERE source_id=2')['gid']===$gid,'Membership update rebound GID');
|
|
check($store->all('SELECT * FROM role_native_menu')===$grants,'Membership update changed role grants');
|
|
$store->execute("CREATE TRIGGER fail_member_audit BEFORE INSERT ON group_audit WHEN NEW.action='membership.update' BEGIN SELECT RAISE(ABORT,'synthetic membership audit failure'); END");
|
|
try{$member(0,0);throw new RuntimeException('Missing membership audit failure');}catch(PDOException $error){}
|
|
check($store->one('SELECT rowid,* FROM membership WHERE company_id=2 AND source_id=2')===$enabled,'Audit failure committed membership change');
|
|
check($store->all('PRAGMA foreign_key_check')===[],'Foreign key violation');
|
|
echo 'PASS SQLite compatibility fixture: '.$checks.' checks; SQLite '.$store->one('SELECT sqlite_version() AS version')['version']."; synthetic only.\n";
|