Bind typed SYSTEM service plans and qualify Domain contract on cloud Linux
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 05:30:21 +01:00
parent 5f356a92ac
commit e85f9ed750
10 changed files with 422 additions and 17 deletions
+89
View File
@@ -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<String> = [
"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(),
+185
View File
@@ -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()
+9
View File
@@ -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
+41 -13
View File
@@ -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/<Fall>/`.
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.
+14
View File
@@ -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();
+11 -1
View File
@@ -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 =>
+20
View File
@@ -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(<SystemPlanNotice plan={plan}/>);
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(<SystemPlanNotice plan={{ plan_payload_bytes: Array.from(new TextEncoder().encode('{"jobs":[]}')) }}/>)).toBe('');
for (const plan_payload_bytes of [[255], [123], 'invalid']) {
const invalid = renderToStaticMarkup(<SystemPlanNotice plan={{ plan_payload_bytes }}/>);
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(); }
});
+11 -2
View File
@@ -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 <details open><summary>{label}</summary><pre>{pretty(value)}</pre></details>; }
export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
let jobs: RecordValue[];
try { jobs = systemPlanJobs(plan); }
catch { return <aside role="alert" className="error">Gespeicherte Planbytes sind nicht lesbar. Keine verlässliche SYSTEM-Plananzeige; Genehmigungsverifikation muss erfolgreich sein.</aside>; }
if (!jobs.length) return null;
return <aside className="warning" aria-label="Feste SYSTEM-Dienstaktionen"><p>{systemWarning}</p><ul>{jobs.map((payload, i) => { const action = record(payload.action); return <li key={i}>Identität: system · Asset: {String(payload.asset_id)} · Dienst: {String(action.unit)} · Zielzustand: {String(action.state)}</li>; })}</ul><p>Diese Definitionen stammen aus den gespeicherten Planbytes; die vollständigen Zielpayloads und Hashes stehen darunter.</p></aside>;
}
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
@@ -51,8 +58,9 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
{action === 'apt_native_acceptance' && <p className="warning">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.</p>}
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive; keine ExecutionPolicy-Umgehung. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={action !== 'set_service_state' || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
{identity === 'root' && <p className="warning">{rootWarning}</p>}
{identity === 'system' && <p className="warning">{systemWarning}</p>}
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" placeholder="UUIDs durch Komma getrennt; keine URL"/></label>
<label>Begründung<input name="reason" required maxLength={1024}/></label><p>Feste Ziele ({selected.length}): {selected.join(', ') || 'keine ausgewählt'}</p>{action === 'reboot' || action === 'apply_updates' || action === 'ensure_package' ? <p className="warning">Zieländerung: Testumfang separat abstimmen. Keine implizite Reboot-/Updateerlaubnis. Neue Versuche und Folgejobs benötigen neue feste Pläne.</p> : null}<button disabled={busy || !selected.length}>Plan erstellen · noch keine Ausführung</button><ErrorBox error={error}/>
@@ -67,6 +75,7 @@ function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id:
const blockers = plan.data ? approvalBlockers(plan.data) : ['Plan noch nicht geladen'];
return <section><h2>Unveränderlicher Plan / Genehmigungsdetail</h2><ErrorBox error={plan.error}/><ErrorBox error={error}/>{plan.data && <>
<p>Plan-ID: {id}</p><p>Exakter gespeicherter Planhash: <code>{stringField(plan.data, 'plan_hash')}</code></p><p>Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.</p>
<SystemPlanNotice plan={plan.data}/>
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
+18
View File
@@ -30,6 +30,24 @@ describe('immutable catalog and strict import contracts', () => {
});
});
describe('root and dedicated dev-test APT actions', () => {
it('requires independent system scope and verifies the exact bounded SYSTEM service plan', async () => {
const value: 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: '', start_before: '', offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'unit only' };
for (const permissions of [undefined, [], ['root:execute']]) await expect(validateSensitiveInput(value, { ...auth, permissions })).rejects.toThrow('system:execute');
const systemAuth = { ...auth, permissions: ['system:execute'] };
const before = JSON.stringify(value); await validateSensitiveInput(value, systemAuth); expect(JSON.stringify(value)).toBe(before);
await expect(validateSensitiveInput({ ...value, action: 'run_script' }, systemAuth)).rejects.toThrow('typisierte');
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, state: 'restarted' } }, systemAuth)).rejects.toThrow('running');
const payload = { execution_identity: 'system', asset_id: 'asset', action: { action: 'set_service_state', unit: 'RmmDiscoveryFixtureService', state: 'running' }, max_runtime_seconds: 30, max_output_bytes: 4096 };
const plan_payload = { jobs: [{ payload }] }, raw = new TextEncoder().encode(JSON.stringify(plan_payload));
const plan = { plan_payload, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: plan_payload.jobs };
await verifyPlanIntegrity(plan);
await expect(verifyPlanIntegrity({ ...plan, plan_payload_bytes: undefined })).rejects.toThrow('exakte gespeicherte');
const changed = structuredClone(plan_payload), first = changed.jobs[0]; if (!first) throw new Error('One fixed service job required'); first.payload.action.state = 'stopped';
await expect(verifyPlanIntegrity({ ...plan, plan_payload: changed })).rejects.toThrow('widerspricht');
const shell = { jobs: [{ payload: { ...payload, action: { action: 'run_script', interpreter: 'powershell' } } }] }, shellRaw = new TextEncoder().encode(JSON.stringify(shell));
await expect(verifyPlanIntegrity({ plan_payload_bytes: Array.from(shellRaw), plan_hash: await sha256(shellRaw) })).rejects.toThrow();
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, execution_identity: 'root' } }, systemAuth)).rejects.toThrow('root:execute');
});
it('shows native acceptance only with explicit server simulation evidence, never upgrades identity', async () => {
expect(availableActions(auth, actions)).toContain('apt_native_acceptance');
expect(availableActions({ ...auth, principal: { ...auth.principal, simulated: false } }, actions)).not.toContain('apt_native_acceptance');
+24 -1
View File
@@ -1,7 +1,8 @@
import { Action, PlanInput, RecordValue, Session, record, text } from './api';
import { Action, PlanInput, RecordValue, Session, record, text, validateSystemService } from './api';
export const hashPattern = /^[0-9a-f]{64}$/;
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst und running/stopped. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; }
export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; }
export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); }
@@ -72,6 +73,11 @@ export function validateAptManifest(value: unknown, acceptance: boolean): Record
export async function verifyAptManifest(value: unknown, acceptance: boolean) { const m = validateAptManifest(value, acceptance); if (await sha256(bytes(m.transaction_bytes)) !== m.transaction_sha256) throw new Error('APT Transaktionshash stimmt nicht überein'); }
export async function validateSensitiveInput(input: PlanInput, auth: Session) {
if (input.parameters.execution_identity === 'root' && !allowed(auth, 'root:execute')) throw new Error('root:execute unbekannt oder nicht erteilt; keine Rechteerhöhung');
if (input.parameters.execution_identity === 'system') {
if (!allowed(auth, 'system:execute')) throw new Error('system:execute unbekannt oder nicht erteilt; root:execute enthält dieses Recht nicht');
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen');
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
}
if (input.action === 'apt_native_acceptance') {
if (!auth.principal.simulated || input.parameters.execution_identity !== 'root') throw new Error('APT-Abnahme ausschließlich explizit simuliert und root');
const m = validateAptManifest(input.parameters.apt_manifest, true), t = record(m.resolved_apt_transaction);
@@ -88,13 +94,30 @@ export async function validateSensitiveInput(input: PlanInput, auth: Session) {
}
}
}
/** Display only definitions decoded from the exact hashed plan bytes. */
export function systemPlanJobs(plan: RecordValue): RecordValue[] {
if (plan.plan_payload_bytes === undefined) return [];
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes(plan.plan_payload_bytes))));
if (!Array.isArray(parsed.jobs)) return [];
return parsed.jobs.map(value => record(record(value).payload)).filter(payload => payload.execution_identity === 'system');
}
export async function verifyPlanIntegrity(plan: RecordValue) {
if (plan.plan_payload_bytes === undefined && Array.isArray(plan.jobs) && plan.jobs.some(value => {
const payload = record(value).payload;
return payload !== null && typeof payload === 'object' && record(payload).execution_identity === 'system';
})) throw new Error('SYSTEM-Plan benötigt exakte gespeicherte Planbytes');
if (plan.plan_payload_bytes !== undefined) {
const exactBytes = bytes(plan.plan_payload_bytes); hash(plan.plan_hash);
if (await sha256(exactBytes) !== plan.plan_hash) throw new Error('Planhash stimmt nicht mit gespeicherten Bytes überein');
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
if (plan.plan_payload !== undefined && canonical(parsed) !== canonical(plan.plan_payload)) throw new Error('Planansicht widerspricht gespeicherten Bytes');
}
for (const payload of systemPlanJobs(plan)) {
const action = record(payload.action);
exact(action, ['action', 'unit', 'state']);
if (action.action !== 'set_service_state') throw new Error('SYSTEM-Plan enthält keine typisierte Dienstaktion');
validateSystemService(action.unit, action.state, payload.max_runtime_seconds, payload.max_output_bytes);
}
const jobs = Array.isArray(plan.jobs) ? plan.jobs : Array.isArray(plan.resolved_targets) ? plan.resolved_targets : [];
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');