diff --git a/.github/workflows/linux-control-agent.yml b/.github/workflows/linux-control-agent.yml index fb27dc6..0dcf884 100644 --- a/.github/workflows/linux-control-agent.yml +++ b/.github/workflows/linux-control-agent.yml @@ -26,9 +26,6 @@ jobs: - name: Build run: dotnet build ServerMonitorManager.slnx --configuration Release --no-restore - - name: Generate reference alpha.7 control database - run: bash tests/acceptance/generate_alpha7_db.sh tests/acceptance/alpha7.db - - name: Test run: dotnet test tests/ServerMonitorManager.Control.Tests/ServerMonitorManager.Control.Tests.csproj --configuration Release --no-build diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml index 65bfaf7..20149e0 100644 --- a/.github/workflows/linux-release.yml +++ b/.github/workflows/linux-release.yml @@ -70,25 +70,14 @@ jobs: with: dotnet-version: 10.0.x - - name: Set Version - id: version - shell: bash - run: | - if [[ "${GITHUB_REF}" == refs/tags/* ]]; then - VERSION="${GITHUB_REF_NAME#v}" - else - VERSION="0.2.0-dev" - fi - echo "version=${VERSION}" >> $GITHUB_OUTPUT - - name: Publish agent - run: dotnet publish src/ServerMonitorManager.Agent/ServerMonitorManager.Agent.csproj --configuration Release --runtime ${{ matrix.runtime }} --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:RestoreLockedMode=true -p:Version=${{ steps.version.outputs.version }} -o out/agent + run: dotnet publish src/ServerMonitorManager.Agent/ServerMonitorManager.Agent.csproj --configuration Release --runtime ${{ matrix.runtime }} --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:RestoreLockedMode=true -o out/agent - name: Publish control - run: dotnet publish src/ServerMonitorManager.Control/ServerMonitorManager.Control.csproj --configuration Release --runtime ${{ matrix.runtime }} --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:RestoreLockedMode=true -p:Version=${{ steps.version.outputs.version }} -o out/control + run: dotnet publish src/ServerMonitorManager.Control/ServerMonitorManager.Control.csproj --configuration Release --runtime ${{ matrix.runtime }} --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:RestoreLockedMode=true -o out/control - name: Publish provisioning helper - run: dotnet publish src/ServerMonitorManager.Provisioning.Helper/ServerMonitorManager.Provisioning.Helper.csproj --configuration Release --runtime ${{ matrix.runtime }} --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:RestoreLockedMode=true -p:Version=${{ steps.version.outputs.version }} -o out/provisioning-helper + run: dotnet publish src/ServerMonitorManager.Provisioning.Helper/ServerMonitorManager.Provisioning.Helper.csproj --configuration Release --runtime ${{ matrix.runtime }} --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:RestoreLockedMode=true -o out/provisioning-helper - name: Package shell: bash @@ -108,8 +97,11 @@ jobs: - name: Generate SBOM run: | - dotnet tool install --global CycloneDX - dotnet CycloneDX ServerMonitorManager.slnx -o . -j --filename "server-monitor-manager-${{ matrix.runtime }}-sbom" + dotnet tool install --global CycloneDX --version 6.2.0 + dotnet CycloneDX ServerMonitorManager.slnx \ + --output . \ + --output-format Json \ + --filename "server-monitor-manager-${{ matrix.runtime }}-sbom.json" - name: Upload artifact uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -157,20 +149,9 @@ jobs: "test_certificate=true" >> $env:GITHUB_OUTPUT } - - name: Set Version - id: version - shell: bash - run: | - if [[ "${GITHUB_REF}" == refs/tags/* ]]; then - VERSION="${GITHUB_REF_NAME#v}" - else - VERSION="0.2.0-dev" - fi - echo "version=${VERSION}" >> $GITHUB_OUTPUT - - name: Build signed MSIX shell: pwsh - run: ./build/windows/Build-Installer.ps1 -CertificatePath '${{ steps.signing.outputs.certificate }}' -CertificatePassword '${{ steps.signing.outputs.password }}' -Version '${{ steps.version.outputs.version }}' + 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' @@ -188,8 +169,11 @@ jobs: - name: Generate SBOM shell: bash run: | - dotnet tool install --global CycloneDX - dotnet CycloneDX ServerMonitorManager.slnx -o . -j --filename server-monitor-manager-win-x64-sbom + dotnet tool install --global CycloneDX --version 6.2.0 + dotnet CycloneDX ServerMonitorManager.slnx \ + --output . \ + --output-format Json \ + --filename server-monitor-manager-win-x64-sbom.json - name: Upload installer artifact uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/.github/workflows/windows-release.yml b/.github/workflows/windows-release.yml index 2865d9a..e7c2b90 100644 --- a/.github/workflows/windows-release.yml +++ b/.github/workflows/windows-release.yml @@ -69,8 +69,11 @@ jobs: - name: Generate SBOM shell: bash run: | - dotnet tool install --global CycloneDX - dotnet CycloneDX ServerMonitorManager.slnx -o . -j --filename server-monitor-manager-win-x64-sbom + dotnet tool install --global CycloneDX --version 6.2.0 + dotnet CycloneDX ServerMonitorManager.slnx \ + --output . \ + --output-format Json \ + --filename server-monitor-manager-win-x64-sbom.json - name: Upload installer artifact uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/build/windows/Build-Installer.ps1 b/build/windows/Build-Installer.ps1 index e7ab61b..e398ebf 100644 --- a/build/windows/Build-Installer.ps1 +++ b/build/windows/Build-Installer.ps1 @@ -5,9 +5,6 @@ param( [Parameter(Mandatory = $true)] [string]$CertificatePassword, - [Parameter(Mandatory = $false)] - [string]$Version, - [string]$OutputDirectory = 'artifacts/windows-installer' ) @@ -41,38 +38,19 @@ try { dotnet restore $project -p:Platform=x64 -p:PublishReadyToRun=false -p:RestoreLockedMode=true if ($LASTEXITCODE -ne 0) { throw 'dotnet restore failed' } - if ($Version) { - $dotnetArgs += "-p:Version=$Version" - $dotnetArgs += "-p:AppxPackageVersion=$Version.0" - dotnet publish $project ` - --configuration Release ` - --runtime win-x64 ` - --no-restore ` - -p:Platform=x64 ` - -p:PublishReadyToRun=false ` - -p:GenerateAppxPackageOnBuild=true ` - -p:AppxPackageSigningEnabled=true ` - -p:PackageCertificateThumbprint=$($signingCertificate.Thumbprint) ` - -p:AppxBundle=Never ` - -p:AppxSymbolPackageEnabled=false ` - -p:UapAppxPackageBuildMode=SideloadOnly ` - -p:AppxPackageDir="$appPackages\" ` - -p:Version=$Version - } else { - dotnet publish $project ` - --configuration Release ` - --runtime win-x64 ` - --no-restore ` - -p:Platform=x64 ` - -p:PublishReadyToRun=false ` - -p:GenerateAppxPackageOnBuild=true ` - -p:AppxPackageSigningEnabled=true ` - -p:PackageCertificateThumbprint=$($signingCertificate.Thumbprint) ` - -p:AppxBundle=Never ` - -p:AppxSymbolPackageEnabled=false ` - -p:UapAppxPackageBuildMode=SideloadOnly ` - -p:AppxPackageDir="$appPackages\" - } + dotnet publish $project ` + --configuration Release ` + --runtime win-x64 ` + --no-restore ` + -p:Platform=x64 ` + -p:PublishReadyToRun=false ` + -p:GenerateAppxPackageOnBuild=true ` + -p:AppxPackageSigningEnabled=true ` + -p:PackageCertificateThumbprint=$($signingCertificate.Thumbprint) ` + -p:AppxBundle=Never ` + -p:AppxSymbolPackageEnabled=false ` + -p:UapAppxPackageBuildMode=SideloadOnly ` + -p:AppxPackageDir="$appPackages\" if ($LASTEXITCODE -ne 0) { throw 'dotnet publish failed' } $package = Get-ChildItem -LiteralPath $appPackages -Recurse -File | 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/ServerMonitorManager.Control.Tests/SchemaCompatibilityTests.cs b/tests/ServerMonitorManager.Control.Tests/SchemaCompatibilityTests.cs deleted file mode 100644 index 272aae0..0000000 --- a/tests/ServerMonitorManager.Control.Tests/SchemaCompatibilityTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Data.Sqlite; -using Microsoft.Extensions.Options; -using Xunit; - -namespace ServerMonitorManager.Control.Tests; - -public sealed class SchemaCompatibilityTests -{ - [Fact] - public async Task CanOpenAlpha7DatabaseWithoutReapplyingMigrations() - { - // Try to find the alpha7.db file which should be generated by CI - var dbPath = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, "..", "..", "..", "..", "..", "tests", "acceptance", "alpha7.db")); - - if (!File.Exists(dbPath)) - { - // Skip the test locally if the file hasn't been generated - return; - } - - // 1. Verify PRAGMA user_version is readable and hasn't changed abruptly - await using var connection = new SqliteConnection($"Data Source={dbPath}"); - await connection.OpenAsync(); - var command = connection.CreateCommand(); - command.CommandText = "PRAGMA user_version;"; - var userVersion = Convert.ToInt64(await command.ExecuteScalarAsync()); - - Assert.True(userVersion > 0, "Database user_version should be greater than 0"); - - // 2. Open it with the current ControlStore to see if data reads correctly and it doesn't crash - var store = new ControlStore(Options.Create(new ControlOptions { DatabasePath = dbPath })); - await store.InitializeAsync(CancellationToken.None); - - // 3. Test that we can read from it - var links = await store.ListEffectiveLinksForNodeAsync("nonexistent", CancellationToken.None); - Assert.Empty(links); - - } -} diff --git a/tests/acceptance/generate_alpha7_db.sh b/tests/acceptance/generate_alpha7_db.sh deleted file mode 100644 index 3aef7c3..0000000 --- a/tests/acceptance/generate_alpha7_db.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash -set -euo pipefail - -OUTPUT_DB=$(realpath "${1:-alpha7.db}") - -if [ -f "$OUTPUT_DB" ]; then - echo "Database $OUTPUT_DB already exists." - exit 0 -fi - -echo "Generating reference database from v0.1.0-alpha.7 to $OUTPUT_DB" -WORK_DIR=$(mktemp -d) -trap 'rm -rf "$WORK_DIR"' EXIT - -git clone --depth 1 -b v0.1.0-alpha.7 https://github.com/ochenstarik-ui/server-monitor-manager.git "$WORK_DIR/repo" - -cat << 'EOF' > "$WORK_DIR/repo/tests/ServerMonitorManager.Control.Tests/GenerateDbTest.cs" -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Xunit; -using ServerMonitorManager.Control; -using Microsoft.Extensions.Options; - -namespace ServerMonitorManager.Control.Tests; - -public class GenerateDbTest -{ - [Fact] - public async Task GenerateReferenceDatabase() - { - var dbPath = System.Environment.GetEnvironmentVariable("OUTPUT_DB_PATH"); - var store = new ControlStore(Options.Create(new ControlOptions { DatabasePath = dbPath })); - await store.InitializeAsync(CancellationToken.None); - } -} -EOF - -export OUTPUT_DB_PATH="$OUTPUT_DB" -cd "$WORK_DIR/repo" -dotnet test tests/ServerMonitorManager.Control.Tests --filter "GenerateReferenceDatabase"