Updater Primary Spec
1. Introduction
CommandIT utilizes a suite of agent components (UI/App, Service, Probe) installed on managed endpoints across various operating systems (Windows, macOS, Linux). To ensure security, stability, and feature availability, these components must be kept up-to-date reliably and efficiently. This document describes the requirements for a dedicated Auto-Update Service (commandit-updater) responsible for managing the installation and updates of itself and all other CommandIT agent components, as well as the requirements for the supporting server-side infrastructure and processes. The updater must operate independently, handle initial installations, support release channels, provide defined rollback capabilities, support immediate update triggers, and follow industry best practices for robustness and security, similar to those employed by RMM and Antivirus solutions.
2. Goals & Objectives
- Reliable Updates: Automatically deploy updates for all CommandIT agent components (UI/App, Service, Probe) and the Updater Service itself across all supported platforms, respecting assigned release channels.
- Simplified Deployment: Facilitate the initial installation of CommandIT agents by bootstrapping the download and setup of the latest component versions appropriate for the target release channel.
- Self-Sufficiency: Operate independently of other CommandIT components, ensuring it can function even if other services are stopped or corrupted.
- Security: Ensure the integrity and authenticity of all downloaded update packages, maintain secure communication channels, protect update processes from tampering, and authenticate client requests.
- Resilience: Gracefully handle network interruptions, failed updates (including defined rollback procedures), concurrency issues, and unexpected system states.
- Efficiency: Minimize resource consumption (CPU, memory, network bandwidth, disk I/O) on the endpoint, both when idle and during active updates.
- Platform Coverage: Support all specified target operating systems and architectures.
- Controlled Rollouts: Support distinct release channels (e.g., Alpha, Beta, Production) for phased updates.
- Manageable Infrastructure: Provide a reliable, scalable, secure, and auditable update server infrastructure and package management process.
- On-Demand Updates: Allow updates to be triggered immediately when required.
3. Scope
3.1. In Scope
- Independent Execution: Updater runs as a standalone process/service on the endpoint, ensuring concurrency control.
- Update Check: Updater periodically checks a designated CommandIT update server (updates.commandit.com) via defined API endpoints for available updates based on the agent's assigned Release Channel.
- Forced Update Trigger ("Update Now"): Support for an external trigger (e.g., via secure IPC from the main Service or specific CLI command) to initiate an immediate update check and application cycle, bypassing the regular schedule.
- Secure Download: Updater downloads update packages over secure channels (HTTPS).
- Integrity & Authenticity Verification: Updater verifies the cryptographic signature and integrity (e.g., SHA-256 hash) of downloaded packages before application using a securely managed public key.
- Self-Update: Updater is capable of updating its own executable/service binary securely.
- Component Update: Updater manages the update process for UI/App, Service, and Probe components (stopping only the target component, backing up previous version, replacing files, restarting service, verifying health). Specific handling for UI/App updates.
- Update Rollback: If an update fails validation, file operations, health checks, or other defined critical steps, the updater automatically reverts the affected component(s) to the previously backed-up version.
- Component Reinstall: Updater provides the ability to perform a clean installation of any managed component.
- Initial Installation/Bootstrap: The updater executable facilitates the initial installation of CommandIT agents.
- Configuration Management: Updater manages its own configuration (update server URL, check interval, component manifest, Release Channel, public key info).
- Detailed Logging: Updater maintains detailed, structured operational logs for diagnostics and auditing, including defined error codes and rollback events.
- Basic Status Reporting: Updater provides a mechanism for status checking including defined status codes.
- Platform Adaptation: Updater handles OS-specific requirements.
- Release Channel Support: Updater fetches updates corresponding to its configured channel.
- Update Package Creation: Building, signing (using secure key management), packaging (structure to be defined by Dev team), and publishing update packages to the update server, including channel management.
- Update Server Infrastructure: Hosting (Digital Ocean), management, scaling, security (including rate limiting and basic client auth), and auditing of the update distribution endpoint (updates.commandit.com) and its APIs.
3.2. Out of Scope
- Centralized Management UI: A user interface for fleet-wide management (interacts with updater/server but is separate).
- Advanced Rollback: Multi-version rollback strategies.
- User-Driven Updates: Updates initiated via the CommandIT UI/App.
- Delta Updates (v1.4): See Section 9.
- On-Network Caching (v1.4): See Section 9.
- Advanced Scheduling/Throttling (v1.4): See Section 9 (e.g., update windows, user activity checks, metered network awareness).
- Offline/Air-gapped Environment Updates: Requires connectivity to updates.commandit.com.
4. Functional Requirements
4.1. Core Update Process (Client-Side: commandit-updater)
- FR-UPD-001: Update Check Trigger - Scheduled: Periodic checks (configurable interval, e.g., 4h + jitter).
- FR-UPD-001B: Update Check Trigger - Forced ("Update Now"): The Updater Service MUST expose a secure mechanism (e.g., specific command-line argument commandit-updater --checknow, or a signal/IPC method callable by the main CommandIT Service) to trigger an immediate update check cycle. This trigger bypasses the regular schedule interval (FR-UPD-001). The rest of the update process (check, download, verify, install, rollback) proceeds as normal. Appropriate security measures must prevent misuse of this trigger by unauthorized processes/users (e.g., CLI only usable by root/SYSTEM, IPC requires authenticated caller).
- FR-UPD-002: Update Server Communication: Outbound HTTPS (TLS 1.2+) to defined API endpoints on https://updates.commandit.com. Include simple authentication header (see NFR-SRV-010). Consider NFR-SEC-005 (Certificate Pinning).
- FR-UPD-003: Update Manifest Request: Send request (defined format, e.g., JSON) including:
- updater_version: string
- os: string (e.g., "windows", "macos", "linux")
- arch: string (e.g., "amd64", "arm64")
- release_channel: string (e.g., "stable", "beta", "alpha")
- components: array of objects [{ "name": string, "version": string }]
- FR-UPD-004: Update Manifest Response Handling: Parse response (defined format, e.g., JSON) from server (see FR-SRV-001). Handle cases where no updates are available or errors occur.
- FR-UPD-005: Secure Download: Download packages via HTTPS from URLs in the manifest. Implement retries with exponential backoff.
- FR-UPD-006: Package Verification: Before installation:
- Verify SHA-256 hash against manifest.
- Verify package signature using the configured public key (see NFR-SEC-006).
- Log verification success/failure clearly. Discard and log errors on failure. Failure triggers rollback (FR-RBK-001).
- FR-UPD-007: Update Sequencing & Transactional Rollback: Apply updates in a safe order (guided by optional server manifest dependencies). If an update sequence involves multiple components (A, B, C), and component B fails to update (at any step triggering rollback), the updater MUST attempt to roll back component B and component A (which previously succeeded in this sequence) to maintain a consistent state. Log the full sequence rollback attempt.
- FR-UPD-008: Temporary Space Management: Check available space before download/backup. Clean up temporary files/downloads post-operation (success, failure, rollback). Failure due to insufficient space during backup/extraction triggers rollback (FR-RBK-001).
- FR-UPD-009: Concurrency Control: Implement mechanism (e.g., system-wide named mutex or lock file in a secure location) to prevent multiple updater instances running simultaneously or interfering with an ongoing update process. Subsequent instances (including --checknow triggers) should exit gracefully or wait if a lock is held, logging the condition.
4.2. Self-Update (commandit-updater)
- FR-SUP-001: Self-Update Mechanism: Robust process (e.g., download new binary -> backup old -> launch new -> new replaces old -> cleanup -> restart service registration). Handle permissions and service registration correctly.
- FR-SUP-002: Self-Update Resilience: Recover from interruptions (reboot) during self-update.
- FR-SUP-003: Self-Update Rollback: If the new updater fails basic health check (e.g., cannot initialize, fails core function check, crashes quickly) immediately after launch, automatically attempt to restore the backed-up binary and restart the previous version. Log clearly. Failure triggers rollback (FR-RBK-001).
4.3. Component Update (UI/App, Service, Probe)
- FR-CMP-001: Component State Management & Graceful Stop: Before updating a component, stop only the target component's service/process. Use OS best practices for graceful stop:
- Send SIGTERM (Linux/macOS) or equivalent service stop control / WM_CLOSE (Windows).
- Wait for a defined period (e.g., 30 seconds) for the process to exit cleanly.
- If the process has not exited, send SIGKILL (Linux/macOS) or TerminateProcess (Windows).
- FR-CMP-002: Backup: Create a backup of the existing component installation directory/files before replacement. Retain only the single immediately preceding version.
- FR-CMP-003: File Replacement: Extract and replace files from the verified package. Preserve designated configuration/data files as specified by package metadata (structure TBD by Devs). Handle file permissions correctly. Critical file operation failures (e.g., permission denied, disk full mid-copy, file corruption during extraction) trigger rollback (FR-RBK-001).
- FR-CMP-004: Component Restart: Restart the service/process after file replacement. Failure to initiate restart (e.g., service registration issue) triggers rollback (FR-RBK-001).
- FR-CMP-005: Restart Verification & Health Check: Verify successful restart. Perform a defined health check (mechanism TBD by Devs for each component; minimum: process running). If verification or health check fails within a timeout period, log the specific error and initiate rollback (FR-RBK-001).
- FR-CMP-006: Post-Update Cleanup: On successful verification, remove the backup created in FR-CMP-002.
- FR-CMP-007: UI/App Update Handling: Updates for the UI/App component (user-session process) should ideally be attempted when the updater detects no active user sessions associated with the app (best-effort detection, OS-dependent). If an update must proceed while the UI/App is running, the updater should attempt graceful stop (FR-CMP-001) but will not stop unrelated components (e.g., the Service). On Terminal Servers, updates may proceed even with active sessions after attempting graceful stop.
4.4. Update Rollback (Client-Side)
- FR-RBK-001: Rollback Execution & Triggers: Rollback MUST be triggered automatically upon detection of the following failures during an update attempt for a component (or self-update):
- Package hash verification failure (FR-UPD-006).
- Package signature verification failure (FR-UPD-006).
- Insufficient disk space during backup or file extraction (FR-UPD-008).
- Failure to gracefully stop the existing service/process within timeout (FR-CMP-001).
- Critical file operation failure during extraction/replacement (e.g., permissions, disk full, corruption) (FR-CMP-003).
- Failure to initiate the restart of the service/process (FR-CMP-004).
- Failure of the updated service/process to start or pass its health check within timeout (FR-CMP-005).
- Failure of the new updater binary to pass its health check during self-update (FR-SUP-003).
- Rollback Procedure:
- Ensure component service/process is stopped.
- Remove files installed during the failed attempt.
- Restore files from the backup (FR-CMP-002). Handle potential errors during restore.
- Attempt to restart the component using the restored (previous) version.
- Verify the rollback: Perform the same health check (FR-CMP-005) on the restored version.
- Log the rollback attempt, specific trigger reason (using defined error code), and success/failure status (including rollback verification result).
- FR-RBK-002: Rollback Failure: If restoring the backup or restarting/verifying the previous version also fails, log a critical error with specific details (using defined error code). Leave the component stopped. Report critical failure status (FR-STA-001). Requires manual intervention.
4.5. Component Reinstall (Client-Side)
- FR-RIN-001: Reinstall Trigger: Support command/flag for full reinstall using the latest version for the channel.
- FR-RIN-002: Clean Slate: Optionally remove existing component directory (preserving designated files) before fresh install. Rollback not applicable.
4.6. Initial Installation / Bootstrap (Client-Side)
- FR-BST-001: Bootstrap Execution: Standalone updater executable serves as installer payload.
- FR-BST-002: First Run Logic: On 'install' or no manifest:
- Determine Release Channel (CLI arg, default 'stable').
- Connect to updates.commandit.com.
- Download manifest for baseline components for the channel.
- Download, verify, install components.
- Install self as persistent service/daemon with correct permissions.
- Create initial config (including channel) and component manifest.
- Securely provision the initial public key (e.g., embedded in bootstrap binary or placed via secure deployment script). (Method TBD by Devs).
- FR-BST-003: Initial Config Security: Ensure initial configuration file permissions are set correctly (FR-CFG-004).
4.7. Configuration (Client-Side)
- FR-CFG-001: Configuration File: Use local config file (e.g., /etc/commandit/updater.conf, %ProgramData%\CommandIT\updater.conf; format JSON/YAML) for:
- update_server_url: string (Default: https://updates.commandit.com)
- update_check_interval_seconds: integer (Default: 14400)
- component_manifest_path: string
- log_file_path: string
- log_max_size_mb: integer
- log_max_files: integer
- public_key_path_or_value: string (Path preferred for easier rotation)
- release_channel: string
- auth_secret: string (For simple shared secret auth - NFR-SRV-010)
- FR-CFG-002: Configuration Override: Allow override via CLI/env vars for initial deployment/testing.
- FR-CFG-003: Component Manifest: Local manifest (e.g., manifest.json) tracking installed components, versions, paths. Updated atomically on success.
- FR-CFG-004: Configuration Security: Configuration files MUST have permissions restricting read/write access to privileged users (System/root) only.
4.8. Logging and Status (Client-Side)
- FR-LOG-001: Detailed Structured Logging: Log key events with timestamps, severity, specific error codes/messages. A defined list/enumeration of machine-parseable error codes will be created by the development team to represent distinct failure conditions. Use a standard format (e.g., JSON lines).
- FR-LOG-002: Log Rotation: Rotate logs based on size (log_max_size_mb) and number of files (log_max_files).
- FR-STA-001: Status Reporting: Provide machine-readable status (file/registry/plist):
- last_check_time: ISO8601 timestamp
- last_update_attempt_time: ISO8601 timestamp
- last_update_success_time: ISO8601 timestamp
- installed_components: array of objects [{ "name": string, "version": string }]
- assigned_channel: string
- last_operation_status_code: integer/enum (A defined list/enumeration will be created by the development team)
- last_error_code: integer/enum (Corresponds to FR-LOG-001 codes, null/0 on success)
- last_error_message: string (Brief human-readable error summary on failure)
4.9. Update Server & Packaging Requirements (Server-Side)
- FR-SRV-002: Package Hosting: Securely host signed packages (HTTPS). Use Digital Ocean Spaces (CDN recommended) for scalability/availability.
- FR-SRV-003: Channel Management: Logic to manage versions across channels. Tool/API for promoting builds (e.g., Beta -> Stable).
- FR-SRV-004: Package Signing: Secure, automated process using dedicated signing keys (NFR-SEC-004). Sign the package archive itself or include a signed manifest within the archive (TBD by Devs).
- FR-SRV-005: Build & Packaging Pipeline: Automated pipeline (CI/CD) to build, package (TR-PACK-001), sign, and upload to hosting, updating server metadata.
- FR-SRV-006: Scalability: Design infrastructure (DO Droplets/App Platform, Load Balancers, Spaces) for expected load.
- FR-SRV-007: Security: Secure server infrastructure (firewalls, access controls, regular updates). Protect signing keys rigorously.
- FR-SRV-008: API Definition: Define and document the specific API endpoints (e.g., /v1/check, /v1/packages/...) and their request/response formats (TR-API-001).
5. Non-Functional Requirements
- NFR-SEC-001: Secure Communication: HTTPS with TLS 1.2+ for all client-server traffic.
- NFR-SEC-002: Update Integrity: SHA-256 hash verification and digital signature verification (e.g., RSA 2048+, ECDSA P-256+) on client for all packages.
- NFR-SEC-003: Least Privilege (Client): Updater service runs as SYSTEM (Windows) or root (Linux/macOS).
- NFR-SEC-004: Secure Signing Process (Server): Use secure key management (HSM preferred, otherwise strictly controlled environment). Strict access control. Regular key rotation policy.
- NFR-SEC-005: Certificate Pinning (Client - Consideration): Evaluate implementing certificate pinning for updates.commandit.com (adds complexity for certificate rotation). Defer decision to detailed design.
- NFR-SEC-006: Public Key Management (Client): Initial public key securely provisioned (FR-BST-002). Define a secure mechanism for updating the public key itself via a signed update package (likely requires special handling/multi-stage process - TBD by Devs).
- NFR-SEC-007: Local File Protection (Client): Updater binary, config files (FR-CFG-004), logs, temporary/backup directories MUST have restrictive file system permissions.
- NFR-PER-001: Low Resource Idle (Client): Minimal resource usage when idle.
- NFR-PER-002: Efficient Download (Client/Server): Server should support HTTP range requests.
- NFR-PER-003: Server Performance: Fast API responses and download speeds. Monitor performance.
- NFR-REL-001: Network Resilience (Client): Tolerate intermittent connectivity; use retries with exponential backoff.
- NFR-REL-002: Installation Atomicity & Rollback (Client): Strive for atomic updates per component. Reliable rollback to previous state on defined failures (FR-RBK-001). Transactional rollback for sequences (FR-UPD-007).
- NFR-REL-003: Crash Recovery (Client): Recover gracefully from crashes/reboots, resuming, cleaning up partial operations, or rolling back as appropriate based on state.
- NFR-REL-004: Server Availability: High availability design for update server.
- NFR-REL-005: Concurrency Safety (Client): Updater MUST handle concurrent execution attempts safely (FR-UPD-009).
- NFR-PLA-001/002/003: Windows/macOS/Linux Support as previously defined.
- NFR-MNT-001: Code Quality: Well-documented, modular, maintainable Go code following best practices.
- NFR-TST-001: Testability (Client): Design for testability (unit, integration). CLI flags for testing modes (including --checknow).
- NFR-TST-002: Testability (Server): Testable API and packaging process.
- NFR-AUD-001: Server-Side Auditing: Log key events on the update server for monitoring and security analysis. Required fields per request/event:
- Timestamp (ISO8601)
- Source IP Address
- Request Endpoint/Operation (e.g., /v1/check, PackageUpload)
- Authentication Identifier (e.g., masked shared secret identifier, or agent ID if available later)
- Authentication Result (Success/Failure)
- Request Parameters (OS, Arch, Channel, Requested Components/Versions)
- Response Status Code (HTTP Status)
- Manifest Content Summary (e.g., Components/Versions offered) or Package Details (Name, Version, Channel)
- Error Message (if applicable)
- Request Duration
- NFR-SRV-009: Rate Limiting (Server): Implement server-side rate limiting on API endpoints (e.g., per IP address, per auth identifier) to prevent accidental or malicious DoS attacks.
- NFR-SRV-010: Client Authentication (Server/Client): Implement simple client authentication. Recommendation: Client sends a pre-configured shared secret via a custom HTTP header (e.g., X-CommandIT-Updater-Secret) with each API request (FR-UPD-002). Server validates this secret. Secret stored securely on client (FR-CFG-001, FR-CFG-004).
6. Technical Requirements
- TR-LANG-001: Client MUST be Go. Server components likely Go, TBD.
- TR-DEPS-001: Minimize client external dependencies.
- TR-BUILD-001: Cross-compiling build pipeline.
- TR-PACK-001: Client: single executable. Update Packages: Archives (ZIP/TAR.GZ). Internal structure, metadata format (e.g., for config preservation rules), and pre/post-script handling TBD by Dev team.
- TR-INFRA-001: Server hosted on Digital Ocean.
- TR-API-001: Formal API definition document (e.g., OpenAPI/Swagger) for server endpoints (FR-SRV-008).
- TR-ERR-001: Define standard error codes/enums for client logging and status reporting (FR-LOG-001, FR-STA-001). (Responsibility: Dev Team).
7. Error Handling & Recovery
- EH-CLI-001: Network Errors (Client): Retry with backoff. Log persistent failures with specific error codes (TR-ERR-001).
- EH-CLI-002: Verification Failure (Client): Log specific failure code (TR-ERR-001: hash mismatch, signature invalid). Discard package. Trigger rollback (FR-RBK-001). Report status.
- EH-CLI-003: Installation/File Op Failure (Client): Log specific error code (TR-ERR-001: permission, disk full, file corrupt). Initiate rollback (FR-RBK-001). Report status based on rollback outcome.
- EH-CLI-004: Service Control Failure (Client): Log specific error code (TR-ERR-001: stop failed, start failed, health check failed). Initiate rollback (FR-RBK-001). Report status.
- EH-CLI-005: Rollback Failure (Client): Log critical error code (TR-ERR-001: restore error, start failed after restore). Report critical failure status. Requires manual intervention.
- EH-SRV-001: Server Errors (Server): Robust error handling/logging. Return appropriate HTTP error codes and structured JSON error messages where possible (e.g., { "error_code": "INVALID_CHANNEL", "message": "..." }).
8. Release Criteria / Success Metrics
- (Previous criteria remain valid)
- Rollback triggers correctly on all specified failure conditions (FR-RBK-001).
- Transactional rollback for multi-component sequences functions correctly (FR-UPD-007).
- Defined error codes (TR-ERR-001) are implemented and used consistently in logs/status.
- UI/App update handling respects active use (FR-CMP-007).
- Graceful stop procedure (FR-CMP-001) is implemented correctly.
- Server implements rate limiting (NFR-SRV-009) and client authentication (NFR-SRV-010).
- Server-side audit logs contain all required fields (NFR-AUD-001).
- Forced update trigger (FR-UPD-001B) successfully initiates an update cycle and functions correctly.
9. Open Issues / Future Considerations (V2+)
- Delta Updates: Binary diffing for bandwidth savings.
- On-Network Cache: Local peer-to-peer or designated cache server for packages.
- Advanced Scheduling & Throttling: Update windows, user activity checks, network awareness (metered connections).
- Offline Installer Package: Bundled installer with packages for offline setup.
- Updater Configuration Updates: Secure mechanism for updating updater.conf itself.
- Advanced Rollback Strategy: Multi-version rollback.
- A/B Testing/Canary Releases: Finer-grained rollouts.
- Client Resource Throttling Implementation: Define specific mechanisms/limits for CPU/IO usage during updates.
- Certificate Pinning Implementation (NFR-SEC-005): Decision and implementation plan.
- Component Health Check Mechanisms (FR-CMP-005): Final definition for each component.
- Package Structure Definition (TR-PACK-001): Final definition including metadata/scripting.
- Initial Public Key Provisioning Method (FR-BST-002): Final definition.
- Public Key Rotation Mechanism (NFR-SEC-006): Final definition.