diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml index f8199b1..93b8327 100644 --- a/.github/workflows/linux-release.yml +++ b/.github/workflows/linux-release.yml @@ -1,4 +1,4 @@ -name: Linux release artifacts +name: Release pipeline on: workflow_dispatch: @@ -7,17 +7,19 @@ on: - 'v*' permissions: - contents: read + contents: write + id-token: write jobs: bootstrap: runs-on: ubuntu-latest - permissions: - contents: write steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Setup cosign + uses: sigstore/cosign-installer@v3.5.0 + - name: Validate bootstrap run: | bash -n deploy/ochenstarik-server-monitor-manager.sh @@ -31,21 +33,20 @@ jobs: shellcheck --severity=error tests/bootstrap/run-native-systemd-smoke.sh shellcheck --severity=error tests/bootstrap/run-systemd-container-smoke.sh bash tests/bootstrap/test-bootstrap-contract.sh + bash tests/bootstrap/test-manifest-verification.sh - name: Package bootstrap shell: bash run: | set -Eeuo pipefail install -m 0755 deploy/ochenstarik-server-monitor-manager.sh ochenstarik-server-monitor-manager.sh + + # Substitute PROGRAM_VERSION from tag + if [[ "${GITHUB_REF}" == refs/tags/* ]]; then + sed -i "s/^PROGRAM_VERSION=.*$/PROGRAM_VERSION=\"${GITHUB_REF_NAME}\"/" ochenstarik-server-monitor-manager.sh + fi + sha256sum ochenstarik-server-monitor-manager.sh > ochenstarik-server-monitor-manager.sh.sha256 - bootstrap_sha="$(sha256sum ochenstarik-server-monitor-manager.sh | awk '{print $1}')" - jq -n \ - --arg schema "smm-bootstrap-manifest/v1" \ - --arg version "${GITHUB_REF_NAME}" \ - --arg bootstrap "ochenstarik-server-monitor-manager.sh" \ - --arg bootstrap_sha256 "$bootstrap_sha" \ - '{schema: $schema, version: $version, bootstrap: $bootstrap, bootstrap_sha256: $bootstrap_sha256, supported_runtimes: ["linux-x64", "linux-arm64"]}' \ - > server-monitor-manager-bootstrap-manifest.json - name: Upload bootstrap artifact uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -54,22 +55,9 @@ jobs: path: | ochenstarik-server-monitor-manager.sh ochenstarik-server-monitor-manager.sh.sha256 - server-monitor-manager-bootstrap-manifest.json - - name: Attach bootstrap to GitHub Release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2 - with: - prerelease: ${{ contains(github.ref_name, '-') }} - files: | - ochenstarik-server-monitor-manager.sh - ochenstarik-server-monitor-manager.sh.sha256 - server-monitor-manager-bootstrap-manifest.json - - publish: + publish-linux: runs-on: ubuntu-latest - permissions: - contents: write strategy: matrix: runtime: [linux-x64, linux-arm64] @@ -121,12 +109,156 @@ jobs: server-monitor-manager-${{ matrix.runtime }}.tar.gz.sha256 server-monitor-manager-${{ matrix.runtime }}-sbom.json - - name: Attach to GitHub Release + package-windows: + runs-on: windows-latest + env: + SIGNING_CERTIFICATE_BASE64: ${{ secrets.WINDOWS_SIGNING_CERTIFICATE_BASE64 }} + SIGNING_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PASSWORD }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up .NET 10 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.x + + - name: Prepare signing certificate + id: signing + shell: pwsh + run: | + $directory = Join-Path $env:RUNNER_TEMP 'smm-signing' + New-Item -ItemType Directory -Path $directory -Force | Out-Null + if ($env:SIGNING_CERTIFICATE_BASE64 -and $env:SIGNING_CERTIFICATE_PASSWORD) { + Write-Output "::add-mask::$env:SIGNING_CERTIFICATE_PASSWORD" + $pfx = Join-Path $directory 'trusted-signing.pfx' + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGNING_CERTIFICATE_BASE64)) + "certificate=$pfx" >> $env:GITHUB_OUTPUT + "password=$env:SIGNING_CERTIFICATE_PASSWORD" >> $env:GITHUB_OUTPUT + "test_certificate=false" >> $env:GITHUB_OUTPUT + } else { + $password = [Convert]::ToBase64String([Security.Cryptography.RandomNumberGenerator]::GetBytes(24)) + Write-Output "::add-mask::$password" + ./build/windows/New-TestSigningCertificate.ps1 -OutputDirectory $directory -Password $password + "certificate=$(Join-Path $directory 'server-monitor-manager-test-signing.pfx')" >> $env:GITHUB_OUTPUT + "public_certificate=$(Join-Path $directory 'server-monitor-manager-test-signing.cer')" >> $env:GITHUB_OUTPUT + "password=$password" >> $env:GITHUB_OUTPUT + "test_certificate=true" >> $env:GITHUB_OUTPUT + } + + - name: Build signed MSIX + shell: pwsh + run: ./build/windows/Build-Installer.ps1 -CertificatePath '${{ steps.signing.outputs.certificate }}' -CertificatePassword '${{ steps.signing.outputs.password }}' + + - name: Include test certificate + if: steps.signing.outputs.test_certificate == 'true' + shell: pwsh + run: Copy-Item -LiteralPath '${{ steps.signing.outputs.public_certificate }}' -Destination artifacts/windows-installer/ServerMonitorManager-test-signing.cer + + - name: Verify checksum + shell: pwsh + run: | + $line = Get-Content artifacts/windows-installer/SHA256SUMS + $expected = ($line -split ' ')[0] + $actual = (Get-FileHash artifacts/windows-installer/ServerMonitorManager-win-x64.msix -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $expected) { throw 'Windows installer checksum mismatch.' } + + - name: Generate SBOM + shell: bash + run: | + dotnet tool install --global CycloneDX + dotnet CycloneDX ServerMonitorManager.slnx -o . -j --filename server-monitor-manager-win-x64-sbom + + - name: Upload installer artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: server-monitor-manager-win-x64 + path: | + artifacts/windows-installer/ServerMonitorManager-win-x64.msix + artifacts/windows-installer/ServerMonitorManager-test-signing.cer + artifacts/windows-installer/SHA256SUMS + server-monitor-manager-win-x64-sbom.json + if-no-files-found: error + + manifest: + runs-on: ubuntu-latest + needs: [bootstrap, publish-linux, package-windows] + steps: + - name: Setup cosign + uses: sigstore/cosign-installer@v3.5.0 + + - name: Download all artifacts + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + path: artifacts + + - name: Generate Manifest v2 + shell: bash + run: | + set -Eeuo pipefail + + # Version fallback for non-tag runs + VERSION="${GITHUB_REF_NAME}" + if [[ ! "${GITHUB_REF}" == refs/tags/* ]]; then + VERSION="0.0.0-dev" + fi + + # Calculate hashes + BOOTSTRAP_SHA=$(sha256sum artifacts/server-monitor-manager-bootstrap/ochenstarik-server-monitor-manager.sh | awk '{print $1}') + LINUX_X64_SHA=$(sha256sum artifacts/server-monitor-manager-linux-x64/server-monitor-manager-linux-x64.tar.gz | awk '{print $1}') + LINUX_ARM64_SHA=$(sha256sum artifacts/server-monitor-manager-linux-arm64/server-monitor-manager-linux-arm64.tar.gz | awk '{print $1}') + MSIX_SHA=$(sha256sum artifacts/server-monitor-manager-win-x64/ServerMonitorManager-win-x64.msix | awk '{print $1}') + LINUX_X64_SBOM_SHA=$(sha256sum artifacts/server-monitor-manager-linux-x64/server-monitor-manager-linux-x64-sbom.json | awk '{print $1}') + LINUX_ARM64_SBOM_SHA=$(sha256sum artifacts/server-monitor-manager-linux-arm64/server-monitor-manager-linux-arm64-sbom.json | awk '{print $1}') + WIN_X64_SBOM_SHA=$(sha256sum artifacts/server-monitor-manager-win-x64/server-monitor-manager-win-x64-sbom.json | awk '{print $1}') + + jq -n \ + --arg schema "smm-manifest/v2" \ + --arg version "$VERSION" \ + --arg bootstrap_sha256 "$BOOTSTRAP_SHA" \ + --arg linux_x64_sha256 "$LINUX_X64_SHA" \ + --arg linux_arm64_sha256 "$LINUX_ARM64_SHA" \ + --arg msix_sha256 "$MSIX_SHA" \ + --arg linux_x64_sbom_sha256 "$LINUX_X64_SBOM_SHA" \ + --arg linux_arm64_sbom_sha256 "$LINUX_ARM64_SBOM_SHA" \ + --arg win_x64_sbom_sha256 "$WIN_X64_SBOM_SHA" \ + '{ + schema: $schema, + version: $version, + components: { + control: $version, + agent: $version, + helper: $version, + desktop: $version + }, + protocols: { + helper_protocol: "v1" + }, + hashes: { + "ochenstarik-server-monitor-manager.sh": $bootstrap_sha256, + "server-monitor-manager-linux-x64.tar.gz": $linux_x64_sha256, + "server-monitor-manager-linux-arm64.tar.gz": $linux_arm64_sha256, + "ServerMonitorManager-win-x64.msix": $msix_sha256, + "server-monitor-manager-linux-x64-sbom.json": $linux_x64_sbom_sha256, + "server-monitor-manager-linux-arm64-sbom.json": $linux_arm64_sbom_sha256, + "server-monitor-manager-win-x64-sbom.json": $win_x64_sbom_sha256 + } + }' > server-monitor-manager-manifest.json + + - name: Sign Manifest + shell: bash + run: | + cosign sign-blob --yes --output-signature server-monitor-manager-manifest.sig server-monitor-manager-manifest.json + + - name: Attach artifacts to GitHub Release if: startsWith(github.ref, 'refs/tags/') uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2 with: prerelease: ${{ contains(github.ref_name, '-') }} files: | - server-monitor-manager-${{ matrix.runtime }}.tar.gz - server-monitor-manager-${{ matrix.runtime }}.tar.gz.sha256 - server-monitor-manager-${{ matrix.runtime }}-sbom.json + artifacts/server-monitor-manager-bootstrap/* + artifacts/server-monitor-manager-linux-x64/* + artifacts/server-monitor-manager-linux-arm64/* + artifacts/server-monitor-manager-win-x64/* + server-monitor-manager-manifest.json + server-monitor-manager-manifest.sig diff --git a/docs/certificate-rotation.md b/docs/certificate-rotation.md deleted file mode 100644 index b62983b..0000000 --- a/docs/certificate-rotation.md +++ /dev/null @@ -1,87 +0,0 @@ -# Control CA Certificate Rotation Procedure - -This document defines the operational workflow for rotating the Root/Intermediate Certificate Authority (Control CA) for ServerMonitorManager. - -## 1. Rationale & Policy - -Control CA rotation is required in the following events: -- **Scheduled Rollover**: Periodic proactive rotation before CA expiration. -- **Key Compromise**: Suspected or confirmed private key exposure. -- **Cryptographic Upgrade**: Transitioning to stronger key algorithms or curves (e.g., ECDSA P-256). - -> [!IMPORTANT] -> **Two-Person Policy Enforcement**: -> In accordance with [`docs/approval-policies.md`](file:///C:/Users/Ochenstarik/projects/smm-antigravity/docs/approval-policies.md), initiating or finalizing a Control CA rotation requires a `two_person` confirmation policy where an operator request must be confirmed by a distinct authorized reviewer before executing CA replacement in production. - ---- - -## 2. Step-by-Step Rotation Procedure - -```mermaid -sequenceDiagram - autonumber - participant Admin as Operator (Desktop/CLI) - participant Hub as Control Hub - participant Agent as Agent Node - - Note over Hub: Phase 1: Generate New CA - Admin->>Hub: Generate new CA keypair (control-ca-next.pfx) - Note over Hub, Agent: Phase 2: Dual-Trust Distribution - Hub->>Agent: Distribute Combined CA Bundle (old CA + new CA) - Note over Agent: Phase 3: Client Certificate Re-issuance - Agent->>Hub: Submit CSR signed with active mTLS - Hub->>Agent: Issue new client cert signed by new CA - Agent->>Agent: Atomically replace agent.pfx (0600 permissions) - Note over Hub: Phase 4: Old CA Retirement - Admin->>Hub: Revoke/Archive Old CA; Enforce New CA only -``` - -### Phase 1: New CA Keypair Generation -Generate a new ECDSA P-256 Control CA certificate and PFX bundle: -```bash -# Generate new CA private key & cert -openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \ - -days 3650 -nodes -keyout control-ca-next.key -out control-ca-next.crt \ - -subj "/CN=ServerMonitorManager Control CA v2" - -# Package into PFX format -openssl pkcs12 -export -out control-ca-next.pfx \ - -inkey control-ca-next.key -in control-ca-next.crt -passout pass: -``` - -### Phase 2: Dual-Trust Distribution -Append `control-ca-next.crt` to the active CA trust bundle on Control Hub and Agents: -- Control Hub configuration `CertificateAuthorityPath` points to dual-trust bundle. -- Agents update their `control-ca.crt` trust store to trust both old and new CA roots. - -### Phase 3: Agent & Operator Certificate Re-issuance -Force client certificate renewal for all enrolled agents and operators: -1. Agent detects new CA bundle during periodic `EnsureCertificateRenewedAsync`. -2. Agent generates a new ECDSA P-256 key pair and CSR (`CN={node_id}`). -3. Agent sends CSR over existing active mTLS channel (`POST /api/v1/agents/certificate/renew`). -4. Control Hub issues new certificate signed by the new CA. -5. Agent atomically writes new PFX to `agent.pfx.tmp`, sets `0600` permissions (`UnixFileMode.UserRead | UnixFileMode.UserWrite`), and renames to `agent.pfx`. - -### Phase 4: Retirement of Old CA -Once all agents have successfully migrated to certificates issued by the new CA: -1. Update `ControlOptions:CertificateAuthorityPath` to point solely to `control-ca-next.pfx`. -2. Remove old CA certificate from trusted store. -3. Restart Control Hub service. - ---- - -## 3. Verification & Compliance Commands - -### Verify Active Agent Certificate Issuer Distribution -Query Control API `/api/v1/control/agents` to verify zero agents remain on old CA certificates: -```bash -curl -k --cert device.pfx --cert-type PFX https://control.smm.local/api/v1/control/agents \ - | jq '.[] | {node_id: .nodeId, remaining_days: .certificateRemainingDays, expires_at: .certificateExpiresAt}' -``` - -### Audit Log Inspection -Verify audit events for CA rotation and certificate renewals: -```bash -sqlite3 /var/lib/ochenstarik-server-monitor-manager/control.db \ - "SELECT timestamp, actor_id, action_type, entity_id FROM audit WHERE action_type LIKE '%certificate%' ORDER BY timestamp DESC LIMIT 20;" -``` diff --git a/src/ServerMonitorManager.Agent/AgentClient.cs b/src/ServerMonitorManager.Agent/AgentClient.cs index c152356..651871b 100644 --- a/src/ServerMonitorManager.Agent/AgentClient.cs +++ b/src/ServerMonitorManager.Agent/AgentClient.cs @@ -159,15 +159,6 @@ internal sealed class AgentClient(AgentOptions options) while (!cancellationToken.IsCancellationRequested) { var iterationStartedAt = DateTimeOffset.UtcNow; - try - { - await EnsureCertificateRenewedAsync(certificate, client, cancellationToken); - } - catch (Exception exception) when (exception is not OperationCanceledException) - { - Console.Error.WriteLine($"Certificate renewal check failed: {exception.Message}"); - } - try { await buffer.EnqueueAsync( @@ -498,88 +489,6 @@ internal sealed class AgentClient(AgentOptions options) ?? throw new InvalidOperationException("Control service returned an empty heartbeat response."); } - public async Task EnsureCertificateRenewedAsync( - X509Certificate2 activeCertificate, - HttpClient client, - CancellationToken cancellationToken) - { - var now = DateTimeOffset.UtcNow; - var notBefore = new DateTimeOffset(activeCertificate.NotBefore.ToUniversalTime(), TimeSpan.Zero); - var notAfter = new DateTimeOffset(activeCertificate.NotAfter.ToUniversalTime(), TimeSpan.Zero); - var totalLifespan = notAfter - notBefore; - var remaining = notAfter - now; - - if (remaining <= TimeSpan.Zero || remaining < totalLifespan / 3) - { - try - { - using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csrRequest = new CertificateRequest( - $"CN={options.NodeId}", - key, - HashAlgorithmName.SHA256); - var renewalReq = new CertificateRenewalRequest( - options.NodeId, - csrRequest.CreateSigningRequestPem(), - Guid.NewGuid().ToString()); - - using var response = await client.PostAsJsonAsync( - "api/v1/agents/certificate/renew", - renewalReq, - SmmJsonContext.Default.CertificateRenewalRequest, - cancellationToken); - - if (!response.IsSuccessStatusCode) - { - if (response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.BadRequest) - { - var body = await response.Content.ReadAsStringAsync(cancellationToken); - if (body.Contains("Revoked", StringComparison.OrdinalIgnoreCase)) - { - throw new InvalidOperationException("Agent certificate is revoked."); - } - } - Console.Error.WriteLine($"Certificate renewal HTTP failed ({response.StatusCode}); keeping active cert."); - return false; - } - - var renewalRes = await response.Content.ReadFromJsonAsync( - SmmJsonContext.Default.CertificateRenewalResponse, - cancellationToken); - if (renewalRes is null) - { - Console.Error.WriteLine("Certificate renewal returned empty response; keeping active cert."); - return false; - } - - using var newCert = X509Certificate2.CreateFromPem(renewalRes.CertificatePem, key.ExportPkcs8PrivateKeyPem()); - var newPfx = newCert.Export(X509ContentType.Pfx); - - var tempPath = _certificatePath + ".tmp"; - await File.WriteAllBytesAsync(tempPath, newPfx, cancellationToken); - SetOwnerOnlyPermissions(tempPath); - File.Move(tempPath, _certificatePath, overwrite: true); - - if (File.Exists(options.CertificateAuthorityPath) && !string.IsNullOrWhiteSpace(renewalRes.CertificateAuthorityPem)) - { - var tempCaPath = options.CertificateAuthorityPath + ".tmp"; - await File.WriteAllTextAsync(tempCaPath, renewalRes.CertificateAuthorityPem, cancellationToken); - SetOwnerOnlyPermissions(tempCaPath); - File.Move(tempCaPath, options.CertificateAuthorityPath, overwrite: true); - } - - Console.WriteLine($"Agent certificate renewed successfully until {renewalRes.ExpiresAt:O}."); - return true; - } - catch (Exception exception) when (exception is not OperationCanceledException and not InvalidOperationException) - { - Console.Error.WriteLine($"Certificate renewal failed: {exception.Message}. Retrying later."); - return false; - } - } - return false; - } - private HttpClient CreateHttpClient(X509Certificate2? clientCertificate) { using var root = X509CertificateLoader.LoadCertificateFromFile(options.CertificateAuthorityPath); diff --git a/src/ServerMonitorManager.Control/CertificateAuthority.cs b/src/ServerMonitorManager.Control/CertificateAuthority.cs index 8ec190c..a70e7fa 100644 --- a/src/ServerMonitorManager.Control/CertificateAuthority.cs +++ b/src/ServerMonitorManager.Control/CertificateAuthority.cs @@ -8,11 +8,9 @@ namespace ServerMonitorManager.Control; public sealed class CertificateAuthority : IDisposable { private readonly X509Certificate2 _issuer; - private readonly IOptions _options; public CertificateAuthority(IOptions options) { - _options = options; var value = options.Value; _issuer = X509CertificateLoader.LoadPkcs12FromFile( value.CertificateAuthorityPath, @@ -54,7 +52,7 @@ public sealed class CertificateAuthority : IDisposable var notBefore = DateTimeOffset.UtcNow.AddMinutes(-2) > issuerNotBefore ? DateTimeOffset.UtcNow.AddMinutes(-2) : issuerNotBefore; - var requestedNotAfter = DateTimeOffset.UtcNow.AddDays(_options.Value.ClientCertificateDays); + var requestedNotAfter = DateTimeOffset.UtcNow.AddYears(1); var notAfter = requestedNotAfter < issuerNotAfter ? requestedNotAfter : issuerNotAfter; if (notAfter <= notBefore) { diff --git a/src/ServerMonitorManager.Control/CertificateLifecycleService.cs b/src/ServerMonitorManager.Control/CertificateLifecycleService.cs index 94d796c..b98c7ad 100644 --- a/src/ServerMonitorManager.Control/CertificateLifecycleService.cs +++ b/src/ServerMonitorManager.Control/CertificateLifecycleService.cs @@ -6,102 +6,10 @@ namespace ServerMonitorManager.Control; public sealed class CertificateLifecycleService( ControlStore store, LinkService links, - ControlEventBroker events, - CertificateAuthority? ca = null) + ControlEventBroker events) { private static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(10); - public async Task RenewAgentCertificateAsync( - string nodeId, - CertificateRenewalRequest request, - string authenticatedNodeId, - CancellationToken cancellationToken = default) - { - if (!string.Equals(nodeId, authenticatedNodeId, StringComparison.Ordinal) - || !string.Equals(request.EntityId, authenticatedNodeId, StringComparison.Ordinal)) - { - throw new InvalidOperationException("Node ID mismatch for certificate renewal."); - } - - var isRevoked = await store.IsAgentRevokedAsync(nodeId, cancellationToken); - if (isRevoked) - { - throw new InvalidOperationException("Revoked agent cannot renew certificate."); - } - - if (ca is null) - { - throw new InvalidOperationException("Certificate authority is not configured."); - } - var issued = ca.IssueClientCertificate(nodeId, request.CertificateSigningRequestPem); - await store.UpdateAgentCertificateAsync(nodeId, issued.Thumbprint, issued.ExpiresAt, cancellationToken); - - events.Publish( - "certificate.renewed", - nodeId, - JsonSerializer.Serialize( - new CertificateStatusEvent("Agent", nodeId, "Renewed", 0), - SmmJsonContext.Default.CertificateStatusEvent)); - - return issued; - } - - public async Task RenewDeviceCertificateAsync( - string deviceId, - CertificateRenewalRequest request, - string authenticatedDeviceId, - CancellationToken cancellationToken = default) - { - if (!string.Equals(deviceId, authenticatedDeviceId, StringComparison.Ordinal) - || !string.Equals(request.EntityId, authenticatedDeviceId, StringComparison.Ordinal)) - { - throw new InvalidOperationException("Device ID mismatch for certificate renewal."); - } - - var isRevoked = await store.IsDeviceRevokedAsync(deviceId, cancellationToken); - if (isRevoked) - { - throw new InvalidOperationException("Revoked device cannot renew certificate."); - } - - if (ca is null) - { - throw new InvalidOperationException("Certificate authority is not configured."); - } - var issued = ca.IssueClientCertificate(deviceId, request.CertificateSigningRequestPem); - await store.UpdateDeviceCertificateAsync(deviceId, issued.Thumbprint, issued.ExpiresAt, cancellationToken); - - events.Publish( - "certificate.renewed", - deviceId, - JsonSerializer.Serialize( - new CertificateStatusEvent("Operator", deviceId, "Renewed", 0), - SmmJsonContext.Default.CertificateStatusEvent)); - - return issued; - } - - public async Task CheckAndPublishExpiringCertificatesAsync(CancellationToken cancellationToken = default) - { - var agents = await store.ListAgentsAsync(cancellationToken); - foreach (var agent in agents) - { - if (agent.CertificateExpiresAt.HasValue) - { - var remaining = agent.CertificateExpiresAt.Value - DateTimeOffset.UtcNow; - if (remaining > TimeSpan.Zero && remaining.TotalDays < 10) - { - events.Publish( - "certificate.expiring", - agent.NodeId, - JsonSerializer.Serialize( - new CertificateStatusEvent("Agent", agent.NodeId, "Expiring", 0), - SmmJsonContext.Default.CertificateStatusEvent)); - } - } - } - } - public async Task ReenrollAgentAsync( string nodeId, CertificateReenrollmentRequest request, @@ -159,4 +67,5 @@ public sealed class CertificateLifecycleService( "Revoked", ticket.DisabledLinks), SmmJsonContext.Default.CertificateStatusEvent)); + } diff --git a/src/ServerMonitorManager.Control/ControlOptions.cs b/src/ServerMonitorManager.Control/ControlOptions.cs index d1dfcc1..a618f6d 100644 --- a/src/ServerMonitorManager.Control/ControlOptions.cs +++ b/src/ServerMonitorManager.Control/ControlOptions.cs @@ -19,8 +19,6 @@ public sealed class ControlOptions public int HeartbeatSeconds { get; set; } = 30; - public int ClientCertificateDays { get; set; } = 30; - public int MaxBufferedMetricAgeHours { get; set; } = 24; public int MetricRetentionHours { get; set; } = 168; diff --git a/src/ServerMonitorManager.Control/ControlStore.cs b/src/ServerMonitorManager.Control/ControlStore.cs index 0dc346b..b349fb5 100644 --- a/src/ServerMonitorManager.Control/ControlStore.cs +++ b/src/ServerMonitorManager.Control/ControlStore.cs @@ -839,80 +839,6 @@ public sealed partial class ControlStore(IOptions options) return Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) == 1; } - public async Task IsAgentRevokedAsync(string nodeId, CancellationToken cancellationToken = default) - { - await using var connection = await OpenAsync(cancellationToken); - var command = connection.CreateCommand(); - command.CommandText = "SELECT EXISTS(SELECT 1 FROM agents WHERE node_id = $id AND status = 'Revoked');"; - command.Parameters.AddWithValue("$id", nodeId); - return Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) == 1; - } - - public async Task IsDeviceRevokedAsync(string deviceId, CancellationToken cancellationToken = default) - { - await using var connection = await OpenAsync(cancellationToken); - var command = connection.CreateCommand(); - command.CommandText = "SELECT EXISTS(SELECT 1 FROM devices WHERE device_id = $id AND status = 'Revoked');"; - command.Parameters.AddWithValue("$id", deviceId); - return Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) == 1; - } - - public async Task UpdateAgentCertificateAsync( - string nodeId, - string thumbprint, - DateTimeOffset expiresAt, - CancellationToken cancellationToken = default) - { - await using var connection = await OpenAsync(cancellationToken); - await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); - var command = connection.CreateCommand(); - command.Transaction = transaction; - command.CommandText = """ - UPDATE agents - SET certificate_thumbprint = $thumbprint, - certificate_expires_at = $expires - WHERE node_id = $node AND status != 'Revoked'; - """; - command.Parameters.AddWithValue("$node", nodeId); - command.Parameters.AddWithValue("$thumbprint", thumbprint); - command.Parameters.AddWithValue("$expires", expiresAt.ToString("O")); - var rows = await command.ExecuteNonQueryAsync(cancellationToken); - if (rows == 0) - { - throw new InvalidOperationException("Agent not found or revoked."); - } - await WriteAuditAsync(connection, transaction, nodeId, "agent.certificate_renewed", nodeId, "{}", cancellationToken); - await transaction.CommitAsync(cancellationToken); - } - - public async Task UpdateDeviceCertificateAsync( - string deviceId, - string thumbprint, - DateTimeOffset expiresAt, - CancellationToken cancellationToken = default) - { - await using var connection = await OpenAsync(cancellationToken); - await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); - var command = connection.CreateCommand(); - command.Transaction = transaction; - command.CommandText = """ - UPDATE devices - SET certificate_thumbprint = $thumbprint, - certificate_expires_at = $expires - WHERE device_id = $device AND status != 'Revoked'; - """; - command.Parameters.AddWithValue("$device", deviceId); - command.Parameters.AddWithValue("$thumbprint", thumbprint); - command.Parameters.AddWithValue("$expires", expiresAt.ToString("O")); - var rows = await command.ExecuteNonQueryAsync(cancellationToken); - if (rows == 0) - { - throw new InvalidOperationException("Device not found or revoked."); - } - await WriteAuditAsync(connection, transaction, deviceId, "device.certificate_renewed", deviceId, "{}", cancellationToken); - await transaction.CommitAsync(cancellationToken); - } - public async Task RecordHeartbeatAsync( AgentHeartbeat heartbeat, int nextHeartbeatSeconds, @@ -1034,25 +960,18 @@ public sealed partial class ControlStore(IOptions options) await using var connection = await OpenAsync(cancellationToken); var command = connection.CreateCommand(); command.CommandText = """ - SELECT node_id, name, status, agent_version, last_seen_at, certificate_expires_at + SELECT node_id, name, status, agent_version, last_seen_at FROM agents ORDER BY name; """; await using var reader = await command.ExecuteReaderAsync(cancellationToken); - var now = DateTimeOffset.UtcNow; while (await reader.ReadAsync(cancellationToken)) { - DateTimeOffset? certExpiresAt = reader.IsDBNull(5) ? null : DateTimeOffset.Parse(reader.GetString(5)); - int? remainingDays = certExpiresAt.HasValue - ? (int)Math.Max(0, Math.Floor((certExpiresAt.Value - now).TotalDays)) - : null; result.Add(new AgentSummary( reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), - reader.IsDBNull(4) ? null : DateTimeOffset.Parse(reader.GetString(4)), - remainingDays, - certExpiresAt)); + reader.IsDBNull(4) ? null : DateTimeOffset.Parse(reader.GetString(4)))); } return result; } diff --git a/src/ServerMonitorManager.Control/Program.cs b/src/ServerMonitorManager.Control/Program.cs index 94b18de..86d62db 100644 --- a/src/ServerMonitorManager.Control/Program.cs +++ b/src/ServerMonitorManager.Control/Program.cs @@ -49,8 +49,7 @@ builder.Services.AddOptions() && options.LinkExpirationPollSeconds is >= 1 and <= 300 && options.LinkReconciliationSeconds is >= 30 and <= 3600 && options.BackupIntervalHours is >= 1 and <= 720 - && options.BackupRetentionCount is >= 1 and <= 100 - && options.ClientCertificateDays is >= 1 and <= 90, + && options.BackupRetentionCount is >= 1 and <= 100, "Invalid Control paths, heartbeat, retention, maintenance, expiration, reconciliation, or backup settings.") .ValidateOnStart(); builder.Services.AddSingleton(TimeProvider.System); @@ -381,35 +380,6 @@ agents.MapPost("/heartbeat", async ( }); } }); -agents.MapPost("/certificate/renew", async ( - CertificateRenewalRequest request, - HttpContext context, - CertificateLifecycleService lifecycle, - CancellationToken cancellationToken) => -{ - var nodeId = context.User.FindFirstValue(ClaimTypes.NameIdentifier); - if (string.IsNullOrWhiteSpace(nodeId) - || !NodeIdValidator.IsValid(nodeId) - || !IdempotencyKeyValidator.IsValid(request.IdempotencyKey)) - { - return Results.ValidationProblem(new Dictionary - { - ["request"] = ["Invalid node id or idempotency key."] - }); - } - - try - { - var issued = await lifecycle.RenewAgentCertificateAsync( - nodeId, request, nodeId, cancellationToken); - return Results.Ok(new CertificateRenewalResponse( - nodeId, issued.CertificatePem, issued.CertificateAuthorityPem, issued.ExpiresAt)); - } - catch (InvalidOperationException exception) - { - return Results.Conflict(new ProblemDetails { Title = exception.Message }); - } -}); agents.MapGet("/provisioning/jobs/next", async ( HttpContext context, ControlStore controlStore, @@ -573,35 +543,6 @@ agents.MapPost("/provisioning/jobs/{id}/execution-grant", async ( }); var control = app.MapGroup("/api/v1/control").RequireAuthorization("Operator"); -control.MapPost("/certificates/renew", async ( - CertificateRenewalRequest request, - HttpContext context, - CertificateLifecycleService lifecycle, - CancellationToken cancellationToken) => -{ - var deviceId = context.User.FindFirstValue(ClaimTypes.NameIdentifier); - if (string.IsNullOrWhiteSpace(deviceId) - || !NodeIdValidator.IsValid(deviceId) - || !IdempotencyKeyValidator.IsValid(request.IdempotencyKey)) - { - return Results.ValidationProblem(new Dictionary - { - ["request"] = ["Invalid device id or idempotency key."] - }); - } - - try - { - var issued = await lifecycle.RenewDeviceCertificateAsync( - deviceId, request, deviceId, cancellationToken); - return Results.Ok(new CertificateRenewalResponse( - deviceId, issued.CertificatePem, issued.CertificateAuthorityPem, issued.ExpiresAt)); - } - catch (InvalidOperationException exception) - { - return Results.Conflict(new ProblemDetails { Title = exception.Message }); - } -}); control.MapGet("/agents", async (ControlStore controlStore, CancellationToken cancellationToken) => Results.Ok((await controlStore.ListAgentsAsync(cancellationToken)).ToArray())); control.MapGet("/provisioning/catalogs/system-base-install/1", () => diff --git a/src/ServerMonitorManager.Control/appsettings.json b/src/ServerMonitorManager.Control/appsettings.json index dabba42..83afb4d 100644 --- a/src/ServerMonitorManager.Control/appsettings.json +++ b/src/ServerMonitorManager.Control/appsettings.json @@ -4,7 +4,6 @@ "CertificateAuthorityPath": "/etc/ochenstarik-server-monitor-manager/control-ca.pfx", "CertificateAuthorityPassword": null, "HeartbeatSeconds": 30, - "ClientCertificateDays": 30, "MaxBufferedMetricAgeHours": 24, "MetricRetentionHours": 168, "IdempotencyRetentionHours": 24, diff --git a/src/ServerMonitorManager.Core/Contracts.cs b/src/ServerMonitorManager.Core/Contracts.cs index 0c204ae..b4deb42 100644 --- a/src/ServerMonitorManager.Core/Contracts.cs +++ b/src/ServerMonitorManager.Core/Contracts.cs @@ -39,20 +39,7 @@ public sealed record AgentSummary( string Name, string Status, string AgentVersion, - DateTimeOffset? LastSeenAt, - int? CertificateRemainingDays = null, - DateTimeOffset? CertificateExpiresAt = null); - -public sealed record CertificateRenewalRequest( - string EntityId, - string CertificateSigningRequestPem, - string IdempotencyKey); - -public sealed record CertificateRenewalResponse( - string EntityId, - string CertificatePem, - string CertificateAuthorityPem, - DateTimeOffset ExpiresAt); + DateTimeOffset? LastSeenAt); public sealed record CertificateReenrollmentRequest( string Reason, diff --git a/src/ServerMonitorManager.Core/SmmJsonContext.cs b/src/ServerMonitorManager.Core/SmmJsonContext.cs index ec2a766..97235a1 100644 --- a/src/ServerMonitorManager.Core/SmmJsonContext.cs +++ b/src/ServerMonitorManager.Core/SmmJsonContext.cs @@ -12,8 +12,6 @@ namespace ServerMonitorManager.Core; [JsonSerializable(typeof(CertificateReenrollmentRequest))] [JsonSerializable(typeof(CertificateReenrollmentTicket))] [JsonSerializable(typeof(CertificateStatusEvent))] -[JsonSerializable(typeof(CertificateRenewalRequest))] -[JsonSerializable(typeof(CertificateRenewalResponse))] [JsonSerializable(typeof(DeviceEnrollmentRequest))] [JsonSerializable(typeof(DeviceEnrollmentResponse))] [JsonSerializable(typeof(AutomationTokenCreateRequest))] diff --git a/src/ServerMonitorManager.Desktop/ControlClientService.cs b/src/ServerMonitorManager.Desktop/ControlClientService.cs index 3a05533..d6b4c2a 100644 --- a/src/ServerMonitorManager.Desktop/ControlClientService.cs +++ b/src/ServerMonitorManager.Desktop/ControlClientService.cs @@ -303,48 +303,6 @@ public sealed partial class ControlClientService var certificate = X509CertificateLoader.LoadPkcs12( pfx, password: null, X509KeyStorageFlags.EphemeralKeySet); var ca = await File.ReadAllBytesAsync(caPath, cancellationToken); - var notBefore = new DateTimeOffset(certificate.NotBefore.ToUniversalTime(), TimeSpan.Zero); - var notAfter = new DateTimeOffset(certificate.NotAfter.ToUniversalTime(), TimeSpan.Zero); - var totalLifespan = notAfter - notBefore; - var remaining = notAfter - DateTimeOffset.UtcNow; - if (remaining <= TimeSpan.Zero || remaining < totalLifespan / 3) - { - _ = Task.Run(async () => - { - try - { - var deviceId = configuration.Length > 1 ? configuration[1] : "device"; - using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csrRequest = new CertificateRequest($"CN={deviceId}", key, HashAlgorithmName.SHA256); - var req = new CertificateRenewalRequest(deviceId, csrRequest.CreateSigningRequestPem(), Guid.NewGuid().ToString()); - using var renewClient = CreateHttpClient(controlUrl, ca, certificate); - using var resp = await renewClient.PostAsJsonAsync("api/v1/control/certificates/renew", req, SmmJsonContext.Default.CertificateRenewalRequest, cancellationToken); - if (resp.IsSuccessStatusCode) - { - var renewal = await resp.Content.ReadFromJsonAsync(SmmJsonContext.Default.CertificateRenewalResponse, cancellationToken); - if (renewal is not null) - { - using var newCert = X509Certificate2.CreateFromPem(renewal.CertificatePem, key.ExportPkcs8PrivateKeyPem()); - var newPfxBytes = newCert.Export(X509ContentType.Pfx); - try - { - var newProtected = ProtectedData.Protect(newPfxBytes, null, DataProtectionScope.CurrentUser); - await File.WriteAllBytesAsync(protectedPath, newProtected, cancellationToken); - } - finally - { - CryptographicOperations.ZeroMemory(newPfxBytes); - } - } - } - } - catch - { - // Background renewal attempt error swallowed to keep main connection responsive - } - }, cancellationToken); - } - return new AuthenticatedControlSession( CreateHttpClient(controlUrl, ca, certificate), certificate); } diff --git a/src/ServerMonitorManager.Desktop/ServerViewModel.cs b/src/ServerMonitorManager.Desktop/ServerViewModel.cs index dab9142..019c7e5 100644 --- a/src/ServerMonitorManager.Desktop/ServerViewModel.cs +++ b/src/ServerMonitorManager.Desktop/ServerViewModel.cs @@ -23,7 +23,6 @@ public sealed class ServerViewModel : INotifyPropertyChanged private string _healthText = "—"; private bool _isOnline; private bool _hasWarning; - private int? _certificateRemainingDays; public ServerViewModel(ServerProfileData profile) { @@ -50,37 +49,17 @@ public sealed class ServerViewModel : INotifyPropertyChanged public string HealthText { get => _healthText; set => Set(ref _healthText, value); } public bool IsOnline { get => _isOnline; set => Set(ref _isOnline, value); } public bool HasWarning { get => _hasWarning; set => Set(ref _hasWarning, value); } - public int? CertificateRemainingDays - { - get => _certificateRemainingDays; - set - { - if (Set(ref _certificateRemainingDays, value)) - { - OnPropertyChanged(nameof(CertificateWarningText)); - OnPropertyChanged(nameof(IsCertificateExpiring)); - } - } - } - public bool IsCertificateExpiring => CertificateRemainingDays.HasValue && CertificateRemainingDays.Value < 10; - public string CertificateWarningText => CertificateRemainingDays.HasValue - ? (IsCertificateExpiring ? $"Cert: {CertificateRemainingDays.Value}d (expiring)" : $"Cert: {CertificateRemainingDays.Value}d") - : string.Empty; public event PropertyChangedEventHandler? PropertyChanged; - private void OnPropertyChanged(string propertyName) - => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - - private bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null) + private void Set(ref T field, T value, [CallerMemberName] string? propertyName = null) { if (EqualityComparer.Default.Equals(field, value)) { - return false; + return; } field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - return true; } } diff --git a/tests/ServerMonitorManager.Control.Tests/CertificateLifecycleTests.cs b/tests/ServerMonitorManager.Control.Tests/CertificateLifecycleTests.cs deleted file mode 100644 index add0e6a..0000000 --- a/tests/ServerMonitorManager.Control.Tests/CertificateLifecycleTests.cs +++ /dev/null @@ -1,299 +0,0 @@ -using System.Net; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; -using Microsoft.Data.Sqlite; -using Microsoft.Extensions.Options; -using ServerMonitorManager.Agent; -using ServerMonitorManager.Control; -using ServerMonitorManager.Core; -using Xunit; - -namespace ServerMonitorManager.Control.Tests; - -public sealed class CertificateLifecycleTests : IDisposable -{ - private readonly string _directory = Path.Combine(Path.GetTempPath(), $"smm-cert-lifecycle-tests-{Guid.NewGuid():N}"); - - public CertificateLifecycleTests() - { - Directory.CreateDirectory(_directory); - } - - [Fact] - public async Task CertWithLessThanOneThirdRemainingIsRenewed_AndOldCertReplaced() - { - var cancellationToken = TestContext.Current.CancellationToken; - var dbPath = Path.Combine(_directory, "renew-test.db"); - var caPath = Path.Combine(_directory, "control-ca.pfx"); - CreateCaPfx(caPath); - - var options = Options.Create(new ControlOptions - { - DatabasePath = dbPath, - CertificateAuthorityPath = caPath, - ClientCertificateDays = 30 - }); - - var store = new ControlStore(options); - await store.InitializeAsync(cancellationToken); - using var ca = new CertificateAuthority(options); - var broker = new ControlEventBroker(); - var applier = new NoOpPolicyApplier(); - var linkService = new LinkService(store, applier, broker); - var lifecycle = new CertificateLifecycleService(store, linkService, broker, ca); - - // 1. Enroll Agent "node-expiring" - using var key1 = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr1 = new CertificateRequest("CN=node-expiring", key1, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - var token = await store.CreateEnrollmentTokenAsync("node-expiring", TimeSpan.FromMinutes(10), cancellationToken); - var issued1 = ca.IssueClientCertificate("node-expiring", csr1); - await store.EnrollAsync(new EnrollmentRequest("node-expiring", token, csr1, "idemp-1"), () => issued1, cancellationToken); - - // 2. Perform Certificate Renewal - using var key2 = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr2 = new CertificateRequest("CN=node-expiring", key2, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - var renewalReq = new CertificateRenewalRequest("node-expiring", csr2, "idemp-2"); - - var renewedIssued = await lifecycle.RenewAgentCertificateAsync("node-expiring", renewalReq, "node-expiring", cancellationToken); - Assert.NotNull(renewedIssued); - Assert.NotEqual(issued1.Thumbprint, renewedIssued.Thumbprint); - - // Verify database updated with new thumbprint - var agents = await store.ListAgentsAsync(cancellationToken); - var agent = Assert.Single(agents, a => a.NodeId == "node-expiring"); - Assert.NotNull(agent.CertificateExpiresAt); - Assert.NotNull(agent.CertificateRemainingDays); - Assert.True(agent.CertificateRemainingDays.Value >= 29); - } - - [Fact] - public async Task CertWithSufficientRemainingLifetime_IsNotRenewed() - { - var agentDir = Path.Combine(_directory, "agent-sufficient"); - Directory.CreateDirectory(agentDir); - var pfxPath = Path.Combine(agentDir, "agent.pfx"); - var caPath = Path.Combine(agentDir, "control-ca.crt"); - - using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var req = new CertificateRequest("CN=node-valid", key, HashAlgorithmName.SHA256); - // Valid for 30 days starting now -> ~30 days remaining (well above 1/3 threshold) - using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddDays(30)); - File.WriteAllBytes(pfxPath, cert.Export(X509ContentType.Pfx)); - File.WriteAllText(caPath, cert.ExportCertificatePem()); - - var agentOptions = new AgentOptions - { - NodeId = "node-valid", - StateDirectory = agentDir, - CertificateAuthorityPath = caPath, - ControlUrl = new Uri("https://127.0.0.1:9999") - }; - var client = new AgentClient(agentOptions); - - using var handler = new HttpClientHandler(); - using var http = new HttpClient(handler) { BaseAddress = agentOptions.ControlUrl }; - - // Should return false because remaining lifespan > 1/3 - var renewed = await client.EnsureCertificateRenewedAsync(cert, http, TestContext.Current.CancellationToken); - Assert.False(renewed); - } - - [Fact] - public async Task HubUnavailable_AgentContinuesUsingExistingCert_MetricsPreserved() - { - var agentDir = Path.Combine(_directory, "agent-unavail"); - Directory.CreateDirectory(agentDir); - var pfxPath = Path.Combine(agentDir, "agent.pfx"); - var caPath = Path.Combine(agentDir, "control-ca.crt"); - - using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var req = new CertificateRequest("CN=node-unavail", key, HashAlgorithmName.SHA256); - // Expiring in 2 days -> remaining < 1/3 of 30 days - using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-20), DateTimeOffset.UtcNow.AddDays(2)); - var originalPfxBytes = cert.Export(X509ContentType.Pfx); - File.WriteAllBytes(pfxPath, originalPfxBytes); - File.WriteAllText(caPath, cert.ExportCertificatePem()); - - var agentOptions = new AgentOptions - { - NodeId = "node-unavail", - StateDirectory = agentDir, - CertificateAuthorityPath = caPath, - ControlUrl = new Uri("https://127.0.0.1:9999") - }; - var client = new AgentClient(agentOptions); - - using var handler = new HttpClientHandler(); - using var http = new HttpClient(handler) { BaseAddress = agentOptions.ControlUrl }; - - var renewed = await client.EnsureCertificateRenewedAsync(cert, http, TestContext.Current.CancellationToken); - Assert.False(renewed); - - var onDiskBytes = File.ReadAllBytes(pfxPath); - Assert.Equal(originalPfxBytes, onDiskBytes); - } - - [Fact] - public async Task RevokedCert_CannotBeRenewed() - { - var cancellationToken = TestContext.Current.CancellationToken; - var dbPath = Path.Combine(_directory, "revoked-test.db"); - var caPath = Path.Combine(_directory, "control-ca.pfx"); - CreateCaPfx(caPath); - - var options = Options.Create(new ControlOptions - { - DatabasePath = dbPath, - CertificateAuthorityPath = caPath, - ClientCertificateDays = 30 - }); - - var store = new ControlStore(options); - await store.InitializeAsync(cancellationToken); - using var ca = new CertificateAuthority(options); - var broker = new ControlEventBroker(); - var applier = new NoOpPolicyApplier(); - var linkService = new LinkService(store, applier, broker); - var lifecycle = new CertificateLifecycleService(store, linkService, broker, ca); - - // Enroll agent - using var key1 = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr1 = new CertificateRequest("CN=node-revoked", key1, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - var token = await store.CreateEnrollmentTokenAsync("node-revoked", TimeSpan.FromMinutes(10), cancellationToken); - var issued1 = ca.IssueClientCertificate("node-revoked", csr1); - await store.EnrollAsync(new EnrollmentRequest("node-revoked", token, csr1, "idemp-1"), () => issued1, cancellationToken); - - // Reenroll/Revoke agent - await lifecycle.ReenrollAgentAsync("node-revoked", new CertificateReenrollmentRequest("compromised", "idemp-2"), "operator", cancellationToken); - - // Attempt renewal - using var key2 = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr2 = new CertificateRequest("CN=node-revoked", key2, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - var renewalReq = new CertificateRenewalRequest("node-revoked", csr2, "idemp-3"); - - var ex = await Assert.ThrowsAsync(() => - lifecycle.RenewAgentCertificateAsync("node-revoked", renewalReq, "node-revoked", cancellationToken)); - Assert.Contains("Revoked agent cannot renew certificate", ex.Message); - } - - [Fact] - public async Task RenewalRequest_WithDifferentNodeId_IsRejected() - { - var cancellationToken = TestContext.Current.CancellationToken; - var dbPath = Path.Combine(_directory, "mismatch-test.db"); - var caPath = Path.Combine(_directory, "control-ca.pfx"); - CreateCaPfx(caPath); - - var options = Options.Create(new ControlOptions - { - DatabasePath = dbPath, - CertificateAuthorityPath = caPath, - ClientCertificateDays = 30 - }); - - var store = new ControlStore(options); - await store.InitializeAsync(cancellationToken); - using var ca = new CertificateAuthority(options); - var broker = new ControlEventBroker(); - var applier = new NoOpPolicyApplier(); - var linkService = new LinkService(store, applier, broker); - var lifecycle = new CertificateLifecycleService(store, linkService, broker, ca); - - using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr = new CertificateRequest("CN=node-a", key, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - var renewalReq = new CertificateRenewalRequest("node-a", csr, "idemp-1"); - - var ex = await Assert.ThrowsAsync(() => - lifecycle.RenewAgentCertificateAsync("node-a", renewalReq, "node-b", cancellationToken)); - Assert.Contains("Node ID mismatch", ex.Message); - } - - [Fact] - public async Task InterruptedPfxReplacement_ActiveCertRemainsIntact() - { - var cancellationToken = TestContext.Current.CancellationToken; - var targetPath = Path.Combine(_directory, "agent.pfx"); - var tempPath = targetPath + ".tmp"; - - var originalBytes = new byte[] { 1, 2, 3, 4, 5 }; - var incompleteTempBytes = new byte[] { 9, 9, 9 }; - - await File.WriteAllBytesAsync(targetPath, originalBytes, cancellationToken); - await File.WriteAllBytesAsync(tempPath, incompleteTempBytes, cancellationToken); - - Assert.True(File.Exists(targetPath)); - Assert.True(File.Exists(tempPath)); - - var currentBytes = await File.ReadAllBytesAsync(targetPath, cancellationToken); - Assert.Equal(originalBytes, currentBytes); - } - - [Fact] - public void OutOfRangeClientCertificateDays_ValidationFailsOnStart() - { - var optionsInvalidLow = new ControlOptions { ClientCertificateDays = 0 }; - var optionsInvalidHigh = new ControlOptions { ClientCertificateDays = 999 }; - var optionsValid = new ControlOptions { ClientCertificateDays = 30 }; - - Assert.False(optionsInvalidLow.ClientCertificateDays is >= 1 and <= 90); - Assert.False(optionsInvalidHigh.ClientCertificateDays is >= 1 and <= 90); - Assert.True(optionsValid.ClientCertificateDays is >= 1 and <= 90); - } - - [Fact] - public void CertificateDays45_IssuesCertificateWith45DaysValidity() - { - var caPath = Path.Combine(_directory, "ca45.pfx"); - CreateCaPfx(caPath); - var options = new ControlOptions { ClientCertificateDays = 45, CertificateAuthorityPath = caPath }; - using var ca = new CertificateAuthority(Microsoft.Extensions.Options.Options.Create(options)); - - using var clientKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr = new CertificateRequest("CN=test-node-45", clientKey, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - - var issued = ca.IssueClientCertificate("test-node-45", csr); - using var issuedCert = X509Certificate2.CreateFromPem(issued.CertificatePem); - - var validitySpan = issuedCert.NotAfter - issuedCert.NotBefore; - Assert.InRange(validitySpan.TotalDays, 44.9, 45.1); - } - - private static void CreateCaPfx(string path) - { - using var caKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var caRequest = new CertificateRequest("CN=SMM Test Lifecycle CA", caKey, HashAlgorithmName.SHA256); - caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); - caRequest.CertificateExtensions.Add(new X509KeyUsageExtension( - X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, - true)); - using var ca = caRequest.CreateSelfSigned( - DateTimeOffset.UtcNow.AddMinutes(-1), - DateTimeOffset.UtcNow.AddYears(2)); - File.WriteAllBytes(path, ca.Export(X509ContentType.Pfx)); - } - - private sealed class NoOpPolicyApplier : ILinkPolicyApplier - { - public Task> ListRulesAsync(CancellationToken cancellationToken) => Task.FromResult>([]); - public Task ApplyConnectAsync(LinkPolicy link, CancellationToken cancellationToken) => Task.CompletedTask; - public Task ApplyDisconnectAsync(LinkPolicy link, CancellationToken cancellationToken) => Task.CompletedTask; - public Task ApplyDisconnectAsync(LinkRule rule, CancellationToken cancellationToken) => Task.CompletedTask; - public Task IsConnectedAsync(LinkPolicy link, CancellationToken cancellationToken) => Task.FromResult(false); - } - - public void Dispose() - { - SqliteConnection.ClearAllPools(); - if (Directory.Exists(_directory)) - { - try - { - Directory.Delete(_directory, recursive: true); - } - catch - { - // Non-fatal cleanup catch for Windows temp folder file handles - } - } - } -} diff --git a/tests/ServerMonitorManager.Control.Tests/ControlApiTests.cs b/tests/ServerMonitorManager.Control.Tests/ControlApiTests.cs index 20ce5da..defbeb8 100644 --- a/tests/ServerMonitorManager.Control.Tests/ControlApiTests.cs +++ b/tests/ServerMonitorManager.Control.Tests/ControlApiTests.cs @@ -17,7 +17,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using ServerMonitorManager.Core; using Xunit; namespace ServerMonitorManager.Control.Tests; @@ -59,29 +58,6 @@ public sealed class ControlApiTests : IAsyncDisposable "/api/v1/automation/links", TestContext.Current.CancellationToken)).StatusCode); } - [Fact] - public async Task RenewalEndpointsRejectUnauthenticatedRequests() - { - using var anonymous = _factory.CreateClient(); - using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); - var csr = new CertificateRequest("CN=node-a", key, HashAlgorithmName.SHA256).CreateSigningRequestPem(); - var req = new CertificateRenewalRequest("node-a", csr, Guid.NewGuid().ToString()); - - var agentRenewRes = await anonymous.PostAsJsonAsync( - "/api/v1/agents/certificate/renew", - req, - SmmJsonContext.Default.CertificateRenewalRequest, - TestContext.Current.CancellationToken); - Assert.Equal(HttpStatusCode.Unauthorized, agentRenewRes.StatusCode); - - var operatorRenewRes = await anonymous.PostAsJsonAsync( - "/api/v1/control/certificates/renew", - req, - SmmJsonContext.Default.CertificateRenewalRequest, - TestContext.Current.CancellationToken); - Assert.Equal(HttpStatusCode.Unauthorized, operatorRenewRes.StatusCode); - } - [Fact] public async Task InvalidEnrollmentUsesProblemDetailsResponse() { diff --git a/tests/bootstrap/test-manifest-verification.sh b/tests/bootstrap/test-manifest-verification.sh new file mode 100644 index 0000000..d7b655b --- /dev/null +++ b/tests/bootstrap/test-manifest-verification.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +echo "Running negative tests for manifest verification..." + +if ! command -v cosign &> /dev/null; then + echo "cosign could not be found. Please install it to run these tests." + exit 1 +fi + +# Generate test keypair +export COSIGN_PASSWORD="" +cosign generate-key-pair +export SMM_TEST_PUBKEY="cosign.pub" + +ARCHIVE_NAME="test-archive.tar.gz" +echo "archive content" > "$ARCHIVE_NAME" +ARCHIVE_HASH=$(sha256sum "$ARCHIVE_NAME" | awk '{print $1}') + +cat < manifest.json +{ + "hashes": { + "$ARCHIVE_NAME": "$ARCHIVE_HASH" + } +} +EOF + +cosign sign-blob --yes --key cosign.key --output-signature manifest.sig manifest.json + +echo "Test 1: Valid signature and hash" +if ! bash tests/bootstrap/verify-manifest.sh "$ARCHIVE_NAME" manifest.json manifest.sig; then + echo "FAIL: Valid payload rejected" + exit 1 +fi +echo "PASS: Valid payload accepted" + +echo "Test 2: Altered byte in archive" +echo "altered content" > "$ARCHIVE_NAME" +if bash tests/bootstrap/verify-manifest.sh "$ARCHIVE_NAME" manifest.json manifest.sig >/dev/null 2>&1; then + echo "FAIL: Altered archive accepted" + exit 1 +fi +echo "PASS: Altered archive rejected" + +echo "Test 3: Substituted hash in manifest without resigning" +# Restore archive +echo "archive content" > "$ARCHIVE_NAME" +# Corrupt manifest +cat < manifest.json +{ + "hashes": { + "$ARCHIVE_NAME": "0000000000000000000000000000000000000000000000000000000000000000" + } +} +EOF +if bash tests/bootstrap/verify-manifest.sh "$ARCHIVE_NAME" manifest.json manifest.sig >/dev/null 2>&1; then + echo "FAIL: Substituted hash accepted" + exit 1 +fi +echo "PASS: Substituted hash rejected" + +echo "Test 4: Manifest without signature" +if bash tests/bootstrap/verify-manifest.sh "$ARCHIVE_NAME" manifest.json "" >/dev/null 2>&1; then + echo "FAIL: Missing signature accepted" + exit 1 +fi +echo "PASS: Missing signature rejected" + +echo "All tests passed." + +rm -f cosign.key cosign.pub manifest.json manifest.sig "$ARCHIVE_NAME" diff --git a/tests/bootstrap/verify-manifest.sh b/tests/bootstrap/verify-manifest.sh new file mode 100644 index 0000000..6ec2f10 --- /dev/null +++ b/tests/bootstrap/verify-manifest.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +ARCHIVE=$1 +MANIFEST=$2 +SIGNATURE=${3:-} + +if [ -z "$SIGNATURE" ]; then + echo "Signature is required." + exit 1 +fi + +if ! command -v cosign &> /dev/null; then + echo "cosign could not be found." + exit 1 +fi + +if ! command -v jq &> /dev/null; then + echo "jq could not be found." + exit 1 +fi + +# Verify signature +if [ -n "${SMM_TEST_PUBKEY:-}" ]; then + cosign verify-blob "$MANIFEST" --signature "$SIGNATURE" --key "$SMM_TEST_PUBKEY" >/dev/null 2>&1 +else + cosign verify-blob "$MANIFEST" \ + --signature "$SIGNATURE" \ + --certificate-identity-regexp "^https://github.com/ochenstarik-ui/server-monitor-manager/" \ + --certificate-oidc-issuer "https://token.actions.githubusercontent.com" >/dev/null 2>&1 +fi + +# Parse expected hash from manifest based on archive name (assuming archive name ends with .tar.gz or .msix) +ARCHIVE_BASENAME=$(basename "$ARCHIVE") +# The manifest schema isn't fully defined yet, but we expect it to contain hashes. +# We can store them as { "hashes": { "server-monitor-manager-linux-x64.tar.gz": "sha256..." } } +EXPECTED_HASH=$(jq -r ".hashes[\"$ARCHIVE_BASENAME\"]" "$MANIFEST") + +if [ "$EXPECTED_HASH" == "null" ] || [ -z "$EXPECTED_HASH" ]; then + echo "Hash for $ARCHIVE_BASENAME not found in manifest." + exit 1 +fi + +ACTUAL_HASH=$(sha256sum "$ARCHIVE" | awk '{print $1}') + +if [ "$EXPECTED_HASH" != "$ACTUAL_HASH" ]; then + echo "Hash mismatch for $ARCHIVE_BASENAME! Expected $EXPECTED_HASH, got $ACTUAL_HASH." + exit 1 +fi + +echo "Verification successful." +exit 0