up
Some checks failed
AOC Guard CI / aoc-guard (push) Has been cancelled
AOC Guard CI / aoc-verify (push) Has been cancelled
Docs CI / lint-and-preview (push) Has been cancelled
Notify Smoke Test / Notify Unit Tests (push) Has been cancelled
Notify Smoke Test / Notifier Service Tests (push) Has been cancelled
Notify Smoke Test / Notification Smoke Test (push) Has been cancelled
Policy Lint & Smoke / policy-lint (push) Has been cancelled
Scanner Analyzers / Discover Analyzers (push) Has been cancelled
Scanner Analyzers / Build Analyzers (push) Has been cancelled
Scanner Analyzers / Test Language Analyzers (push) Has been cancelled
Scanner Analyzers / Validate Test Fixtures (push) Has been cancelled
Scanner Analyzers / Verify Deterministic Output (push) Has been cancelled
Signals CI & Image / signals-ci (push) Has been cancelled
Signals Reachability Scoring & Events / reachability-smoke (push) Has been cancelled
Signals Reachability Scoring & Events / sign-and-upload (push) Has been cancelled
Manifest Integrity / Validate Schema Integrity (push) Has been cancelled
Manifest Integrity / Validate Contract Documents (push) Has been cancelled
Manifest Integrity / Validate Pack Fixtures (push) Has been cancelled
Manifest Integrity / Audit SHA256SUMS Files (push) Has been cancelled
Manifest Integrity / Verify Merkle Roots (push) Has been cancelled
devportal-offline / build-offline (push) Has been cancelled
Mirror Thin Bundle Sign & Verify / mirror-sign (push) Has been cancelled

This commit is contained in:
StellaOps Bot
2025-12-13 18:08:55 +02:00
parent 6e45066e37
commit f1a39c4ce3
234 changed files with 24038 additions and 6910 deletions

View File

@@ -0,0 +1,44 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Npgsql;
using StellaOps.Infrastructure.Postgres.Connections;
using StellaOps.Infrastructure.Postgres.Options;
namespace StellaOps.AirGap.Storage.Postgres;
/// <summary>
/// PostgreSQL data source for AirGap module.
/// </summary>
public sealed class AirGapDataSource : DataSourceBase
{
/// <summary>
/// Default schema name for AirGap tables.
/// </summary>
public const string DefaultSchemaName = "airgap";
/// <summary>
/// Creates a new AirGap data source.
/// </summary>
public AirGapDataSource(IOptions<PostgresOptions> options, ILogger<AirGapDataSource> logger)
: base(CreateOptions(options.Value), logger)
{
}
/// <inheritdoc />
protected override string ModuleName => "AirGap";
/// <inheritdoc />
protected override void ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder builder)
{
base.ConfigureDataSourceBuilder(builder);
}
private static PostgresOptions CreateOptions(PostgresOptions baseOptions)
{
if (string.IsNullOrWhiteSpace(baseOptions.SchemaName))
{
baseOptions.SchemaName = DefaultSchemaName;
}
return baseOptions;
}
}

View File

@@ -0,0 +1,275 @@
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Npgsql;
using StellaOps.AirGap.Controller.Domain;
using StellaOps.AirGap.Controller.Stores;
using StellaOps.AirGap.Time.Models;
using StellaOps.Infrastructure.Postgres.Repositories;
namespace StellaOps.AirGap.Storage.Postgres.Repositories;
/// <summary>
/// PostgreSQL-backed store for AirGap sealing state.
/// </summary>
public sealed class PostgresAirGapStateStore : RepositoryBase<AirGapDataSource>, IAirGapStateStore
{
private volatile bool _initialized;
private readonly SemaphoreSlim _initLock = new(1, 1);
public PostgresAirGapStateStore(AirGapDataSource dataSource, ILogger<PostgresAirGapStateStore> logger)
: base(dataSource, logger)
{
}
public async Task<AirGapState> GetAsync(string tenantId, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(tenantId);
await EnsureTableAsync(cancellationToken).ConfigureAwait(false);
await using var connection = await DataSource.OpenConnectionAsync("public", "reader", cancellationToken).ConfigureAwait(false);
const string sql = """
SELECT id, tenant_id, sealed, policy_hash, time_anchor, last_transition_at,
staleness_budget, drift_baseline_seconds, content_budgets
FROM airgap.state
WHERE LOWER(tenant_id) = LOWER(@tenant_id);
""";
await using var command = CreateCommand(sql, connection);
AddParameter(command, "tenant_id", tenantId);
await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
// Return default state for tenant if not found
return new AirGapState { TenantId = tenantId };
}
return Map(reader);
}
public async Task SetAsync(AirGapState state, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(state);
await EnsureTableAsync(cancellationToken).ConfigureAwait(false);
await using var connection = await DataSource.OpenConnectionAsync("public", "writer", cancellationToken).ConfigureAwait(false);
const string sql = """
INSERT INTO airgap.state (
id, tenant_id, sealed, policy_hash, time_anchor, last_transition_at,
staleness_budget, drift_baseline_seconds, content_budgets
)
VALUES (
@id, @tenant_id, @sealed, @policy_hash, @time_anchor, @last_transition_at,
@staleness_budget, @drift_baseline_seconds, @content_budgets
)
ON CONFLICT (tenant_id) DO UPDATE SET
id = EXCLUDED.id,
sealed = EXCLUDED.sealed,
policy_hash = EXCLUDED.policy_hash,
time_anchor = EXCLUDED.time_anchor,
last_transition_at = EXCLUDED.last_transition_at,
staleness_budget = EXCLUDED.staleness_budget,
drift_baseline_seconds = EXCLUDED.drift_baseline_seconds,
content_budgets = EXCLUDED.content_budgets,
updated_at = NOW();
""";
await using var command = CreateCommand(sql, connection);
AddParameter(command, "id", state.Id);
AddParameter(command, "tenant_id", state.TenantId);
AddParameter(command, "sealed", state.Sealed);
AddParameter(command, "policy_hash", (object?)state.PolicyHash ?? DBNull.Value);
AddJsonbParameter(command, "time_anchor", SerializeTimeAnchor(state.TimeAnchor));
AddParameter(command, "last_transition_at", state.LastTransitionAt);
AddJsonbParameter(command, "staleness_budget", SerializeStalenessBudget(state.StalenessBudget));
AddParameter(command, "drift_baseline_seconds", state.DriftBaselineSeconds);
AddJsonbParameter(command, "content_budgets", SerializeContentBudgets(state.ContentBudgets));
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
private static AirGapState Map(NpgsqlDataReader reader)
{
var id = reader.GetString(0);
var tenantId = reader.GetString(1);
var sealed_ = reader.GetBoolean(2);
var policyHash = reader.IsDBNull(3) ? null : reader.GetString(3);
var timeAnchorJson = reader.GetFieldValue<string>(4);
var lastTransitionAt = reader.GetFieldValue<DateTimeOffset>(5);
var stalenessBudgetJson = reader.GetFieldValue<string>(6);
var driftBaselineSeconds = reader.GetInt64(7);
var contentBudgetsJson = reader.IsDBNull(8) ? null : reader.GetFieldValue<string>(8);
var timeAnchor = DeserializeTimeAnchor(timeAnchorJson);
var stalenessBudget = DeserializeStalenessBudget(stalenessBudgetJson);
var contentBudgets = DeserializeContentBudgets(contentBudgetsJson);
return new AirGapState
{
Id = id,
TenantId = tenantId,
Sealed = sealed_,
PolicyHash = policyHash,
TimeAnchor = timeAnchor,
LastTransitionAt = lastTransitionAt,
StalenessBudget = stalenessBudget,
DriftBaselineSeconds = driftBaselineSeconds,
ContentBudgets = contentBudgets
};
}
#region Serialization
private static string SerializeTimeAnchor(TimeAnchor anchor)
{
var obj = new
{
anchorTime = anchor.AnchorTime,
source = anchor.Source,
format = anchor.Format,
signatureFingerprint = anchor.SignatureFingerprint,
tokenDigest = anchor.TokenDigest
};
return JsonSerializer.Serialize(obj);
}
private static TimeAnchor DeserializeTimeAnchor(string json)
{
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var anchorTime = root.GetProperty("anchorTime").GetDateTimeOffset();
var source = root.GetProperty("source").GetString() ?? "unknown";
var format = root.GetProperty("format").GetString() ?? "unknown";
var signatureFingerprint = root.TryGetProperty("signatureFingerprint", out var sf) && sf.ValueKind == JsonValueKind.String
? sf.GetString() ?? ""
: "";
var tokenDigest = root.TryGetProperty("tokenDigest", out var td) && td.ValueKind == JsonValueKind.String
? td.GetString() ?? ""
: "";
return new TimeAnchor(anchorTime, source, format, signatureFingerprint, tokenDigest);
}
catch
{
return TimeAnchor.Unknown;
}
}
private static string SerializeStalenessBudget(StalenessBudget budget)
{
var obj = new
{
warningSeconds = budget.WarningSeconds,
breachSeconds = budget.BreachSeconds
};
return JsonSerializer.Serialize(obj);
}
private static StalenessBudget DeserializeStalenessBudget(string json)
{
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var warningSeconds = root.GetProperty("warningSeconds").GetInt64();
var breachSeconds = root.GetProperty("breachSeconds").GetInt64();
return new StalenessBudget(warningSeconds, breachSeconds);
}
catch
{
return StalenessBudget.Default;
}
}
private static string SerializeContentBudgets(IReadOnlyDictionary<string, StalenessBudget> budgets)
{
if (budgets.Count == 0)
{
return "{}";
}
var dict = budgets.ToDictionary(
kv => kv.Key,
kv => new { warningSeconds = kv.Value.WarningSeconds, breachSeconds = kv.Value.BreachSeconds });
return JsonSerializer.Serialize(dict);
}
private static IReadOnlyDictionary<string, StalenessBudget> DeserializeContentBudgets(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return new Dictionary<string, StalenessBudget>(StringComparer.OrdinalIgnoreCase);
}
try
{
using var doc = JsonDocument.Parse(json);
var result = new Dictionary<string, StalenessBudget>(StringComparer.OrdinalIgnoreCase);
foreach (var property in doc.RootElement.EnumerateObject())
{
var warningSeconds = property.Value.GetProperty("warningSeconds").GetInt64();
var breachSeconds = property.Value.GetProperty("breachSeconds").GetInt64();
result[property.Name] = new StalenessBudget(warningSeconds, breachSeconds);
}
return result;
}
catch
{
return new Dictionary<string, StalenessBudget>(StringComparer.OrdinalIgnoreCase);
}
}
#endregion
private async ValueTask EnsureTableAsync(CancellationToken cancellationToken)
{
if (_initialized)
{
return;
}
await _initLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_initialized)
{
return;
}
await using var connection = await DataSource.OpenSystemConnectionAsync(cancellationToken).ConfigureAwait(false);
const string sql = """
CREATE SCHEMA IF NOT EXISTS airgap;
CREATE TABLE IF NOT EXISTS airgap.state (
id TEXT NOT NULL,
tenant_id TEXT NOT NULL PRIMARY KEY,
sealed BOOLEAN NOT NULL DEFAULT FALSE,
policy_hash TEXT,
time_anchor JSONB NOT NULL DEFAULT '{}',
last_transition_at TIMESTAMPTZ NOT NULL DEFAULT '0001-01-01T00:00:00Z',
staleness_budget JSONB NOT NULL DEFAULT '{"warningSeconds":3600,"breachSeconds":7200}',
drift_baseline_seconds BIGINT NOT NULL DEFAULT 0,
content_budgets JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_airgap_state_sealed ON airgap.state(sealed) WHERE sealed = TRUE;
""";
await using var command = CreateCommand(sql, connection);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
_initialized = true;
}
finally
{
_initLock.Release();
}
}
}

View File

@@ -0,0 +1,49 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StellaOps.AirGap.Controller.Stores;
using StellaOps.AirGap.Storage.Postgres.Repositories;
using StellaOps.Infrastructure.Postgres.Options;
namespace StellaOps.AirGap.Storage.Postgres;
/// <summary>
/// Extension methods for configuring AirGap PostgreSQL storage services.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds AirGap PostgreSQL storage services.
/// </summary>
/// <param name="services">Service collection.</param>
/// <param name="configuration">Configuration root.</param>
/// <param name="sectionName">Configuration section name for PostgreSQL options.</param>
/// <returns>Service collection for chaining.</returns>
public static IServiceCollection AddAirGapPostgresStorage(
this IServiceCollection services,
IConfiguration configuration,
string sectionName = "Postgres:AirGap")
{
services.Configure<PostgresOptions>(sectionName, configuration.GetSection(sectionName));
services.AddSingleton<AirGapDataSource>();
services.AddScoped<IAirGapStateStore, PostgresAirGapStateStore>();
return services;
}
/// <summary>
/// Adds AirGap PostgreSQL storage services with explicit options.
/// </summary>
/// <param name="services">Service collection.</param>
/// <param name="configureOptions">Options configuration action.</param>
/// <returns>Service collection for chaining.</returns>
public static IServiceCollection AddAirGapPostgresStorage(
this IServiceCollection services,
Action<PostgresOptions> configureOptions)
{
services.Configure(configureOptions);
services.AddSingleton<AirGapDataSource>();
services.AddScoped<IAirGapStateStore, PostgresAirGapStateStore>();
return services;
}
}

View File

@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>StellaOps.AirGap.Storage.Postgres</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../StellaOps.AirGap.Controller/StellaOps.AirGap.Controller.csproj" />
<ProjectReference Include="../../__Libraries/StellaOps.Infrastructure.Postgres/StellaOps.Infrastructure.Postgres.csproj" />
</ItemGroup>
</Project>