使用Mounted Secret以文件形式挂载证书并监听文件变化?

解读

在国内云原生场景下,Kubernetes 的 Secret 常以“文件挂载”方式注入到 Pod 中,证书(tls.crt/tls.key)默认挂载到指定目录。业务容器需要:

  1. 读取证书并绑定到 Kestrel/TCP 端口;
  2. 当 Secret 更新(证书轮转)时,不重启 Pod 就能重新加载新证书,实现“热更新”。

面试官想确认候选人是否理解:

  • Linux 文件挂载行为(符号链接、tmpfs、inode 变化);
  • .NET 6+ 的证书加载 API;
  • 高效、低耗的文件监听方案;
  • 灰度发布、回滚、异常兜底等生产细节。

知识点

  1. K8s Secret 挂载机制
    • 默认使用 tmpfs,更新时原子替换文件内容,inode 可能不变;
    • 目录下会出现 ..data -> ..timestamp -> 实际文件的符号链。
  2. .NET 证书加载
    • new X509Certificate2(string fileName, string password) 默认会锁文件;
    • 应使用 X509Certificate2.CreateFromPemFile 或先读入 byte[] 再构造,避免锁文件。
  3. 文件监听
    • FileSystemWatcher 在 Linux 下依赖 inotify,句柄数受内核参数限制;
    • 需启用 NotifyFilters.LastWrite | NotifyFilters.CreationTime,过滤 Change/Created/Renamed;
    • 收到事件后必须 debounce(≥200 ms 无新事件再处理),防止多次触发。
  4. 热加载流程
    • 监听目录:/app/certs;
    • 事件触发 → 校验文件大小 & 首尾行(-----BEGIN/END)→ 构造新证书 → 调用 IConnectionListenerFactory 或 KestrelServerOptions 的 ReplaceCertificate() → 原子切换;
    • 老证书对象需 Dispose,否则内存泄漏。
  5. 异常与回滚
    • 新证书格式错误、私钥不匹配时,捕获 CryptographicException,记录 Error 日志,保持旧证书继续工作;
    • 提供 /healthz/cert-ready 探针,返回 503 表示证书加载失败,配合 K8s readinessProbe 自动摘除流量。
  6. 权限与安全
    • 容器以非 root 运行,需 fsGroup 设置 65534,保证证书文件可读;
    • 禁止将私钥打印到日志;
    • 使用 dotnet-counters 监控 “TLS 握手失败” 计数,及时告警。

答案

以下示例基于 .NET 8,Linux x64,Kestrel 监听 443,证书通过 Secret 挂载到 /app/certs,支持热更新。

// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel((ctx, opts) =>
{
    var certPath = ctx.Configuration["Certs:Path"] ?? "/app/certs/tls.crt";
    var keyPath  = ctx.Configuration["Certs:KeyPath"] ?? "/app/certs/tls.key";

    // 初始加载
    var cert = LoadCertificate(certPath, keyPath);
    opts.ListenAnyIP(443, lo => lo.UseHttps(cert));

    // 启动后台监听
    _ = Task.Run(() => WatchCertificate(certPath, keyPath, opts));
});

var app = builder.Build();
app.MapGet("/healthz/cert-ready", () => Results.Ok());
app.Run();

static X509Certificate2 LoadCertificate(string crt, string key)
{
    if (!File.Exists(crt) || !File.Exists(key))
        throw new FileNotFoundException("证书文件缺失");

    // 先读入内存,避免锁文件
    var certPem = File.ReadAllText(crt);
    var keyPem  = File.ReadAllText(key);
    return X509Certificate2.CreateFromPem(certPem, keyPem);
}

static void WatchCertificate(string crt, string key, KestrelServerOptions opts)
{
    using var watcher = new FileSystemWatcher(Path.GetDirectoryName(crt)!)
    {
        NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime,
        Filter = "*",
        IncludeSubdirectories = false
    };

    var debounce = new System.Timers.Timer(300) { AutoReset = false };
    debounce.Elapsed += (_, _) =>
    {
        try
        {
            var newCert = LoadCertificate(crt, key);
            opts.ConfigureHttpsDefaults(h => h.ServerCertificate = newCert);
            Log.Information("证书已热更新,指纹={Thumbprint}", newCert.Thumbprint);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "证书热更新失败,继续使用旧证书");
        }
    };

    watcher.Changed += (_, _) => { debounce.Stop(); debounce.Start(); };
    watcher.EnableRaisingEvents = true;

    Thread.Sleep(Timeout.Infinite); // 保持线程存活
}

部署要点

  1. Deployment 中 volumeMounts 挂载同名 Secret,readOnly: true;
  2. 设置 securityContext.fsGroup=65534,确保非 root 用户可读;
  3. readinessProbe 调用 /healthz/cert-ready,失败时 Pod 自动从 Service 摘除;
  4. 通过 kubectl rollout restart 可验证零中断轮转。

拓展思考

  1. 证书轮转频率高(短周期 ACME)时,FileSystemWatcher 事件风暴如何优化?
    答:可改用 inotifywait 脚本一次性扫描,或轮询(Poll)+ 哈希比对,降低 CPU。
  2. 如果证书由外部 Vault/PKI 系统推送,如何确保“原子性”?
    答:采用“写临时文件 + rename 覆盖”方式,Linux rename 是原子操作,监听 Created 事件即可。
  3. 多实例副本同时加载,如何避免“证书不一致”导致 TLS 握手失败?
    答:在 K8s 层保证 Secret 更新策略为 RollingUpdate,配合 PodDisruptionBudget,逐台更新;或统一走 Ingress 网关终止 TLS,后端使用明文。
  4. 证书包含中间链,如何自动构建 X509Chain?
    答:将 fullchain.crt 挂载,读取后调用 X509Chain.Build 验证,再传入 Kestrel;失败则回滚。
  5. 如果业务同时监听双向 TLS(mTLS),客户端 CA 也放在 Secret 中,如何同步刷新?
    答:将客户端 CA 作为单独文件 ca.crt,监听后更新 KestrelServerOptions.ConfigureHttpsDefaults 的 ClientCertificateMode 与 ClientCertificateValidation 委托,实现“双证书”热更新。