feat: backend service
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
const (
|
||||
// EventDomainMarkerV1 binds the v1 server event signature to the Galaxy
|
||||
// gateway transport contract.
|
||||
EventDomainMarkerV1 = "galaxy-event-v1"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidEventSignature reports that a gateway stream event signature is
|
||||
// not a raw Ed25519 signature for the canonical event signing input.
|
||||
ErrInvalidEventSignature = errors.New("invalid event signature")
|
||||
)
|
||||
|
||||
// EventSigningFields contains the canonical v1 stream-event fields that are
|
||||
// bound into the server signing input.
|
||||
type EventSigningFields struct {
|
||||
// EventType identifies the stable client-facing event category.
|
||||
EventType string
|
||||
|
||||
// EventID is the stable event correlation identifier.
|
||||
EventID string
|
||||
|
||||
// TimestampMS carries the server event timestamp in milliseconds.
|
||||
TimestampMS int64
|
||||
|
||||
// RequestID optionally correlates the event to the opening client request.
|
||||
RequestID string
|
||||
|
||||
// TraceID optionally carries the client-supplied tracing correlation value.
|
||||
TraceID string
|
||||
|
||||
// PayloadHash is the raw SHA-256 digest of event payload bytes.
|
||||
PayloadHash []byte
|
||||
}
|
||||
|
||||
// BuildEventSigningInput returns the canonical byte sequence the v1 gateway
|
||||
// stream-event signature covers. String and byte fields are length-prefixed
|
||||
// with uvarint(len(field)) followed by raw bytes, while TimestampMS is
|
||||
// appended as an 8-byte big-endian uint64.
|
||||
func BuildEventSigningInput(fields EventSigningFields) []byte {
|
||||
size := len(EventDomainMarkerV1) +
|
||||
len(fields.EventType) +
|
||||
len(fields.EventID) +
|
||||
len(fields.RequestID) +
|
||||
len(fields.TraceID) +
|
||||
len(fields.PayloadHash) +
|
||||
(6 * binary.MaxVarintLen64) +
|
||||
8
|
||||
|
||||
buf := make([]byte, 0, size)
|
||||
buf = appendLengthPrefixedString(buf, EventDomainMarkerV1)
|
||||
buf = appendLengthPrefixedString(buf, fields.EventType)
|
||||
buf = appendLengthPrefixedString(buf, fields.EventID)
|
||||
buf = binary.BigEndian.AppendUint64(buf, uint64(fields.TimestampMS))
|
||||
buf = appendLengthPrefixedString(buf, fields.RequestID)
|
||||
buf = appendLengthPrefixedString(buf, fields.TraceID)
|
||||
buf = appendLengthPrefixedBytes(buf, fields.PayloadHash)
|
||||
|
||||
return buf
|
||||
}
|
||||
|
||||
// VerifyEventSignature verifies that signature authenticates fields under
|
||||
// publicKey using the canonical v1 event signing input.
|
||||
func VerifyEventSignature(publicKey ed25519.PublicKey, signature []byte, fields EventSigningFields) error {
|
||||
if len(publicKey) != ed25519.PublicKeySize || len(signature) != ed25519.SignatureSize {
|
||||
return ErrInvalidEventSignature
|
||||
}
|
||||
if !ed25519.Verify(publicKey, BuildEventSigningInput(fields), signature) {
|
||||
return ErrInvalidEventSignature
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildEventSigningInputChangesWhenSignedFieldChanges(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := EventSigningFields{
|
||||
EventType: "gateway.server_time",
|
||||
EventID: "request-123",
|
||||
TimestampMS: 123456789,
|
||||
RequestID: "request-123",
|
||||
TraceID: "trace-123",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
baseInput := BuildEventSigningInput(base)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(EventSigningFields) EventSigningFields
|
||||
}{
|
||||
{
|
||||
name: "event type",
|
||||
mutate: func(fields EventSigningFields) EventSigningFields {
|
||||
fields.EventType = "gateway.other"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "event id",
|
||||
mutate: func(fields EventSigningFields) EventSigningFields {
|
||||
fields.EventID = "request-456"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "timestamp",
|
||||
mutate: func(fields EventSigningFields) EventSigningFields {
|
||||
fields.TimestampMS++
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "request id",
|
||||
mutate: func(fields EventSigningFields) EventSigningFields {
|
||||
fields.RequestID = "request-456"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "trace id",
|
||||
mutate: func(fields EventSigningFields) EventSigningFields {
|
||||
fields.TraceID = "trace-456"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "payload hash",
|
||||
mutate: func(fields EventSigningFields) EventSigningFields {
|
||||
fields.PayloadHash = mustSHA256([]byte("other"))
|
||||
return fields
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mutated := BuildEventSigningInput(tt.mutate(base))
|
||||
assert.False(t, bytes.Equal(baseInput, mutated))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignAndVerifyEventSignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
signer, err := NewEd25519ResponseSigner(privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
fields := EventSigningFields{
|
||||
EventType: "gateway.server_time",
|
||||
EventID: "request-123",
|
||||
TimestampMS: 123456789,
|
||||
RequestID: "request-123",
|
||||
TraceID: "trace-123",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
signature, err := signer.SignEvent(fields)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, VerifyEventSignature(signer.PublicKey(), signature, fields))
|
||||
|
||||
fields.TraceID = "changed"
|
||||
require.ErrorIs(t, VerifyEventSignature(signer.PublicKey(), signature, fields), ErrInvalidEventSignature)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// Package authn defines the authenticated transport helpers used by
|
||||
// the gateway edge verification pipeline. The package is public so
|
||||
// that external clients (notably the integration test suite under
|
||||
// `galaxy/integration/testenv`) can reuse the canonical signing
|
||||
// input builders and the response/event verifiers without having to
|
||||
// duplicate the wire contract documented in
|
||||
// `../../ARCHITECTURE.md` §15.
|
||||
package authn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
const (
|
||||
// RequestDomainMarkerV1 binds the v1 client request signature to the Galaxy
|
||||
// gateway transport contract.
|
||||
RequestDomainMarkerV1 = "galaxy-request-v1"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidPayloadHash reports that payloadHash is not a raw SHA-256 digest.
|
||||
ErrInvalidPayloadHash = errors.New("payload_hash must be a 32-byte SHA-256 digest")
|
||||
|
||||
// ErrPayloadHashMismatch reports that payloadHash does not match payloadBytes.
|
||||
ErrPayloadHashMismatch = errors.New("payload_hash does not match payload_bytes")
|
||||
)
|
||||
|
||||
// RequestSigningFields contains the canonical v1 request fields that are bound
|
||||
// into the client signing input after the gateway validates and normalizes the
|
||||
// request envelope.
|
||||
type RequestSigningFields struct {
|
||||
// ProtocolVersion identifies the transport envelope version.
|
||||
ProtocolVersion string
|
||||
|
||||
// DeviceSessionID identifies the authenticated device session bound to the
|
||||
// request.
|
||||
DeviceSessionID string
|
||||
|
||||
// MessageType is the stable downstream routing key.
|
||||
MessageType string
|
||||
|
||||
// TimestampMS carries the client request timestamp in milliseconds.
|
||||
TimestampMS int64
|
||||
|
||||
// RequestID is the transport correlation and anti-replay identifier.
|
||||
RequestID string
|
||||
|
||||
// PayloadHash is the raw SHA-256 digest of payload bytes.
|
||||
PayloadHash []byte
|
||||
}
|
||||
|
||||
// BuildRequestSigningInput returns the canonical byte sequence the v1 client
|
||||
// request signature covers. String and byte fields are length-prefixed with
|
||||
// uvarint(len(field)) followed by raw bytes, while TimestampMS is appended as
|
||||
// an 8-byte big-endian uint64. The caller is expected to pass fields that have
|
||||
// already passed earlier envelope validation.
|
||||
func BuildRequestSigningInput(fields RequestSigningFields) []byte {
|
||||
size := len(RequestDomainMarkerV1) +
|
||||
len(fields.ProtocolVersion) +
|
||||
len(fields.DeviceSessionID) +
|
||||
len(fields.MessageType) +
|
||||
len(fields.RequestID) +
|
||||
len(fields.PayloadHash) +
|
||||
(6 * binary.MaxVarintLen64) +
|
||||
8
|
||||
|
||||
buf := make([]byte, 0, size)
|
||||
buf = appendLengthPrefixedString(buf, RequestDomainMarkerV1)
|
||||
buf = appendLengthPrefixedString(buf, fields.ProtocolVersion)
|
||||
buf = appendLengthPrefixedString(buf, fields.DeviceSessionID)
|
||||
buf = appendLengthPrefixedString(buf, fields.MessageType)
|
||||
buf = binary.BigEndian.AppendUint64(buf, uint64(fields.TimestampMS))
|
||||
buf = appendLengthPrefixedString(buf, fields.RequestID)
|
||||
buf = appendLengthPrefixedBytes(buf, fields.PayloadHash)
|
||||
|
||||
return buf
|
||||
}
|
||||
|
||||
// VerifyPayloadHash checks that payloadHash is the raw SHA-256 digest of
|
||||
// payloadBytes. Empty payloadBytes are valid and must use sha256.Sum256(nil).
|
||||
func VerifyPayloadHash(payloadBytes, payloadHash []byte) error {
|
||||
if len(payloadHash) != sha256.Size {
|
||||
return ErrInvalidPayloadHash
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(payloadBytes)
|
||||
if !bytes.Equal(sum[:], payloadHash) {
|
||||
return ErrPayloadHashMismatch
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func appendLengthPrefixedString(dst []byte, value string) []byte {
|
||||
return appendLengthPrefixedBytes(dst, []byte(value))
|
||||
}
|
||||
|
||||
func appendLengthPrefixedBytes(dst []byte, value []byte) []byte {
|
||||
dst = binary.AppendUvarint(dst, uint64(len(value)))
|
||||
dst = append(dst, value...)
|
||||
|
||||
return dst
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestVerifyPayloadHash(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
payloadSum := sha256.Sum256([]byte("payload"))
|
||||
emptySum := sha256.Sum256(nil)
|
||||
otherSum := sha256.Sum256([]byte("other"))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
payload []byte
|
||||
payloadHash []byte
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "matches non-empty payload",
|
||||
payload: []byte("payload"),
|
||||
payloadHash: payloadSum[:],
|
||||
},
|
||||
{
|
||||
name: "matches empty payload",
|
||||
payload: nil,
|
||||
payloadHash: emptySum[:],
|
||||
},
|
||||
{
|
||||
name: "rejects digest with invalid length",
|
||||
payload: []byte("payload"),
|
||||
payloadHash: []byte("short"),
|
||||
wantErr: ErrInvalidPayloadHash,
|
||||
},
|
||||
{
|
||||
name: "rejects digest mismatch",
|
||||
payload: []byte("payload"),
|
||||
payloadHash: otherSum[:],
|
||||
wantErr: ErrPayloadHashMismatch,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := VerifyPayloadHash(tt.payload, tt.payloadHash)
|
||||
if tt.wantErr == nil {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestSigningInput(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fields := RequestSigningFields{
|
||||
ProtocolVersion: "v1",
|
||||
DeviceSessionID: "device-session-123",
|
||||
MessageType: "fleet.move",
|
||||
TimestampMS: 123456789,
|
||||
RequestID: "request-123",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
got := BuildRequestSigningInput(fields)
|
||||
|
||||
want, err := hex.DecodeString("1167616c6178792d726571756573742d7631027631126465766963652d73657373696f6e2d3132330a666c6565742e6d6f766500000000075bcd150b726571756573742d31323320239f59ed55e737c77147cf55ad0c1b030b6d7ee748a7426952f9b852d5a935e5")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
}
|
||||
|
||||
func TestBuildRequestSigningInputChangesWhenSignedFieldChanges(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := RequestSigningFields{
|
||||
ProtocolVersion: "v1",
|
||||
DeviceSessionID: "device-session-123",
|
||||
MessageType: "fleet.move",
|
||||
TimestampMS: 123456789,
|
||||
RequestID: "request-123",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
baseInput := BuildRequestSigningInput(base)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(RequestSigningFields) RequestSigningFields
|
||||
}{
|
||||
{
|
||||
name: "protocol version",
|
||||
mutate: func(fields RequestSigningFields) RequestSigningFields {
|
||||
fields.ProtocolVersion = "v2"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "device session id",
|
||||
mutate: func(fields RequestSigningFields) RequestSigningFields {
|
||||
fields.DeviceSessionID = "device-session-456"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "message type",
|
||||
mutate: func(fields RequestSigningFields) RequestSigningFields {
|
||||
fields.MessageType = "fleet.attack"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "timestamp",
|
||||
mutate: func(fields RequestSigningFields) RequestSigningFields {
|
||||
fields.TimestampMS++
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "request id",
|
||||
mutate: func(fields RequestSigningFields) RequestSigningFields {
|
||||
fields.RequestID = "request-456"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "payload hash",
|
||||
mutate: func(fields RequestSigningFields) RequestSigningFields {
|
||||
fields.PayloadHash = mustSHA256([]byte("other"))
|
||||
return fields
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mutated := BuildRequestSigningInput(tt.mutate(base))
|
||||
assert.False(t, bytes.Equal(baseInput, mutated))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustSHA256(payload []byte) []byte {
|
||||
sum := sha256.Sum256(payload)
|
||||
return sum[:]
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
// ResponseDomainMarkerV1 binds the v1 server response signature to the
|
||||
// Galaxy gateway transport contract.
|
||||
ResponseDomainMarkerV1 = "galaxy-response-v1"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidResponsePrivateKeyPEM reports that the configured response
|
||||
// signer private key is not a strict PKCS#8 PEM-encoded private key.
|
||||
ErrInvalidResponsePrivateKeyPEM = errors.New("response signer private key is not a valid PKCS#8 PEM block")
|
||||
|
||||
// ErrInvalidResponsePrivateKey reports that the configured response signer
|
||||
// private key is not an Ed25519 private key.
|
||||
ErrInvalidResponsePrivateKey = errors.New("response signer private key must be an Ed25519 PKCS#8 private key")
|
||||
|
||||
// ErrInvalidResponseSignature reports that a server response signature is
|
||||
// not a raw Ed25519 signature for the canonical response signing input.
|
||||
ErrInvalidResponseSignature = errors.New("invalid response signature")
|
||||
)
|
||||
|
||||
// ResponseSigningFields contains the canonical v1 response fields that are
|
||||
// bound into the server signing input.
|
||||
type ResponseSigningFields struct {
|
||||
// ProtocolVersion identifies the transport envelope version.
|
||||
ProtocolVersion string
|
||||
|
||||
// RequestID is the transport correlation identifier copied from the
|
||||
// authenticated request.
|
||||
RequestID string
|
||||
|
||||
// TimestampMS carries the server response timestamp in milliseconds.
|
||||
TimestampMS int64
|
||||
|
||||
// ResultCode is the opaque downstream result code returned to the client.
|
||||
ResultCode string
|
||||
|
||||
// PayloadHash is the raw SHA-256 digest of response payload bytes.
|
||||
PayloadHash []byte
|
||||
}
|
||||
|
||||
// ResponseSigner signs authenticated unary responses and client-facing stream
|
||||
// events with one server-side key.
|
||||
type ResponseSigner interface {
|
||||
// SignResponse returns the raw Ed25519 signature for the canonical response
|
||||
// signing input built from fields.
|
||||
SignResponse(fields ResponseSigningFields) ([]byte, error)
|
||||
|
||||
// SignEvent returns the raw Ed25519 signature for the canonical event
|
||||
// signing input built from fields.
|
||||
SignEvent(fields EventSigningFields) ([]byte, error)
|
||||
}
|
||||
|
||||
// Ed25519ResponseSigner signs authenticated responses with one Ed25519 private
|
||||
// key loaded during process startup.
|
||||
type Ed25519ResponseSigner struct {
|
||||
privateKey ed25519.PrivateKey
|
||||
}
|
||||
|
||||
// NewEd25519ResponseSigner validates privateKey and constructs a signer using
|
||||
// a defensive key copy.
|
||||
func NewEd25519ResponseSigner(privateKey ed25519.PrivateKey) (*Ed25519ResponseSigner, error) {
|
||||
if len(privateKey) != ed25519.PrivateKeySize {
|
||||
return nil, ErrInvalidResponsePrivateKey
|
||||
}
|
||||
|
||||
return &Ed25519ResponseSigner{
|
||||
privateKey: bytes.Clone(privateKey),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LoadEd25519ResponseSignerFromPEMFile loads a strict PKCS#8 PEM-encoded
|
||||
// Ed25519 private key from path and constructs a signer.
|
||||
func LoadEd25519ResponseSignerFromPEMFile(path string) (*Ed25519ResponseSigner, error) {
|
||||
pemBytes, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response signer private key PEM: %w", err)
|
||||
}
|
||||
|
||||
signer, err := ParseEd25519ResponseSignerPEM(pemBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
// ParseEd25519ResponseSignerPEM parses one strict PKCS#8 PEM-encoded Ed25519
|
||||
// private key and constructs a signer from it.
|
||||
func ParseEd25519ResponseSignerPEM(pemBytes []byte) (*Ed25519ResponseSigner, error) {
|
||||
block, rest := pem.Decode(pemBytes)
|
||||
if block == nil || block.Type != "PRIVATE KEY" || len(bytes.TrimSpace(rest)) > 0 {
|
||||
return nil, ErrInvalidResponsePrivateKeyPEM
|
||||
}
|
||||
|
||||
parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidResponsePrivateKeyPEM
|
||||
}
|
||||
|
||||
privateKey, ok := parsedKey.(ed25519.PrivateKey)
|
||||
if !ok {
|
||||
return nil, ErrInvalidResponsePrivateKey
|
||||
}
|
||||
|
||||
return NewEd25519ResponseSigner(privateKey)
|
||||
}
|
||||
|
||||
// PublicKey returns the Ed25519 public key that corresponds to the configured
|
||||
// response signer private key.
|
||||
func (s *Ed25519ResponseSigner) PublicKey() ed25519.PublicKey {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
publicKey, _ := s.privateKey.Public().(ed25519.PublicKey)
|
||||
return bytes.Clone(publicKey)
|
||||
}
|
||||
|
||||
// SignResponse signs the canonical v1 response signing input built from
|
||||
// fields.
|
||||
func (s *Ed25519ResponseSigner) SignResponse(fields ResponseSigningFields) ([]byte, error) {
|
||||
if s == nil || len(s.privateKey) != ed25519.PrivateKeySize {
|
||||
return nil, ErrInvalidResponsePrivateKey
|
||||
}
|
||||
|
||||
signature := ed25519.Sign(s.privateKey, BuildResponseSigningInput(fields))
|
||||
return bytes.Clone(signature), nil
|
||||
}
|
||||
|
||||
// SignEvent signs the canonical v1 stream-event signing input built from
|
||||
// fields.
|
||||
func (s *Ed25519ResponseSigner) SignEvent(fields EventSigningFields) ([]byte, error) {
|
||||
if s == nil || len(s.privateKey) != ed25519.PrivateKeySize {
|
||||
return nil, ErrInvalidResponsePrivateKey
|
||||
}
|
||||
|
||||
signature := ed25519.Sign(s.privateKey, BuildEventSigningInput(fields))
|
||||
return bytes.Clone(signature), nil
|
||||
}
|
||||
|
||||
// BuildResponseSigningInput returns the canonical byte sequence the v1 server
|
||||
// response signature covers. String and byte fields are length-prefixed with
|
||||
// uvarint(len(field)) followed by raw bytes, while TimestampMS is appended as
|
||||
// an 8-byte big-endian uint64.
|
||||
func BuildResponseSigningInput(fields ResponseSigningFields) []byte {
|
||||
size := len(ResponseDomainMarkerV1) +
|
||||
len(fields.ProtocolVersion) +
|
||||
len(fields.RequestID) +
|
||||
len(fields.ResultCode) +
|
||||
len(fields.PayloadHash) +
|
||||
(5 * binary.MaxVarintLen64) +
|
||||
8
|
||||
|
||||
buf := make([]byte, 0, size)
|
||||
buf = appendLengthPrefixedString(buf, ResponseDomainMarkerV1)
|
||||
buf = appendLengthPrefixedString(buf, fields.ProtocolVersion)
|
||||
buf = appendLengthPrefixedString(buf, fields.RequestID)
|
||||
buf = binary.BigEndian.AppendUint64(buf, uint64(fields.TimestampMS))
|
||||
buf = appendLengthPrefixedString(buf, fields.ResultCode)
|
||||
buf = appendLengthPrefixedBytes(buf, fields.PayloadHash)
|
||||
|
||||
return buf
|
||||
}
|
||||
|
||||
// VerifyResponseSignature verifies that signature authenticates fields under
|
||||
// publicKey using the canonical v1 response signing input.
|
||||
func VerifyResponseSignature(publicKey ed25519.PublicKey, signature []byte, fields ResponseSigningFields) error {
|
||||
if len(publicKey) != ed25519.PublicKeySize || len(signature) != ed25519.SignatureSize {
|
||||
return ErrInvalidResponseSignature
|
||||
}
|
||||
if !ed25519.Verify(publicKey, BuildResponseSigningInput(fields), signature) {
|
||||
return ErrInvalidResponseSignature
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildResponseSigningInputChangesWhenSignedFieldChanges(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := ResponseSigningFields{
|
||||
ProtocolVersion: "v1",
|
||||
RequestID: "request-123",
|
||||
TimestampMS: 123456789,
|
||||
ResultCode: "ok",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
baseInput := BuildResponseSigningInput(base)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(ResponseSigningFields) ResponseSigningFields
|
||||
}{
|
||||
{
|
||||
name: "protocol version",
|
||||
mutate: func(fields ResponseSigningFields) ResponseSigningFields {
|
||||
fields.ProtocolVersion = "v2"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "request id",
|
||||
mutate: func(fields ResponseSigningFields) ResponseSigningFields {
|
||||
fields.RequestID = "request-456"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "timestamp",
|
||||
mutate: func(fields ResponseSigningFields) ResponseSigningFields {
|
||||
fields.TimestampMS++
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "result code",
|
||||
mutate: func(fields ResponseSigningFields) ResponseSigningFields {
|
||||
fields.ResultCode = "denied"
|
||||
return fields
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "payload hash",
|
||||
mutate: func(fields ResponseSigningFields) ResponseSigningFields {
|
||||
fields.PayloadHash = mustSHA256([]byte("other"))
|
||||
return fields
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
mutated := BuildResponseSigningInput(tt.mutate(base))
|
||||
assert.False(t, bytes.Equal(baseInput, mutated))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEd25519ResponseSignerPEMRejectsMalformedPEM(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := ParseEd25519ResponseSignerPEM([]byte("not-pem"))
|
||||
require.ErrorIs(t, err, ErrInvalidResponsePrivateKeyPEM)
|
||||
}
|
||||
|
||||
func TestParseEd25519ResponseSignerPEMRejectsNonPKCS8PEM(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
pemBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
block := pem.Block{
|
||||
Type: "ED25519 PRIVATE KEY",
|
||||
Bytes: pemBytes,
|
||||
}
|
||||
|
||||
_, err = ParseEd25519ResponseSignerPEM(pem.EncodeToMemory(&block))
|
||||
require.ErrorIs(t, err, ErrInvalidResponsePrivateKeyPEM)
|
||||
}
|
||||
|
||||
func TestParseEd25519ResponseSignerPEMRejectsNonEd25519Key(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
|
||||
require.NoError(t, err)
|
||||
|
||||
pemBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = ParseEd25519ResponseSignerPEM(pem.EncodeToMemory(&pem.Block{
|
||||
Type: "PRIVATE KEY",
|
||||
Bytes: pemBytes,
|
||||
}))
|
||||
require.ErrorIs(t, err, ErrInvalidResponsePrivateKey)
|
||||
}
|
||||
|
||||
func TestSignAndVerifyResponseSignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
signer, err := NewEd25519ResponseSigner(privateKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
fields := ResponseSigningFields{
|
||||
ProtocolVersion: "v1",
|
||||
RequestID: "request-123",
|
||||
TimestampMS: 123456789,
|
||||
ResultCode: "ok",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
signature, err := signer.SignResponse(fields)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, VerifyResponseSignature(signer.PublicKey(), signature, fields))
|
||||
|
||||
fields.ResultCode = "changed"
|
||||
require.ErrorIs(t, VerifyResponseSignature(signer.PublicKey(), signature, fields), ErrInvalidResponseSignature)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidClientPublicKey reports that cached client public key material
|
||||
// is not a base64-encoded raw Ed25519 public key.
|
||||
ErrInvalidClientPublicKey = errors.New("client_public_key is not a valid base64-encoded Ed25519 public key")
|
||||
|
||||
// ErrInvalidRequestSignature reports that a request signature is not a raw
|
||||
// Ed25519 signature for the canonical request signing input.
|
||||
ErrInvalidRequestSignature = errors.New("invalid request signature")
|
||||
)
|
||||
|
||||
// VerifyRequestSignature validates the base64-encoded raw Ed25519 public key
|
||||
// from session cache, builds the canonical v1 signing input from fields, and
|
||||
// verifies that signature authenticates the request.
|
||||
func VerifyRequestSignature(clientPublicKey string, signature []byte, fields RequestSigningFields) error {
|
||||
publicKey, err := decodeClientPublicKey(clientPublicKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(signature) != ed25519.SignatureSize {
|
||||
return ErrInvalidRequestSignature
|
||||
}
|
||||
if !ed25519.Verify(publicKey, BuildRequestSigningInput(fields), signature) {
|
||||
return ErrInvalidRequestSignature
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeClientPublicKey(value string) (ed25519.PublicKey, error) {
|
||||
decoded, err := base64.StdEncoding.Strict().DecodeString(value)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidClientPublicKey
|
||||
}
|
||||
if len(decoded) != ed25519.PublicKeySize {
|
||||
return nil, ErrInvalidClientPublicKey
|
||||
}
|
||||
|
||||
return ed25519.PublicKey(decoded), nil
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package authn
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestVerifyRequestSignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
clientPrivateKey := newTestPrivateKey("primary")
|
||||
clientPublicKey := clientPrivateKey.Public().(ed25519.PublicKey)
|
||||
otherPrivateKey := newTestPrivateKey("other")
|
||||
|
||||
fields := RequestSigningFields{
|
||||
ProtocolVersion: "v1",
|
||||
DeviceSessionID: "device-session-123",
|
||||
MessageType: "fleet.move",
|
||||
TimestampMS: 123456789,
|
||||
RequestID: "request-123",
|
||||
PayloadHash: mustSHA256([]byte("payload")),
|
||||
}
|
||||
|
||||
signature := ed25519.Sign(clientPrivateKey, BuildRequestSigningInput(fields))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
clientPublicKey string
|
||||
signature []byte
|
||||
fields RequestSigningFields
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "valid signature",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey),
|
||||
signature: signature,
|
||||
fields: fields,
|
||||
},
|
||||
{
|
||||
name: "message type change rejects signature",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey),
|
||||
signature: signature,
|
||||
fields: func() RequestSigningFields {
|
||||
mutated := fields
|
||||
mutated.MessageType = "fleet.attack"
|
||||
return mutated
|
||||
}(),
|
||||
wantErr: ErrInvalidRequestSignature,
|
||||
},
|
||||
{
|
||||
name: "request id change rejects signature",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey),
|
||||
signature: signature,
|
||||
fields: func() RequestSigningFields {
|
||||
mutated := fields
|
||||
mutated.RequestID = "request-456"
|
||||
return mutated
|
||||
}(),
|
||||
wantErr: ErrInvalidRequestSignature,
|
||||
},
|
||||
{
|
||||
name: "payload hash change rejects signature",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey),
|
||||
signature: signature,
|
||||
fields: func() RequestSigningFields {
|
||||
mutated := fields
|
||||
mutated.PayloadHash = mustSHA256([]byte("other"))
|
||||
return mutated
|
||||
}(),
|
||||
wantErr: ErrInvalidRequestSignature,
|
||||
},
|
||||
{
|
||||
name: "wrong key rejects signature",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(otherPrivateKey.Public().(ed25519.PublicKey)),
|
||||
signature: signature,
|
||||
fields: fields,
|
||||
wantErr: ErrInvalidRequestSignature,
|
||||
},
|
||||
{
|
||||
name: "bit flipped signature rejects",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey),
|
||||
signature: func() []byte {
|
||||
corrupted := append([]byte(nil), signature...)
|
||||
corrupted[0] ^= 0xff
|
||||
return corrupted
|
||||
}(),
|
||||
fields: fields,
|
||||
wantErr: ErrInvalidRequestSignature,
|
||||
},
|
||||
{
|
||||
name: "invalid signature length rejects",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey),
|
||||
signature: signature[:len(signature)-1],
|
||||
fields: fields,
|
||||
wantErr: ErrInvalidRequestSignature,
|
||||
},
|
||||
{
|
||||
name: "invalid base64 public key rejects",
|
||||
clientPublicKey: "%%%not-base64%%%",
|
||||
signature: signature,
|
||||
fields: fields,
|
||||
wantErr: ErrInvalidClientPublicKey,
|
||||
},
|
||||
{
|
||||
name: "invalid public key length rejects",
|
||||
clientPublicKey: base64.StdEncoding.EncodeToString([]byte("short")),
|
||||
signature: signature,
|
||||
fields: fields,
|
||||
wantErr: ErrInvalidClientPublicKey,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := VerifyRequestSignature(tt.clientPublicKey, tt.signature, tt.fields)
|
||||
if tt.wantErr == nil {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newTestPrivateKey(label string) ed25519.PrivateKey {
|
||||
seed := sha256.Sum256([]byte("gateway-authn-signature-test-" + label))
|
||||
return ed25519.NewKeyFromSeed(seed[:])
|
||||
}
|
||||
Reference in New Issue
Block a user