Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions internal/service/effector/signer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// Package effector is the API side of effector agents (docs/effectors/wire-interface.md),
// starting with delivery signing: Standard Webhooks v1a (Ed25519) signatures and the
// delivery keys agents verify them with.
package effector

import (
"crypto/ed25519"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"net/http"
"os"
"strconv"

"github.com/compliance-framework/api/internal/config"
"github.com/compliance-framework/api/sdk/types"
)

// Standard Webhooks headers (https://www.standardwebhooks.com/).
const (
HeaderWebhookID = "webhook-id"
HeaderWebhookTimestamp = "webhook-timestamp"
HeaderWebhookSignature = "webhook-signature"
)

// SignatureVersion is the Standard Webhooks asymmetric (Ed25519) signature version.
const SignatureVersion = "v1a"

// AlgEd25519 is the only delivery key algorithm.
const AlgEd25519 = "Ed25519"

// ErrNoSigningKey is returned by LoadSigner when no key is configured.
var ErrNoSigningKey = errors.New("no effector signing key configured")

// Key is one delivery key pair.
type Key struct {
Kid string
Public ed25519.PublicKey
private ed25519.PrivateKey
}

// NewKey wraps a private key.
func NewKey(priv ed25519.PrivateKey) *Key {
pub := priv.Public().(ed25519.PublicKey)
return &Key{Kid: Kid(pub), Public: pub, private: priv}
}

// Kid is the key ID: the first 16 hex characters of the SHA-256 of the raw public key.
func Kid(pub ed25519.PublicKey) string {
sum := sha256.Sum256(pub)
return hex.EncodeToString(sum[:])[:16]
}

// Signer signs deliveries with the current key and publishes the current and next public
// keys. One key pair for the whole API.
type Signer struct {
current *Key
next *Key
}

// NewSigner builds a signer from the current and (optional) next private keys.
func NewSigner(current, next ed25519.PrivateKey) *Signer {
s := &Signer{current: NewKey(current)}
if next != nil {
s.next = NewKey(next)
}
return s
}

// LoadSigner reads CCF_EFFECTOR_SIGNING_KEY and, if set, CCF_EFFECTOR_SIGNING_KEY_NEXT
// (PKCS#8 PEM Ed25519 private keys, as `openssl genpkey -algorithm ed25519` writes them).
func LoadSigner(cfg *config.EffectorConfig) (*Signer, error) {
if cfg == nil || cfg.SigningKeyPath == "" {
return nil, ErrNoSigningKey
}
current, err := ReadPrivateKeyFile(cfg.SigningKeyPath)
if err != nil {
return nil, fmt.Errorf("effector signing key: %w", err)
}
var next ed25519.PrivateKey
if cfg.SigningKeyNextPath != "" {
if next, err = ReadPrivateKeyFile(cfg.SigningKeyNextPath); err != nil {
return nil, fmt.Errorf("next effector signing key: %w", err)
}
}
return NewSigner(current, next), nil
}

// ReadPrivateKeyFile reads a PEM Ed25519 private key file.
func ReadPrivateKeyFile(path string) (ed25519.PrivateKey, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return ParsePrivateKeyPEM(raw)
}

// ParsePrivateKeyPEM parses a PKCS#8 PEM Ed25519 private key.
func ParsePrivateKeyPEM(raw []byte) (ed25519.PrivateKey, error) {
block, _ := pem.Decode(raw)
if block == nil {
return nil, errors.New("no PEM block found")
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parse PKCS#8 private key: %w", err)
}
priv, ok := key.(ed25519.PrivateKey)
if !ok {
return nil, fmt.Errorf("private key is %T, want Ed25519", key)
}
return priv, nil
}

// MarshalPrivateKeyPEM encodes a private key as PKCS#8 PEM (tests and tooling).
func MarshalPrivateKeyPEM(priv ed25519.PrivateKey) ([]byte, error) {
der, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), nil
}

// CurrentKid is the kid deliveries are signed with.
func (s *Signer) CurrentKid() string {
return s.current.Kid
}

// DeliveryKeys are the public keys agents verify deliveries with: the current key and, during
// a rotation, the next one. Public keys are base64 (standard encoding) of the raw 32 bytes.
func (s *Signer) DeliveryKeys() []types.DeliveryKey {
if s == nil {
return []types.DeliveryKey{}
}
out := []types.DeliveryKey{publish(s.current, types.DeliveryKeyCurrent)}
if s.next != nil {
out = append(out, publish(s.next, types.DeliveryKeyNext))
}
return out
}

func publish(k *Key, status string) types.DeliveryKey {
return types.DeliveryKey{Kid: k.Kid, Alg: AlgEd25519, PublicKey: base64.StdEncoding.EncodeToString(k.Public), Status: status}
}

// SignedContent is what a v1a signature covers: "{webhook-id}.{webhook-timestamp}.{body}".
func SignedContent(id string, timestamp int64, body []byte) []byte {
ts := strconv.FormatInt(timestamp, 10)
out := make([]byte, 0, len(id)+len(ts)+len(body)+2)
out = append(out, id...)
out = append(out, '.')
out = append(out, ts...)
out = append(out, '.')
return append(out, body...)
}

// Sign returns the webhook-signature header value: "v1a,<base64 signature>".
func (s *Signer) Sign(id string, timestamp int64, body []byte) string {
sig := ed25519.Sign(s.current.private, SignedContent(id, timestamp, body))
return SignatureVersion + "," + base64.StdEncoding.EncodeToString(sig)
}

// Headers returns the signed delivery headers for body.
func (s *Signer) Headers(id string, timestamp int64, body []byte) http.Header {
h := http.Header{}
h.Set(HeaderWebhookID, id)
h.Set(HeaderWebhookTimestamp, strconv.FormatInt(timestamp, 10))
h.Set(HeaderWebhookSignature, s.Sign(id, timestamp, body))
h.Set(types.EffectorProtocolHeader, types.EffectorProtocolVersion)
h.Set("Content-Type", "application/json")
return h
}
148 changes: 148 additions & 0 deletions internal/service/effector/signer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package effector

import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"testing"

"github.com/compliance-framework/api/internal/config"
"github.com/compliance-framework/api/sdk/types"
"github.com/stretchr/testify/require"
)

func newKey(t *testing.T) ed25519.PrivateKey {
t.Helper()
_, priv, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
return priv
}

// agentVerify is the agent's verification (agent internal/effector/verifier.go), byte for
// byte: decode the published key (base64, std or raw, std or URL alphabet), then accept the
// first v1a signature among the space-separated header entries that verifies over
// "{id}.{trimmed timestamp}.{body}".
func agentVerify(keys []types.DeliveryKey, id, timestamp string, body []byte, header string) error {
var pubs []ed25519.PublicKey
for _, k := range keys {
if k.Alg != "" && !strings.EqualFold(k.Alg, "Ed25519") {
continue
}
for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding} {
if b, err := enc.DecodeString(strings.TrimSpace(k.PublicKey)); err == nil && len(b) == ed25519.PublicKeySize {
pubs = append(pubs, ed25519.PublicKey(b))
break
}
}
}
msg := []byte(id + "." + strings.TrimSpace(timestamp) + "." + string(body))
for _, part := range strings.Fields(header) {
version, sig, ok := strings.Cut(part, ",")
if !ok || version != "v1a" {
continue
}
raw, err := base64.StdEncoding.DecodeString(sig)
if err != nil {
continue
}
for _, k := range pubs {
if ed25519.Verify(k, msg, raw) {
return nil
}
}
}
return errors.New("signature does not verify")
}

func TestSignerVerifiesWithTheAgentAlgorithm(t *testing.T) {
s := NewSigner(newKey(t), newKey(t))
body := []byte(`{"type":"effect.apply","effect":{"id":"e1","generation":3}}`)
h := s.Headers("dlv_abc_3", 1764500000, body)

require.Equal(t, "dlv_abc_3", h.Get(HeaderWebhookID))
require.Equal(t, "1764500000", h.Get(HeaderWebhookTimestamp))
require.Equal(t, "1", h.Get(types.EffectorProtocolHeader))
require.True(t, strings.HasPrefix(h.Get(HeaderWebhookSignature), "v1a,"))

keys := s.DeliveryKeys()
require.NoError(t, agentVerify(keys, h.Get(HeaderWebhookID), h.Get(HeaderWebhookTimestamp), body, h.Get(HeaderWebhookSignature)))
require.Error(t, agentVerify(keys, "dlv_abc_4", h.Get(HeaderWebhookTimestamp), body, h.Get(HeaderWebhookSignature)), "the id is signed")
require.Error(t, agentVerify(keys, h.Get(HeaderWebhookID), "1764500001", body, h.Get(HeaderWebhookSignature)), "the timestamp is signed")
require.Error(t, agentVerify(keys, h.Get(HeaderWebhookID), h.Get(HeaderWebhookTimestamp), append(body, ' '), h.Get(HeaderWebhookSignature)), "the body is signed")
// Only the next key: a delivery signed with the current one doesn't verify.
require.Error(t, agentVerify(keys[1:], h.Get(HeaderWebhookID), h.Get(HeaderWebhookTimestamp), body, h.Get(HeaderWebhookSignature)))
}

func TestSignedContentAndKeys(t *testing.T) {
priv := newKey(t)
s := NewSigner(priv, nil)
require.Equal(t, "id.42.{}", string(SignedContent("id", 42, []byte("{}"))))

pub := priv.Public().(ed25519.PublicKey)
sum := sha256.Sum256(pub)
keys := s.DeliveryKeys()
require.Len(t, keys, 1)
require.Equal(t, hex.EncodeToString(sum[:])[:16], keys[0].Kid)
require.Equal(t, s.CurrentKid(), keys[0].Kid)
require.Equal(t, "Ed25519", keys[0].Alg)
require.Equal(t, types.DeliveryKeyCurrent, keys[0].Status)
raw, err := base64.StdEncoding.DecodeString(keys[0].PublicKey)
require.NoError(t, err)
require.Equal(t, []byte(pub), raw)

sig := s.Sign("id", 42, []byte("{}"))
decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sig, "v1a,"))
require.NoError(t, err)
require.True(t, ed25519.Verify(pub, []byte("id."+strconv.Itoa(42)+".{}"), decoded))
}

func TestLoadSigner(t *testing.T) {
dir := t.TempDir()
write := func(name string, priv ed25519.PrivateKey) string {
raw, err := MarshalPrivateKeyPEM(priv)
require.NoError(t, err)
path := filepath.Join(dir, name)
require.NoError(t, os.WriteFile(path, raw, 0o600))
return path
}
current, next := newKey(t), newKey(t)
s, err := LoadSigner(&config.EffectorConfig{SigningKeyPath: write("current.pem", current), SigningKeyNextPath: write("next.pem", next)})
require.NoError(t, err)
keys := s.DeliveryKeys()
require.Len(t, keys, 2)
require.Equal(t, Kid(current.Public().(ed25519.PublicKey)), keys[0].Kid)
require.Equal(t, Kid(next.Public().(ed25519.PublicKey)), keys[1].Kid)
require.Equal(t, types.DeliveryKeyNext, keys[1].Status)

_, err = LoadSigner(&config.EffectorConfig{})
require.ErrorIs(t, err, ErrNoSigningKey)
bad := filepath.Join(dir, "bad.pem")
require.NoError(t, os.WriteFile(bad, []byte("not a key"), 0o600))
_, err = LoadSigner(&config.EffectorConfig{SigningKeyPath: bad})
require.Error(t, err)
_, err = LoadSigner(&config.EffectorConfig{SigningKeyPath: write("ok.pem", current), SigningKeyNextPath: bad})
require.ErrorContains(t, err, "next effector signing key")

// A PKCS#8 key of another type is rejected.
ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
der, err := x509.MarshalPKCS8PrivateKey(ec)
require.NoError(t, err)
_, err = ParsePrivateKeyPEM(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}))
require.ErrorContains(t, err, "want Ed25519")

var none *Signer
require.Empty(t, none.DeliveryKeys(), "effectors off: no delivery keys")
require.NotNil(t, none.DeliveryKeys())
}
Loading
Loading