Test beta endpoint contracts, privacy filtering, malformed manifests and delivery validation

这个提交包含在:
mac 于 2026-11-02 17:30:51 +08:00 提交
1 父节点 15d644c7e7
当前提交 55acdaa4b1
3 个文件已更改
+165

没有与搜索条件相匹配的文件

+86
查看文件
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
# coding: utf-8
"""Deploy only the Dayu Color beta namespace from the scoped local workspace."""
from pathlib import Path
import argparse,datetime,hashlib,json,os,re,shutil,subprocess,uuid
ROOT=Path(__file__).resolve().parent.parent
LOCAL=Path('/Users/mac/Downloads/dayumedia/dayu-color-beta')
MOUNT=Path('/Volumes/dayumedia (存储空间1)')
NAS=MOUNT/'wwwroot/dayu_media'
REL=Path('wp-content/mu-plugins/dayu-color-beta.php')
UPLOAD=Path('wp-content/uploads/dayu-color-beta/updates')
STAMP=datetime.datetime.now().strftime('%Y%m%d%H%M')
def sha(path):
h=hashlib.sha256()
with path.open('rb') as f:
for part in iter(lambda:f.read(1024*1024),b''):h.update(part)
return h.hexdigest()
def write_json(path,data):
path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
def check_mount():
lines=subprocess.check_output(['/sbin/mount'],text=True).splitlines()
match=[s for s in lines if f' on {MOUNT} (smbfs,' in s]
assert len(match)==1 and '@192.168.31.21/dayumedia%' in match[0], '目标不是已确认的 NAS SMB 共享'
assert NAS.is_dir() and os.access(NAS/'wp-content/mu-plugins',os.W_OK), '目标共享不可写'
return match[0]
def backup(path):
target=path.with_name(f'{path.stem}-{STAMP}.{path.suffix[1:]}bak' if path.suffix else f'{path.name}-{STAMP}.bak')
assert not target.exists(), '旁路备份重名,请换时间戳'
shutil.copyfile(path,target);assert sha(target)==sha(path)
return str(target)
def deploy_file(source,target,allow_new=False,expected=None):
target.parent.mkdir(parents=True,exist_ok=True);old=None
if target.exists():
if sha(target)==sha(source):return dict(path=str(target),sha256=sha(target),reused=True)
assert expected and sha(target)==expected,'生产基线已变化,停止覆盖'
old=backup(target)
else:assert allow_new,'预期生产基线不存在'
temp=target.with_name('.dayu-color-stage-'+uuid.uuid4().hex)
try:
shutil.copyfile(source,temp);temp.chmod(0o644);assert sha(temp)==sha(source);os.replace(temp,target)
finally:
if temp.exists():temp.unlink()
assert sha(source)==sha(target) and os.access(target,os.R_OK)
return dict(path=str(target),sha256=sha(target),backup=old,size=target.stat().st_size)
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--backend',action='store_true');p.add_argument('--package',type=Path);args=p.parse_args()
assert args.backend or args.package
mount=check_mount();LOCAL.mkdir(parents=True,exist_ok=True)
lock=LOCAL/'.deployment.lock';lock.mkdir();write_json(lock/'owner.json',dict(PID=os.getpid(),cwd=str(ROOT),started=STAMP))
try:
if args.backend:
subprocess.run(['php','-l',str(ROOT/'Backend'/REL)],check=True)
local=LOCAL/REL;local.parent.mkdir(parents=True,exist_ok=True)
record=ROOT/'verification/BetaBackendDeployment.json'
previous=json.loads(record.read_text()) if record.exists() else {}
if local.exists() and sha(local)!=sha(ROOT/'Backend'/REL):
assert previous.get('sha256')==sha(local),'本地专项工程有未部署改动,停止覆盖'
shutil.copyfile(ROOT/'Backend'/REL,local)
result=deploy_file(local,NAS/REL,allow_new=not previous,expected=previous.get('sha256'))
result.update(timestamp=STAMP,mount=mount,localProject=str(LOCAL),sourceCommit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip())
write_json(record,result);print(json.dumps(result,ensure_ascii=False))
if args.package:
package=args.package.resolve();report=json.loads((ROOT/'verification/Package.json').read_text());delivery=json.loads((ROOT/'verification/Delivery.json').read_text())
assert report['notarization']['status']=='Accepted' and delivery['status']=='verified'
# Independent final-container checks before uploading any bytes.
subprocess.run(['pkgutil','--check-signature',str(package)],check=True,stdout=subprocess.DEVNULL)
subprocess.run(['xcrun','stapler','validate',str(package)],check=True,stdout=subprocess.DEVNULL)
subprocess.run(['spctl','--assess','--type','install',str(package)],check=True)
version=delivery['version'];build=int(delivery['build']);digest=sha(package)
filename=f'dayu-color-{version.replace(".","-")}-{build}.pkg';relative=UPLOAD/filename
local=LOCAL/relative;local.parent.mkdir(parents=True,exist_ok=True)
if not local.exists():shutil.copyfile(package,local)
assert sha(local)==digest
result=deploy_file(local,NAS/relative,allow_new=True)
manifest=dict(bundle_id='com.dayu.color',channel='beta',version=version,build=build,package_type='pkg',install_mode='pkg_installer',
size=package.stat().st_size,sha256=digest,download_url='https://dayu.media/'+str(relative),minimum_system_version='14.6',
notes='公测版:接入自动更新与可关闭的云端诊断,记录插件加载耗时及错误摘要。请保存并退出 FCP / Motion 后安装。')
dest=NAS/UPLOAD/'beta.json';old=json.loads(dest.read_text()) if dest.exists() else None
if old:assert int(old['build'])<=build, '禁止更新通道倒退'
localManifest=LOCAL/UPLOAD/'beta.json';write_json(localManifest,manifest)
published=deploy_file(localManifest,dest,allow_new=True,expected=sha(dest) if old else None)
result.update(manifest=published,version=version,build=build,downloadURL=manifest['download_url'],timestamp=STAMP)
write_json(ROOT/'verification/BetaPublication.json',result);print(json.dumps(result,ensure_ascii=False))
finally:
(lock/'owner.json').unlink();lock.rmdir()
if __name__=='__main__':main()
+53
查看文件
@@ -0,0 +1,53 @@
<?php
// Product endpoint contracts; WordPress and DB are stubbed, never load production settings.
error_reporting(E_ALL);
set_error_handler(function($severity,$message,$file,$line){ throw new ErrorException($message,0,$severity,$file,$line); });
define('ABSPATH',__DIR__.'/');define('MINUTE_IN_SECONDS',60);define('DAY_IN_SECONDS',86400);define('ARRAY_A','ARRAY_A');
$testRoot=sys_get_temp_dir().'/dayu-color-contract-'.bin2hex(random_bytes(6));mkdir($testRoot,0700,true);
function add_action(...$args){}
function get_option($key){return '1';}
function register_rest_route($namespace,$route,$args){$GLOBALS['routes'][$route]=$args;}
function current_user_can($permission){return false;}
function wp_upload_dir(...$args){return array('basedir'=>$GLOBALS['testRoot']);}
function sanitize_textarea_field($value){return strip_tags($value);}
function sanitize_text_field($value){return strip_tags($value);}
function wp_salt($scheme){return 'test-only-not-production';}
function get_transient($key){return 0;}
function set_transient(...$args){}
function wp_json_encode($value,$options=0){return json_encode($value,$options);}
class WP_Error {public $code,$data;function __construct($code,$message,$data){$this->code=$code;$this->data=$data;}}
class WP_REST_Response {public $data,$status;function __construct($data,$status,$headers){$this->data=$data;$this->status=$status;}}
class WP_REST_Request {public $params,$body;function __construct($params=array(),$body=null){$this->params=$params;$this->body=$body;}function get_param($name){return $this->params[$name]??null;}function get_body(){return json_encode($this->body);}function get_json_params(){return $this->body;}}
class FakeDB {public $prefix='wp_',$rows=array();function prepare($sql,...$args){return $args[0]??$sql;}function get_var($sql){return isset($this->rows[$sql])?$sql:null;}function insert($table,$row){$this->rows[$row['event_id']]=$row;return 1;}}
$wpdb=new FakeDB;
require dirname(__DIR__).'/wp-content/mu-plugins/dayu-color-beta.php';
$checks=0;
function check($value,$label){global $checks;if(!$value)throw new RuntimeException($label);$checks++;}
function request($body){return new WP_REST_Request(array(),$body);}
try {
Dayu_Color_Beta::routes();
check(($routes['/diagnostics'][1]['permission_callback'])()===false,'anonymous log reads denied');
check(Dayu_Color_Beta::update(new WP_REST_Request(array('bundle_id'=>'other')))->data['status']===400,'product separation');
$response=Dayu_Color_Beta::update(new WP_REST_Request(array('bundle_id'=>'com.dayu.color','current_build'=>44)));
check($response->status===200 && !$response->data['update_available'],'empty feed is usable');
$fields=Dayu_Color_Beta::clean_fields(array('frames'=>'/Users/test/secret.mov','error_domain'=>'token=not-a-token','arbitrary'=>'private','duration_ms'=>INF,'gpu'=>'M4'));
check($fields['frames']==='[REDACTED]' && $fields['error_domain']==='[REDACTED]' && !isset($fields['arbitrary']) && !isset($fields['duration_ms']) && $fields['gpu']==='M4','allowlist and redaction');
$id='12345678-1234-4234-8234-123456789012';
$event=array('event_id'=>$id,'session_id'=>$id,'source'=>'plugin','version'=>'1.7.0','build'=>45,'event'=>'first_render','occurred_at'=>time(),'fields'=>array('duration_ms'=>1200));
$body=array('bundle_id'=>'com.dayu.color','installation_id'=>$id,'events'=>array($event));
$reply=Dayu_Color_Beta::ingest(request($body));
check($reply->status===200 && $reply->data['accepted'] && count($wpdb->rows)===1,'valid event accepted');
Dayu_Color_Beta::ingest(request($body));check(count($wpdb->rows)===1,'retry idempotency');
foreach(array('version'=>array(),'build'=>array(),'event'=>'material_path','session_id'=>'bad','occurred_at'=>null) as $key=>$bad){$b=$body;$b['events'][0][$key]=$bad;check(Dayu_Color_Beta::ingest(request($b))->data['status']===400,'malformed '.$key);}
$b=$body;$b['events']=array_fill(0,33,$event);check(Dayu_Color_Beta::ingest(request($b))->data['status']===400,'batch limit');
$b=$body;$b['padding']=str_repeat('a',100000);check(Dayu_Color_Beta::ingest(request($b))->data['status']===413,'byte limit');
$manifest=array('bundle_id'=>'com.dayu.color','channel'=>'beta','version'=>'1.7.0','build'=>45,'package_type'=>'pkg','install_mode'=>'pkg_installer','size'=>123,'sha256'=>str_repeat('a',64),'download_url'=>'https://dayu.media/wp-content/uploads/dayu-color-beta/updates/dayu-color-1-7-0-45.pkg');
mkdir(dirname(Dayu_Color_Beta::manifest_path()),0700,true);file_put_contents(Dayu_Color_Beta::manifest_path(),json_encode($manifest));
check(Dayu_Color_Beta::update(new WP_REST_Request(array('bundle_id'=>'com.dayu.color','current_build'=>44)))->data['update_available']===true,'older build sees update');
check(Dayu_Color_Beta::update(new WP_REST_Request(array('bundle_id'=>'com.dayu.color','current_build'=>45)))->data['update_available']===false,'current build no downgrade');
foreach(array('download_url'=>'https://other.example/evil.pkg','sha256'=>'bad','build'=>array(),'size'=>1073741825,'install_mode'=>'zip_replace') as $key=>$bad){$m=$manifest;$m[$key]=$bad;file_put_contents(Dayu_Color_Beta::manifest_path(),json_encode($m));check(Dayu_Color_Beta::manifest()===array(),'bad manifest '.$key);}
echo json_encode(array('passed'=>true,'checks'=>$checks),JSON_PRETTY_PRINT)."\n";
} finally {
if(is_file(Dayu_Color_Beta::manifest_path()))unlink(Dayu_Color_Beta::manifest_path());
@rmdir($testRoot.'/dayu-color-beta/updates');@rmdir($testRoot.'/dayu-color-beta');@rmdir($testRoot);
}
+26
查看文件
@@ -0,0 +1,26 @@
#import <AppKit/AppKit.h>
#import "../大鱼调色/Shared/DYBetaDiagnostics.h"
#import "../大鱼调色/Wrapper Application/DYBetaUpdater.h"
static NSUInteger checks;
static void check(BOOL pass,NSString *name){if(!pass){fprintf(stderr,"FAIL %s\n",name.UTF8String);exit(1);}checks++;}
int main(int argc,char **argv){@autoreleasepool{
NSString *base=@"https://dayu.media/wp-content/uploads/dayu-color-beta/updates/";
NSMutableDictionary *manifest=[@{@"bundle_id":@"com.dayu.color",@"channel":@"beta",@"version":@"1.7.0",@"build":@45,@"size":@123,
@"sha256":[@"a" stringByPaddingToLength:64 withString:@"a" startingAtIndex:0],@"package_type":@"pkg",@"install_mode":@"pkg_installer",@"download_url":[base stringByAppendingString:@"dayu-color-1-7-0-45.pkg"]}mutableCopy];
check([DYBetaUpdater validateManifest:manifest error:nil],@"valid manifest");
for(NSString *key in manifest.allKeys){for(id bad in @[[NSNull null],@[],@{},@YES,@"",@(-1)]){NSMutableDictionary *changed=[[manifest mutableCopy]autorelease];changed[key]=bad;
check(![DYBetaUpdater validateManifest:changed error:nil],[NSString stringWithFormat:@"reject %@ %@",key,bad]);}}
check(![DYBetaUpdater validateManifest:(id)@[] error:nil],@"non dictionary manifest");
for(NSString *bad in @[@"http://dayu.media/wp-json/dayu-color/v1/update",@"https://dayu.media.evil.test/wp-json/dayu-color/v1/update",@"https://dayu.media:444/wp-json/dayu-color/v1/update",@"https://user@dayu.media/wp-json/dayu-color/v1/update",@"https://dayu.media/wp-json/other/v1/update",@"https://dayu.media/wp-json/dayu-color/v1/../other"])
check(!DYBetaAllowedURL([NSURL URLWithString:bad],NO),@"reject foreign URL");
NSDictionary *safe=DYBetaSafeFields(@{@"phase":@"end",@"frames":@"/Users/test/secret.mov",@"error_domain":@"token=secret",@"email":@"private@example.invalid",@"duration_ms":@(NAN)});
check([safe[@"frames"]isEqual:@"[REDACTED]"]&&[safe[@"error_domain"]isEqual:@"[REDACTED]"]&&!safe[@"email"]&&!safe[@"duration_ms"],@"privacy allowlist and redaction");
check(DYBetaSafeFields((id)@[]).count==0,@"bad fields do not crash");
if(argc==3){NSData *data=[NSData dataWithContentsOfFile:[NSString stringWithUTF8String:argv[2]]];NSDictionary *real=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];NSError *error=nil;
BOOL verified=[DYBetaUpdater validatePackage:[NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]] manifest:real error:&error];
if(!verified)fprintf(stderr,"%s\n",error.localizedDescription.UTF8String);check(verified,@"signed notarized full product package");
NSMutableDictionary *wrong=[[real mutableCopy]autorelease];wrong[@"sha256"]=[@"0" stringByPaddingToLength:64 withString:@"0" startingAtIndex:0];
check(![DYBetaUpdater validatePackage:[NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]] manifest:wrong error:nil],@"corrupt checksum refused before install");
}
printf("{\"passed\":true,\"checks\":%lu}\n",(unsigned long)checks);[manifest release];
}return 0;}