diff --git a/crates/domain/src/jobs.rs b/crates/domain/src/jobs.rs index 741e0c8..4d6b217 100644 --- a/crates/domain/src/jobs.rs +++ b/crates/domain/src/jobs.rs @@ -211,6 +211,9 @@ impl Action { } /// Shared plan/revalidation/start gate. Passive Windows never implies job support. pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool { + if identity == "system" && !matches!(self, Self::SetServiceState { .. }) { + return false; + } let has = |cap: &str| capabilities.iter().any(|c| c == cap); if !has(self.name()) { return false; @@ -234,6 +237,17 @@ impl Action { && !(has("linux.base/1") && has("windows.base/1")) && (scope != "windows.base" || has("rmm.sync.v1")) } + Self::SetServiceState { state, .. } + if identity == "system" || has("windows.base/1") => + { + identity == "system" + && has("windows.base/1") + && !has("linux.base/1") + && has("rmm.sync.v1") + && has("helper.system.v1") + && has("system:set_service_state") + && matches!(state.as_str(), "running" | "stopped") + } _ => !has("windows.base/1"), // Windows adapters are separately qualified. } } @@ -431,6 +445,81 @@ impl JobState { mod tests { use super::*; #[test] + fn windows_system_scm_is_explicit_and_preserves_linux_service_bytes() { + let caps: Vec = [ + "windows.base/1", + "rmm.sync.v1", + "helper.system.v1", + "system:set_service_state", + "set_service_state", + ] + .into_iter() + .map(str::to_string) + .collect(); + for state in ["running", "stopped"] { + let action = Action::SetServiceState { + unit: "RmmDiscoveryFixtureService".into(), + state: state.into(), + }; + assert!(action.validate() && action.available_for("system", &caps)); + for missing in 0..caps.len() { + let mut incomplete = caps.clone(); + incomplete.remove(missing); + assert!(!action.available_for("system", &incomplete)); + } + for identity in ["root", "agent_service", "SYSTEM"] { + assert!(!action.available_for(identity, &caps)); + } + let mut mixed = caps.clone(); + mixed.push("linux.base/1".into()); + assert!(!action.available_for("system", &mixed)); + assert!(!action.available_for( + "system", + &["linux.base/1".into(), "set_service_state".into()] + )); + } + let restart = Action::SetServiceState { + unit: "rmm-mvp-test.service".into(), + state: "restarted".into(), + }; + assert!(!restart.available_for("system", &caps)); + let linux = vec!["linux.base/1".into(), "set_service_state".into()]; + for identity in ["root", "agent_service"] { + assert!(restart.available_for(identity, &linux)); + } + assert_eq!( + encode(&restart).unwrap(), + br#"{"action":"set_service_state","unit":"rmm-mvp-test.service","state":"restarted"}"# + ); + let script = Action::RunScript { + interpreter: "powershell".into(), + script_utf8: "Write-Output 'hi'\r\n".into(), + arguments: vec![], + expected_stdout: None, + }; + let mut all = caps; + all.extend(["run_script".into(), "script.powershell/1".into()]); + assert!(!script.available_for("system", &all)); + let posix = Action::RunScript { + interpreter: "posix_sh".into(), + script_utf8: "printf hi\n".into(), + arguments: vec![], + expected_stdout: None, + }; + let reboot = Action::Reboot { + reason: "fixed test".into(), + reconnect_timeout_seconds: 180, + dependency_group: "one-test-vm".into(), + }; + let linux = ["linux.base/1", "run_script", "reboot"].map(str::to_string); + assert!(!posix.available_for("system", &linux)); + assert!(!reboot.available_for("system", &linux)); + for identity in ["root", "agent_service"] { + assert!(posix.available_for(identity, &linux)); + assert!(reboot.available_for(identity, &linux)); + } + } + #[test] fn windows_interpreter_and_capability_contract() { let mut action = Action::RunScript { interpreter: "powershell".into(), diff --git a/deploy/domain_scm_acceptance.py b/deploy/domain_scm_acceptance.py new file mode 100644 index 0000000..61adbfe --- /dev/null +++ b/deploy/domain_scm_acceptance.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Frozen pure Domain lib units, Linux VM FIRST then Windows VM; no RMM jobs. + +Local builds never contact a VM. Native starts require an explicit flag. Lost +replies permit same-case readback only; existing SharedCore profiles stay intact. +""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import uuid + +import remote_client_bootstrap as linux +import vm_mvp_acceptance as contract +from windows import client_bootstrap as windows + +ROOT=Path(__file__).resolve().parents[1] +STATE=ROOT/'devstate/domain-scm' +IMAGE='rust-discovery-durable-final-build:local' +JOBS_SHA='1566d849c23b3f2792f9e003ac589022525f94cf8b088176ccdae50b99162417' +REMOTE='/var/lib/rmm-domain-unit-acceptance' +COUNT=15 +require=contract.require + +def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest() +def store(folder,name,value): + fd=os.open(folder/name,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as out:json.dump(value,out,indent=2);out.write('\n');out.flush();os.fsync(out.fileno()) +def source_files(): + paths=[ROOT/'Cargo.toml',ROOT/'Cargo.lock',ROOT/'rust-toolchain.toml',ROOT/'crates/domain/Cargo.toml'] + paths.extend((ROOT/'crates/domain/src').rglob('*.rs')) + require(sha(ROOT/'crates/domain/src/jobs.rs')==JOBS_SHA,'final reviewed Domain SYSTEM guard source required') + return {str(p.relative_to(ROOT)):sha(p) for p in sorted(set(paths))} +def command(args,timeout=300): + p=subprocess.run(args,capture_output=True,timeout=timeout) + if p.returncode:raise RuntimeError(p.stderr.decode(errors='replace')[-3000:]) + return p.stdout + +def build(): + os.umask(0o077);STATE.mkdir(mode=0o700,parents=True,exist_ok=True);folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700) + before=source_files();runner=sha(__file__);store(folder,'source-before.json',before) + image=command(['docker','image','inspect','--format','{{.Id}}',IMAGE]).decode().strip();require(re.fullmatch('sha256:[0-9a-f]{64}',image),'immutable local build image') + target=STATE/'target';target.mkdir(mode=0o700,exist_ok=True) + common=['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m','-v',str(ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','cargo',image] + artifacts={} + for platform,architecture in [('linux',None),('windows','x86_64-pc-windows-gnu')]: + options=['--manifest-path','/src/Cargo.toml','--locked','--offline','-p','rmm-domain'] + if architecture:options+=['--target',architecture] + command(common+['clippy']+options+['--all-targets','--','-D','warnings']) + raw=command(common+['test']+options+['--lib','--release','--no-run','--message-format=json']) + linked=[] + for line in raw.splitlines(): + try:value=json.loads(line) + except ValueError:continue + if value.get('reason')=='compiler-artifact' and value.get('target',{}).get('name')=='rmm_domain' and value.get('profile',{}).get('test') and value.get('executable'): + linked.append(target/Path(value['executable']).relative_to('/target')) + require(len(linked)==1,'exact Domain lib-test executable') + name='domain-tests'+('.exe' if platform=='windows' else '');copy=folder/name;shutil.copyfile(linked[0],copy);copy.chmod(0o600);original=sha(linked[0]) + strip='x86_64-w64-mingw32-strip' if architecture else 'strip' + command(['docker','run','--rm','--network','none','--read-only','-v',str(folder.resolve())+':/artifacts','--entrypoint',strip,image,'--strip-debug','/artifacts/'+name]) + require(sha(linked[0])==original,'original linked unit executable preserved') + data=copy.read_bytes() + if platform=='linux':require(data[:6]==b'\x7fELF\x02\x01' and data[18:20]==b'\x3e\x00','Linux x64 ELF') + else: + offset=int.from_bytes(data[60:64],'little');require(data[:2]==b'MZ' and data[offset:offset+6]==b'PE\0\0\x64\x86','Windows x64 PE') + artifacts[platform]=dict(path=str(copy.resolve()),sha256=sha(copy),bytes=len(data),original_link_sha256=original,debug_stripped_copy=True) + run=['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=64m','-v',artifacts['linux']['path']+':/domain-tests:ro','--entrypoint','/bin/sh',image,'-c'] + listed=command(run+['exec /lib64/ld-linux-x86-64.so.2 /domain-tests --list --format terse']) + names=sorted(s.decode() for s in re.findall(rb'^(.+): test$',listed,re.M));require(len(names)==COUNT and len(set(names))==COUNT,'exact fifteen portable Domain lib units') + local=command(run+['exec /lib64/ld-linux-x86-64.so.2 /domain-tests --test-threads=1']) + require(b'15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;' in local,'all fifteen local units; no ignored/filtering') + require(source_files()==before and sha(__file__)==runner,'frozen source before/after equality') + libc=command(['docker','run','--rm','--network','none','--read-only','--entrypoint','ldd',image,'--version']).decode().splitlines()[0] + manifest=dict(schema_version=1,profile='domain-scm-lib-15',runner_sha256=runner,source_files=before,source_before_after_equal=True,build_image_id=image,build_libc=libc, + test_names=names,test_count=COUNT,artifacts=artifacts,clippy_both_targets_D_warnings=True,local_linux_tests_passed=COUNT,local_linux_stdout_sha256=hashlib.sha256(local).hexdigest(), + native_linux_executed=False,native_windows_executed=False,database=False,services=False,network=False,rmm_jobs=False) + store(folder,'manifest.json',manifest);print(json.dumps(dict(manifest=str((folder/'manifest.json').resolve()),artifacts=artifacts,test_count=COUNT,native_executed=False))) + +def verified(path): + m=contract.protected_json(path) + require(m['profile']=='domain-scm-lib-15' and m['runner_sha256']==sha(__file__) and m['source_files']==source_files() and m['source_before_after_equal'] is True,'same frozen source/runner') + require(m['test_count']==COUNT and len(set(m['test_names']))==COUNT,'exact pure lib tests') + for item in m['artifacts'].values():require(sha(item['path'])==item['sha256'] and Path(item['path']).stat().st_size==item['bytes'],'immutable unit delivery copy') + return m + +def linux_case(p): + import resource + import stat + require(os.geteuid()==0 and os.uname().machine=='x86_64','Linux x64 bootstrap unit qualification') + ident=str(uuid.UUID(p['id']));require(ident==p['id'] and p['action'] in ('prepare','run','read'),'fixed native case') + require(len(p['sha256'])==64 and all(c in '0123456789abcdef' for c in p['sha256']) and p['test_count']==15,'fixed Domain unit bytes/count') + root=Path('/var/lib/rmm-domain-unit-acceptance') + def safe(path,directory): + s=path.lstat();require(s.st_uid==0 and s.st_mode&0o077==0 and not stat.S_ISLNK(s.st_mode) and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode)),'private fixed unit path') + def save(path,value): + fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600) + with os.fdopen(fd,'w') as f:json.dump(value,f);f.flush();os.fsync(f.fileno()) + if not root.exists():root.mkdir(mode=0o700) + safe(root,True);case=root/ident + if p['action']=='prepare':case.mkdir(mode=0o700);save(case/'intent.json',p);return dict(prepared=True) + safe(case,True);safe(case/'intent.json',False);intent=json.loads((case/'intent.json').read_bytes());require(all(p[k]==intent[k] for k in ('id','sha256','manifest_sha256','test_count')),'same original native case') + if p['action']=='read':safe(case/'result.json',False);return json.loads((case/'result.json').read_bytes()) + binary=case/'domain-tests';safe(binary,False);require(hashlib.sha256(binary.read_bytes()).hexdigest()==p['sha256'],'exact Linux lib unit artifact') + save(case/'started.json',dict(start_once=True,sha256=p['sha256']));binary.chmod(0o500);tmp=case/'tmp';tmp.mkdir(mode=0o700) + env={'PATH':'/usr/bin:/bin','LANG':'C.UTF-8','TMPDIR':str(tmp),'RUST_BACKTRACE':'0'} + require(subprocess.run(['/usr/bin/unshare','--net','--','/usr/bin/true'],env=env,capture_output=True,timeout=3).returncode==0,'network namespace required') + listed=subprocess.run(['/usr/bin/unshare','--net','--',str(binary),'--list','--format','terse'],env=env,capture_output=True,timeout=5) + require(listed.returncode==0 and len(listed.stdout)<=32768,'bounded exact unit listing') + def limits():resource.setrlimit(resource.RLIMIT_CORE,(0,0));resource.setrlimit(resource.RLIMIT_FSIZE,(131072,131072));resource.setrlimit(resource.RLIMIT_CPU,(10,10)) + with (case/'stdout.bin').open('xb') as out,(case/'stderr.bin').open('xb') as err: + os.chmod(out.name,0o600);os.chmod(err.name,0o600);timed=False + try:code=subprocess.run(['/usr/bin/unshare','--net','--',str(binary),'--test-threads=1'],cwd=case,env=env,stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=20,preexec_fn=limits).returncode + except subprocess.TimeoutExpired:timed=True;code=None + out.flush();err.flush();os.fsync(out.fileno());os.fsync(err.fileno()) + raw=(case/'stdout.bin').read_bytes();errors=(case/'stderr.bin').read_bytes();require(len(raw)<=131072 and len(errors)<=131072,'bounded unit output') + libc=subprocess.run(['/usr/bin/ldd','--version'],env=env,capture_output=True,timeout=3);require(libc.returncode==0 and len(libc.stdout)<=4096,'actual VM libc metadata') + result=dict(id=ident,platform='linux',sha256=p['sha256'],manifest_sha256=p['manifest_sha256'],listed_stdout=listed.stdout.decode(),exit_code=code,timed_out=timed,stdout_b64=base64.b64encode(raw).decode(),stderr_b64=base64.b64encode(errors).decode(),actual_vm_libc=libc.stdout.decode().splitlines()[0],network_namespace=True,environment_cleared=True,no_rmm_job=True) + save(case/'result.json',result);return result + +WINDOWS=r''' +$ErrorActionPreference='Stop' +$p=([Console]::In.ReadLine()|ConvertFrom-Json) +if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('run','read')-or$p.sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first unit case'} +$case='C:\ProgramData\RustDiscoveryBootstrap\domain-unit-'+$p.id +$exe='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\windows-tests-lib.exe' +function WriteNew($path,$v){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($v|ConvertTo-Json -Depth 8 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}} +if($p.action-eq'read'){$i=Get-Content -LiteralPath (Join-Path $case 'intent.json') -Raw|ConvertFrom-Json;if($i.sha256-cne$p.sha256-or$i.manifest_sha256-cne$p.manifest_sha256-or$i.linux_proof_sha256-cne$p.linux_proof_sha256){throw 'Original case'};Get-Content -LiteralPath (Join-Path $case 'result.json') -Raw;exit 0} +if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.sha256-or(Test-Path -LiteralPath $case)){throw 'Exact fresh unit artifact/case'} +New-Item -ItemType Directory -Path $case|Out-Null +WriteNew (Join-Path $case 'intent.json') $p +function RunUnit([string]$arguments){$si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$exe;$si.Arguments=$arguments;$si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true;$proc=New-Object Diagnostics.Process;$proc.StartInfo=$si;if(!$proc.Start()){throw 'Unit start'};try{$o=$proc.StandardOutput.ReadToEndAsync();$e=$proc.StandardError.ReadToEndAsync();if(!$proc.WaitForExit(30000)){$proc.Kill();throw 'Unit timeout'};if($o.Result.Length-gt 131072-or$e.Result.Length-gt 131072){throw 'Bounded unit output'};return @{exit_code=$proc.ExitCode;stdout=$o.Result;stderr=$e.Result}}finally{$proc.Dispose()}} +WriteNew (Join-Path $case 'started.json') @{start_once=$true;sha256=$p.sha256} +$list=RunUnit '--list --format terse';$result=RunUnit '--test-threads=1' +$value=@{platform='windows';sha256=$p.sha256;manifest_sha256=$p.manifest_sha256;linux_proof_sha256=$p.linux_proof_sha256;listed_stdout=$list.stdout;list_exit_code=$list.exit_code;result=$result;bootstrap_administrator_unit_tests=$true;local_service_proof=$false;no_rmm_job=$true;no_service_change=$true} +WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 8 -Compress +''' + +def check_result(m,platform,result): + require(result['platform']==platform and result['sha256']==m['artifacts'][platform]['sha256'],'actual platform/artifact binding') + names=sorted(re.findall(r'^(.+): test\r?$',result['listed_stdout'],re.M));require(names==m['test_names'],'all same fifteen actual lib tests') + if platform=='linux': + require(result['exit_code']==0 and result['timed_out'] is False,'actual Linux unit success');out=base64.b64decode(result['stdout_b64'],validate=True) + else: + require(result['list_exit_code']==result['result']['exit_code']==0,'actual Windows unit success');out=result['result']['stdout'].encode() + require(b'15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;' in out,'fifteen executed; no skipped/filtered tests') + +def execute(manifest_path,platform,case=None): + m=verified(manifest_path);os.umask(0o077) + if case is None: + case=str(uuid.uuid4());folder=STATE/case;folder.mkdir(mode=0o700) + store(folder,'intent.json',dict(id=case,platform=platform,manifest_path=str(manifest_path.resolve()),manifest_sha256=sha(manifest_path))) + else: + case=str(uuid.UUID(case));folder=STATE/case;intent=contract.protected_json(folder/'intent.json');require(intent['platform']==platform and intent['manifest_sha256']==sha(manifest_path),'original platform/manifest case') + read=(folder/'started-local.json').exists() + item=m['artifacts'][platform];payload=dict(id=case,sha256=item['sha256'],manifest_sha256=sha(manifest_path),test_count=COUNT) + if platform=='linux': + if not read: + linux.rpc('linux-vm.conf',linux_case,dict(payload,action='prepare')) + cfg=linux.access.load_config(ROOT/'credentials/linux-vm.conf');args=['sftp','-F','/dev/null','-P',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','-i',str(Path(cfg['ssh_key_path']).expanduser()),'-b','-',cfg['username']+'@'+cfg['address']] + uploaded=subprocess.run(args,input=('put '+json.dumps(item['path'])+' '+json.dumps(REMOTE+'/'+case+'/domain-tests')+'\n').encode(),capture_output=True,timeout=120);store(folder,'upload.json',dict(returncode=uploaded.returncode));require(uploaded.returncode==0,'fixed Linux unit upload') + if not read:store(folder,'started-local.json',dict(run_once=True)) + result=linux.rpc('linux-vm.conf',linux_case,dict(payload,action='read' if read else 'run')) + else: + proof=contract.protected_json(Path(manifest_path).parent/'linux-passed.json');require(proof['verified'] is True and proof['manifest_sha256']==sha(manifest_path),'same-manifest real Linux proof before Windows') + check_result(m,'linux',proof['native']);payload['linux_proof_sha256']=sha(Path(manifest_path).parent/'linux-passed.json') + if not read:windows.upload(Path(item['path']),'windows-tests-lib.exe');store(folder,'started-local.json',dict(run_once=True,linux_proof_sha256=payload['linux_proof_sha256'])) + result=windows.powershell(WINDOWS,dict(payload,action='read' if read else 'run'),timeout=75) + store(folder,'readback-'+str(uuid.uuid4())+'.json',result);require(result['manifest_sha256']==sha(manifest_path),'native result bound to original manifest');check_result(m,platform,result) + value=dict(verified=True,manifest_sha256=sha(manifest_path),case_id=case,platform=platform,native=result) + path=Path(manifest_path).parent/(platform+'-passed.json') + if path.exists():require(contract.protected_json(path)==value,'retain identical original native lib proof') + else:store(path.parent,path.name,value) + print(json.dumps(dict(verified=True,platform=platform,case_id=case,test_count=COUNT))) + +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=('build-local','linux','windows','readback-linux','readback-windows'));p.add_argument('--manifest',type=Path);p.add_argument('--case');p.add_argument('--execute-native-tests',action='store_true');a=p.parse_args() + if a.action=='build-local':require(not(a.manifest or a.case or a.execute_native_tests),'local build only');build() + elif a.action.startswith('readback-'):require(a.manifest and a.case and not a.execute_native_tests,'same case readback only');require((STATE/str(uuid.UUID(a.case))/'started-local.json').exists(),'never start from a readback command');execute(a.manifest,a.action.removeprefix('readback-'),a.case) + else:require(a.manifest and a.execute_native_tests and not a.case,'explicit one native platform start');execute(a.manifest,a.action) +if __name__=='__main__':main() diff --git a/docs/handover.md b/docs/handover.md index 8e6fdff..deab62d 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -53,6 +53,15 @@ Zugänge und private Rohbelege bleiben gitignoriert. ## Aktuelle Windowsfortsetzung +Enger Domain-/WebUI-SCM-Schnitt implementiert: explizites `system:execute`, +feste Fixturezustände und sichtbare Bindung aus gespeicherten Planbytes. +15 Domain-/26 Webtests, Clippy/Typecheck/Build lokal bestanden; anschließend +15 Domainunits nativ zuerst Cloud-Linux, Fall `0dd12ed9…`, Binary `635a6dd6…`. +Windowsunits noch offen, kein Deployment oder Capabilitysetup. Vorbereiteter +Runtimepfad bleibt wegen Reviewbefund zu Vor-Delegation-Consumption gesperrt; +dessen Korrektur darf den unabhängigen Helperabgleich nicht aufweichen. +[SYSTEM-Vertrag und Nachweise](windows-system-policy.md). + Helper-Peer-Kontrollfall `603c2f9d…`: native Windows5-Speicherproben der ACL-Konstruktoren, geschützte Vorbereitung und rohe Administrator-/fremde LocalService-Kontrolle bestanden (Pipeöffnen jeweils verweigert5, tatsächliche diff --git a/docs/windows-system-policy.md b/docs/windows-system-policy.md index 0b085f0..d3846ae 100644 --- a/docs/windows-system-policy.md +++ b/docs/windows-system-policy.md @@ -4,9 +4,10 @@ Stand 2026-11-14: Die Serverstrecke ist **implementiert, lokal geprüft und mit 13 ausgewählten reinen Policytests auf der tatsächlichen Cloud-Linux-VM geprüft**. Sie wurde nicht auf den Cloudserver ausgerollt und nicht über einen echten Windows-SYSTEM-Job abgenommen. Kein Principal erhielt ein neues Recht; keine -Policydatei oder Capability wurde installiert/veröffentlicht. Domain, Shared Core, -Windowsquellen, deren laufende native Qualifikation und WebUI bleiben unverändert. -Die derzeitige gemeinsame `Action::available_for` verweigert Windows-SCM weiterhin. +Policydatei oder Capability wurde installiert/veröffentlicht. Der neue enge +Domain-/WebUI-SCM-Schnitt ist inzwischen separat implementiert und zuerst mit +15 reinen Domain-Vertragstests auf Cloud-Linux geprüft; Windowsnachweis folgt. +Keine bestehende Linux-Job-/Grantserialisierung wurde geändert. `system` ist eine explizite eigene Ausführungsidentität. Der Dispatcher in `root_policy::authorize` führt ausschließlich diese Identität zur neuen @@ -104,13 +105,40 @@ Windows-SYSTEM-Jobabnahme. Es wurden kein Serverdaemon oder DB-Test gestartet, keine Dienste ersetzt, Schlüssel/Journale gelesen oder RMM-Jobs erzeugt. Geschützte Rohbelege liegen unter `devstate/server-windows-policy//`. -Der nächste kleine Integrationspatch bleibt **geplant, nicht ausgeführt**: -Nach nativer Helper-/Clock-/SCM-Qualifikation im Shared Domain ausschließlich den -Windows-`SetServiceState`-Zweig für `system` und diese expliziten Caps ergänzen; -alle anderen Windows-SYSTEM-Aktionen bleiben verweigert. Danach im Agenten den -bereits typisierten Helper-Execute-Pfad mit unabhängiger Helper-Sync-Bestätigung -und erhaltenem Grant-/Outcomeledger anbinden. Die WebUI muss die konkrete -SYSTEM-Identität sichtbar im unveränderlichen SCM-Plan darstellen und weiterhin -interaktiv genehmigen. Erst nach gesondert geprüftem Policy-/Rechtesetup folgen -neue tatsächliche WebUI-Pläne und unabhängige OS-Nachprüfungen. Spezifikation und -Projektentscheidungen werden vom Eltern-Orchestrator nach dem Review abgestimmt. +## Enger Domain-/WebUI-Schnitt und erster Linuxnachweis + +`Action::available_for` verlangt bei SYSTEM ausschließlich typisiertes SCM mit +Windowsbasis ohne Linuxbasis, Helper-/Sync-/SCM-Caps und `running|stopped`. +Alle anderen SYSTEM-Aktionen werden auch bei Linuxcaps schon hier verweigert; +die zentrale Policy bleibt eine zusätzliche unabhängige Grenze. Linux-Root- +und Agentservice-Verhalten sowie die Goldenbytes bleiben erhalten. + +Die WebUI bietet SYSTEM ausdrücklich nur für diese Aktion und mit eigenem +`system:execute` an. Sie prüft feste Fixturekennung, Zustand und120s/64KiB- +Obergrenzen. Die konkrete Identität/Dienst-/Asset-/Zustandsbindung stammt in der +Detailansicht aus den gespeicherten Planbytes. Unlesbare Bytes erzeugen einen +Fehlerhinweis; die strenge Hash-/Genehmigungsprüfung bleibt bestehen. Keine +automatische Rechteerhöhung und keine zusätzlichen Genehmigungscontrols. + +Lokal15 Domain- und26 betroffene Webtests, Clippy, Typecheck und Webbuild +bestanden. Nach unabhängigem Review wurden zwei konkrete Fehler behoben: +SYSTEM durfte nicht in den Linux-Fallback anderer Aktionen fallen; fehlerhafte +Planbytes dürfen den Renderer nicht abstürzen lassen. Die früheren lokalen +Belege bleiben getrennt erhalten. + +Danach15 Domain-Bibliothekstests auf der Cloud-Linux-VM tatsächlich bestanden, +Fall `0dd12ed9-cc0b-407e-8b27-9334527ef91d`, Binary `635a6dd6…`, Manifest +`build-162ecea1…`.0 fehlgeschlagen/ignoriert/gefiltert, geleerte Umgebung und +eigene Netzwerknamespace; keine Dienste, DB-/RMM-Jobs oder Zielwirkung. +[`domain_scm_acceptance.py`](../deploy/domain_scm_acceptance.py) verlangt diesen +exakten Linuxbeleg vor der noch offenen Windows-Unitphase desselben Manifests. +Geschützte Rohbelege liegen unter `devstate/domain-scm/`. + +Der vorbereitete Runtime-/Helperclient-SCM-Pfad ist **noch nicht freigegeben**: +Ein unabhängiger Quellreview fand den Vor-Delegation-Abbruchfall, bei dem eine +lokale SYSTEM-Consumption ohne Helperconsumption den späteren Sync dauerhaft +verweigern würde. Diese Invariante wird vor einer Runtimequalifikation korrigiert; +keine Abschwächung des gemeinsamen Helperabgleichs. Neue Capabilities, Jobs, +Clockqualifikation oder Helperwirkungen wurden dadurch nicht aktiviert. +Tatsächliche Helper-/Clock-/SCM-/WebUI- und Policy-/Rechtesetupabnahmen bleiben +eigenständige nächste Schritte unter Spezifikation1.16. diff --git a/web/src/api.test.ts b/web/src/api.test.ts index 7860755..f87eded 100644 --- a/web/src/api.test.ts +++ b/web/src/api.test.ts @@ -65,6 +65,20 @@ describe('JSON contract boundary', () => { expect(() => validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root' } })).toThrow('agent_service'); validateInput({ ...input, parameters: { ...input.parameters, variants: [{ ...windows, script_utf8: "\ufeffWrite-Output 'é'\r\n" }] } }); }); + it('allows SYSTEM only for exact bounded fixture SCM parameters without changing Linux restart', () => { + const input: PlanInput = { tenant_id: 't', action: 'set_service_state', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', unit: 'RmmDiscoveryFixtureService', state: 'running', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed SCM plan' }; + const before = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(before); + validateInput({ ...input, parameters: { ...input.parameters, state: 'stopped' } }); + for (const parameters of [ + { ...input.parameters, unit: 'Spooler' }, { ...input.parameters, unit: 'RmmDiscoveryFixture*' }, + { ...input.parameters, state: 'restarted' }, { ...input.parameters, timeout_seconds: 121 }, + { ...input.parameters, max_output_bytes: 65537 }, { ...input.parameters, script_utf8: 'whoami' }, + { ...input.parameters, execution_identity: 'SYSTEM' }, + ]) expect(() => validateInput({ ...input, parameters })).toThrow(); + expect(() => validateInput({ ...input, action: 'refresh_inventory' })).toThrow('SYSTEM'); + expect(() => validateInput({ ...input, action: 'run_script', parameters: { ...input.parameters, variants: [{ os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: 'whoami' }] } })).toThrow('agent_service'); + validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root', unit: 'rmm-mvp-test.service', state: 'restarted', timeout_seconds: 180 } }); + }); it('accepts explicit existing dev simulation evidence but not a principal-name guess', () => { expect(session({ principal: 'sim-test', tenant_id: 't', testsimulation: true, csrf_token: 'csrf' }).principal.simulated).toBe(true); expect(() => session({ principal: 'sim-test', tenant_id: 't', csrf_token: 'csrf' })).toThrow(); diff --git a/web/src/api.ts b/web/src/api.ts index 2028afb..276712e 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -85,7 +85,12 @@ export function validateInput(input: PlanInput): void { }) || new Set(variants.map(v => record(v).os_family)).size !== variants.length) throw new Error('Je Plattform genau eine passende UTF-8 Variante (max.32KiB); PowerShell5.1: ASCII oder explizites UTF-8-BOM vor Hashbildung'); if (variants.some(v => record(v).os_family === 'windows') && input.parameters.execution_identity !== 'agent_service') throw new Error('Windows PowerShell benötigt agent_service; kein SYSTEM-/Root-Fallback'); } - if (!['agent_service', 'root'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich'); + if (!['agent_service', 'root', 'system'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich'); + if (input.parameters.execution_identity === 'system') { + if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste; keine SYSTEM-Shell'); + validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes); + if (Object.keys(input.parameters).some(k => !['execution_identity', 'unit', 'state', 'timeout_seconds', 'max_output_bytes'].includes(k))) throw new Error('SYSTEM-Dienstauftrag enthält fremde Parameter'); + } const required = (key: string) => text(input.parameters[key], `parameters.${key}`); if (input.action === 'refresh_inventory') required('scope'); if (input.action === 'query_logs') { required('unit'); const since = Date.parse(required('since')), until = Date.parse(required('until')); if (!Number.isFinite(since) || !Number.isFinite(until) || until <= since) throw new Error('Exaktes Log-Zeitfenster erforderlich'); if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein'); } @@ -94,6 +99,11 @@ export function validateInput(input: PlanInput): void { if (input.action === 'apply_updates') { required('provider'); if (!Array.isArray(input.parameters.packages) || !input.parameters.packages.length || !input.parameters.packages.every(v => typeof v === 'string' && v.length > 0)) throw new Error('Feste Updatepakete erforderlich'); if (input.parameters.reboot_policy !== 'never') throw new Error('Kein impliziter Reboot; eigenen festen Plan erstellen'); } if (input.action === 'reboot') { required('reason'); required('dependency_group'); const n = input.parameters.reconnect_timeout_seconds; if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 60 || n > 3600) throw new Error('Reboot-Wiederanmeldefrist muss 60–3600 s sein'); } } +export function validateSystemService(unit: unknown, state: unknown, runtime: unknown, output: unknown): void { + if (typeof unit !== 'string' || !/^RmmDiscoveryFixture[A-Za-z0-9_-]+$/.test(unit) || unit.length > 80) throw new Error('Exakter eigener Windows-Fixturedienst erforderlich'); + if (state !== 'running' && state !== 'stopped') throw new Error('SYSTEM-Dienstzustand ausschließlich running oder stopped'); + if (typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 1 || runtime > 120 || typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1 || output > 65536) throw new Error('SYSTEM-Dienstlimits maximal 120 s und 64 KiB'); +} /** These are immutable target definitions, never evidence of executable jobs. */ export function planTargetPreviews(plan: RecordValue): unknown[] | null { if (Array.isArray(plan.resolved_targets) && plan.resolved_targets.some(value => diff --git a/web/src/json-view.test.tsx b/web/src/json-view.test.tsx index 93809e5..8c0ec18 100644 --- a/web/src/json-view.test.tsx +++ b/web/src/json-view.test.tsx @@ -25,3 +25,23 @@ it('renders hostile log content only as text, without executable nodes, approval vi.unstubAllGlobals(); } }); + +it('shows fixed SYSTEM identity and service state from stored plan bytes without approving or issuing requests', async () => { + const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) }); + try { + const { SystemPlanNotice } = await import('./main'); + const payload = { jobs: [{ payload: { execution_identity: 'system', asset_id: 'fixed-asset', action: { action: 'set_service_state', unit: 'RmmDiscoveryFixtureService', state: 'stopped' } } }] }; + const plan = { plan_payload_bytes: Array.from(new TextEncoder().encode(JSON.stringify(payload))), jobs: [{ payload: { execution_identity: 'root', action: { unit: 'untrusted-view' } } }] }; + const html = renderToStaticMarkup(); + expect(html).toContain('SYSTEM'); expect(html).toContain('system:execute'); expect(html).toContain('Identität: system'); + for (const expected of ['fixed-asset', 'RmmDiscoveryFixtureService', 'Zielzustand: stopped', 'Keine SYSTEM-Shell']) expect(html).toContain(expected); + expect(html).not.toContain('untrusted-view'); expect(html).not.toMatch(/<(button|input|form|pre)\b/); + expect(renderToStaticMarkup()).toBe(''); + for (const plan_payload_bytes of [[255], [123], 'invalid']) { + const invalid = renderToStaticMarkup(); + expect(invalid).toContain('role="alert"'); expect(invalid).toContain('nicht lesbar'); + expect(invalid).not.toMatch(/<(button|input|form)\b/); + } + expect(fetch).not.toHaveBeenCalled(); + } finally { vi.unstubAllGlobals(); } +}); diff --git a/web/src/main.tsx b/web/src/main.tsx index 4cc98c1..e160aa5 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -3,11 +3,18 @@ import { createRoot } from 'react-dom/client'; import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api'; import './style.css'; import { AdminControl, Catalog, TenantControls } from './management'; -import { allowed, availableActions, parseStrictJson, rootWarning, validateSensitiveInput, verifyPlanIntegrity } from './safety'; +import { allowed, availableActions, parseStrictJson, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity } from './safety'; import { Login } from './login'; const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler'; export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return
{label}
{pretty(value)}
; } +export function SystemPlanNotice({ plan }: { plan: RecordValue }) { + let jobs: RecordValue[]; + try { jobs = systemPlanJobs(plan); } + catch { return ; } + if (!jobs.length) return null; + return ; +} function ErrorBox({ error }: { error: string | null }) { return error ?
{error}
: null; } function useResource(load: (signal: AbortSignal) => Promise, deps: React.DependencyList, poll = false) { const [data, setData] = useState(null), [error, setError] = useState(null), [revision, setRevision] = useState(0); @@ -51,8 +58,9 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut {action === 'apt_native_acceptance' &&

NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.

} {action === 'run_script' ? <>{scriptPlatform === 'mixed' ?