diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3a4bb9..f7cb227 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,17 @@ jobs: - uses: dtolnay/rust-toolchain@stable - run: cargo test --workspace --all-targets + msrv: + name: rust 1.88 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.88.0 + - name: Install OpenSSL + run: sudo apt-get update && sudo apt-get install -y pkg-config libssl-dev + - name: Test on the minimum supported Rust + run: cargo test --workspace --all-targets + build: name: build runs-on: ubuntu-latest diff --git a/.github/workflows/helm-install.yml b/.github/workflows/helm-install.yml new file mode 100644 index 0000000..ae91b67 --- /dev/null +++ b/.github/workflows/helm-install.yml @@ -0,0 +1,51 @@ +name: helm install + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +jobs: + helm-install: + name: kind 1.28 helm install + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - name: Install kubectl + uses: azure/setup-kubectl@v4 + + - name: Install Helm + uses: azure/setup-helm@v4 + with: + version: v3.14.0 + + - name: Install kind + run: | + curl -fsSL -o /usr/local/bin/kind https://kind.sigs.k8s.io/dl/v0.23.0/kind-linux-amd64 + sudo chmod +x /usr/local/bin/kind + + - name: Install jq + run: sudo apt-get update && sudo apt-get install -y jq + + - name: Install chart on Kubernetes 1.28 and fail over the lease + run: ./scripts/helm-install-proof.sh + env: + KIND_NODE_IMAGE: kindest/node:v1.28.15 + + - name: Upload install and failover evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: setpoint-helm-proof-${{ github.sha }} + path: | + artifacts/helm-install/ + artifacts/leader-failover/ + retention-days: 30 + + - name: Teardown + if: always() + run: kind delete cluster --name setpoint-helm || true diff --git a/AGENTS.md b/AGENTS.md index ca0b51a..8a06c27 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,6 +65,7 @@ Run from repo root unless noted otherwise. - Build local demo images: `make build-images-local` - Helm lint: `make helm-lint` - Helm render: `make helm-template` +- Clean kind install plus lease failover: `make helm-install-proof` (needs Docker, kind, kubectl, Helm, and jq; CI runs it on Kubernetes 1.28) ### Kubernetes and demo flows @@ -76,7 +77,7 @@ Run from repo root unless noted otherwise. - Clean up demo environment: `make demo-cleanup` - Inject drift into the Auto-correct conveyor register: `make demo-drift-conveyor` - Inject drift into the Alert-only print-head register: `make demo-drift-printhead` -- Trigger the Halt safety fault: `make demo-drift-halt` +- Trigger the Halt policy fault (marks the IndustrialPLC Failed; not a certified emergency stop): `make demo-drift-halt` - Run flagship proof: `make flagship-proof` - Proof cleanup only: `make proof-cleanup` - Regenerate proof report from captured artifacts: `make proof-report` @@ -137,7 +138,7 @@ This is the path a reviewer can run end-to-end. Each step lists the commands dis ```sh make demo-drift-conveyor # Auto strategy: operator silently corrects make demo-drift-printhead # Alert strategy: detected, never written - make demo-drift-halt # Halt strategy: IndustrialPLC marked Failed + make demo-drift-halt # Halt strategy: IndustrialPLC marked Failed (operator status, not a certified emergency stop) ``` 7. Tear down: `make demo-cleanup`. 8. Reproduce the CI proof locally: `make flagship-proof`. The verdict and artifacts land under `artifacts/latest/`. @@ -206,6 +207,8 @@ Document these instead of guessing: - `landing/.next/` and `landing/node_modules/` are present in the working tree. Treat them as generated local artifacts, not source. - The console at `landing/app/console/page.tsx` calls the Axum API at `http://localhost:8081`. When the API is offline, it falls back to a typed bundled replica and surfaces a "Demo data fallback" banner. Audit and SSE streams are always labeled as mock data in the response payload (`isMock: true`, `source: "mock"`). - Drift demo commands (`make demo-drift-conveyor`, `make demo-drift-printhead`, `make demo-drift-halt`) target `127.0.0.1:5502`, which only works after `make demo` port-forwards the mock PLC service. +- Halt marks an IndustrialPLC Failed. It is an operator status, not a certified emergency stop. Physical PLC validation is pending; proofs use the mock PLC or an in-process Modbus peer. +- Minimum Kubernetes is 1.28 (`docs/SUPPORT.md`, chart `kubeVersion`). Minimum Rust is the workspace `rust-version`. `make helm-install-proof` needs Docker, kind, kubectl, Helm, and jq. ## Verification Guidance diff --git a/Cargo.toml b/Cargo.toml index 1123416..65ef46c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ license = "MIT" repository = "https://github.com/apinzon/setpoint-operator" homepage = "https://github.com/apinzon/setpoint-operator" authors = ["Setpoint Maintainers"] +rust-version = "1.88" [workspace.dependencies] tokio = { version = "1.35", features = ["full"] } diff --git a/Dockerfile.mock-plc b/Dockerfile.mock-plc index 4d1da64..57a5a0e 100644 --- a/Dockerfile.mock-plc +++ b/Dockerfile.mock-plc @@ -11,7 +11,7 @@ RUN apt-get update && apt-get install -y \ # Copy workspace configuration COPY Cargo.toml ./ -COPY Cargo.lock ./ +# Cargo.lock is gitignored. The image resolves the workspace itself. COPY crates/mock-plc/Cargo.toml ./crates/mock-plc/ COPY crates/mock-plc/src ./crates/mock-plc/src/ COPY crates/operator/Cargo.toml ./crates/operator/ @@ -24,7 +24,7 @@ COPY crates/api/Cargo.toml ./crates/api/ COPY crates/api/src ./crates/api/src/ # Build the mock-plc -RUN cargo build --release -p mock-plc +RUN cargo generate-lockfile && cargo build --release -p mock-plc # Runtime stage FROM debian:bookworm-slim diff --git a/Dockerfile.operator b/Dockerfile.operator index 67cd78f..71f33c1 100644 --- a/Dockerfile.operator +++ b/Dockerfile.operator @@ -11,7 +11,7 @@ RUN apt-get update && apt-get install -y \ # Copy workspace configuration COPY Cargo.toml ./ -COPY Cargo.lock ./ +# Cargo.lock is gitignored. The image resolves the workspace itself. COPY crates/operator/Cargo.toml ./crates/operator/ COPY crates/operator/src ./crates/operator/src/ COPY crates/setpointctl/Cargo.toml ./crates/setpointctl/ @@ -24,7 +24,7 @@ COPY crates/api/Cargo.toml ./crates/api/ COPY crates/api/src ./crates/api/src/ # Build the operator -RUN cargo build --release -p operator +RUN cargo generate-lockfile && cargo build --release -p operator # Runtime stage FROM debian:bookworm-slim diff --git a/Makefile b/Makefile index c0d4af5..a8b0f48 100644 --- a/Makefile +++ b/Makefile @@ -91,6 +91,10 @@ helm-install: ## Install the chart into the current cluster helm-uninstall: ## Uninstall the chart helm uninstall setpoint --namespace $(NAMESPACE) || true +.PHONY: helm-install-proof +helm-install-proof: ## Install the chart on a clean kind 1.28 cluster and fail over the lease + ./scripts/helm-install-proof.sh + # ---- Local demo ---- .PHONY: demo diff --git a/README.md b/README.md index 61f4f22..3f17886 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,9 @@ The desired state of every register is git-tracked YAML. The operator polls the live device, detects drift, and applies the per-register remediation policy. **Auto** silently writes the desired value back; **Alert** emits a `Warning DriftDetected` event and bumps a metric -but does not write; **Halt** marks the resource `Failed`. +but does not write; **Halt** marks the resource `Failed`. Halt is an +operator status, not a safety-certified industrial emergency stop. +Physical PLC validation is pending; the proofs below use a simulated device. ## Run the flagship proof @@ -200,7 +202,8 @@ make demo # start local demo environment make demo-cleanup # stop demo resources and local processes make demo-drift-conveyor # inject drift into the Auto conveyor register make demo-drift-printhead # inject drift into the Alert print-head register -make demo-drift-halt # trigger the Halt safety fault +make demo-drift-halt # Halt policy: mark the IndustrialPLC Failed +make helm-install-proof # clean kind 1.28 install, then lease failover make flagship-proof # run the proof end to end make proof-cleanup # clean resources created by the proof make proof-report # regenerate report from captured artifacts @@ -365,6 +368,6 @@ or behavior claims tied to the end-to-end demo. MIT. See [LICENSE](LICENSE). -The CI matrix runs separate disposable kind clusters for Auto, Alert and Halt. Run locally after `kind create cluster --name setpoint-e2e`: `make flagship-proof` (Alert); override `PROOF_POLICY=Auto DRIFT_REGISTER=4001 DRIFT_VALUE=3500` or `PROOF_POLICY=Halt DRIFT_REGISTER=4003 DRIFT_VALUE=1`. No hardware safety certification is claimed. +The CI matrix runs separate disposable kind clusters for Auto, Alert and Halt. Run locally after `kind create cluster --name setpoint-e2e`: `make flagship-proof` (Alert); override `PROOF_POLICY=Auto DRIFT_REGISTER=4001 DRIFT_VALUE=3500` or `PROOF_POLICY=Halt DRIFT_REGISTER=4003 DRIFT_VALUE=1`. Halt is an operator status, not a safety-certified emergency stop. Physical PLC validation is pending. Supported versions are in [docs/SUPPORT.md](docs/SUPPORT.md). See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, policy proof commands and pull request expectations. diff --git a/charts/setpoint/Chart.yaml b/charts/setpoint/Chart.yaml index d8519be..0785b37 100644 --- a/charts/setpoint/Chart.yaml +++ b/charts/setpoint/Chart.yaml @@ -4,6 +4,7 @@ description: Setpoint - GitOps control plane for industrial PLC drift detection type: application version: 0.2.0 appVersion: "0.2.0" +kubeVersion: ">=1.28.0-0" keywords: - industrial - plc diff --git a/charts/setpoint/templates/deployment.yaml b/charts/setpoint/templates/deployment.yaml index 904f349..8333163 100644 --- a/charts/setpoint/templates/deployment.yaml +++ b/charts/setpoint/templates/deployment.yaml @@ -46,11 +46,25 @@ spec: {{- toYaml .Values.resources | nindent 12 }} env: - name: RUST_LOG - value: {{ .Values.config.logLevel }} - - name: HOSTNAME + value: {{ .Values.config.logLevel | quote }} + - name: POD_NAME valueFrom: fieldRef: - fieldPath: spec.nodeName + fieldPath: metadata.name + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: AUDIT_LEDGER_DIR + value: {{ .Values.audit.dir | quote }} + - name: AUDIT_CONFIGMAP_NAME + value: {{ .Values.audit.configMapName | quote }} + volumeMounts: + - name: audit-ledger + mountPath: {{ .Values.audit.dir | quote }} + volumes: + - name: audit-ledger + emptyDir: {} {{- with .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} diff --git a/charts/setpoint/templates/rbac.yaml b/charts/setpoint/templates/rbac.yaml index 25c2fd0..486ff02 100644 --- a/charts/setpoint/templates/rbac.yaml +++ b/charts/setpoint/templates/rbac.yaml @@ -1,15 +1,4 @@ {{- if .Values.serviceAccount.create -}} -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ include "setpoint.serviceAccountName" . }} - labels: - {{- include "setpoint.labels" . | nindent 4 }} - {{- with .Values.serviceAccount.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} ---- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: @@ -76,4 +65,43 @@ subjects: - kind: ServiceAccount name: {{ include "setpoint.serviceAccountName" . }} namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "setpoint.fullname" . }}-audit + labels: + {{- include "setpoint.labels" . | nindent 4 }} +rules: + - apiGroups: + - "" + resources: + - configmaps + verbs: + - create + - apiGroups: + - "" + resources: + - configmaps + resourceNames: + - {{ .Values.audit.configMapName | quote }} + verbs: + - get + - update + - patch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "setpoint.fullname" . }}-audit + labels: + {{- include "setpoint.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "setpoint.fullname" . }}-audit +subjects: + - kind: ServiceAccount + name: {{ include "setpoint.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} {{- end }} diff --git a/charts/setpoint/values.yaml b/charts/setpoint/values.yaml index 1b49bff..c02ca33 100644 --- a/charts/setpoint/values.yaml +++ b/charts/setpoint/values.yaml @@ -26,6 +26,7 @@ podLabels: {} podSecurityContext: runAsNonRoot: true runAsUser: 1000 + fsGroup: 1000 securityContext: allowPrivilegeEscalation: false @@ -71,6 +72,12 @@ config: logLevel: "info" metricsPort: 8080 +# Deletion audit records are appended under dir (process restart on the same +# pod) and copied into a ConfigMap (survives pod replacement). +audit: + dir: /var/lib/setpoint/audit + configMapName: setpoint-audit-ledger + # Prometheus ServiceMonitor serviceMonitor: enabled: false diff --git a/crates/api/Cargo.toml b/crates/api/Cargo.toml index e6b0363..ab7c7c7 100644 --- a/crates/api/Cargo.toml +++ b/crates/api/Cargo.toml @@ -2,6 +2,7 @@ name = "api" version = "0.2.0" edition = "2021" +rust-version.workspace = true description = "Setpoint API Gateway - serves telemetry and control plane API to the web console" license = "MIT" repository = "https://github.com/AngelP17/fabgitops" diff --git a/crates/api/src/policy_sim.rs b/crates/api/src/policy_sim.rs index 1f68210..535ec4e 100644 --- a/crates/api/src/policy_sim.rs +++ b/crates/api/src/policy_sim.rs @@ -70,7 +70,7 @@ pub fn map_decision(req: &SimulationRequest, decision: PolicyDecision) -> Simula ), PolicyDecision::Halt { reason } => ( "System Halt".to_string(), - "Mark IndustrialPLC Failed, halt operational line".to_string(), + "Mark the IndustrialPLC Failed. This is an operator status, not a safety-certified emergency stop.".to_string(), reason, "High / Critical".to_string(), "halt", @@ -150,6 +150,7 @@ mod tests { let out = evaluate(&r); assert_eq!(out.decision, "halt"); assert!(out.risk.contains("Critical")); + assert!(out.action.contains("not a safety-certified emergency stop")); } #[test] diff --git a/crates/drift-simulator/Cargo.toml b/crates/drift-simulator/Cargo.toml index 1ca621a..189edbd 100644 --- a/crates/drift-simulator/Cargo.toml +++ b/crates/drift-simulator/Cargo.toml @@ -2,6 +2,7 @@ name = "drift-simulator" version = "0.2.0" edition = "2021" +rust-version.workspace = true description = "Setpoint drift simulator - injects deterministic register drift to exercise the operator's remediation policies" license = "MIT" repository = "https://github.com/apinzon/setpoint-operator" diff --git a/crates/mock-plc/Cargo.toml b/crates/mock-plc/Cargo.toml index 24e5031..96b574a 100644 --- a/crates/mock-plc/Cargo.toml +++ b/crates/mock-plc/Cargo.toml @@ -2,6 +2,7 @@ name = "mock-plc" version = "0.2.0" edition = "2021" +rust-version.workspace = true description = "Mock Modbus TCP server for Setpoint development and proof runs" license = "MIT" repository = "https://github.com/apinzon/setpoint-operator" diff --git a/crates/operator/Cargo.toml b/crates/operator/Cargo.toml index 134b147..b1deaf4 100644 --- a/crates/operator/Cargo.toml +++ b/crates/operator/Cargo.toml @@ -2,6 +2,7 @@ name = "operator" version = "0.2.0" edition = "2021" +rust-version.workspace = true description = "Setpoint Kubernetes operator - reconciler for industrial PLCs" license = "MIT" repository = "https://github.com/apinzon/setpoint-operator" diff --git a/crates/operator/src/audit_retention.rs b/crates/operator/src/audit_retention.rs new file mode 100644 index 0000000..dd78b36 --- /dev/null +++ b/crates/operator/src/audit_retention.rs @@ -0,0 +1,274 @@ +use crate::crypto::{verify_signed, AuditBlock, RegisterAuditState, SignedView}; +use k8s_openapi::api::core::v1::ConfigMap; +use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; +use kube::api::{Api, PostParams}; +use kube::Client; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const DATA_KEY: &str = "deletions.json"; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DeletionRecord { + pub namespace: String, + pub uid: String, + pub plc_name: String, + pub timestamp: String, + pub registers: Vec, + pub action_taken: String, + pub prev_hash: String, + pub hash: String, + pub signature: String, + pub verifying_key: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DeletionLog { + pub records: Vec, +} + +impl DeletionRecord { + pub fn from_block(namespace: &str, block: &AuditBlock, verifying_key: &str) -> Self { + Self { + namespace: namespace.to_string(), + uid: block.uid.clone(), + plc_name: block.plc_name.clone(), + timestamp: block.timestamp.clone(), + registers: block.registers.clone(), + action_taken: block.action_taken.clone(), + prev_hash: block.prev_hash.clone(), + hash: block.hash.clone(), + signature: block.signature.clone(), + verifying_key: verifying_key.to_string(), + } + } + + pub fn verify(&self) -> Result<(), crate::crypto::AuditError> { + verify_signed( + SignedView { + timestamp: &self.timestamp, + namespace: &self.namespace, + uid: &self.uid, + plc_name: &self.plc_name, + registers: &self.registers, + action_taken: &self.action_taken, + prev_hash: &self.prev_hash, + hash: &self.hash, + signature: &self.signature, + }, + &self.verifying_key, + ) + } +} + +pub fn configmap_name() -> String { + std::env::var("AUDIT_CONFIGMAP_NAME").unwrap_or_else(|_| "setpoint-audit-ledger".to_string()) +} + +pub fn operator_namespace() -> String { + std::env::var("POD_NAMESPACE").unwrap_or_else(|_| "default".to_string()) +} + +#[cfg(test)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VersionedDocument { + pub version: u64, + pub body: String, +} + +#[cfg(test)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DocumentCommit { + Stored, + Conflict, +} + +/// Apply one deletion onto a document version. A stale version is a conflict +/// and does not change the document, so the caller can re-read and merge again. +#[cfg(test)] +pub fn commit_merged_record( + document: &mut VersionedDocument, + seen_version: u64, + record: &DeletionRecord, +) -> Result { + if document.version != seen_version { + return Ok(DocumentCommit::Conflict); + } + let updated = merge_deletion_json(&document.body, record)?; + if updated != document.body { + document.body = updated; + document.version = document.version.saturating_add(1); + } + Ok(DocumentCommit::Stored) +} + +/// Merge a deletion record into the ConfigMap document. +/// The same hash is stored once. Corrupt input is rejected so a retry cannot wipe history. +pub fn merge_deletion_json( + existing: &str, + record: &DeletionRecord, +) -> Result { + let mut log = if existing.trim().is_empty() { + DeletionLog::default() + } else { + serde_json::from_str::(existing)? + }; + if !log.records.iter().any(|stored| stored.hash == record.hash) { + log.records.push(record.clone()); + } + serde_json::to_string_pretty(&log) +} + +/// Write the deletion record into the operator-namespace ConfigMap. +/// The controller removes the PLC finalizer only after this returns. +pub async fn retain_deletion_event( + client: &Client, + plc_namespace: &str, + block: &AuditBlock, +) -> Result<(), String> { + let verifying_key = hex::encode(crate::crypto::get_verifying_key().to_bytes()); + let record = DeletionRecord::from_block(plc_namespace, block, &verifying_key); + record.verify().map_err(|err| err.to_string())?; + + let namespace = operator_namespace(); + let name = configmap_name(); + let api: Api = Api::namespaced(client.clone(), &namespace); + + for _ in 0..5 { + match api.get(&name).await { + Ok(existing) => { + let raw = existing + .data + .as_ref() + .and_then(|data| data.get(DATA_KEY)) + .map(|value| value.as_str()) + .unwrap_or(""); + let updated = merge_deletion_json(raw, &record).map_err(|err| err.to_string())?; + if updated == raw { + return Ok(()); + } + let mut data = existing.data.clone().unwrap_or_default(); + data.insert(DATA_KEY.to_string(), updated); + let mut replaced = existing; + replaced.data = Some(data); + // PUT carries metadata.resourceVersion, so a concurrent writer gets 409 + // and this loop re-reads and merges instead of overwriting their record. + match api.replace(&name, &PostParams::default(), &replaced).await { + Ok(_) => return Ok(()), + Err(kube::Error::Api(err)) if err.code == 409 => continue, + Err(err) => return Err(err.to_string()), + } + } + Err(kube::Error::Api(err)) if err.code == 404 => { + let updated = merge_deletion_json("", &record).map_err(|err| err.to_string())?; + let mut data = BTreeMap::new(); + data.insert(DATA_KEY.to_string(), updated); + let config_map = ConfigMap { + metadata: ObjectMeta { + name: Some(name.clone()), + namespace: Some(namespace.clone()), + ..Default::default() + }, + data: Some(data), + ..Default::default() + }; + match api.create(&PostParams::default(), &config_map).await { + Ok(_) => return Ok(()), + Err(kube::Error::Api(err)) if err.code == 409 => continue, + Err(err) => return Err(err.to_string()), + } + } + Err(err) => return Err(err.to_string()), + } + } + Err("audit configmap update conflicted too many times".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::crypto::Ledger; + + fn identity(namespace: &str, name: &str, uid: &str) -> crate::crypto::ResourceIdentity { + crate::crypto::ResourceIdentity { + namespace: namespace.to_string(), + name: name.to_string(), + uid: uid.to_string(), + } + } + + #[test] + fn deletion_record_is_idempotent_and_independently_verifiable() { + let ledger = Ledger::in_memory(); + let block = ledger + .ensure_deletion(&identity("factory", "line-1-printer-plc", "uid-1")) + .unwrap(); + let record = DeletionRecord::from_block("factory", &block, &ledger.verifying_key_hex()); + record.verify().unwrap(); + + let once = merge_deletion_json("", &record).unwrap(); + let twice = merge_deletion_json(&once, &record).unwrap(); + let log: DeletionLog = serde_json::from_str(&twice).unwrap(); + assert_eq!(log.records.len(), 1); + assert_eq!(log.records[0].action_taken, "Deleted"); + assert_eq!(log.records[0].namespace, "factory"); + assert_eq!(log.records[0].uid, "uid-1"); + log.records[0].verify().unwrap(); + } + + #[test] + fn corrupt_ledger_document_is_not_replaced() { + let ledger = Ledger::in_memory(); + let block = ledger + .ensure_deletion(&identity("factory", "pump-1", "uid-1")) + .unwrap(); + let record = DeletionRecord::from_block("factory", &block, &ledger.verifying_key_hex()); + let err = merge_deletion_json("{not-json", &record).unwrap_err(); + assert!(!err.to_string().is_empty()); + } + + #[test] + fn concurrent_deletions_remerge_instead_of_overwriting() { + let ledger = Ledger::in_memory(); + let first = DeletionRecord::from_block( + "factory", + &ledger + .ensure_deletion(&identity("factory", "pump-1", "uid-a")) + .unwrap(), + &ledger.verifying_key_hex(), + ); + let second = DeletionRecord::from_block( + "factory", + &ledger + .ensure_deletion(&identity("factory", "pump-2", "uid-b")) + .unwrap(), + &ledger.verifying_key_hex(), + ); + let mut document = VersionedDocument { + version: 1, + body: String::new(), + }; + let seen = document.version; + assert_eq!( + commit_merged_record(&mut document, seen, &first).unwrap(), + DocumentCommit::Stored + ); + assert_eq!( + commit_merged_record(&mut document, seen, &second).unwrap(), + DocumentCommit::Conflict + ); + let log: DeletionLog = serde_json::from_str(&document.body).unwrap(); + assert_eq!(log.records.len(), 1); + let latest = document.version; + assert_eq!( + commit_merged_record(&mut document, latest, &second).unwrap(), + DocumentCommit::Stored + ); + let log: DeletionLog = serde_json::from_str(&document.body).unwrap(); + assert_eq!(log.records.len(), 2); + assert!(log.records.iter().any(|record| record.uid == "uid-a")); + assert!(log.records.iter().any(|record| record.uid == "uid-b")); + } +} diff --git a/crates/operator/src/controller.rs b/crates/operator/src/controller.rs index 3023fa2..f8e297e 100644 --- a/crates/operator/src/controller.rs +++ b/crates/operator/src/controller.rs @@ -1,6 +1,7 @@ use crate::crd::{IndustrialPLC, IndustrialPLCStatus, RemediationStrategy}; use crate::metrics::OperatorMetrics; use crate::plc_client::{build_adapter, PLCAdapter}; +use crate::reconcile_safety::{admit_reconcile, gate_auto_write, WriteGate}; use chrono::{DateTime, Utc}; use kube::api::{Api, Patch, PatchParams}; use kube::runtime::controller::Action; @@ -27,8 +28,8 @@ pub async fn reconcile(plc: Arc, ctx: Arc) -> Result, ctx: Arc) -> Result, ctx: Arc) -> Result, ctx: Arc) -> Result {} + Ok(RegisterStep::LeadershipLost) => { + info!( + "Leadership expired before an Auto write to {}/{}", + namespace, name + ); + return Ok(Action::requeue(Duration::from_secs(1))); + } + Ok(RegisterStep::SpecChanged) => { + info!( + "Spec for {}/{} changed during reconcile; skipping writes until the next pass", + namespace, name + ); + // Earlier registers in this pass may already have been corrected. + // Save their cooldown bookkeeping before skipping the rest. + update_status(&api, &name, status).await?; + return Ok(Action::requeue(Duration::from_secs(1))); + } + Err(err) => { + warn!( + "Register '{}' reconcile error on PLC {}/{}: {}", + register_spec.name, namespace, name, err + ); + } } } @@ -185,8 +217,16 @@ pub async fn reconcile(plc: Arc, ctx: Arc) -> Result, ctx: Arc) -> Result { + api: &'a Api, + generation: i64, +} + async fn reconcile_register( + observed: &ObservedSpec<'_>, plc_name: &str, register_spec: &crate::crd::RegisterSpec, plc_client: &dyn PLCAdapter, status: &mut IndustrialPLCStatus, recorder: &Recorder, metrics: &OperatorMetrics, -) -> Result<(), Error> { +) -> Result { let reg_name = ®ister_spec.name; let strategy = ®ister_spec.remediation.strategy; let strategy_label = strategy_label(strategy); @@ -341,19 +393,40 @@ async fn reconcile_register( .await .ok(); - apply_auto_correction( - plc_name, - register_spec, - plc_client, - status, - recorder, - metrics, - ) - .await?; + let fresh = observed.api.get(plc_name).await.map_err(Error::Kube)?; + let latest_generation = fresh.metadata.generation.unwrap_or(observed.generation); + let latest_desired = fresh + .spec + .registers + .iter() + .find(|register| ®ister.name == reg_name) + .map(|register| register.desired_value); + match gate_auto_write( + observed.generation, + latest_generation, + register_spec.desired_value, + latest_desired, + ) { + WriteGate::Apply(_) => { + if !crate::leader::is_leader() { + return Ok(RegisterStep::LeadershipLost); + } + apply_auto_correction( + plc_name, + register_spec, + plc_client, + status, + recorder, + metrics, + ) + .await?; + } + WriteGate::Stale => return Ok(RegisterStep::SpecChanged), + } } } - Ok(()) + Ok(RegisterStep::Done) } async fn apply_auto_correction( @@ -445,4 +518,7 @@ pub enum Error { #[error("PLC client error: {0}")] PlcClient(#[from] anyhow::Error), + + #[error("Audit retention error: {0}")] + Audit(String), } diff --git a/crates/operator/src/crd.rs b/crates/operator/src/crd.rs index dd8dd79..d603370 100644 --- a/crates/operator/src/crd.rs +++ b/crates/operator/src/crd.rs @@ -92,7 +92,8 @@ pub struct RegisterSpec { #[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)] #[serde(rename_all = "camelCase")] pub struct RemediationPolicy { - /// Strategy: Auto (correct), Alert (detect only), or Halt (mark PLC Failed) + /// Strategy: Auto (correct), Alert (detect only), or Halt (mark the resource Failed). + /// Halt is an operator status. It is not a safety-certified industrial emergency stop. #[serde(default = "default_strategy")] pub strategy: RemediationStrategy, diff --git a/crates/operator/src/crypto.rs b/crates/operator/src/crypto.rs index 886db0c..fef04a7 100644 --- a/crates/operator/src/crypto.rs +++ b/crates/operator/src/crypto.rs @@ -1,17 +1,23 @@ -use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; +use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use rand_core::OsRng; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock}; -static SIGNING_KEY: OnceLock = OnceLock::new(); -static AUDIT_LEDGERS: OnceLock>>> = OnceLock::new(); +const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000"; -#[derive(Serialize, Deserialize, Clone, Debug)] +static LEDGER: OnceLock = OnceLock::new(); + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct AuditBlock { pub timestamp: String, + pub namespace: String, + pub uid: String, pub plc_name: String, pub registers: Vec, pub action_taken: String, @@ -20,7 +26,22 @@ pub struct AuditBlock { pub signature: String, } -#[derive(Serialize, Deserialize, Clone, Debug)] +/// Kubernetes identity of one IndustrialPLC. Deletion retries reuse a block +/// only when namespace, name, and UID all match. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResourceIdentity { + pub namespace: String, + pub name: String, + pub uid: String, +} + +impl ResourceIdentity { + pub fn key(&self) -> String { + format!("{}/{}/{}", self.namespace, self.name, self.uid) + } +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct RegisterAuditState { pub name: String, @@ -30,81 +51,472 @@ pub struct RegisterAuditState { pub strategy: String, } -pub fn get_signing_key() -> &'static SigningKey { - SIGNING_KEY.get_or_init(|| SigningKey::generate(&mut OsRng)) +#[derive(Debug)] +pub enum AuditError { + Io(std::io::Error), + Json(serde_json::Error), + Chain(String), + Signature, + AlreadyInit, +} + +impl std::fmt::Display for AuditError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AuditError::Io(err) => write!(f, "audit ledger io: {err}"), + AuditError::Json(err) => write!(f, "audit ledger json: {err}"), + AuditError::Chain(msg) => write!(f, "audit chain: {msg}"), + AuditError::Signature => write!(f, "audit signature verification failed"), + AuditError::AlreadyInit => write!(f, "audit ledger was already initialized"), + } + } +} + +impl std::error::Error for AuditError {} + +impl From for AuditError { + fn from(err: std::io::Error) -> Self { + AuditError::Io(err) + } +} + +impl From for AuditError { + fn from(err: serde_json::Error) -> Self { + AuditError::Json(err) + } +} + +pub struct SignedView<'a> { + pub timestamp: &'a str, + pub namespace: &'a str, + pub uid: &'a str, + pub plc_name: &'a str, + pub registers: &'a [RegisterAuditState], + pub action_taken: &'a str, + pub prev_hash: &'a str, + pub hash: &'a str, + pub signature: &'a str, +} + +pub struct Ledger { + blocks: Mutex>>, + dir: Option, + signing_key: SigningKey, +} + +impl Ledger { + pub fn in_memory() -> Self { + Self { + blocks: Mutex::new(BTreeMap::new()), + dir: None, + signing_key: SigningKey::generate(&mut OsRng), + } + } + + /// Open a file-backed ledger. Blocks and the signing key survive process restart. + pub fn open(dir: impl Into) -> Result { + let dir = dir.into(); + fs::create_dir_all(&dir)?; + let signing_key = load_or_create_key(&dir)?; + let mut blocks = BTreeMap::new(); + for entry in fs::read_dir(&dir)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if !name.ends_with(".jsonl") { + continue; + } + let text = fs::read_to_string(entry.path())?; + let mut chain = Vec::new(); + for line in text.lines() { + if line.trim().is_empty() { + continue; + } + chain.push(serde_json::from_str::(line)?); + } + if chain.is_empty() { + continue; + } + verify_chain(&chain, &signing_key.verifying_key())?; + let key = block_key(&chain[0]); + if chain.iter().any(|block| block_key(block) != key) { + return Err(AuditError::Chain(format!( + "ledger file {name} mixes resource identities" + ))); + } + blocks.insert(key, chain); + } + Ok(Self { + blocks: Mutex::new(blocks), + dir: Some(dir), + signing_key, + }) + } + + #[cfg(test)] + pub fn verifying_key_hex(&self) -> String { + hex::encode(self.signing_key.verifying_key().to_bytes()) + } + + pub fn blocks(&self, plc_name: &str) -> Vec { + self.blocks + .lock() + .expect("audit ledger lock") + .values() + .filter(|chain| chain.first().map(|block| block.plc_name.as_str()) == Some(plc_name)) + .flat_map(|chain| chain.clone()) + .collect() + } + + pub fn append( + &self, + identity: &ResourceIdentity, + registers: Vec, + action_taken: String, + ) -> Result { + let mut ledgers = self.blocks.lock().expect("audit ledger lock"); + let history = ledgers.entry(identity.key()).or_default(); + let prev_hash = history + .last() + .map(|b| b.hash.clone()) + .unwrap_or_else(|| GENESIS.to_string()); + let block = sign_block( + &self.signing_key, + identity, + registers, + action_taken, + prev_hash, + )?; + persist_block(self.dir.as_deref(), &block)?; + history.push(block.clone()); + Ok(block) + } + + /// Record a deletion once for this namespace, name, and UID. + /// A retry after a crash returns the stored block. A different UID does not. + pub fn ensure_deletion(&self, identity: &ResourceIdentity) -> Result { + if let Some(existing) = self + .blocks + .lock() + .expect("audit ledger lock") + .get(&identity.key()) + .and_then(|history| history.last().cloned()) + { + if existing.action_taken == "Deleted" + && existing.namespace == identity.namespace + && existing.plc_name == identity.name + && existing.uid == identity.uid + { + return Ok(existing); + } + } + self.append(identity, Vec::new(), "Deleted".to_string()) + } +} + +/// Load `AUDIT_LEDGER_DIR` when it is set. Without it, the process keeps an +/// in-memory ledger and deletion retention depends on the Kubernetes ConfigMap. +pub fn init_durable_ledger() -> Result<(), AuditError> { + if LEDGER.get().is_some() { + return Err(AuditError::AlreadyInit); + } + let ledger = match std::env::var("AUDIT_LEDGER_DIR") { + Ok(dir) if !dir.is_empty() => Ledger::open(dir)?, + _ => Ledger::in_memory(), + }; + LEDGER.set(ledger).map_err(|_| AuditError::AlreadyInit)?; + Ok(()) +} + +fn global() -> &'static Ledger { + LEDGER.get_or_init(Ledger::in_memory) } pub fn get_verifying_key() -> VerifyingKey { - get_signing_key().verifying_key() + global().signing_key.verifying_key() } pub fn get_ledger(plc_name: &str) -> Vec { - let ledgers = AUDIT_LEDGERS - .get_or_init(|| Mutex::new(BTreeMap::new())) - .lock() - .unwrap(); - ledgers.get(plc_name).cloned().unwrap_or_default() + global().blocks(plc_name) } pub fn generate_audit_block( - plc_name: String, + identity: &ResourceIdentity, registers: Vec, action_taken: String, -) -> AuditBlock { - let mut ledgers = AUDIT_LEDGERS - .get_or_init(|| Mutex::new(BTreeMap::new())) - .lock() - .unwrap(); - - let history = ledgers.entry(plc_name.clone()).or_default(); - - let prev_hash = if let Some(last) = history.last() { - last.hash.clone() - } else { - "0000000000000000000000000000000000000000000000000000000000000000".to_string() - }; +) -> Result { + global().append(identity, registers, action_taken) +} + +pub fn ensure_deletion_block(identity: &ResourceIdentity) -> Result { + global().ensure_deletion(identity) +} + +pub fn verify_signed(view: SignedView<'_>, verifying_key_hex: &str) -> Result<(), AuditError> { + let key_bytes = + hex::decode(verifying_key_hex).map_err(|err| AuditError::Chain(err.to_string()))?; + let key_bytes: [u8; 32] = key_bytes + .try_into() + .map_err(|_| AuditError::Chain("verifying key must be 32 bytes".into()))?; + let verifying_key = VerifyingKey::from_bytes(&key_bytes).map_err(|_| AuditError::Signature)?; + let payload = canonical_bytes( + view.timestamp, + view.namespace, + view.uid, + view.plc_name, + view.registers, + view.action_taken, + view.prev_hash, + )?; + let digest = Sha256::digest(&payload); + let hash = hex::encode(digest); + if hash != view.hash { + return Err(AuditError::Chain( + "stored hash does not match payload".into(), + )); + } + let signature_bytes = + hex::decode(view.signature).map_err(|err| AuditError::Chain(err.to_string()))?; + let signature = Signature::from_slice(&signature_bytes).map_err(|_| AuditError::Signature)?; + verifying_key + .verify(digest.as_slice(), &signature) + .map_err(|_| AuditError::Signature)?; + Ok(()) +} +fn sign_block( + signing_key: &SigningKey, + identity: &ResourceIdentity, + registers: Vec, + action_taken: String, + prev_hash: String, +) -> Result { let timestamp = chrono::Utc::now().to_rfc3339(); + let payload = canonical_bytes( + ×tamp, + &identity.namespace, + &identity.uid, + &identity.name, + ®isters, + &action_taken, + &prev_hash, + )?; + let digest = Sha256::digest(&payload); + let hash = hex::encode(digest); + let signature = hex::encode(signing_key.sign(digest.as_slice()).to_bytes()); + Ok(AuditBlock { + timestamp, + namespace: identity.namespace.clone(), + uid: identity.uid.clone(), + plc_name: identity.name.clone(), + registers, + action_taken, + prev_hash, + hash, + signature, + }) +} +fn canonical_bytes( + timestamp: &str, + namespace: &str, + uid: &str, + plc_name: &str, + registers: &[RegisterAuditState], + action_taken: &str, + prev_hash: &str, +) -> Result, AuditError> { #[derive(Serialize)] struct SignTarget<'a> { timestamp: &'a str, + namespace: &'a str, + uid: &'a str, plc_name: &'a str, registers: &'a [RegisterAuditState], action_taken: &'a str, prev_hash: &'a str, } - - let target = SignTarget { - timestamp: ×tamp, - plc_name: &plc_name, - registers: ®isters, - action_taken: &action_taken, - prev_hash: &prev_hash, - }; - - let serialized = serde_json::to_vec(&target).unwrap(); - - let mut hasher = Sha256::new(); - hasher.update(&serialized); - let hash_bytes = hasher.finalize(); - let hash = hex::encode(hash_bytes); - - let signing_key = get_signing_key(); - let signature_bytes = signing_key.sign(&hash_bytes); - let signature = hex::encode(signature_bytes.to_bytes()); - - let block = AuditBlock { + Ok(serde_json::to_vec(&SignTarget { timestamp, + namespace, + uid, plc_name, registers, action_taken, prev_hash, - hash, - signature, + })?) +} + +fn block_key(block: &AuditBlock) -> String { + format!("{}/{}/{}", block.namespace, block.plc_name, block.uid) +} + +fn verify_chain(blocks: &[AuditBlock], verifying_key: &VerifyingKey) -> Result<(), AuditError> { + let key_hex = hex::encode(verifying_key.to_bytes()); + let mut prev = GENESIS.to_string(); + for block in blocks { + if block.prev_hash != prev { + return Err(AuditError::Chain(format!( + "prev hash mismatch at {}", + block.hash + ))); + } + verify_signed( + SignedView { + timestamp: &block.timestamp, + namespace: &block.namespace, + uid: &block.uid, + plc_name: &block.plc_name, + registers: &block.registers, + action_taken: &block.action_taken, + prev_hash: &block.prev_hash, + hash: &block.hash, + signature: &block.signature, + }, + &key_hex, + )?; + prev = block.hash.clone(); + } + Ok(()) +} + +fn persist_block(dir: Option<&Path>, block: &AuditBlock) -> Result<(), AuditError> { + let Some(dir) = dir else { + return Ok(()); }; + let path = dir.join(ledger_file_name(&block_key(block))); + let mut file = OpenOptions::new().create(true).append(true).open(path)?; + writeln!(file, "{}", serde_json::to_string(block)?)?; + file.sync_all()?; + Ok(()) +} + +fn ledger_file_name(plc_name: &str) -> String { + let mut safe: String = plc_name + .chars() + .map(|ch| { + if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { + ch + } else { + '_' + } + }) + .collect(); + if safe.is_empty() { + safe = "plc".to_string(); + } + format!("{safe}.jsonl") +} + +fn load_or_create_key(dir: &Path) -> Result { + let path = dir.join("signing-key.hex"); + if path.exists() { + let text = fs::read_to_string(&path)?; + let bytes = hex::decode(text.trim()).map_err(|err| AuditError::Chain(err.to_string()))?; + let bytes: [u8; 32] = bytes + .try_into() + .map_err(|_| AuditError::Chain("signing key must be 32 bytes".into()))?; + return Ok(SigningKey::from_bytes(&bytes)); + } + let key = SigningKey::generate(&mut OsRng); + fs::write(&path, hex::encode(key.to_bytes()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600)); + } + Ok(key) +} - history.push(block.clone()); +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; - block + fn scratch(label: &str) -> PathBuf { + static N: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "setpoint-audit-{label}-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn identity(namespace: &str, name: &str, uid: &str) -> ResourceIdentity { + ResourceIdentity { + namespace: namespace.to_string(), + name: name.to_string(), + uid: uid.to_string(), + } + } + + #[test] + fn deletion_event_survives_process_restart_and_verifies() { + let dir = scratch("restart"); + let first = Ledger::open(&dir).unwrap(); + let plc = identity("factory", "line-1-printer-plc", "uid-1"); + let reconciled = first + .append( + &plc, + vec![RegisterAuditState { + name: "conveyor-speed".into(), + address: 4001, + desired_value: 2500, + current_value: Some(2500), + strategy: "Auto".into(), + }], + "Reconciled".into(), + ) + .unwrap(); + let deleted = first.ensure_deletion(&plc).unwrap(); + assert_eq!(deleted.action_taken, "Deleted"); + assert_eq!(deleted.prev_hash, reconciled.hash); + drop(first); + + let reopened = Ledger::open(&dir).unwrap(); + let blocks = reopened.blocks(&plc.name); + assert_eq!(blocks.len(), 2); + assert_eq!(blocks[1].hash, deleted.hash); + assert_eq!(blocks[1].action_taken, "Deleted"); + let again = reopened.ensure_deletion(&plc).unwrap(); + assert_eq!(again.hash, deleted.hash); + assert_eq!(reopened.blocks(&plc.name).len(), 2); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn deletion_identity_includes_namespace_and_uid() { + let ledger = Ledger::in_memory(); + let first = identity("factory-a", "pump-1", "uid-a"); + let other_namespace = identity("factory-b", "pump-1", "uid-b"); + let recreated = identity("factory-a", "pump-1", "uid-c"); + let deleted = ledger.ensure_deletion(&first).unwrap(); + let other = ledger.ensure_deletion(&other_namespace).unwrap(); + let again = ledger.ensure_deletion(&first).unwrap(); + let created_again = ledger.ensure_deletion(&recreated).unwrap(); + assert_eq!(again.hash, deleted.hash); + assert_ne!(other.hash, deleted.hash); + assert_ne!(created_again.hash, deleted.hash); + assert_eq!(ledger.blocks("pump-1").len(), 3); + } + + #[test] + fn tampered_deletion_block_fails_to_load() { + let dir = scratch("tamper"); + let ledger = Ledger::open(&dir).unwrap(); + let plc = identity("factory", "pump-1", "uid-1"); + ledger.ensure_deletion(&plc).unwrap(); + drop(ledger); + + let path = dir.join(ledger_file_name(&plc.key())); + let raw = fs::read_to_string(&path).unwrap(); + fs::write(&path, raw.replace("Deleted", "Edited")).unwrap(); + match Ledger::open(&dir) { + Err(err) => assert!(matches!(err, AuditError::Chain(_) | AuditError::Signature)), + Ok(_) => panic!("tampered ledger must not load"), + } + let _ = fs::remove_dir_all(&dir); + } } diff --git a/crates/operator/src/leader.rs b/crates/operator/src/leader.rs index 47aca24..525bfd6 100644 --- a/crates/operator/src/leader.rs +++ b/crates/operator/src/leader.rs @@ -1,26 +1,39 @@ +use chrono::{DateTime, Utc}; use k8s_openapi::api::coordination::v1::{Lease, LeaseSpec}; use k8s_openapi::apimachinery::pkg::apis::meta::v1::{MicroTime, ObjectMeta}; use kube::api::PostParams; use kube::{Api, Client}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::OnceLock; -use std::time::Duration; +use std::sync::Mutex; +use std::time::{Duration, Instant}; use tracing::{error, info, warn}; -static IS_LEADER: OnceLock> = OnceLock::new(); +pub const DEFAULT_LEASE_DURATION_SECS: i64 = 15; -pub fn get_leader_handle() -> std::sync::Arc { - IS_LEADER - .get_or_init(|| std::sync::Arc::new(AtomicBool::new(false))) - .clone() +// Reserve seven seconds of the remote Lease for a bounded Modbus operation. +// This is a conservative local deadline, not device-side fencing. +const LOCAL_LEADERSHIP_TTL: Duration = Duration::from_secs(8); +const LEASE_REQUEST_TIMEOUT: Duration = Duration::from_secs(4); +static LEADER_UNTIL: Mutex> = Mutex::new(None); + +fn leadership_valid_until(deadline: Option, now: Instant) -> bool { + deadline.is_some_and(|deadline| now < deadline) } pub fn is_leader() -> bool { - get_leader_handle().load(Ordering::Relaxed) + LEADER_UNTIL + .lock() + .is_ok_and(|deadline| leadership_valid_until(*deadline, Instant::now())) +} + +fn set_leader_until(deadline: Option) { + if let Ok(mut stored) = LEADER_UNTIL.lock() { + *stored = deadline; + } } -pub fn set_leader(val: bool) { - get_leader_handle().store(val, Ordering::Relaxed); +/// `Ok(true)` keeps leadership. A lost race or an API error steps down. +pub fn leadership_after_attempt(acquired: Option) -> bool { + acquired.unwrap_or(false) } pub fn get_holder_id() -> String { @@ -29,6 +42,67 @@ pub fn get_holder_id() -> String { .unwrap_or_else(|_| format!("setpoint-operator-{}", std::process::id())) } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LeaseSnapshot { + pub holder_identity: String, + pub lease_duration_seconds: i64, + pub renew_time: DateTime, + pub acquire_time: DateTime, + pub lease_transitions: i32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LeaseProposal { + pub holder_identity: String, + pub lease_duration_seconds: i32, + pub acquire_time: DateTime, + pub renew_time: DateTime, + pub lease_transitions: i32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LeaseDecision { + Claim(LeaseProposal), + StandDown, +} + +/// Decide whether `holder_id` may write the lease at `now`. +/// A foreign holder is expired only when the age is strictly greater than the duration. +pub fn decide_lease( + current: Option<&LeaseSnapshot>, + holder_id: &str, + now: DateTime, +) -> LeaseDecision { + let Some(current) = current else { + return LeaseDecision::Claim(LeaseProposal { + holder_identity: holder_id.to_string(), + lease_duration_seconds: DEFAULT_LEASE_DURATION_SECS as i32, + acquire_time: now, + renew_time: now, + lease_transitions: 1, + }); + }; + + let age = (now - current.renew_time).num_seconds(); + let expired = age > current.lease_duration_seconds; + let ours = current.holder_identity == holder_id; + if !(ours || expired) { + return LeaseDecision::StandDown; + } + + LeaseDecision::Claim(LeaseProposal { + holder_identity: holder_id.to_string(), + lease_duration_seconds: DEFAULT_LEASE_DURATION_SECS as i32, + acquire_time: if ours { current.acquire_time } else { now }, + renew_time: now, + lease_transitions: if ours { + current.lease_transitions + } else { + current.lease_transitions.saturating_add(1) + }, + }) +} + pub async fn start_leader_election(client: Client, namespace: String) { let holder_id = get_holder_id(); info!( @@ -41,21 +115,32 @@ pub async fn start_leader_election(client: Client, namespace: String) { tokio::spawn(async move { loop { - match try_acquire_or_renew_lease(&lease_api, lease_name, &holder_id).await { - Ok(acquired) => { - let old_leader = is_leader(); - set_leader(acquired); - if acquired && !old_leader { - info!("Acquired leadership lock!"); - } else if !acquired && old_leader { - warn!("Lost leadership lock!"); - } + let started_at = Instant::now(); + let acquired = match tokio::time::timeout( + LEASE_REQUEST_TIMEOUT, + try_acquire_or_renew_lease(&lease_api, lease_name, &holder_id), + ) + .await + { + Ok(Ok(acquired)) => Some(acquired), + Ok(Err(err)) => { + error!("Leader election error: {:?}", err); + None } - Err(e) => { - error!("Leader election error: {:?}", e); - // On error, step down to be safe - set_leader(false); + Err(_) => { + warn!("Lease request timed out; stepping down"); + None } + }; + let old_leader = is_leader(); + let deadline = + leadership_after_attempt(acquired).then_some(started_at + LOCAL_LEADERSHIP_TTL); + set_leader_until(deadline); + let now_leader = is_leader(); + if now_leader && !old_leader { + info!("Acquired leadership lock!"); + } else if !now_leader && old_leader { + warn!("Lost leadership lock!"); } tokio::time::sleep(Duration::from_secs(5)).await; @@ -63,79 +148,196 @@ pub async fn start_leader_election(client: Client, namespace: String) { }); } +fn snapshot_from_lease(lease: &Lease, now: DateTime) -> LeaseSnapshot { + let spec = lease.spec.clone().unwrap_or_default(); + LeaseSnapshot { + holder_identity: spec.holder_identity.unwrap_or_default(), + lease_duration_seconds: i64::from( + spec.lease_duration_seconds + .unwrap_or(DEFAULT_LEASE_DURATION_SECS as i32), + ), + renew_time: spec.renew_time.map(|time| time.0).unwrap_or(now), + acquire_time: spec.acquire_time.map(|time| time.0).unwrap_or(now), + lease_transitions: spec.lease_transitions.unwrap_or(0), + } +} + +fn proposal_to_spec(proposal: &LeaseProposal) -> LeaseSpec { + LeaseSpec { + holder_identity: Some(proposal.holder_identity.clone()), + lease_duration_seconds: Some(proposal.lease_duration_seconds), + acquire_time: Some(MicroTime(proposal.acquire_time)), + renew_time: Some(MicroTime(proposal.renew_time)), + lease_transitions: Some(proposal.lease_transitions), + } +} + async fn try_acquire_or_renew_lease( api: &Api, name: &str, holder_id: &str, ) -> Result { - let now = chrono::Utc::now(); - let now_micro = MicroTime(now); + let now = Utc::now(); match api.get(name).await { Ok(lease) => { - let spec = lease.spec.clone().unwrap_or_default(); - let holder = spec.holder_identity.as_deref().unwrap_or(""); - let duration = spec.lease_duration_seconds.unwrap_or(15) as i64; - let last_renew = spec.renew_time.as_ref().map(|mt| mt.0).unwrap_or(now); - - let is_expired = (now - last_renew).num_seconds() > duration; - let is_us = holder == holder_id; - - if is_us || is_expired { - let new_spec = LeaseSpec { - holder_identity: Some(holder_id.to_string()), - lease_duration_seconds: Some(15), - acquire_time: Some(if is_us { - spec.acquire_time.unwrap_or(now_micro.clone()) - } else { - now_micro.clone() - }), - renew_time: Some(now_micro), - lease_transitions: Some(if is_us { - spec.lease_transitions.unwrap_or(0) - } else { - spec.lease_transitions.unwrap_or(0) + 1 - }), - }; - - let mut new_lease = lease.clone(); - new_lease.spec = Some(new_spec); - - match api.replace(name, &PostParams::default(), &new_lease).await { - Ok(_) => Ok(true), - Err(e) => { - warn!("Failed to renew lease (possibly conflict): {}", e); - Ok(false) + let snapshot = snapshot_from_lease(&lease, now); + match decide_lease(Some(&snapshot), holder_id, now) { + LeaseDecision::StandDown => Ok(false), + LeaseDecision::Claim(proposal) => { + let mut new_lease = lease; + new_lease.spec = Some(proposal_to_spec(&proposal)); + match api.replace(name, &PostParams::default(), &new_lease).await { + Ok(_) => Ok(true), + Err(err) => { + warn!("Failed to renew lease (possibly conflict): {}", err); + Ok(false) + } } } - } else { - Ok(false) } } - Err(kube::Error::Api(ref err_val)) if err_val.code == 404 => { + Err(kube::Error::Api(ref err)) if err.code == 404 => { + let LeaseDecision::Claim(proposal) = decide_lease(None, holder_id, now) else { + return Ok(false); + }; info!("Lease not found, creating a new one: {}", name); let new_lease = Lease { metadata: ObjectMeta { name: Some(name.to_string()), ..Default::default() }, - spec: Some(LeaseSpec { - holder_identity: Some(holder_id.to_string()), - lease_duration_seconds: Some(15), - acquire_time: Some(now_micro.clone()), - renew_time: Some(now_micro), - lease_transitions: Some(1), - }), + spec: Some(proposal_to_spec(&proposal)), }; - match api.create(&PostParams::default(), &new_lease).await { Ok(_) => Ok(true), - Err(e) => { - warn!("Failed to create lease: {}", e); + Err(err) => { + warn!("Failed to create lease: {}", err); Ok(false) } } } - Err(e) => Err(e), + Err(err) => Err(err), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + #[derive(Clone, Debug)] + struct MemoryLease { + snapshot: Option, + resource_version: u64, + } + + fn commit( + store: &Mutex, + read_version: u64, + snapshot: Option, + holder: &str, + now: DateTime, + ) -> bool { + let decision = decide_lease(snapshot.as_ref(), holder, now); + let LeaseDecision::Claim(proposal) = decision else { + return false; + }; + let mut guard = store.lock().expect("lease"); + if guard.resource_version != read_version { + return false; + } + guard.snapshot = Some(LeaseSnapshot { + holder_identity: proposal.holder_identity, + lease_duration_seconds: i64::from(proposal.lease_duration_seconds), + renew_time: proposal.renew_time, + acquire_time: proposal.acquire_time, + lease_transitions: proposal.lease_transitions, + }); + guard.resource_version += 1; + true + } + + fn observe(store: &Mutex, holder: &str, now: DateTime) -> bool { + let (snapshot, version) = { + let guard = store.lock().expect("lease"); + (guard.snapshot.clone(), guard.resource_version) + }; + commit(store, version, snapshot, holder, now) + } + + #[test] + fn local_leadership_expires_even_without_renewal_progress() { + let start = Instant::now(); + let deadline = start + LOCAL_LEADERSHIP_TTL; + assert!(!leadership_valid_until(None, start)); + assert!(leadership_valid_until(Some(deadline), start)); + assert!(!leadership_valid_until(Some(deadline), deadline)); + assert!(!leadership_valid_until( + Some(deadline), + deadline + Duration::from_secs(1), + )); + } + + #[test] + fn lease_errors_step_down() { + assert!(leadership_after_attempt(Some(true))); + assert!(!leadership_after_attempt(Some(false))); + assert!(!leadership_after_attempt(None)); + } + + #[test] + fn stale_resource_version_loses_the_race() { + let store = Mutex::new(MemoryLease { + snapshot: None, + resource_version: 0, + }); + let now = Utc::now(); + assert!(commit(&store, 0, None, "pod-a", now)); + assert!(!commit(&store, 0, None, "pod-b", now)); + let holder = store + .lock() + .expect("lease") + .snapshot + .as_ref() + .unwrap() + .holder_identity + .clone(); + assert_eq!(holder, "pod-a"); + } + + #[test] + fn two_replicas_elect_one_leader_and_fail_over_after_expiry() { + let store = Mutex::new(MemoryLease { + snapshot: None, + resource_version: 0, + }); + let t0 = Utc::now(); + assert!(observe(&store, "pod-a", t0)); + assert!(!observe(&store, "pod-b", t0)); + + let t1 = t0 + chrono::Duration::seconds(5); + assert!(observe(&store, "pod-a", t1)); + assert!(!observe(&store, "pod-b", t1)); + assert_eq!( + store + .lock() + .expect("lease") + .snapshot + .as_ref() + .unwrap() + .lease_transitions, + 1 + ); + + let still_held = t1 + chrono::Duration::seconds(DEFAULT_LEASE_DURATION_SECS); + assert!(!observe(&store, "pod-b", still_held)); + + let expired = t1 + chrono::Duration::seconds(DEFAULT_LEASE_DURATION_SECS + 1); + assert!(observe(&store, "pod-b", expired)); + let snapshot = store.lock().expect("lease").snapshot.clone().unwrap(); + assert_eq!(snapshot.holder_identity, "pod-b"); + assert_eq!(snapshot.lease_transitions, 2); + assert!(!observe(&store, "pod-a", expired)); } } diff --git a/crates/operator/src/lib.rs b/crates/operator/src/lib.rs index 4fb0d0a..4f38a5e 100644 --- a/crates/operator/src/lib.rs +++ b/crates/operator/src/lib.rs @@ -1,3 +1,4 @@ +pub mod audit_retention; pub mod controller; pub mod crd; pub mod crypto; @@ -5,3 +6,4 @@ pub mod leader; pub mod metrics; pub mod plc_client; pub mod policy; +pub mod reconcile_safety; diff --git a/crates/operator/src/main.rs b/crates/operator/src/main.rs index 1984c4f..b20f4f4 100644 --- a/crates/operator/src/main.rs +++ b/crates/operator/src/main.rs @@ -1,3 +1,4 @@ +mod audit_retention; mod controller; mod crd; mod crypto; @@ -5,6 +6,7 @@ mod leader; mod metrics; mod plc_client; mod policy; +mod reconcile_safety; use crate::controller::{error_policy, reconcile, Context}; use crate::crd::IndustrialPLC; @@ -32,6 +34,9 @@ async fn main() -> anyhow::Result<()> { info!("Starting Setpoint Operator..."); + crypto::init_durable_ledger() + .map_err(|err| anyhow::anyhow!("failed to open the audit ledger: {err}"))?; + // Initialize Kubernetes client let client = Client::try_default().await?; info!("Connected to Kubernetes cluster"); @@ -268,7 +273,8 @@ async fn validate_handler( } } - // Rule B: Validate safety registers (e.g. emergency-halt or SafetyCritical criticality) strategy cannot be modified from Halt to Alert/Auto + // Rule B: A register locked to Halt cannot be downgraded. + // Halt is an operator status, not a safety-certified emergency stop. if let Some(old_val) = req.old_object { if let Ok(old_plc) = serde_json::from_value::(old_val) { for old_r in &old_plc.spec.registers { @@ -289,7 +295,7 @@ async fn validate_handler( status: Some(AdmissionStatus { code: 400, message: format!( - "Validation failed: safety register '{}' remediation strategy cannot be downgraded from Halt to {:?}", + "Validation failed: register '{}' is locked to Halt and cannot be downgraded to {:?}. Halt is an operator status, not a certified emergency stop", old_r.name, new_r.remediation.strategy ), }), diff --git a/crates/operator/src/plc_client.rs b/crates/operator/src/plc_client.rs index 39b18b1..dbef56d 100644 --- a/crates/operator/src/plc_client.rs +++ b/crates/operator/src/plc_client.rs @@ -1,8 +1,12 @@ use anyhow::{Context, Result}; use async_trait::async_trait; +use std::time::Duration; use tokio::net::TcpStream; use tokio_modbus::prelude::*; +const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +const DEFAULT_IO_TIMEOUT: Duration = Duration::from_secs(3); + #[async_trait] pub trait PLCAdapter: Send + Sync { async fn read_register(&self, address: u16) -> Result; @@ -13,31 +17,55 @@ pub trait PLCAdapter: Send + Sync { pub struct ModbusAdapter { address: String, port: u16, + connect_timeout: Duration, + io_timeout: Duration, } impl ModbusAdapter { pub fn new(address: String, port: u16) -> Self { - Self { address, port } + Self::with_timeouts(address, port, DEFAULT_CONNECT_TIMEOUT, DEFAULT_IO_TIMEOUT) + } + + pub fn with_timeouts( + address: String, + port: u16, + connect_timeout: Duration, + io_timeout: Duration, + ) -> Self { + Self { + address, + port, + connect_timeout, + io_timeout, + } } fn addr_str(&self) -> String { format!("{}:{}", self.address, self.port) } + + /// Each call opens a new TCP connection. A dropped peer fails that call; + /// the next call connects again. + async fn connect_ctx(&self) -> Result { + let stream = + tokio::time::timeout(self.connect_timeout, TcpStream::connect(self.addr_str())) + .await + .context("Modbus connect timed out")? + .context("Failed to connect to Modbus PLC")?; + Ok(tcp::attach(stream)) + } } #[async_trait] impl PLCAdapter for ModbusAdapter { async fn read_register(&self, register: u16) -> Result { - let stream = TcpStream::connect(self.addr_str()) - .await - .context("Failed to connect to Modbus PLC")?; + let mut ctx = self.connect_ctx().await?; - let mut ctx = tcp::attach(stream); - - let response = ctx - .read_holding_registers(register, 1) - .await - .context("Failed to read Modbus register")?; + let response = + tokio::time::timeout(self.io_timeout, ctx.read_holding_registers(register, 1)) + .await + .context("Modbus read timed out")? + .context("Failed to read Modbus register")?; ctx.disconnect().await.ok(); @@ -48,14 +76,11 @@ impl PLCAdapter for ModbusAdapter { } async fn write_register(&self, register: u16, value: u16) -> Result<()> { - let stream = TcpStream::connect(self.addr_str()) - .await - .context("Failed to connect to Modbus PLC")?; + let mut ctx = self.connect_ctx().await?; - let mut ctx = tcp::attach(stream); - - ctx.write_single_register(register, value) + tokio::time::timeout(self.io_timeout, ctx.write_single_register(register, value)) .await + .context("Modbus write timed out")? .context("Failed to write Modbus register")?; ctx.disconnect().await.ok(); @@ -64,9 +89,10 @@ impl PLCAdapter for ModbusAdapter { } async fn health_check(&self) -> Result { - match TcpStream::connect(self.addr_str()).await { - Ok(_) => Ok(true), - Err(_) => Ok(false), + match tokio::time::timeout(self.connect_timeout, TcpStream::connect(self.addr_str())).await + { + Ok(Ok(_)) => Ok(true), + Ok(Err(_)) | Err(_) => Ok(false), } } } @@ -162,3 +188,169 @@ pub fn build_adapter( crate::crd::PLCProtocol::EtherNetIP => Box::new(EtherNetIPAdapter::new(address, port)), } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU16, Ordering}; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + #[derive(Clone, Copy)] + enum Peer { + Serve, + Drop, + Stall, + } + + async fn serve( + listener: TcpListener, + value: Arc, + peer: Peer, + mut shutdown: tokio::sync::oneshot::Receiver<()>, + ) { + loop { + let accepted = tokio::select! { + _ = &mut shutdown => break, + accepted = listener.accept() => accepted, + }; + let Ok((mut socket, _)) = accepted else { + break; + }; + let value = Arc::clone(&value); + let mode = peer; + tokio::spawn(async move { + match mode { + Peer::Drop => {} + Peer::Stall => { + tokio::time::sleep(Duration::from_secs(30)).await; + } + Peer::Serve => { + let mut buf = [0_u8; 260]; + loop { + let n = match socket.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => n, + }; + if n < 12 { + continue; + } + let unit = buf[6]; + let function = buf[7]; + if function == 3 { + let current = value.load(Ordering::Relaxed); + let response = [ + buf[0], + buf[1], + 0, + 0, + 0, + 5, + unit, + 3, + 2, + (current >> 8) as u8, + (current & 0xff) as u8, + ]; + if socket.write_all(&response).await.is_err() { + return; + } + } else if function == 6 { + let written = u16::from_be_bytes([buf[10], buf[11]]); + value.store(written, Ordering::Relaxed); + if socket.write_all(&buf[..12]).await.is_err() { + return; + } + } + } + } + } + }); + } + } + + fn spawn_peer( + listener: TcpListener, + value: Arc, + peer: Peer, + ) -> ( + tokio::sync::oneshot::Sender<()>, + tokio::task::JoinHandle<()>, + ) { + let (stop, shutdown) = tokio::sync::oneshot::channel(); + let handle = tokio::spawn(serve(listener, value, peer, shutdown)); + (stop, handle) + } + + fn adapter(port: u16) -> ModbusAdapter { + ModbusAdapter::with_timeouts( + "127.0.0.1".into(), + port, + Duration::from_millis(400), + Duration::from_millis(400), + ) + } + + #[tokio::test] + async fn read_times_out_when_the_peer_accepts_and_stalls() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let value = Arc::new(AtomicU16::new(1)); + let (_stop, server) = spawn_peer(listener, value, Peer::Stall); + let started = std::time::Instant::now(); + let err = adapter(port).read_register(1).await.unwrap_err(); + let elapsed = started.elapsed(); + assert!( + elapsed >= Duration::from_millis(300), + "returned too fast: {elapsed:?}" + ); + assert!(elapsed < Duration::from_secs(2), "hung: {elapsed:?}"); + let message = format!("{err:#}"); + assert!(message.contains("timed out"), "{message}"); + server.abort(); + } + + #[tokio::test] + async fn disconnect_fails_the_call_and_the_next_call_reconnects() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let port = addr.port(); + let value = Arc::new(AtomicU16::new(42)); + let (stop, server) = spawn_peer(listener, Arc::clone(&value), Peer::Drop); + let client = adapter(port); + let err = client.read_register(1).await.unwrap_err(); + assert!( + !format!("{err:#}").contains("timed out"), + "disconnect was reported as a timeout: {err:#}" + ); + let _ = stop.send(()); + server.await.unwrap(); + + let listener = TcpListener::bind(addr).await.unwrap(); + let (_stop, server) = spawn_peer(listener, Arc::clone(&value), Peer::Serve); + assert_eq!(client.read_register(1).await.unwrap(), 42); + client.write_register(1, 77).await.unwrap(); + assert_eq!(client.read_register(1).await.unwrap(), 77); + assert!(client.health_check().await.unwrap()); + server.abort(); + } + + #[tokio::test] + async fn connect_attempt_stays_inside_the_deadline() { + let client = ModbusAdapter::with_timeouts( + "192.0.2.1".into(), + 9, + Duration::from_millis(200), + Duration::from_millis(200), + ); + let started = std::time::Instant::now(); + let err = client.read_register(1).await.unwrap_err(); + let elapsed = started.elapsed(); + assert!( + elapsed < Duration::from_secs(2), + "hung for {elapsed:?}: {err:#}" + ); + assert!(!client.health_check().await.unwrap()); + } +} diff --git a/crates/operator/src/policy.rs b/crates/operator/src/policy.rs index 31ac789..652a524 100644 --- a/crates/operator/src/policy.rs +++ b/crates/operator/src/policy.rs @@ -235,6 +235,51 @@ mod tests { )); } + #[test] + fn restarted_operator_uses_the_persisted_cooldown_and_spec() { + let mut ctx = PolicyContext { + plc_name: "test-plc".into(), + register_name: "reg1".into(), + desired_value: 100, + current_value: 80, + strategy: RemediationStrategy::Auto, + last_correction_at: Some(Utc::now() - Duration::seconds(5)), + corrections_last_hour: 1, + max_corrections_per_hour: 5, + cooldown_secs: 30, + }; + assert!(matches!( + PolicyEngine::evaluate(&ctx), + PolicyDecision::Skip { .. } + )); + + ctx.last_correction_at = Some(Utc::now() - Duration::seconds(60)); + ctx.desired_value = 70; + match PolicyEngine::evaluate(&ctx) { + PolicyDecision::Correct { desired_value, .. } => assert_eq!(desired_value, 70), + other => panic!("restart must correct toward the spec, got {other:?}"), + } + } + + #[test] + fn restarted_halt_policy_does_not_write() { + let ctx = PolicyContext { + plc_name: "test-plc".into(), + register_name: "reg1".into(), + desired_value: 100, + current_value: 1, + strategy: RemediationStrategy::Halt, + last_correction_at: None, + corrections_last_hour: 0, + max_corrections_per_hour: 5, + cooldown_secs: 0, + }; + assert!(!matches!( + PolicyEngine::evaluate(&ctx), + PolicyDecision::Correct { .. } + )); + } + #[test] fn future_correction_timestamp_fails_closed() { let ctx = PolicyContext { diff --git a/crates/operator/src/reconcile_safety.rs b/crates/operator/src/reconcile_safety.rs new file mode 100644 index 0000000..c9a6e4e --- /dev/null +++ b/crates/operator/src/reconcile_safety.rs @@ -0,0 +1,137 @@ +/// Whether this process may reconcile. Followers must not read or write the PLC. +pub fn admit_reconcile(is_leader: bool) -> bool { + is_leader +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WriteGate { + Apply(u16), + Stale, +} + +/// A correction is safe only when the spec generation and desired value +/// still match the values the decision was computed from. +/// A restart loads both from the API; it does not keep an in-memory desired value. +pub fn gate_auto_write( + observed_generation: i64, + latest_generation: i64, + decided_desired: u16, + latest_desired: Option, +) -> WriteGate { + match latest_desired { + Some(value) if observed_generation == latest_generation && decided_desired == value => { + WriteGate::Apply(value) + } + _ => WriteGate::Stale, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + use std::thread; + + #[test] + fn follower_is_not_admitted() { + assert!(admit_reconcile(true)); + assert!(!admit_reconcile(false)); + } + + #[test] + fn spec_change_between_decision_and_write_is_rejected() { + assert_eq!(gate_auto_write(1, 1, 100, Some(100)), WriteGate::Apply(100)); + assert_eq!(gate_auto_write(1, 2, 100, Some(80)), WriteGate::Stale); + assert_eq!(gate_auto_write(1, 1, 100, Some(80)), WriteGate::Stale); + assert_eq!(gate_auto_write(1, 1, 100, None), WriteGate::Stale); + } + + #[test] + fn concurrent_spec_changes_never_write_a_stale_desired_value() { + struct Spec { + generation: i64, + desired: u16, + } + + let spec = Arc::new(Mutex::new(Spec { + generation: 1, + desired: 100, + })); + let history = Arc::new(Mutex::new(vec![(1_i64, 100_u16)])); + let applied = Arc::new(Mutex::new(Vec::<(i64, u16)>::new())); + let mut handles = Vec::new(); + + for id in 0..4_u16 { + let spec = Arc::clone(&spec); + let history = Arc::clone(&history); + handles.push(thread::spawn(move || { + for step in 0..40 { + let mut current = spec.lock().expect("spec"); + current.generation += 1; + current.desired = 300 + id * 20 + (step % 5); + history + .lock() + .expect("history") + .push((current.generation, current.desired)); + } + })); + } + + for _ in 0..4 { + let spec = Arc::clone(&spec); + let applied = Arc::clone(&applied); + handles.push(thread::spawn(move || { + for _ in 0..40 { + let (observed_generation, observed_desired) = { + let current = spec.lock().expect("spec"); + (current.generation, current.desired) + }; + thread::yield_now(); + let (latest_generation, latest_desired) = { + let current = spec.lock().expect("spec"); + (current.generation, Some(current.desired)) + }; + if let WriteGate::Apply(value) = gate_auto_write( + observed_generation, + latest_generation, + observed_desired, + latest_desired, + ) { + applied + .lock() + .expect("applied") + .push((observed_generation, value)); + } + } + })); + } + + for handle in handles { + handle.join().expect("worker"); + } + + let (settled_generation, settled_desired) = { + let current = spec.lock().expect("spec"); + (current.generation, current.desired) + }; + assert_eq!( + gate_auto_write( + settled_generation, + settled_generation, + settled_desired, + Some(settled_desired) + ), + WriteGate::Apply(settled_desired) + ); + + let history = history.lock().expect("history"); + let applied = applied.lock().expect("applied"); + for (generation, value) in applied.iter() { + let expected = history + .iter() + .find(|(stored_generation, _)| stored_generation == generation) + .map(|(_, desired)| *desired); + assert_eq!(expected, Some(*value)); + } + } +} diff --git a/crates/setpointctl/Cargo.toml b/crates/setpointctl/Cargo.toml index 835cf03..0a4766c 100644 --- a/crates/setpointctl/Cargo.toml +++ b/crates/setpointctl/Cargo.toml @@ -2,6 +2,7 @@ name = "setpointctl" version = "0.2.0" edition = "2021" +rust-version.workspace = true description = "Setpoint CLI - reconcile industrial PLCs from the command line" license = "MIT" repository = "https://github.com/apinzon/setpoint-operator" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 48b7827..258cadf 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -513,28 +513,28 @@ flowchart TB ### Reliability -- **Crash Recovery**: Automatic on restart -- **Network Partitions**: Exponential backoff retry -- **PLC Failures**: Isolated per PLC resource -- **Zero-Downtime Deploy**: Rolling update support +- **Crash Recovery**: Desired values and cooldowns are read from the IndustrialPLC spec and status on every reconcile. Deletion audit blocks are reloaded from `AUDIT_LEDGER_DIR`. +- **Leader election**: A `coordination.k8s.io/v1` Lease named `setpoint-operator-lease`. Followers skip reconciliation. Pod identity comes from `POD_NAME`. +- **PLC Failures**: Isolated per PLC resource. Modbus connect and I/O calls return within their timeouts, and the next call opens a new TCP connection. +- **Rolling update**: Only the lease holder reconciles. A replacement pod acquires the lease after the previous holder's duration expires. ## Future Considerations ### Potential Enhancements -1. **Webhook Validation**: Admission webhooks for CRD validation -2. **Leader Election**: Multi-replica operator with leader election -3. **Protocol Extensions**: Support for OPC-UA, EtherNet/IP -4. **Alerting**: Prometheus Alertmanager integration -5. **Backup/Restore**: Velero integration for CRD backup -6. **Multi-Cluster**: Fleet management across clusters +1. **Webhook Validation**: Admission webhooks for CRD validation are present in the operator process; cluster webhook registration is still a deployment choice +2. **Protocol Extensions**: Support for OPC-UA, EtherNet/IP +3. **Alerting**: Prometheus Alertmanager integration +4. **Backup/Restore**: Velero integration for CRD backup +5. **Multi-Cluster**: Fleet management across clusters ### Known Limitations -1. **Modbus TCP Only**: No serial (RTU/ASCII) support -2. **Single Register**: Per-PLC resource (no batch operations) -3. **No Authentication**: Modbus protocol limitation -4. **Polling Only**: No interrupt-driven updates +1. **Modbus TCP Only**: No serial (RTU/ASCII) support. Physical PLC validation is pending; proofs use a simulated peer. +2. **Halt is not a certified emergency stop**: Halt sets the resource phase to Failed and does not write the register. +3. **Single Register writes**: The reconciler writes one holding register per correction. +4. **No Authentication**: Modbus protocol limitation +5. **Polling Only**: No interrupt-driven updates --- diff --git a/docs/CLAIMS.md b/docs/CLAIMS.md index 18b9085..799d9cc 100644 --- a/docs/CLAIMS.md +++ b/docs/CLAIMS.md @@ -1,20 +1,32 @@ # Claim-to-proof matrix -The flagship proof uses a disposable kind cluster and a simulated PLC, not industrial hardware. +The flagship proof uses a disposable kind cluster and a simulated PLC, not industrial hardware. Physical PLC validation is **pending**. + +Halt marks the `IndustrialPLC` phase `Failed`. It is an operator status, not a safety-certified industrial emergency stop, and it does not write the register. | Claim | Implementation | Evidence | |---|---|---| -| Per-register Auto/Alert/Halt policy | crates/operator/src/policy.rs | Rust unit tests | -| Alert drift detected on the injected register | scripts/aggregate-proof.sh | drift-after.json | -| Alert policy does not write in the tested scenario | scripts/modbus-proof.py; mock PLC write-attempt log | plc-readback.json, mock-plc.log, proof.json | -| Prometheus exposure | crates/operator/src/metrics.rs | prometheus-metrics.txt | +| Per-register Auto/Alert/Halt policy | `crates/operator/src/policy.rs` | Rust unit tests | +| Alert drift detected on the injected register | `scripts/aggregate-proof.sh` | `drift-after.json` | +| Alert policy does not write in the tested scenario | `scripts/modbus-proof.py`; mock PLC write-attempt log | `plc-readback.json`, `mock-plc.log`, `proof.json` | +| Prometheus exposure | `crates/operator/src/metrics.rs` | `prometheus-metrics.txt` | +| Multi-replica leader election and failover | `crates/operator/src/leader.rs` | `two_replicas_elect_one_leader_and_fail_over_after_expiry`, `stale_resource_version_loses_the_race`; kind proof `scripts/leader-failover-proof.sh` | +| Modbus disconnect, timeout, and reconnect | `crates/operator/src/plc_client.rs` | `disconnect_fails_the_call_and_the_next_call_reconnects`, `read_times_out_when_the_peer_accepts_and_stalls`, `connect_attempt_stays_inside_the_deadline` | +| Reconciliation stays safe across process restart | `crates/operator/src/policy.rs`, `crates/operator/src/reconcile_safety.rs`, `crates/operator/src/crypto.rs` | cooldown is read from status; auto writes are gated on spec generation; deletion blocks reload from disk | +| Detect a changed generation or desired value at the pre-write re-read | `crates/operator/src/reconcile_safety.rs`, generation check in `controller.rs` | Unit tests for the generation/value check; no atomic fencing of in-flight Modbus writes. | +| Durable audit retention for deletion events | `crates/operator/src/crypto.rs`, `crates/operator/src/audit_retention.rs` | file ledger survives reopen; ConfigMap document is idempotent and signature-checked; finalizer is removed only after both succeed | +| Minimum Kubernetes and Rust | `docs/SUPPORT.md`, `charts/setpoint/Chart.yaml`, workspace `rust-version` | Helm proof on kind `v1.28.15`; CI job `msrv` | +| Helm install on a clean cluster | `scripts/helm-install-proof.sh`, `.github/workflows/helm-install.yml` | `artifacts/helm-install/proof.json` | +| Physical PLC validation | — | **Pending.** Current claims are simulated. | -Run `make flagship-proof` against a disposable kind cluster. CI uploads evidence on failure and success. The CI matrix independently exercises all three policies in separate simulated clusters. Auto requires one correction and restoration; Alert/Halt require exactly one write attempt (injection) and persistent drift. Halt also requires Failed status. Halt is an operator state, not a certified physical safety mechanism. All three policy jobs passed in [run 46988705127](https://github.com/AngelP17/Setpoint/actions/runs/46988705127) at commit `2909f30`. The combined-verdict job validates the artifact schema, policy, register, commit and expected write count for every policy and fails if a result is absent or the matrix fails. This new combined job requires its own CI run. +Run `make flagship-proof` against a disposable kind cluster. CI uploads evidence on failure and success. The CI matrix independently exercises all three policies in separate simulated clusters. Auto requires one correction and restoration; Alert/Halt require exactly one write attempt (injection) and persistent drift. Halt also requires Failed status. All three policy jobs passed in [run 46988705127](https://github.com/AngelP17/Setpoint/actions/runs/46988705127) at commit `2909f30`. The combined-verdict job validates the artifact schema, policy, register, commit and expected write count for every policy and fails if a result is absent or the matrix fails. | Claim | Evidence | Status | |---|---|---| -| A Kubernetes Lease controls operator leadership | `crates/operator/src/leader.rs`, reconciliation guard in `controller.rs` | Implemented. Multi-replica failover needs a test. | -| Halt changes the resource phase to Failed | `scripts/aggregate-proof.sh`, Halt job in `.github/workflows/e2e-proof.yml` | Asserted by the simulated policy proof. | -| Deletion creates an audit block | `crates/operator/src/controller.rs` deletion finalizer | Generated and logged. Durable retention needs a test and storage. | +| A Kubernetes Lease controls operator leadership | `crates/operator/src/leader.rs`; failover script | Unit-tested for two holders, expiry, and a lost compare-and-swap. The kind job deletes the holder pod and waits for a new `holderIdentity`. Local leadership expires on a monotonic deadline even if renewal stalls, and is rechecked just before an Auto write. | +| Halt changes the resource phase to Failed | `scripts/aggregate-proof.sh`, Halt job in `.github/workflows/e2e-proof.yml` | Asserted by the simulated policy proof. Not a certified emergency stop. | +| Deletion creates a durable audit record | file ledger plus ConfigMap `setpoint-audit-ledger` | The finalizer stays until `ensure_deletion_block` has fsynced and `retain_deletion_event` has stored the signed record. The ledger key is namespace, name, and UID. The ConfigMap update is a resourceVersion replace, and a conflict re-merges. | | `setpoint_drift_events_total` is exported | `crates/operator/src/metrics.rs`, `prometheus-metrics.txt` from the proof | Implemented. Inspect the uploaded artifact for a run. | -| Rust and Kubernetes version support | CI installs stable Rust and creates a kind cluster | Minimum versions are unverified. | +| Rust and Kubernetes version support | `docs/SUPPORT.md` | Minimum Kubernetes is 1.28. Minimum Rust is the workspace `rust-version`, exercised by the `msrv` CI job. | + +`make helm-install-proof` is the clean-cluster check. It needs Docker, kind, kubectl, Helm, and jq. This environment may not have them; the GitHub Actions workflow is the runner that executes it. diff --git a/docs/SUPPORT.md b/docs/SUPPORT.md new file mode 100644 index 0000000..df2f5eb --- /dev/null +++ b/docs/SUPPORT.md @@ -0,0 +1,33 @@ +# Supported versions + +Setpoint is proven against a simulated Modbus TCP device and a disposable Kubernetes cluster. Physical PLC validation is **pending**. + +Halt marks an `IndustrialPLC` `Failed` and does not write the register. It is an operator status, not a safety-certified industrial emergency stop. + +## Kubernetes + +**Minimum: 1.28.0** + +The operator is compiled with the `k8s-openapi` feature `v1_28`. The chart declares: + +```yaml +kubeVersion: ">=1.28.0-0" +``` + +That floor is the oldest API surface this repo claims. The Helm installation proof (`make helm-install-proof`, workflow `.github/workflows/helm-install.yml`) creates a kind v0.23.0 cluster with `kindest/node:v1.28.15`, installs `charts/setpoint`, waits for the deployment, and checks that `industrialplcs.setpoint.io` exists. The same run then scales the operator to two replicas and deletes the lease holder. + +The operator uses stable APIs that 1.28 already serves: custom resources, `apps/v1` Deployments, `coordination.k8s.io/v1` Leases, and core ConfigMaps. Clusters newer than 1.28 are the expected target. Clusters older than 1.28 are not supported. + +When reusing a ServiceAccount with `serviceAccount.create=false`, set `serviceAccount.name` and provision the required RBAC separately. The chart does not create or bind that account. + +## Rust + +**Minimum: Rust 1.88** (`rust-version` in the workspace `Cargo.toml`). + +That floor is the highest `rust-version` declared by the crates the unlocked workspace resolves today (1.88, from the `icu_*`, `pest`, and `encoding_rs` releases). CI job `msrv` in `.github/workflows/ci.yml` tests the workspace with Rust 1.88.0. The other Rust jobs use stable. `Cargo.lock` is gitignored, so a future dependency release can raise this floor; when it does, update `rust-version`, this document, and the `msrv` job together. + +## What is not supported + +- Device-side fencing. Lease expiry and a pre-write generation re-read reduce stale writes; they cannot make a Kubernetes spec change atomic with a Modbus write or cancel a request already accepted by the device. A process loss before status persistence can also lose the correction cooldown record. +- Physical PLC hardware. Every current proof uses `crates/mock-plc` or an in-process Modbus peer. Label those results simulated. +- Treating Halt as a certified emergency stop or a hardware safety function. diff --git a/docs/demo-script.md b/docs/demo-script.md index b1911b5..cf91b8d 100644 --- a/docs/demo-script.md +++ b/docs/demo-script.md @@ -30,10 +30,12 @@ cargo --version Open `config/samples/industrialplc-line1.yaml`. Read the spec aloud. > "This is a single git-tracked YAML. It declares the desired state of -> two Modbus registers on the same physical device. Notice the per-register -> remediation policy: `Auto` for the conveyor belt, `Alert` for the -> print head. The two registers live on the same PLC and the policies -> are per-register, not per-device." +> two Modbus registers on the simulated PLC used by this demo. Physical PLC +> validation is pending. Notice the per-register remediation policy: `Auto` +> for the conveyor belt, `Alert` for the print head. Halt, when you show it, +> marks the IndustrialPLC Failed. It is an operator status, not a +> safety-certified emergency stop. The two registers live on the same PLC +> and the policies are per-register, not per-device." ## Step 2 — start observability (10s) diff --git a/docs/executive-summary.md b/docs/executive-summary.md index b8d1de8..5ddfc07 100644 --- a/docs/executive-summary.md +++ b/docs/executive-summary.md @@ -24,9 +24,9 @@ detects drift, and applies a per-register remediation policy: - **Auto** — write the desired value back. For drift you want silently fixed. - **Alert** — emit a Warning event and bump a metric, but do not write. For drift that needs a human at the panel. -- **Halt** — mark the resource `Failed` and stop reconciling. For drift that - should never be auto-corrected because the cost of being wrong is worse - than the cost of waiting. +- **Halt** — mark the resource `Failed` and do not write the register. For + drift that should never be auto-corrected. Halt is an operator status, not + a safety-certified industrial emergency stop. Per-register policies live next to the register they govern, so the "conveyor belt can self-correct, the print head needs a human" rule is diff --git a/docs/proof.md b/docs/proof.md index 63851b6..67735e4 100644 --- a/docs/proof.md +++ b/docs/proof.md @@ -3,6 +3,12 @@ This document is the technical deep-dive on the proof run. For a non-technical overview, see [`docs/executive-summary.md`](executive-summary.md). +The proof uses a simulated Modbus device. **Physical PLC validation is pending.** + +Halt requires the resource phase `Failed` and no corrective write. Halt is an operator status, not a safety-certified industrial emergency stop. + +Supported Kubernetes and Rust versions are recorded in [`docs/SUPPORT.md`](SUPPORT.md). A clean-cluster Helm install, including leader failover, is `make helm-install-proof`. + ## The scenario A production line has a Modbus TCP device (the `line-1-printer-plc`) diff --git a/k8s/deployment-local.yaml b/k8s/deployment-local.yaml index b02e745..715e88f 100644 --- a/k8s/deployment-local.yaml +++ b/k8s/deployment-local.yaml @@ -51,10 +51,6 @@ spec: env: - name: RUST_LOG value: info - - name: HOSTNAME - valueFrom: - fieldRef: - fieldPath: spec.nodeName - name: POD_NAME valueFrom: fieldRef: @@ -63,6 +59,13 @@ spec: valueFrom: fieldRef: fieldPath: metadata.namespace + - name: AUDIT_LEDGER_DIR + value: /var/lib/setpoint/audit + - name: AUDIT_CONFIGMAP_NAME + value: setpoint-audit-ledger + volumeMounts: + - name: audit-ledger + mountPath: /var/lib/setpoint/audit resources: limits: cpu: 500m @@ -70,6 +73,9 @@ spec: requests: cpu: 100m memory: 128Mi + volumes: + - name: audit-ledger + emptyDir: {} --- apiVersion: v1 kind: Service diff --git a/k8s/deployment.yaml b/k8s/deployment.yaml index 48d116c..c0e5222 100644 --- a/k8s/deployment.yaml +++ b/k8s/deployment.yaml @@ -51,10 +51,6 @@ spec: env: - name: RUST_LOG value: info - - name: HOSTNAME - valueFrom: - fieldRef: - fieldPath: spec.nodeName - name: POD_NAME valueFrom: fieldRef: @@ -63,6 +59,13 @@ spec: valueFrom: fieldRef: fieldPath: metadata.namespace + - name: AUDIT_LEDGER_DIR + value: /var/lib/setpoint/audit + - name: AUDIT_CONFIGMAP_NAME + value: setpoint-audit-ledger + volumeMounts: + - name: audit-ledger + mountPath: /var/lib/setpoint/audit resources: limits: cpu: 500m @@ -70,6 +73,9 @@ spec: requests: cpu: 100m memory: 128Mi + volumes: + - name: audit-ledger + emptyDir: {} --- apiVersion: v1 kind: Service diff --git a/k8s/rbac.yaml b/k8s/rbac.yaml index d8d7274..619dc3a 100644 --- a/k8s/rbac.yaml +++ b/k8s/rbac.yaml @@ -46,6 +46,16 @@ rules: - "" resources: - configmaps + verbs: + - get + - list + - watch + - create + - update + - patch + - apiGroups: + - "" + resources: - secrets verbs: - get diff --git a/landing/app/console/_components/dashboard.tsx b/landing/app/console/_components/dashboard.tsx index 6828bbb..598288c 100644 --- a/landing/app/console/_components/dashboard.tsx +++ b/landing/app/console/_components/dashboard.tsx @@ -39,7 +39,7 @@ export function DashboardView({
diff --git a/landing/app/console/_components/proof.tsx b/landing/app/console/_components/proof.tsx index 616f464..a4f1ae4 100644 --- a/landing/app/console/_components/proof.tsx +++ b/landing/app/console/_components/proof.tsx @@ -76,7 +76,7 @@ export function ProofView({ : "text-zinc-400" }`} > - {proof.verdict === "PASS" ? "Verifiably certified" : proof.verdict === "FAIL" ? "Invariant violated" : "Awaiting run"} + {proof.verdict === "PASS" ? "Simulated proof passed" : proof.verdict === "FAIL" ? "Invariant violated" : "Awaiting run"}
{proof.verdict} @@ -131,7 +131,7 @@ export function ProofView({

The flagship proof enforces strict invariants: any write to an Alert-only register - fails the verification suite. Run make flagship-proof to refresh. + fails the verification suite. Halt marks the resource Failed. It is an operator status, not a safety-certified emergency stop. Physical PLC validation is pending. Run make flagship-proof to refresh.

diff --git a/landing/app/console/_components/simulator.tsx b/landing/app/console/_components/simulator.tsx index f2360cd..c4c3405 100644 --- a/landing/app/console/_components/simulator.tsx +++ b/landing/app/console/_components/simulator.tsx @@ -43,7 +43,8 @@ const offlineFallback = (form: FormState): SimulationResponse => { if (form.strategy === "Halt") { return { verdict: "System Halt", - action: "Mark IndustrialPLC Failed, halt operational line", + action: + "Mark the IndustrialPLC Failed. This is an operator status, not a safety-certified emergency stop.", reason: `Halt strategy: drift detected (desired ${form.desiredValue}, actual ${form.currentValue}).`, risk: "Critical", }; @@ -275,13 +276,13 @@ export function SimulatorView() { disabled={submitting} className="w-full rounded-lg bg-emerald-500 px-4 py-2.5 font-bold text-zinc-950 transition hover:bg-emerald-400 disabled:opacity-50" > - {submitting ? "Evaluating…" : "Evaluate safety engine"} + {submitting ? "Evaluating…" : "Evaluate policy"}
diff --git a/landing/components/hero.tsx b/landing/components/hero.tsx index 676a2d6..2702f0b 100644 --- a/landing/components/hero.tsx +++ b/landing/components/hero.tsx @@ -106,7 +106,8 @@ export function Hero() {

Setpoint turns PLC registers into declarative resources, explains every remediation - decision, and ships a proof run that fails CI when safety policy is violated. + decision, and ships a proof run that fails CI when a remediation policy is violated. + Halt is an operator status, not a certified emergency stop.

diff --git a/landing/components/how-it-works.tsx b/landing/components/how-it-works.tsx index f51192f..5c3b273 100644 --- a/landing/components/how-it-works.tsx +++ b/landing/components/how-it-works.tsx @@ -8,7 +8,7 @@ const steps = [ icon: BracketsCurly, title: "Declare the machine surface.", body: - "Each IndustrialPLC resource names the device, port, registers, and remediation strategy. Auto writes back. Alert holds state and emits evidence. Halt fails fast.", + "Each IndustrialPLC resource names the device, port, registers, and remediation strategy. Auto writes back. Alert holds state and emits evidence. Halt marks the resource Failed. It is not a certified emergency stop.", code: `apiVersion: setpoint.io/v1 kind: IndustrialPLC metadata: diff --git a/landing/components/scada-console.tsx b/landing/components/scada-console.tsx index dd34b7c..4be233d 100644 --- a/landing/components/scada-console.tsx +++ b/landing/components/scada-console.tsx @@ -179,7 +179,7 @@ function scadaReducer(state: SCADAState, action: SCADAAction): SCADAState { id: nextId(), time: getTimestamp(), level: "FAIL", - message: `CRITICAL: policy=Halt triggered on reactor-temp. Marking IndustrialPLC Failed.`, + message: `policy=Halt on reactor-temp. Marking IndustrialPLC Failed. Not a certified emergency stop.`, }; return { ...state, @@ -286,7 +286,7 @@ export function SCADAConsole() { Watch the same fault trigger three different responses.

- Auto corrects. Alert reports. Halt fails fast. This sandbox keeps the page grounded in the actual safety model instead of abstract product copy. + Auto corrects. Alert reports. Halt marks the resource Failed. Halt is an operator status, not a safety-certified industrial emergency stop. This sandbox uses a simulated PLC. Physical PLC validation is pending.

diff --git a/landing/components/yaml-builder.tsx b/landing/components/yaml-builder.tsx index af4f0d6..17b9de5 100644 --- a/landing/components/yaml-builder.tsx +++ b/landing/components/yaml-builder.tsx @@ -115,7 +115,8 @@ spec:

{strategy === "Auto" && "Silently writes the desired value back on drift."} {strategy === "Alert" && "Observes register and emits events, monitoring only."} - {strategy === "Halt" && "Marks the resource failed and halts operational loop."} + {strategy === "Halt" && + "Marks the IndustrialPLC Failed. Not a certified emergency stop."}

diff --git a/scripts/helm-install-proof.sh b/scripts/helm-install-proof.sh new file mode 100755 index 0000000..ff5ed2a --- /dev/null +++ b/scripts/helm-install-proof.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Install the Setpoint chart into a clean kind cluster and record the verdict. +# Default node image is Kubernetes 1.28, the minimum version this repo claims. +# Physical PLC validation is pending: this proof only checks the chart on kind. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +KIND_CLUSTER="${KIND_CLUSTER:-setpoint-helm}" +KIND_NODE_IMAGE="${KIND_NODE_IMAGE:-kindest/node:v1.28.15}" +NAMESPACE="${NAMESPACE:-setpoint-helm}" +ARTIFACTS_DIR="${ARTIFACTS_DIR:-${ROOT}/artifacts/helm-install}" +mkdir -p "$ARTIFACTS_DIR" + +need() { + command -v "$1" >/dev/null 2>&1 || { + echo "missing required command: $1" >&2 + exit 1 + } +} +need kind +need kubectl +need helm +need docker +need jq + +if ! kind get clusters | grep -qx "$KIND_CLUSTER"; then + kind create cluster --name "$KIND_CLUSTER" --image "$KIND_NODE_IMAGE" --wait 5m +fi +kubectl config use-context "kind-${KIND_CLUSTER}" + +if ! docker image inspect setpoint-operator:latest >/dev/null 2>&1; then + docker build -t setpoint-operator:latest -f Dockerfile.operator . +fi +kind load docker-image setpoint-operator:latest --name "$KIND_CLUSTER" + +helm upgrade --install setpoint charts/setpoint \ + --namespace "$NAMESPACE" \ + --create-namespace \ + --set image.repository=setpoint-operator \ + --set image.tag=latest \ + --set image.pullPolicy=IfNotPresent \ + --set replicaCount=1 + +kubectl -n "$NAMESPACE" rollout status deployment/setpoint --timeout=180s +kubectl get crd industrialplcs.setpoint.io >/dev/null + +server_version="$(kubectl version -o json | jq -r '.serverVersion.gitVersion')" +ready="$(kubectl -n "$NAMESPACE" get deployment setpoint -o jsonpath='{.status.readyReplicas}')" + +jq -n \ + --arg kubernetes "$server_version" \ + --arg namespace "$NAMESPACE" \ + --arg image "$KIND_NODE_IMAGE" \ + --argjson ready "${ready:-0}" \ + '{ + claim: "helm-install", + verdict: "PASS", + kubernetes: $kubernetes, + kindNodeImage: $image, + namespace: $namespace, + deploymentReadyReplicas: $ready, + crdPresent: true, + minimumKubernetes: "1.28.0", + simulated: true, + physicalPlcValidation: "pending", + note: "Helm install on a clean kind cluster. Halt is an operator status, not a safety-certified emergency stop." + }' > "${ARTIFACTS_DIR}/proof.json" + +echo "helm install PASS on ${server_version}" +cat "${ARTIFACTS_DIR}/proof.json" + +if [[ "${SKIP_FAILOVER:-0}" != "1" ]]; then + NAMESPACE="$NAMESPACE" ARTIFACTS_DIR="${ROOT}/artifacts/leader-failover" \ + "${ROOT}/scripts/leader-failover-proof.sh" +fi diff --git a/scripts/leader-failover-proof.sh b/scripts/leader-failover-proof.sh new file mode 100755 index 0000000..999cbe7 --- /dev/null +++ b/scripts/leader-failover-proof.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# Prove two operator replicas elect a single lease holder, and that a +# second replica acquires the lease after the holder pod is deleted. +# Kubernetes here is a simulator for the control plane. The PLC is not involved. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +NAMESPACE="${NAMESPACE:-setpoint-helm}" +DEPLOYMENT="${DEPLOYMENT:-setpoint}" +LEASE_NAME="${LEASE_NAME:-setpoint-operator-lease}" +ARTIFACTS_DIR="${ARTIFACTS_DIR:-${ROOT}/artifacts/leader-failover}" +mkdir -p "$ARTIFACTS_DIR" + +need() { + command -v "$1" >/dev/null 2>&1 || { + echo "missing required command: $1" >&2 + exit 1 + } +} +need kubectl +need jq + +kubectl -n "$NAMESPACE" scale "deployment/${DEPLOYMENT}" --replicas=2 +kubectl -n "$NAMESPACE" rollout status "deployment/${DEPLOYMENT}" --timeout=180s + +holder="" +for _ in $(seq 1 30); do + holder="$(kubectl -n "$NAMESPACE" get lease "$LEASE_NAME" -o jsonpath='{.spec.holderIdentity}' 2>/dev/null || true)" + if [[ -n "$holder" ]]; then + break + fi + sleep 2 +done +if [[ -z "$holder" ]]; then + echo "lease ${LEASE_NAME} was not acquired" >&2 + kubectl -n "$NAMESPACE" get lease,pods >&2 || true + exit 1 +fi + +kubectl -n "$NAMESPACE" delete pod "$holder" --wait=true + +new_holder="" +transitions="" +for _ in $(seq 1 40); do + new_holder="$(kubectl -n "$NAMESPACE" get lease "$LEASE_NAME" -o jsonpath='{.spec.holderIdentity}' 2>/dev/null || true)" + transitions="$(kubectl -n "$NAMESPACE" get lease "$LEASE_NAME" -o jsonpath='{.spec.leaseTransitions}' 2>/dev/null || true)" + if [[ -n "$new_holder" && "$new_holder" != "$holder" ]]; then + break + fi + sleep 2 +done + +if [[ -z "$new_holder" || "$new_holder" == "$holder" ]]; then + echo "leadership did not move after deleting ${holder}" >&2 + kubectl -n "$NAMESPACE" get lease "$LEASE_NAME" -o yaml >&2 || true + exit 1 +fi + +if ! kubectl -n "$NAMESPACE" get pod "$new_holder" >/dev/null 2>&1; then + echo "new holder ${new_holder} is not a pod in ${NAMESPACE}" >&2 + exit 1 +fi + +jq -n \ + --arg previous "$holder" \ + --arg current "$new_holder" \ + --arg transitions "${transitions:-0}" \ + '{ + claim: "leader-failover", + verdict: "PASS", + previousHolder: $previous, + currentHolder: $current, + leaseTransitions: ($transitions | tonumber), + simulated: true, + physicalPlcValidation: "pending", + note: "Two replicas share one Kubernetes Lease. Deleting the holder pod lets the standby acquire it after the lease duration. Halt is an operator status, not a safety-certified emergency stop." + }' > "${ARTIFACTS_DIR}/proof.json" + +echo "leader failover PASS: ${holder} -> ${new_holder}" +cat "${ARTIFACTS_DIR}/proof.json"