feat: deploy platform inventory and signed APT retry client compatibility
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -15,6 +15,20 @@ struct Observation {
|
||||
data: Value,
|
||||
}
|
||||
pub fn validate(bytes: &[u8], now: DateTime<Utc>) -> Result<Value, &'static str> {
|
||||
validate_for_scope(bytes, now, "linux.base")
|
||||
}
|
||||
/// Snapshot scope is supplied by the authenticated ingestion path, never inferred
|
||||
/// from an arbitrary observation's label. Windows does not manufacture inodes.
|
||||
pub fn validate_for_scope(
|
||||
bytes: &[u8],
|
||||
now: DateTime<Utc>,
|
||||
scope: &str,
|
||||
) -> Result<Value, &'static str> {
|
||||
let prefix = match scope {
|
||||
"linux.base" => "linux.",
|
||||
"windows.base" => "windows.",
|
||||
_ => return Err("UNSUPPORTED_INVENTORY_SCOPE"),
|
||||
};
|
||||
if bytes.len() > 512 * 1024 {
|
||||
return Err("INVENTORY_SIZE");
|
||||
}
|
||||
@@ -23,10 +37,36 @@ pub fn validate(bytes: &[u8], now: DateTime<Utc>) -> Result<Value, &'static str>
|
||||
let observations = base.remove("observations");
|
||||
let started = base.remove("collection_started_at");
|
||||
let completed = base.remove("collection_completed_at");
|
||||
let inventory: crate::Inventory =
|
||||
serde_json::from_value(Value::Object(base)).map_err(|_| "INVALID_BASE_INVENTORY")?;
|
||||
if !inventory.validate() {
|
||||
return Err("INVALID_BASE_INVENTORY");
|
||||
if scope == "windows.base" {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct WindowsInventory {
|
||||
os: String,
|
||||
hostname: String,
|
||||
architecture: String,
|
||||
root_total_bytes: u64,
|
||||
root_available_bytes: u64,
|
||||
root_available_inodes: Option<u64>,
|
||||
}
|
||||
let inventory: WindowsInventory =
|
||||
serde_json::from_value(Value::Object(base)).map_err(|_| "INVALID_BASE_INVENTORY")?;
|
||||
if !inventory.os.starts_with("Windows")
|
||||
|| inventory.os.len() > 4096
|
||||
|| inventory.hostname.is_empty()
|
||||
|| inventory.hostname.len() > 255
|
||||
|| inventory.architecture != "x86_64"
|
||||
|| inventory.root_total_bytes == 0
|
||||
|| inventory.root_available_bytes > inventory.root_total_bytes
|
||||
|| inventory.root_available_inodes.is_some()
|
||||
{
|
||||
return Err("INVALID_WINDOWS_BASE_INVENTORY");
|
||||
}
|
||||
} else {
|
||||
let inventory: crate::Inventory =
|
||||
serde_json::from_value(Value::Object(base)).map_err(|_| "INVALID_BASE_INVENTORY")?;
|
||||
if !inventory.validate() {
|
||||
return Err("INVALID_BASE_INVENTORY");
|
||||
}
|
||||
}
|
||||
if let Some(observations) = observations {
|
||||
let started: DateTime<Utc> =
|
||||
@@ -57,7 +97,7 @@ pub fn validate(bytes: &[u8], now: DateTime<Utc>) -> Result<Value, &'static str>
|
||||
}
|
||||
let o: Observation =
|
||||
serde_json::from_value(item.clone()).map_err(|_| "INVALID_OBSERVATION")?;
|
||||
if !o.scope.starts_with("linux.")
|
||||
if !o.scope.starts_with(prefix)
|
||||
|| o.scope.len() > 64
|
||||
|| !o
|
||||
.scope
|
||||
@@ -114,4 +154,27 @@ mod tests {
|
||||
unknown["tenant_id"] = json!("forged");
|
||||
assert!(validate(&serde_json::to_vec(&unknown).unwrap(), now).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn windows_scope_does_not_weaken_linux_or_accept_platform_spoofing() {
|
||||
let now = Utc::now();
|
||||
let mut v = base();
|
||||
v["os"] = json!("Windows 11 Pro");
|
||||
v["root_available_inodes"] = Value::Null;
|
||||
let bytes = serde_json::to_vec(&v).unwrap();
|
||||
assert!(validate(&bytes, now).is_err());
|
||||
assert!(validate_for_scope(&bytes, now, "windows.base").is_ok());
|
||||
assert!(validate_for_scope(&bytes, now, "arbitrary.base").is_err());
|
||||
v["root_available_inodes"] = json!(0);
|
||||
assert!(validate_for_scope(&serde_json::to_vec(&v).unwrap(), now, "windows.base").is_err());
|
||||
v["root_available_inodes"] = Value::Null;
|
||||
v["collection_started_at"] = json!(now);
|
||||
v["collection_completed_at"] = json!(now);
|
||||
v["observations"] = json!([{"scope":"linux.os","source_id":"windows.native","observed_at":now,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{}}]);
|
||||
assert_eq!(
|
||||
validate_for_scope(&serde_json::to_vec(&v).unwrap(), now, "windows.base").unwrap_err(),
|
||||
"INVALID_OBSERVATION_SCOPE"
|
||||
);
|
||||
v["observations"][0]["scope"] = json!("windows.os");
|
||||
assert!(validate_for_scope(&serde_json::to_vec(&v).unwrap(), now, "windows.base").is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ pub async fn ingest(
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
control_lock(&mut tx, tenant, agent).await?;
|
||||
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
|
||||
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence,capabilities FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
|
||||
let active = row.get::<Option<DateTime<Utc>>, _>("revoked_at").is_none()
|
||||
&& row.get::<i64, _>("connection_generation") == i64::try_from(e.connection_generation)?
|
||||
&& row.get::<String, _>("transport") == transport;
|
||||
@@ -145,7 +145,7 @@ pub async fn ingest(
|
||||
}
|
||||
Some(Payload::InventorySnapshot(s)) => {
|
||||
ensure!(
|
||||
s.scope == "linux.base"
|
||||
matches!(s.scope.as_str(), "linux.base" | "windows.base")
|
||||
&& s.schema_version == 1
|
||||
&& s.chunk_count == 1
|
||||
&& s.chunk_index == 0
|
||||
@@ -157,12 +157,18 @@ pub async fn ingest(
|
||||
s.sha256 == Sha256::digest(&s.data).as_slice(),
|
||||
"snapshot hash mismatch"
|
||||
);
|
||||
let inventory = rmm_domain::inventory_document::validate(&s.data, Utc::now())
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let capabilities: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
ensure!(
|
||||
capabilities.contains(&format!("{}/1", s.scope)),
|
||||
"snapshot capability mismatch"
|
||||
);
|
||||
let inventory =
|
||||
rmm_domain::inventory_document::validate_for_scope(&s.data, Utc::now(), &s.scope)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let mut identity = e.clone();
|
||||
identity.connection_generation = 0;
|
||||
let hash = hex::encode(Sha256::digest(identity.encode_to_vec()));
|
||||
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,$5,$6,'linux.base','valid','partial',$7,$8,$9) ON CONFLICT(tenant_id,message_id) DO NOTHING").bind(tenant).bind(agent).bind(Uuid::parse_str(&e.message_id)?).bind(Uuid::parse_str(&e.boot_id)?).bind(i64::try_from(e.sequence)?).bind(observed).bind(Uuid::parse_str(&s.snapshot_id)?).bind(serde_json::to_value(inventory)?).bind(&hash).execute(&mut *tx).await?;
|
||||
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,$5,$6,$10,'valid','partial',$7,$8,$9) ON CONFLICT(tenant_id,message_id) DO NOTHING").bind(tenant).bind(agent).bind(Uuid::parse_str(&e.message_id)?).bind(Uuid::parse_str(&e.boot_id)?).bind(i64::try_from(e.sequence)?).bind(observed).bind(Uuid::parse_str(&s.snapshot_id)?).bind(serde_json::to_value(inventory)?).bind(&hash).bind(&s.scope).execute(&mut *tx).await?;
|
||||
let stored: String =
|
||||
sqlx::query_scalar("SELECT payload_sha256 FROM observations WHERE message_id=$1")
|
||||
.bind(Uuid::parse_str(&e.message_id)?)
|
||||
|
||||
@@ -128,7 +128,7 @@ async fn device_list(
|
||||
.map_err(|e| e.0)?;
|
||||
let mut page =
|
||||
crate::pagination::Cursor::parse(state, &principal, "devices:agent_id:asc", query)?;
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
let rows = sqlx::query("SELECT a.agent_id,a.asset_id,a.revoked_at,a.last_contact_at,a.certificate_sha256,a.last_authenticated_certificate_sha256,a.last_authenticated_at,a.capabilities,a.enrollment_generation,a.assignment_version,o.observed_at,o.received_at,o.data,o.source_id FROM agent_installations a LEFT JOIN LATERAL (SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND received_at<=$2 ORDER BY observed_at DESC, received_at DESC LIMIT 1) o ON true WHERE ($1::uuid IS NULL OR a.asset_id=$1) AND a.agent_id>$3 AND a.created_at<=$2 ORDER BY a.agent_id LIMIT $4")
|
||||
.bind(asset)
|
||||
.bind(page.as_of).bind(page.last).bind(i64::from(page.limit)+1)
|
||||
.fetch_all(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
|
||||
@@ -141,7 +141,7 @@ async fn device_list(
|
||||
let revoked: Option<chrono::DateTime<Utc>> = r.get("revoked_at");
|
||||
let age = last.map(|t| (Utc::now()-t).num_seconds());
|
||||
let presence = if revoked.is_some() { "revoked" } else { match age { None=>"never_seen",Some(n) if n<90=>"online",Some(n) if n<180=>"stale",_=>"unreachable" } };
|
||||
json!({"agent_id":r.get::<Uuid,_>("agent_id"),"asset_id":r.get::<Uuid,_>("asset_id"),"certificate_sha256":r.get::<String,_>("certificate_sha256"),"last_authenticated_certificate_sha256":r.get::<Option<String>,_>("last_authenticated_certificate_sha256"),"last_authenticated_at":r.get::<Option<chrono::DateTime<Utc>>,_>("last_authenticated_at"),"capabilities":r.get::<Value,_>("capabilities"),"enrollment_generation":r.get::<i64,_>("enrollment_generation"),"assignment_version":r.get::<i64,_>("assignment_version"),"presence":presence,"last_contact_at":last,"inventory":r.get::<Option<Value>,_>("data"),"observed_at":r.get::<Option<chrono::DateTime<Utc>>,_>("observed_at"),"received_at":r.get::<Option<chrono::DateTime<Utc>>,_>("received_at"),"source_id":"linux.base","quality":if r.get::<Option<Value>,_>("data").is_some(){"valid"}else{"unknown"},"completeness":"partial","health":"unknown"})
|
||||
json!({"agent_id":r.get::<Uuid,_>("agent_id"),"asset_id":r.get::<Uuid,_>("asset_id"),"certificate_sha256":r.get::<String,_>("certificate_sha256"),"last_authenticated_certificate_sha256":r.get::<Option<String>,_>("last_authenticated_certificate_sha256"),"last_authenticated_at":r.get::<Option<chrono::DateTime<Utc>>,_>("last_authenticated_at"),"capabilities":r.get::<Value,_>("capabilities"),"enrollment_generation":r.get::<i64,_>("enrollment_generation"),"assignment_version":r.get::<i64,_>("assignment_version"),"presence":presence,"last_contact_at":last,"inventory":r.get::<Option<Value>,_>("data"),"observed_at":r.get::<Option<chrono::DateTime<Utc>>,_>("observed_at"),"received_at":r.get::<Option<chrono::DateTime<Utc>>,_>("received_at"),"source_id":r.get::<Option<String>,_>("source_id"),"quality":if r.get::<Option<Value>,_>("data").is_some(){"valid"}else{"unknown"},"completeness":"partial","health":"unknown"})
|
||||
}).collect::<Vec<_>>();
|
||||
let next = if truncated {
|
||||
Some(page.next(state, rows[usize::from(page.limit) - 1].get("agent_id"))?)
|
||||
|
||||
@@ -25,6 +25,39 @@ STATE = cloud.ROOT / 'devstate/cloud-apt-retry'
|
||||
CASES = ('apt_install_retry', 'apt_native_update', 'ensure_package', 'apply_updates')
|
||||
|
||||
|
||||
def upgrade_agent(payload):
|
||||
"""Parser compatibility upgrade only; same identity/journal, no execution."""
|
||||
import sqlite3
|
||||
os.umask(0o077)
|
||||
state = Path('/var/lib/rmm-agent-remote'); binary = Path('/usr/local/libexec/rmm-agent-remote')
|
||||
require(not binary.is_symlink() and binary.stat().st_uid == 0 and binary.stat().st_mode&0o022 == 0 and
|
||||
hashlib.sha256(binary.read_bytes()).hexdigest() == payload['previous_sha256'], 'reviewed prior agent required')
|
||||
require(json.loads((state/'identity.json').read_text())['agent_id'] == payload['agent_id'], 'fixed identity required')
|
||||
with sqlite3.connect((state/'journal.sqlite').as_uri()+'?mode=ro', uri=True) as db:
|
||||
require(db.execute('PRAGMA integrity_check').fetchone()[0] == 'ok' and
|
||||
db.execute("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired')").fetchone()[0] == 0,
|
||||
'unresolved native job')
|
||||
backup = Path('/var/lib/rmm-bootstrap-history')/('cloud-agent-schema3-'+payload['id']); backup.mkdir(mode=0o700)
|
||||
raw = base64.b64decode(payload['binary'], validate=True)
|
||||
require(hashlib.sha256(raw).hexdigest() == payload['sha256'] and raw[:6] == b'\x7fELF\x02\x01' and raw[18:20] == b'\x3e\x00', 'reviewed x64 artifact')
|
||||
staged = backup/'agent-next'
|
||||
with staged.open('xb') as f: f.write(raw); f.flush(); os.fsync(f.fileno()); os.fchmod(f.fileno(), 0o755)
|
||||
subprocess.run(['/lib64/ld-linux-x86-64.so.2','--list',str(staged)], capture_output=True, check=True, timeout=15)
|
||||
subprocess.run(['systemctl','stop','rmm-agent-remote.service'], capture_output=True, check=True, timeout=20)
|
||||
def manifest():
|
||||
result = {}
|
||||
for p in state.rglob('*'):
|
||||
require(not p.is_symlink(), 'agent state symlink')
|
||||
if p.is_file(): result[str(p.relative_to(state))] = hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
return result
|
||||
before = manifest()
|
||||
require(binary.stat().st_dev == backup.stat().st_dev, 'same-filesystem preserved binary')
|
||||
os.rename(binary, backup/'previous-agent'); os.rename(staged, binary)
|
||||
require(before == manifest(), 'identity/journal bytes changed during upgrade')
|
||||
subprocess.run(['systemctl','start','rmm-agent-remote.service'], capture_output=True, check=True, timeout=20)
|
||||
return dict(binary_sha256=payload['sha256'], state_preserved_before_start=True, package_effects=False, backup=str(backup))
|
||||
|
||||
|
||||
def switch_endpoint(payload):
|
||||
import sqlite3
|
||||
os.umask(0o077)
|
||||
|
||||
@@ -77,11 +77,35 @@ def status(payload):
|
||||
|
||||
|
||||
def deploy(payload):
|
||||
import io
|
||||
import tarfile
|
||||
root = Path('/opt/rust-discovery'); backup = root/'devstate'/('source-upgrade-'+payload['id'])
|
||||
record = json.loads((backup/'source.json').read_text())
|
||||
require(json.loads((backup/'build-result.json').read_text())['exit_code'] == 0, 'build must pass')
|
||||
require(all(hashlib.sha256((root/name).read_bytes()).hexdigest() == sha for name,sha in record['files'].items()), 'source drift')
|
||||
require(not (backup/'deploy-result.json').exists(), 'deployment already recorded')
|
||||
raw = base64.b64decode(payload['web_tar'], validate=True)
|
||||
require(hashlib.sha256(raw).hexdigest() == payload['web_sha256'], 'reviewed web archive hash')
|
||||
# Publish immutable hashed assets before index, keeping the bind-mounted
|
||||
# dist directory inode. Retain old files; no recursive deletion.
|
||||
with tarfile.open(fileobj=io.BytesIO(raw), mode='r:') as archive:
|
||||
members = sorted(archive.getmembers(), key=lambda m: m.name == 'index.html')
|
||||
require(any(m.name == 'index.html' for m in members), 'built UI index required')
|
||||
for member in members:
|
||||
name = member.name
|
||||
require(member.isfile() and not Path(name).is_absolute() and '..' not in Path(name).parts and
|
||||
(name == 'index.html' or name.startswith('assets/') and name.endswith(('.js','.css'))), 'built web path allowlist')
|
||||
data = archive.extractfile(member).read(); require(len(data) < 2*1024*1024, 'web file limit')
|
||||
dest = root/'web/dist'/name
|
||||
require(not dest.is_symlink() and not dest.parent.is_symlink(), 'web symlink')
|
||||
dest.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
|
||||
if dest.exists():
|
||||
retained = backup/'web'/name; retained.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with retained.open('xb') as f: f.write(dest.read_bytes()); f.flush(); os.fsync(f.fileno())
|
||||
next_path = dest.with_name(dest.name+'.upgrade-next')
|
||||
fd = os.open(next_path, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW, 0o644)
|
||||
with os.fdopen(fd, 'wb') as f: f.write(data); f.flush(); os.fsync(f.fileno()); os.fchmod(f.fileno(), 0o644)
|
||||
os.replace(next_path, dest)
|
||||
cmd = ['docker','compose','--env-file',str(root/'devstate/.env'),'-f',str(root/'deploy/server.compose.yaml')]
|
||||
# Existing migration image runs without rebuild; preserves PG volume/PKI.
|
||||
migrate = subprocess.run(cmd+['run','--rm','--no-deps','migrate'], capture_output=True, timeout=25)
|
||||
@@ -115,7 +139,16 @@ def main():
|
||||
target = cloud.contract.protected_json(cloud.ROOT/'devstate/remote-vm.json')['identity']
|
||||
gate = cloud.bootstrap.rpc('server.conf', cloud.server, dict(kind='gate', tenant_id=cloud.TENANT, agent_id=target['agent_id']))
|
||||
require(gate['unresolved'] == 0, 'unresolved cloud job; no server switch')
|
||||
result = cloud.bootstrap.rpc('server.conf', status if args.action == 'status' else deploy, dict(id=ident))
|
||||
payload = dict(id=ident)
|
||||
if args.action == 'deploy':
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w:') as archive:
|
||||
for p in sorted((cloud.ROOT/'web/dist').rglob('*')):
|
||||
if p.is_file():
|
||||
require(not p.is_symlink(), 'built UI symlink')
|
||||
archive.add(p, arcname=str(p.relative_to(cloud.ROOT/'web/dist')), recursive=False)
|
||||
data = stream.getvalue(); payload.update(web_tar=base64.b64encode(data).decode(), web_sha256=hashlib.sha256(data).hexdigest())
|
||||
result = cloud.bootstrap.rpc('server.conf', status if args.action == 'status' else deploy, payload)
|
||||
print(result)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,40 @@
|
||||
# Tatsächlicher Implementierungsstand
|
||||
|
||||
## Cloudserver und Linux-Agent aktualisiert, ohne neue Jobs — 2026-11-13
|
||||
|
||||
Versionierter Cloudserver-Sourceupload/ARM64-Releasebuild tatsächlich erfolgreich,
|
||||
Migrationen erfolgreich und API/Gateway auf neues Image gewechselt. PostgreSQL,
|
||||
PKI und Gerätehistorie erhalten. Neue Inventarvalidierung unterscheidet explizit
|
||||
`linux.base` und `windows.base` samt gemeldeter Capability; Windows erfindet
|
||||
keine Inodes. API übernimmt die gespeicherte Quelle statt jedes Gerät als Linux
|
||||
zu beschriften. Windows-Plattformvalidator nativ-unabhängig lokal geprüft;
|
||||
echter Windows-Clientnachweis folgt separat.
|
||||
|
||||
WebUI akzeptiert jetzt die vollständige signierte Schema-3-Retryreferenz nur
|
||||
im eigenen dev/test-Abnahmeplan; fehlende/zusätzliche Felder, ungültige UUIDs,
|
||||
Null-IDs/Hashplatzhalter und Retry im Normaljob werden verweigert. Bestehende
|
||||
Updateeingabe an den Backendvertrag angeglichen: feste Paketnamen, Versionen
|
||||
aus vollständigem signiertem Manifest. Fremde/fehlende Auswahl bleibt verboten.
|
||||
**25 WebUI-Tests**, Typecheck und Vitebuild bestanden; gebautes UI tatsächlich
|
||||
auf Cloudserver veröffentlicht, alte Assets/Index versioniert erhalten.
|
||||
|
||||
Linux-Agent mit neuem Manifestparser gebaut: **55 Tests**, Clippy/Format/Release
|
||||
bestanden, ELF x86-64 maximal glibc 2.34. Tatsächlicher nativer Loadercheck und
|
||||
identitätsbewahrendes Upgrade auf Cloud-VM bestanden; alle State-/Journalbytes
|
||||
vor neuem Start identisch. SHA
|
||||
`8e79f881b7cd6e11d3bf0c1ce31d4c3f3afed354eeae72b4d188d376d8dff747`.
|
||||
Danach serverseitig **online, sync_ready=true, restore_blocked=false** beobachtet.
|
||||
Weiter **12/12/11, 0 unresolved**, keine neue Wirkung. **8 Cloud- / 28 MVP-Guards**
|
||||
bestanden. APT-Endpunkt anschließend mit unabhängigem Nonce-/Peer-/Sharedledger-
|
||||
Readinesscheck wieder aktiviert; neue zweistündige Policy begrenzt ausschließlich
|
||||
dieses Gerät, festen APT-Provider und simulierten UI-Principal. Keine Rootskript-,
|
||||
Dienst- oder Rebootrechte und keine Jobgenehmigung durch die Policy.
|
||||
|
||||
Neue Paketabnahmen **noch nicht ausgeführt**. Geschützte Belege:
|
||||
`devstate/server-upgrades/`, `devstate/cloud-apt-retry/agent-upgraded.json`,
|
||||
`after-server-agent-upgrade.json`, `policy.json`. Frühere Abschnitte beschreiben
|
||||
jeweils ihren damaligen abgeschlossenen Schritt.
|
||||
|
||||
## Signierte APT-Wiederaufnahme: neue Runtime nativ bereit — 2026-11-13
|
||||
|
||||
Für den explizit beauftragten neuen Abnahmeschritt ist ein eigener sicherer
|
||||
|
||||
@@ -4,6 +4,15 @@ Stand: 2026-11-13 · Spezifikation 1.9 · Linux-MVP weiterhin nicht abgenommen.
|
||||
|
||||
## Neuester APT-/Bootstrapstand
|
||||
|
||||
**Fortsetzung:** Signierter einzelner Retryvertrag implementiert, neue
|
||||
Helper-Sandboxreadiness auf Cloud-VM bestanden. Cloudserver und Linux-Agent
|
||||
identitäts-/journalbewahrend aktualisiert, Linux online/sync-ready. APT-Endpunkt
|
||||
wieder aktiv, befristete ausschließlich begrenzende APT-Testpolicy; noch kein
|
||||
neuer Paketjob. Zähler unverändert 12/12/11. Windows-Inventarserverpfad bereit,
|
||||
nativer Windows-Clientnachweis noch offen. Neueste Details:
|
||||
[implementation-status.md](implementation-status.md). Die folgenden Angaben
|
||||
sind der vorige abgeschlossene Snapshot.
|
||||
|
||||
APT-Ursache und Sourcekorrektur nativ eingegrenzt/geprüft: `--no-download`
|
||||
verhinderte die lokale Archivpfadauflösung, echter Hook meldete `**ERROR**`.
|
||||
Lokale Acquisition erlaubt, echte IP-Socketsperre in Worker/Hook/Probe geprüft;
|
||||
|
||||
@@ -48,6 +48,26 @@ describe('root and dedicated dev-test APT actions', () => {
|
||||
const before = JSON.stringify(value); await validateSensitiveInput(value, auth); expect(JSON.stringify(value)).toBe(before);
|
||||
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, version: '2' } }, auth)).rejects.toThrow('Paketidentität');
|
||||
});
|
||||
it('requires an explicit schema3 native retry reference; rejects missing/unknown/normal retry fields', async () => {
|
||||
const base = await manifest();
|
||||
const native_retry = { schema_version: 1, previous_grant_id: '11111111-1111-4111-8111-111111111111', previous_attempt_id: '22222222-2222-4222-8222-222222222222', bootstrap_marker_sha256: 'a'.repeat(64) };
|
||||
const m = { ...base, schema_version: 3, native_retry };
|
||||
await validateSensitiveInput(input(m), auth);
|
||||
expect(() => validateAptManifest({ ...base, schema_version: 3 }, true)).toThrow();
|
||||
expect(() => validateAptManifest({ ...base, native_retry }, true)).toThrow();
|
||||
expect(() => validateAptManifest({ ...m, native_retry: { ...native_retry, previous_grant_id: '../active' } }, true)).toThrow();
|
||||
expect(() => validateAptManifest({ ...m, native_retry: { ...native_retry, previous_attempt_id: '00000000-0000-0000-0000-000000000000' } }, true)).toThrow();
|
||||
expect(() => validateAptManifest({ ...m, native_retry: { ...native_retry, bootstrap_marker_sha256: '0'.repeat(64) } }, true)).toThrow();
|
||||
expect(() => validateAptManifest({ ...m, action: 'apt-execute' }, false)).toThrow('eigener nativer');
|
||||
});
|
||||
it('binds update package names to the exact versions in the unchanged signed manifest', async () => {
|
||||
const m = await manifest(false); const value = input(m); value.action = 'apply_updates';
|
||||
value.parameters = { execution_identity: 'root', provider: 'apt', packages: ['rmm-mvp-test'], reboot_policy: 'never', apt_manifest: m };
|
||||
await validateSensitiveInput(value, auth);
|
||||
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, packages: ['other'] } }, auth)).rejects.toThrow('Updateauswahl');
|
||||
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, packages: [] } }, auth)).rejects.toThrow('Updateauswahl');
|
||||
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, packages: ['rmm-mvp-test=1.0'] } }, auth)).rejects.toThrow('Updateauswahl');
|
||||
});
|
||||
it('checks exact plan byte hash and manifest consistency without demanding execution IDs', async () => {
|
||||
const p = { targets: ['asset'], jobs: [{ payload: { asset_id: 'asset', action: { action: 'apt_native_acceptance', apt_manifest: await manifest() } } }] }, raw = new TextEncoder().encode(JSON.stringify(p));
|
||||
const plan = { plan_payload: p, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: p.jobs };
|
||||
|
||||
+10
-3
@@ -27,8 +27,15 @@ export async function sha256(value: Uint8Array<ArrayBuffer>): Promise<string> {
|
||||
function canonical(v: unknown): string { if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`; if (v !== null && typeof v === 'object') return `{${Object.entries(v).sort(([a], [b]) => a.localeCompare(b)).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}`; return JSON.stringify(v); }
|
||||
export function validateAptManifest(value: unknown, acceptance: boolean): RecordValue {
|
||||
const m = record(value, 'apt_manifest');
|
||||
exact(m, ['type', 'schema_version', 'action', 'execution_profile', 'transaction_sha256', 'resolved_apt_transaction', 'transaction_bytes', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256', 'test_result_id']);
|
||||
if (m.type !== 'rmm.apt.helper-action' || m.schema_version !== 2 || m.execution_profile !== 'dev-test' || m.action !== (acceptance ? 'apt-native-acceptance' : 'apt-execute')) throw new Error('APT Schema 2 / explizites dev-test-Profil erforderlich');
|
||||
exact(m, ['type', 'schema_version', 'action', 'execution_profile', 'transaction_sha256', 'resolved_apt_transaction', 'transaction_bytes', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256', 'test_result_id', ...(m.schema_version === 3 ? ['native_retry'] : [])]);
|
||||
if (m.type !== 'rmm.apt.helper-action' || ![2, 3].includes(Number(m.schema_version)) || typeof m.schema_version !== 'number' || m.execution_profile !== 'dev-test' || m.action !== (acceptance ? 'apt-native-acceptance' : 'apt-execute')) throw new Error('APT Schema 2/3 / explizites dev-test-Profil erforderlich');
|
||||
if (m.schema_version === 3) {
|
||||
if (!acceptance) throw new Error('Wiederaufnahme nur als eigener nativer Abnahmeplan');
|
||||
const retry = record(m.native_retry); exact(retry, ['schema_version', 'previous_grant_id', 'previous_attempt_id', 'bootstrap_marker_sha256']);
|
||||
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
if (retry.schema_version !== 1 || ['previous_grant_id', 'previous_attempt_id'].some(k => typeof retry[k] !== 'string' || !uuid.test(retry[k] as string) || retry[k] === '00000000-0000-0000-0000-000000000000')) throw new Error('Exakte ursprüngliche Grant-/Versuchsbindung erforderlich');
|
||||
hash(retry.bootstrap_marker_sha256);
|
||||
}
|
||||
for (const k of ['transaction_sha256', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256']) hash(m[k]);
|
||||
if (typeof m.test_result_id !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(m.test_result_id)) throw new Error('Exakte Testnachweis-ID erforderlich');
|
||||
const transaction = record(m.resolved_apt_transaction);
|
||||
@@ -68,7 +75,7 @@ export async function validateSensitiveInput(input: PlanInput, auth: Session) {
|
||||
if (!Array.isArray(packages)) throw new Error('Paketclosure fehlt');
|
||||
if (input.action === 'ensure_package' && (input.parameters.recipe_version !== t.recipe_version || (input.parameters.recipe_id !== undefined && input.parameters.recipe_id !== t.recipe_id))) throw new Error('Äußere Rezeptbindung widerspricht Manifest');
|
||||
if (input.action === 'ensure_package' && !packages.some(v => { const p = record(v); return p.name === input.parameters.package && p.new_version === input.parameters.version && p.architecture === input.parameters.architecture; })) throw new Error('Exakte Paketidentität fehlt in Closure');
|
||||
if (input.action === 'apply_updates' && (!Array.isArray(input.parameters.packages) || !input.parameters.packages.every(v => typeof v === 'string' && packages.some(x => { const p = record(x); return v === `${p.name}=${p.new_version}`; })))) throw new Error('Feste Updateversionen fehlen in Closure');
|
||||
if (input.action === 'apply_updates' && (!Array.isArray(input.parameters.packages) || input.parameters.packages.length !== packages.length || !input.parameters.packages.every(v => typeof v === 'string' && packages.some(x => { const p = record(x); return v === p.name; })))) throw new Error('Exakte Updateauswahl fehlt in versionsgebundener Closure');
|
||||
await verifyAptManifest(m, false);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user