feat(queue): optional signing hook applied to the final message

This commit is contained in:
tgiachi 2026-11-09 19:58:47 +01:00
commit aa55cd3c17
2 changed files with 62 additions and 0 deletions

View file

@ -52,6 +52,9 @@ type Worker struct {
Batch int // deliveries taken per run
Timeout time.Duration // per send
Interval time.Duration // idle polling, to pick up retries that have become due
// Sign, when set, signs the final message (DKIM). On error the message is sent unsigned:
// not delivering is worse than a missed signature.
Sign func(msg []byte) ([]byte, error)
wakeOnce sync.Once
wake chan struct{}
@ -165,6 +168,13 @@ func (w *Worker) deliver(ctx context.Context, it store.OutboxItem) Stats {
}
msg := make([]byte, 0, len(it.Prefix)+len(data))
msg = append(append(msg, it.Prefix...), data...)
if w.Sign != nil {
if signed, err := w.Sign(msg); err != nil {
log.Printf("queue: sign message for %s: %v (sending unsigned)", it.Rcpt, err)
} else {
msg = signed
}
}
timeout := w.Timeout
if timeout <= 0 {

View file

@ -447,3 +447,55 @@ func TestIdleRunPollsForDueRetries(t *testing.T) {
e.clk.set(t0.Add(2 * time.Minute)) // the backoff has passed; no Wake needed
waitFor(t, "retry by polling", func() bool { return e.snd.count() == 1 })
}
func TestSignHookSeesTheFinalMessageIncludingThePerRecipientHeaders(t *testing.T) {
e := setup(t)
e.enqueue(t, 1)
var seen []byte
e.w.Sign = func(msg []byte) ([]byte, error) {
seen = append([]byte(nil), msg...)
return append([]byte("X-Signed: yes\r\n"), msg...), nil
}
if st, _ := e.w.RunOnce(context.Background()); st.Sent != 1 {
t.Fatalf("%+v", st)
}
if string(seen) != "X-Rcpt: a\r\nSubject: hi\r\n\r\nbody\r\n" {
t.Fatalf("the signer must see prefix + message, so List-Unsubscribe is covered: %q", seen)
}
if string(e.snd.sent[0].Data) != "X-Signed: yes\r\nX-Rcpt: a\r\nSubject: hi\r\n\r\nbody\r\n" {
t.Fatalf("the relay must get the signed message: %q", e.snd.sent[0].Data)
}
}
func TestSigningFailureSendsTheMessageUnsigned(t *testing.T) {
e := setup(t)
e.enqueue(t, 1)
e.w.Sign = func(msg []byte) ([]byte, error) { return nil, errors.New("hsm unavailable") }
st, _ := e.w.RunOnce(context.Background())
if st.Sent != 1 || e.pending(t) != 0 {
t.Fatalf("a signing error must not stop delivery: %+v", st)
}
if string(e.snd.sent[0].Data) != "X-Rcpt: a\r\nSubject: hi\r\n\r\nbody\r\n" {
t.Fatalf("unsigned message expected: %q", e.snd.sent[0].Data)
}
}
func TestEachAttemptIsSignedAgain(t *testing.T) {
e := setup(t)
e.enqueue(t, 1)
calls := 0
e.w.Sign = func(msg []byte) ([]byte, error) { calls++; return msg, nil }
failures := int32(1)
e.snd.fn = func(context.Context, string, []string) error {
if atomic.AddInt32(&failures, -1) >= 0 {
return errors.New("down")
}
return nil
}
e.w.RunOnce(context.Background())
e.clk.set(t0.Add(2 * time.Minute))
e.w.RunOnce(context.Background())
if calls != 2 {
t.Fatalf("a retry is signed afresh (new timestamp), signing calls = %d", calls)
}
}