Add vault seal/unseal lifecycle
- New internal/vault package: thread-safe Vault struct with seal/unseal state, key material zeroing, and key derivation - REST: POST /v1/vault/unseal, POST /v1/vault/seal, GET /v1/vault/status; health returns sealed status - UI: /unseal page with passphrase form, redirect when sealed - gRPC: sealedInterceptor rejects RPCs when sealed - Middleware: RequireUnsealed blocks all routes except exempt paths; RequireAuth reads pubkey from vault at request time - Startup: server starts sealed when passphrase unavailable - All servers share single *vault.Vault by pointer - CSRF manager derives key lazily from vault Security: Key material is zeroed on seal. Sealed middleware runs before auth. Handlers fail closed if vault becomes sealed mid-request. Unseal endpoint is rate-limited (3/s burst 5). No CSRF on unseal page (no session to protect; chicken-and-egg with master key). Passphrase never logged. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -17,8 +17,12 @@ type adminServiceServer struct {
|
||||
s *Server
|
||||
}
|
||||
|
||||
// Health returns {"status":"ok"} to signal the server is operational.
|
||||
// Health returns {"status":"ok"} to signal the server is operational, or
|
||||
// {"status":"sealed"} when the vault is sealed.
|
||||
func (a *adminServiceServer) Health(_ context.Context, _ *mciasv1.HealthRequest) (*mciasv1.HealthResponse, error) {
|
||||
if a.s.vault.IsSealed() {
|
||||
return &mciasv1.HealthResponse{Status: "sealed"}, nil
|
||||
}
|
||||
return &mciasv1.HealthResponse{Status: "ok"}, nil
|
||||
}
|
||||
|
||||
@@ -26,11 +30,12 @@ func (a *adminServiceServer) Health(_ context.Context, _ *mciasv1.HealthRequest)
|
||||
// The "x" field is the raw 32-byte public key base64url-encoded without padding,
|
||||
// matching the REST /v1/keys/public response format.
|
||||
func (a *adminServiceServer) GetPublicKey(_ context.Context, _ *mciasv1.GetPublicKeyRequest) (*mciasv1.GetPublicKeyResponse, error) {
|
||||
if len(a.s.pubKey) == 0 {
|
||||
return nil, status.Error(codes.Internal, "public key not available")
|
||||
pubKey, err := a.s.vault.PubKey()
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
// Encode as base64url without padding — identical to the REST handler.
|
||||
x := base64.RawURLEncoding.EncodeToString(a.s.pubKey)
|
||||
x := base64.RawURLEncoding.EncodeToString(pubKey)
|
||||
return &mciasv1.GetPublicKeyResponse{
|
||||
Kty: "OKP",
|
||||
Crv: "Ed25519",
|
||||
|
||||
@@ -86,7 +86,11 @@ func (a *authServiceServer) Login(ctx context.Context, req *mciasv1.LoginRequest
|
||||
a.s.db.WriteAuditEvent(model.EventLoginFail, &acct.ID, nil, ip, `{"reason":"totp_missing"}`) //nolint:errcheck
|
||||
return nil, status.Error(codes.Unauthenticated, "TOTP code required")
|
||||
}
|
||||
secret, err := crypto.OpenAESGCM(a.s.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
|
||||
masterKey, mkErr := a.s.vault.MasterKey()
|
||||
if mkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
|
||||
if err != nil {
|
||||
a.s.logger.Error("decrypt TOTP secret", "error", err, "account_id", acct.ID)
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
@@ -121,7 +125,11 @@ func (a *authServiceServer) Login(ctx context.Context, req *mciasv1.LoginRequest
|
||||
}
|
||||
}
|
||||
|
||||
tokenStr, claims, err := token.IssueToken(a.s.privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
|
||||
privKey, pkErr := a.s.vault.PrivKey()
|
||||
if pkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
tokenStr, claims, err := token.IssueToken(privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
|
||||
if err != nil {
|
||||
a.s.logger.Error("issue token", "error", err)
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
@@ -186,7 +194,11 @@ func (a *authServiceServer) RenewToken(ctx context.Context, _ *mciasv1.RenewToke
|
||||
}
|
||||
}
|
||||
|
||||
newTokenStr, newClaims, err := token.IssueToken(a.s.privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
|
||||
privKey, pkErr := a.s.vault.PrivKey()
|
||||
if pkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
newTokenStr, newClaims, err := token.IssueToken(privKey, a.s.cfg.Tokens.Issuer, acct.UUID, roles, expiry)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
@@ -245,7 +257,11 @@ func (a *authServiceServer) EnrollTOTP(ctx context.Context, req *mciasv1.EnrollT
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
|
||||
secretEnc, secretNonce, err := crypto.SealAESGCM(a.s.masterKey, rawSecret)
|
||||
masterKey, mkErr := a.s.vault.MasterKey()
|
||||
if mkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
secretEnc, secretNonce, err := crypto.SealAESGCM(masterKey, rawSecret)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
@@ -283,7 +299,11 @@ func (a *authServiceServer) ConfirmTOTP(ctx context.Context, req *mciasv1.Confir
|
||||
return nil, status.Error(codes.FailedPrecondition, "TOTP enrollment not started")
|
||||
}
|
||||
|
||||
secret, err := crypto.OpenAESGCM(a.s.masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
|
||||
masterKey, mkErr := a.s.vault.MasterKey()
|
||||
if mkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
secret, err := crypto.OpenAESGCM(masterKey, acct.TOTPSecretNonce, acct.TOTPSecretEnc)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
|
||||
@@ -47,7 +47,11 @@ func (c *credentialServiceServer) GetPGCreds(ctx context.Context, req *mciasv1.G
|
||||
}
|
||||
|
||||
// Decrypt the password for admin retrieval.
|
||||
password, err := crypto.OpenAESGCM(c.s.masterKey, cred.PGPasswordNonce, cred.PGPasswordEnc)
|
||||
masterKey, mkErr := c.s.vault.MasterKey()
|
||||
if mkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
password, err := crypto.OpenAESGCM(masterKey, cred.PGPasswordNonce, cred.PGPasswordEnc)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
@@ -94,7 +98,11 @@ func (c *credentialServiceServer) SetPGCreds(ctx context.Context, req *mciasv1.S
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
|
||||
enc, nonce, err := crypto.SealAESGCM(c.s.masterKey, []byte(cr.Password))
|
||||
masterKey, mkErr := c.s.vault.MasterKey()
|
||||
if mkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
enc, nonce, err := crypto.SealAESGCM(masterKey, []byte(cr.Password))
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ package grpcserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
@@ -35,6 +34,7 @@ import (
|
||||
"git.wntrmute.dev/kyle/mcias/internal/config"
|
||||
"git.wntrmute.dev/kyle/mcias/internal/db"
|
||||
"git.wntrmute.dev/kyle/mcias/internal/token"
|
||||
"git.wntrmute.dev/kyle/mcias/internal/vault"
|
||||
)
|
||||
|
||||
// contextKey is the unexported context key type for this package.
|
||||
@@ -57,21 +57,17 @@ type Server struct {
|
||||
cfg *config.Config
|
||||
logger *slog.Logger
|
||||
rateLimiter *grpcRateLimiter
|
||||
privKey ed25519.PrivateKey
|
||||
pubKey ed25519.PublicKey
|
||||
masterKey []byte
|
||||
vault *vault.Vault
|
||||
}
|
||||
|
||||
// New creates a Server with the given dependencies (same as the REST Server).
|
||||
// A fresh per-IP rate limiter (10 req/s, burst 10) is allocated per Server
|
||||
// instance so that tests do not share state across test cases.
|
||||
func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) *Server {
|
||||
func New(database *db.DB, cfg *config.Config, v *vault.Vault, logger *slog.Logger) *Server {
|
||||
return &Server{
|
||||
db: database,
|
||||
cfg: cfg,
|
||||
privKey: priv,
|
||||
pubKey: pub,
|
||||
masterKey: masterKey,
|
||||
vault: v,
|
||||
logger: logger,
|
||||
rateLimiter: newGRPCRateLimiter(10, 10),
|
||||
}
|
||||
@@ -106,6 +102,7 @@ func (s *Server) buildServer(extra ...grpc.ServerOption) *grpc.Server {
|
||||
[]grpc.ServerOption{
|
||||
grpc.ChainUnaryInterceptor(
|
||||
s.loggingInterceptor,
|
||||
s.sealedInterceptor,
|
||||
s.authInterceptor,
|
||||
s.rateLimitInterceptor,
|
||||
),
|
||||
@@ -162,14 +159,36 @@ func (s *Server) loggingInterceptor(
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// sealedInterceptor rejects all RPCs (except Health) when the vault is sealed.
|
||||
//
|
||||
// Security: This is the first interceptor in the chain (after logging). It
|
||||
// prevents any authenticated or data-serving handler from running while the
|
||||
// vault is sealed and key material is unavailable.
|
||||
func (s *Server) sealedInterceptor(
|
||||
ctx context.Context,
|
||||
req interface{},
|
||||
info *grpc.UnaryServerInfo,
|
||||
handler grpc.UnaryHandler,
|
||||
) (interface{}, error) {
|
||||
if !s.vault.IsSealed() {
|
||||
return handler(ctx, req)
|
||||
}
|
||||
// Health is always allowed — returns sealed status.
|
||||
if info.FullMethod == "/mcias.v1.AdminService/Health" {
|
||||
return handler(ctx, req)
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
|
||||
// authInterceptor validates the Bearer JWT from gRPC metadata and injects
|
||||
// claims into the context. Public methods bypass this check.
|
||||
//
|
||||
// Security: Same validation path as the REST RequireAuth middleware:
|
||||
// 1. Extract "authorization" metadata value (case-insensitive key lookup).
|
||||
// 2. Validate JWT (alg-first, then signature, then expiry/issuer).
|
||||
// 3. Check JTI against revocation table.
|
||||
// 4. Inject claims into context.
|
||||
// 2. Read public key from vault (fail closed if sealed).
|
||||
// 3. Validate JWT (alg-first, then signature, then expiry/issuer).
|
||||
// 4. Check JTI against revocation table.
|
||||
// 5. Inject claims into context.
|
||||
func (s *Server) authInterceptor(
|
||||
ctx context.Context,
|
||||
req interface{},
|
||||
@@ -186,7 +205,13 @@ func (s *Server) authInterceptor(
|
||||
return nil, status.Error(codes.Unauthenticated, "missing or invalid authorization")
|
||||
}
|
||||
|
||||
claims, err := token.ValidateToken(s.pubKey, tokenStr, s.cfg.Tokens.Issuer)
|
||||
// Security: read the public key from vault at request time.
|
||||
pubKey, err := s.vault.PubKey()
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
|
||||
claims, err := token.ValidateToken(pubKey, tokenStr, s.cfg.Tokens.Issuer)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid or expired token")
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"git.wntrmute.dev/kyle/mcias/internal/db"
|
||||
"git.wntrmute.dev/kyle/mcias/internal/model"
|
||||
"git.wntrmute.dev/kyle/mcias/internal/token"
|
||||
"git.wntrmute.dev/kyle/mcias/internal/vault"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -73,7 +74,8 @@ func newTestEnv(t *testing.T) *testEnv {
|
||||
cfg := config.NewTestConfig(testIssuer)
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
|
||||
srv := New(database, cfg, priv, pub, masterKey, logger)
|
||||
v := vault.NewUnsealed(masterKey, priv, pub)
|
||||
srv := New(database, cfg, v, logger)
|
||||
grpcSrv := srv.GRPCServer()
|
||||
|
||||
lis := bufconn.Listen(bufConnSize)
|
||||
|
||||
@@ -32,7 +32,11 @@ func (t *tokenServiceServer) ValidateToken(_ context.Context, req *mciasv1.Valid
|
||||
return &mciasv1.ValidateTokenResponse{Valid: false}, nil
|
||||
}
|
||||
|
||||
claims, err := token.ValidateToken(t.s.pubKey, tokenStr, t.s.cfg.Tokens.Issuer)
|
||||
pubKey, pkErr := t.s.vault.PubKey()
|
||||
if pkErr != nil {
|
||||
return &mciasv1.ValidateTokenResponse{Valid: false}, nil
|
||||
}
|
||||
claims, err := token.ValidateToken(pubKey, tokenStr, t.s.cfg.Tokens.Issuer)
|
||||
if err != nil {
|
||||
return &mciasv1.ValidateTokenResponse{Valid: false}, nil
|
||||
}
|
||||
@@ -67,7 +71,11 @@ func (ts *tokenServiceServer) IssueServiceToken(ctx context.Context, req *mciasv
|
||||
return nil, status.Error(codes.InvalidArgument, "token issue is only for system accounts")
|
||||
}
|
||||
|
||||
tokenStr, claims, err := token.IssueToken(ts.s.privKey, ts.s.cfg.Tokens.Issuer, acct.UUID, nil, ts.s.cfg.ServiceExpiry())
|
||||
privKey, pkErr := ts.s.vault.PrivKey()
|
||||
if pkErr != nil {
|
||||
return nil, status.Error(codes.Unavailable, "vault sealed")
|
||||
}
|
||||
tokenStr, claims, err := token.IssueToken(privKey, ts.s.cfg.Tokens.Issuer, acct.UUID, nil, ts.s.cfg.ServiceExpiry())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "internal error")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user