forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
// Package cursor signs and verifies resource-bound keyset positions.
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
cursorSigningKeyBytes = 32
|
||||
maxEncodedCursorBytes = 1024
|
||||
)
|
||||
|
||||
// ErrInvalid means a cursor is malformed, tampered with or bound to another resource.
|
||||
var ErrInvalid = errors.New("invalid cursor")
|
||||
|
||||
// Position identifies the last record already returned by keyset pagination.
|
||||
type Position struct {
|
||||
// CreatedAt is the creation timestamp of the last returned record.
|
||||
CreatedAt time.Time
|
||||
// ID breaks ties between records sharing a timestamp.
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// Codec authenticates pagination positions with an immutable process-local key.
|
||||
type Codec struct {
|
||||
key [cursorSigningKeyBytes]byte
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
// Resource binds the position to a chat history or one user's chat list.
|
||||
Resource string `json:"r"`
|
||||
// Time is the creation timestamp of the last record in the previous page.
|
||||
Time time.Time `json:"t"`
|
||||
// ID breaks ties between records with the same creation timestamp.
|
||||
ID uuid.UUID `json:"i"`
|
||||
}
|
||||
|
||||
// New creates a cursor codec with a random process-local signing key.
|
||||
func New() (*Codec, error) {
|
||||
codec := &Codec{}
|
||||
if _, err := rand.Read(codec.key[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return codec, nil
|
||||
}
|
||||
|
||||
// Encode serializes and signs a pagination position bound to a resource.
|
||||
func (codec *Codec) Encode(resource string, position Position) (string, error) {
|
||||
payload, err := json.Marshal(cursorPayload{
|
||||
Resource: resource,
|
||||
Time: position.CreatedAt,
|
||||
ID: position.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encode cursor: %w", err)
|
||||
}
|
||||
payload = append(payload, codec.signature(payload)...)
|
||||
return base64.RawURLEncoding.EncodeToString(payload), nil
|
||||
}
|
||||
|
||||
// Decode verifies the cursor signature and extracts its resource-bound position.
|
||||
func (codec *Codec) Decode(encoded, resource string) (Position, error) {
|
||||
if encoded == "" {
|
||||
return Position{}, nil
|
||||
}
|
||||
if len(encoded) > maxEncodedCursorBytes {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
signed, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil || len(signed) <= sha256.Size {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
boundary := len(signed) - sha256.Size
|
||||
payload, signature := signed[:boundary], signed[boundary:]
|
||||
if !hmac.Equal(signature, codec.signature(payload)) {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
return decodeCursorPosition(payload, resource)
|
||||
}
|
||||
|
||||
// signature computes the HMAC-SHA256 authentication tag for a cursor payload.
|
||||
func (codec *Codec) signature(payload []byte) []byte {
|
||||
mac := hmac.New(sha256.New, codec.key[:])
|
||||
// hash.Hash.Write is documented to always return a nil error.
|
||||
_, _ = mac.Write(payload)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
// decodeCursorPosition validates the decoded cursor resource and timestamp.
|
||||
func decodeCursorPosition(payload []byte, resource string) (Position, error) {
|
||||
var cursor cursorPayload
|
||||
if err := json.Unmarshal(payload, &cursor); err != nil {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
if cursor.Resource != resource || cursor.Time.IsZero() {
|
||||
return Position{}, ErrInvalid
|
||||
}
|
||||
return Position{CreatedAt: cursor.Time, ID: cursor.ID}, nil
|
||||
}
|
||||
|
||||
// NewShared creates a codec from the common 256-bit key provisioned to every replica.
|
||||
func NewShared(encoded string) (*Codec, error) {
|
||||
key, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil || len(key) != cursorSigningKeyBytes {
|
||||
return nil, fmt.Errorf("CURSOR_SIGNING_KEY must encode exactly 32 bytes as base64")
|
||||
}
|
||||
codec := &Codec{}
|
||||
copy(codec.key[:], key)
|
||||
return codec, nil
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestCodec_EncodeDecode preserves the complete position through an authenticated round trip.
|
||||
func TestCodec_EncodeDecode(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
position := Position{CreatedAt: time.Unix(1700000000, 123456789).UTC(), ID: uuid.New()}
|
||||
|
||||
// Act.
|
||||
encoded, err := codec.Encode("chats:alice", position)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded == "" {
|
||||
t.Fatal("encoded position is empty")
|
||||
}
|
||||
decoded, err := codec.Decode(encoded, "chats:alice")
|
||||
if err != nil || decoded != position {
|
||||
t.Fatalf("decoded=%v, want=%v, error=%v", decoded, position, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCodec_Decode checks first-page behavior and independent rejection conditions.
|
||||
func TestCodec_Decode(t *testing.T) {
|
||||
t.Run("Positive: empty token starts first page", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode("", "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if err != nil || got != (Position{}) {
|
||||
t.Fatalf("first-page position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: another resource", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := encodeFixture(t, codec, "chats:alice")
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:bob")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: another process key", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := encodeFixture(t, codec, "chats:alice")
|
||||
codec = newTestCodec(t)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: tampered payload", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := encodeFixture(t, codec, "chats:alice")
|
||||
signed, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signed[0] ^= 1
|
||||
encoded = base64.RawURLEncoding.EncodeToString(signed)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: oversized token", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := strings.Repeat("a", 1025)
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed base64", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := "!invalid!"
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: signed malformed JSON", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := signedPayload(codec, []byte("not JSON"))
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: signed zero timestamp", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec := newTestCodec(t)
|
||||
encoded := signedPayload(codec, []byte(`{"r":"chats:alice","t":"0001-01-01T00:00:00Z","i":"11111111-1111-1111-1111-111111111111"}`))
|
||||
|
||||
// Act.
|
||||
got, err := codec.Decode(encoded, "chats:alice")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
|
||||
t.Fatalf("position=%v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// signedPayload creates authenticated malformed fixtures to isolate payload validation.
|
||||
func signedPayload(codec *Codec, payload []byte) string {
|
||||
return base64.RawURLEncoding.EncodeToString(append(payload, codec.signature(payload)...))
|
||||
}
|
||||
|
||||
// newTestCodec creates an independent signing key for one scenario.
|
||||
func newTestCodec(t *testing.T) *Codec {
|
||||
t.Helper()
|
||||
codec, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return codec
|
||||
}
|
||||
|
||||
// encodeFixture prepares a valid token before testing a separate decoding condition.
|
||||
func encodeFixture(t *testing.T, codec *Codec, resource string) string {
|
||||
t.Helper()
|
||||
token, err := codec.Encode(resource, Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// TestSharedCodec verifies a second process can verify the first process's cursor.
|
||||
func TestSharedCodec(t *testing.T) {
|
||||
key := base64.StdEncoding.EncodeToString(make([]byte, 32))
|
||||
first, err := NewShared(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := NewShared(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
position := Position{CreatedAt: time.Now().UTC(), ID: uuid.New()}
|
||||
encoded, err := first.Encode("chat", position)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := second.Decode(encoded, "chat")
|
||||
if err != nil || result != position {
|
||||
t.Fatalf("cross-replica cursor: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSharedCodecRejectsInvalidKey requires a full 256-bit decoded secret.
|
||||
func TestSharedCodecRejectsInvalidKey(t *testing.T) {
|
||||
for _, key := range []string{"", "broken!", base64.StdEncoding.EncodeToString([]byte("short"))} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
if _, err := NewShared(key); err == nil {
|
||||
t.Fatal("invalid key accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user