Agent configuration (agent-<role>.yaml, strict decoding, role section passed undecoded to the role factory) and the state directory of ADR 0011: identity with interrupted-renewal recovery, verified revisions under revisions/<n>/, state.json with apply results, lease sequence and queued deployment reports, atomic writes, pruning and a lock file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
321 lines
10 KiB
Go
321 lines
10 KiB
Go
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package core
|
|
|
|
import (
|
|
"crypto"
|
|
"crypto/ecdsa"
|
|
"crypto/ed25519"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"crypto/x509/pkix"
|
|
"encoding/json"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"git.beugsiud.de/beug.k/DDI/internal/agentpki"
|
|
)
|
|
|
|
// Files in identity/.
|
|
const (
|
|
keyFile = "key.pem"
|
|
certFile = "cert.pem"
|
|
caFile = "ca.pem"
|
|
bundleKeyFile = "bundle-signing.pub"
|
|
agentFile = "agent.json"
|
|
newSuffix = ".new"
|
|
)
|
|
|
|
// ErrNotEnrolled is returned by LoadIdentity if the agent has no identity.
|
|
var ErrNotEnrolled = errors.New("agent is not enrolled (run the enroll command first)")
|
|
|
|
// errAlreadyEnrolled is returned by SaveIdentity without force.
|
|
var errAlreadyEnrolled = errors.New("agent is already enrolled (use --force to enroll again)")
|
|
|
|
// Identity is the enrolled identity of the agent.
|
|
type Identity struct {
|
|
AgentID string
|
|
Role Kind
|
|
Server string // host:port of the agent API
|
|
ServerName string // TLS server name
|
|
EnrolledAt time.Time
|
|
CA *x509.Certificate
|
|
// Certificate holds the client certificate (Leaf set) and its key.
|
|
Certificate tls.Certificate
|
|
BundleKey ed25519.PublicKey
|
|
}
|
|
|
|
// agentInfo is identity/agent.json.
|
|
type agentInfo struct {
|
|
AgentID string `json:"agent_id"`
|
|
Role Kind `json:"role"`
|
|
Server string `json:"server"`
|
|
ServerName string `json:"server_name"`
|
|
EnrolledAt time.Time `json:"enrolled_at"`
|
|
CAFingerprint string `json:"ca_fingerprint"`
|
|
}
|
|
|
|
func (s *Store) identityPath(name string) string {
|
|
return filepath.Join(s.dir, identityDir, name)
|
|
}
|
|
|
|
// Enrolled reports whether an identity exists.
|
|
func (s *Store) Enrolled() bool {
|
|
_, err := os.Stat(s.identityPath(agentFile))
|
|
return err == nil
|
|
}
|
|
|
|
// LoadIdentity reads identity/. It completes an interrupted certificate
|
|
// renewal (see SaveCertificate).
|
|
func (s *Store) LoadIdentity() (*Identity, error) {
|
|
data, err := os.ReadFile(s.identityPath(agentFile))
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, ErrNotEnrolled
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read identity: %w", err)
|
|
}
|
|
var info agentInfo
|
|
if err := json.Unmarshal(data, &info); err != nil {
|
|
return nil, fmt.Errorf("decode %s: %w", agentFile, err)
|
|
}
|
|
if !agentpki.ValidAgentID(info.AgentID) {
|
|
return nil, fmt.Errorf("%s holds an invalid agent ID", agentFile)
|
|
}
|
|
id := &Identity{
|
|
AgentID: info.AgentID, Role: info.Role, Server: info.Server,
|
|
ServerName: info.ServerName, EnrolledAt: info.EnrolledAt,
|
|
}
|
|
if id.CA, err = readCertPEM(s.identityPath(caFile)); err != nil {
|
|
return nil, err
|
|
}
|
|
if id.BundleKey, err = readBundleKey(s.identityPath(bundleKeyFile)); err != nil {
|
|
return nil, err
|
|
}
|
|
if id.Certificate, err = s.loadKeyPair(); err != nil {
|
|
return nil, err
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
// loadKeyPair loads key.pem and cert.pem. If they do not match and a
|
|
// cert.pem.new matching the key exists, a renewal was interrupted after the
|
|
// key was replaced; the new certificate is moved into place.
|
|
func (s *Store) loadKeyPair() (tls.Certificate, error) {
|
|
keyPEM, err := os.ReadFile(s.identityPath(keyFile))
|
|
if err != nil {
|
|
return tls.Certificate{}, fmt.Errorf("read identity: %w", err)
|
|
}
|
|
certPEM, err := os.ReadFile(s.identityPath(certFile))
|
|
if err != nil {
|
|
return tls.Certificate{}, fmt.Errorf("read identity: %w", err)
|
|
}
|
|
pair, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
if err == nil {
|
|
s.removeStaleNew()
|
|
return pair, nil
|
|
}
|
|
newCert, nerr := os.ReadFile(s.identityPath(certFile + newSuffix))
|
|
if nerr != nil {
|
|
return tls.Certificate{}, fmt.Errorf("load client certificate: %w", err)
|
|
}
|
|
pair, nerr = tls.X509KeyPair(newCert, keyPEM)
|
|
if nerr != nil {
|
|
return tls.Certificate{}, fmt.Errorf("load client certificate: %w", err)
|
|
}
|
|
if err := os.Rename(s.identityPath(certFile+newSuffix), s.identityPath(certFile)); err != nil {
|
|
return tls.Certificate{}, fmt.Errorf("complete certificate renewal: %w", err)
|
|
}
|
|
syncDir(filepath.Join(s.dir, identityDir))
|
|
return pair, nil
|
|
}
|
|
|
|
func (s *Store) removeStaleNew() {
|
|
_ = os.Remove(s.identityPath(keyFile + newSuffix))
|
|
_ = os.Remove(s.identityPath(certFile + newSuffix))
|
|
}
|
|
|
|
// SaveIdentity writes a new identity directory. Without force it refuses to
|
|
// replace an existing identity.
|
|
func (s *Store) SaveIdentity(id *Identity, key crypto.Signer, force bool) error {
|
|
if s.Enrolled() && !force {
|
|
return errAlreadyEnrolled
|
|
}
|
|
keyPEM, err := encodeKey(key)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pubDER, err := x509.MarshalPKIXPublicKey(id.BundleKey)
|
|
if err != nil {
|
|
return fmt.Errorf("encode bundle signing key: %w", err)
|
|
}
|
|
info, err := json.MarshalIndent(agentInfo{
|
|
AgentID: id.AgentID, Role: id.Role, Server: id.Server, ServerName: id.ServerName,
|
|
EnrolledAt: id.EnrolledAt.UTC(), CAFingerprint: agentpki.Fingerprint(id.CA),
|
|
}, "", " ")
|
|
if err != nil {
|
|
return fmt.Errorf("encode identity: %w", err)
|
|
}
|
|
tmp, err := os.MkdirTemp(s.dir, tmpPrefix+identityDir+"-")
|
|
if err != nil {
|
|
return fmt.Errorf("create identity directory: %w", err)
|
|
}
|
|
defer func() { _ = os.RemoveAll(tmp) }()
|
|
if err := os.Chmod(tmp, 0o700); err != nil { //nolint:gosec // directories need the search bit
|
|
return fmt.Errorf("create identity directory: %w", err)
|
|
}
|
|
files := []struct {
|
|
name string
|
|
data []byte
|
|
perm fs.FileMode
|
|
}{
|
|
{keyFile, keyPEM, 0o600},
|
|
{certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: id.Certificate.Leaf.Raw}), 0o644},
|
|
{caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: id.CA.Raw}), 0o644},
|
|
{bundleKeyFile, pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}), 0o644},
|
|
{agentFile, append(info, '\n'), 0o644},
|
|
}
|
|
for _, f := range files {
|
|
if err := writeFileSync(filepath.Join(tmp, f.name), f.data, f.perm); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
syncDir(tmp)
|
|
if err := replaceDir(tmp, filepath.Join(s.dir, identityDir)); err != nil {
|
|
return err
|
|
}
|
|
syncDir(s.dir)
|
|
return nil
|
|
}
|
|
|
|
// SaveCertificate stores a renewed key and certificate. Both are written as
|
|
// *.new first; key.pem is replaced before cert.pem, and LoadIdentity
|
|
// completes the second rename if the process died in between.
|
|
func (s *Store) SaveCertificate(key crypto.Signer, cert *x509.Certificate) error {
|
|
keyPEM, err := encodeKey(key)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
|
|
keyNew, certNew := s.identityPath(keyFile+newSuffix), s.identityPath(certFile+newSuffix)
|
|
if err := writeFileAtomic(keyNew, keyPEM, 0o600); err != nil {
|
|
return err
|
|
}
|
|
if err := writeFileAtomic(certNew, certPEM, 0o644); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Rename(keyNew, s.identityPath(keyFile)); err != nil {
|
|
return fmt.Errorf("replace key: %w", err)
|
|
}
|
|
if err := os.Rename(certNew, s.identityPath(certFile)); err != nil {
|
|
return fmt.Errorf("replace certificate: %w", err)
|
|
}
|
|
syncDir(filepath.Join(s.dir, identityDir))
|
|
return nil
|
|
}
|
|
|
|
func readCertPEM(path string) (*x509.Certificate, error) {
|
|
data, err := os.ReadFile(path) //nolint:gosec // path built from the state directory
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read identity: %w", err)
|
|
}
|
|
block, _ := pem.Decode(data)
|
|
if block == nil || block.Type != "CERTIFICATE" {
|
|
return nil, fmt.Errorf("%s holds no certificate", filepath.Base(path))
|
|
}
|
|
cert, err := x509.ParseCertificate(block.Bytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse %s: %w", filepath.Base(path), err)
|
|
}
|
|
return cert, nil
|
|
}
|
|
|
|
func readBundleKey(path string) (ed25519.PublicKey, error) {
|
|
data, err := os.ReadFile(path) //nolint:gosec // path built from the state directory
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read identity: %w", err)
|
|
}
|
|
block, _ := pem.Decode(data)
|
|
if block == nil || block.Type != "PUBLIC KEY" {
|
|
return nil, fmt.Errorf("%s holds no public key", filepath.Base(path))
|
|
}
|
|
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse %s: %w", filepath.Base(path), err)
|
|
}
|
|
key, ok := pub.(ed25519.PublicKey)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%s is not an Ed25519 key", filepath.Base(path))
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
func encodeKey(key crypto.Signer) ([]byte, error) {
|
|
der, err := x509.MarshalPKCS8PrivateKey(key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encode private key: %w", err)
|
|
}
|
|
return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), nil
|
|
}
|
|
|
|
// newKeyAndCSR generates an ECDSA P-256 key and a CSR for it. The server
|
|
// sets subject and SANs itself; commonName is informational.
|
|
func newKeyAndCSR(commonName string) (*ecdsa.PrivateKey, []byte, error) {
|
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("generate key: %w", err)
|
|
}
|
|
csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
|
|
Subject: pkix.Name{CommonName: commonName},
|
|
}, key)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("create certificate request: %w", err)
|
|
}
|
|
return key, csr, nil
|
|
}
|
|
|
|
// checkIssued verifies a certificate issued by the server: it must chain to
|
|
// ca for client authentication, carry agentID and certify key.
|
|
func checkIssued(der []byte, ca *x509.Certificate, agentID string, key *ecdsa.PrivateKey) (*x509.Certificate, error) {
|
|
cert, err := x509.ParseCertificate(der)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse issued certificate: %w", err)
|
|
}
|
|
roots := x509.NewCertPool()
|
|
roots.AddCert(ca)
|
|
// Tolerate a server clock that is slightly ahead of ours.
|
|
at := time.Now()
|
|
if at.Before(cert.NotBefore) {
|
|
at = cert.NotBefore
|
|
}
|
|
if _, err := cert.Verify(x509.VerifyOptions{
|
|
Roots: roots, CurrentTime: at, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
|
|
}); err != nil {
|
|
return nil, fmt.Errorf("verify issued certificate: %w", err)
|
|
}
|
|
id, err := agentpki.AgentID(cert)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if id != agentID {
|
|
return nil, fmt.Errorf("issued certificate is for agent %s, not %s", id, agentID)
|
|
}
|
|
pub, ok := cert.PublicKey.(*ecdsa.PublicKey)
|
|
if !ok || !pub.Equal(&key.PublicKey) {
|
|
return nil, errors.New("issued certificate does not certify the generated key")
|
|
}
|
|
return cert, nil
|
|
}
|
|
|
|
// keyPair combines a key and its certificate.
|
|
func keyPair(key *ecdsa.PrivateKey, cert *x509.Certificate) tls.Certificate {
|
|
return tls.Certificate{Certificate: [][]byte{cert.Raw}, PrivateKey: key, Leaf: cert}
|
|
}
|