diff --git a/.gitea/workflows/ui-release.yaml b/.gitea/workflows/ui-release.yaml index efca94b..f772f86 100644 --- a/.gitea/workflows/ui-release.yaml +++ b/.gitea/workflows/ui-release.yaml @@ -45,6 +45,7 @@ jobs: go test -count=1 \ ./gateway/... \ ./game/... \ + ./ui/core/... \ ./pkg/calc/... \ ./pkg/connector/... \ ./pkg/cronutil/... \ diff --git a/.gitea/workflows/ui-test.yaml b/.gitea/workflows/ui-test.yaml index 30bbe3d..b57a455 100644 --- a/.gitea/workflows/ui-test.yaml +++ b/.gitea/workflows/ui-test.yaml @@ -63,6 +63,7 @@ jobs: go test -count=1 \ ./gateway/... \ ./game/... \ + ./ui/core/... \ ./pkg/calc/... \ ./pkg/connector/... \ ./pkg/cronutil/... \ diff --git a/gateway/authn/parity_with_ui_core_test.go b/gateway/authn/parity_with_ui_core_test.go new file mode 100644 index 0000000..f54cef6 --- /dev/null +++ b/gateway/authn/parity_with_ui_core_test.go @@ -0,0 +1,227 @@ +package authn_test + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "testing" + + "galaxy/core/canon" + "galaxy/core/keypair" + "galaxy/gateway/authn" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func sha256Of(payload []byte) []byte { + sum := sha256.Sum256(payload) + return sum[:] +} + +// TestParityWithUICoreCanonicalBytes proves that the gateway-side +// authn package and the client-side ui/core canon package produce the +// exact same canonical signing input for every v1 envelope. Any drift +// here means a client signature would be silently rejected by the +// gateway (or vice versa). +func TestParityWithUICoreCanonicalBytes(t *testing.T) { + t.Parallel() + + t.Run("request", func(t *testing.T) { + t.Parallel() + + gatewayFields := authn.RequestSigningFields{ + ProtocolVersion: "v1", + DeviceSessionID: "device-session-parity", + MessageType: "user.games.command", + TimestampMS: 1_700_000_000_000, + RequestID: "request-parity", + PayloadHash: sha256Of([]byte("payload")), + } + clientFields := canon.RequestSigningFields{ + ProtocolVersion: gatewayFields.ProtocolVersion, + DeviceSessionID: gatewayFields.DeviceSessionID, + MessageType: gatewayFields.MessageType, + TimestampMS: gatewayFields.TimestampMS, + RequestID: gatewayFields.RequestID, + PayloadHash: gatewayFields.PayloadHash, + } + + assert.Equal(t, + authn.BuildRequestSigningInput(gatewayFields), + canon.BuildRequestSigningInput(clientFields)) + }) + + t.Run("response", func(t *testing.T) { + t.Parallel() + + gatewayFields := authn.ResponseSigningFields{ + ProtocolVersion: "v1", + RequestID: "request-parity", + TimestampMS: 1_700_000_000_500, + ResultCode: "ok", + PayloadHash: sha256Of([]byte("response-payload")), + } + clientFields := canon.ResponseSigningFields{ + ProtocolVersion: gatewayFields.ProtocolVersion, + RequestID: gatewayFields.RequestID, + TimestampMS: gatewayFields.TimestampMS, + ResultCode: gatewayFields.ResultCode, + PayloadHash: gatewayFields.PayloadHash, + } + + assert.Equal(t, + authn.BuildResponseSigningInput(gatewayFields), + canon.BuildResponseSigningInput(clientFields)) + }) + + t.Run("event", func(t *testing.T) { + t.Parallel() + + gatewayFields := authn.EventSigningFields{ + EventType: "gateway.server_time", + EventID: "evt-parity", + TimestampMS: 1_700_000_001_000, + RequestID: "request-parity", + TraceID: "trace-parity", + PayloadHash: sha256Of([]byte("event-payload")), + } + clientFields := canon.EventSigningFields{ + EventType: gatewayFields.EventType, + EventID: gatewayFields.EventID, + TimestampMS: gatewayFields.TimestampMS, + RequestID: gatewayFields.RequestID, + TraceID: gatewayFields.TraceID, + PayloadHash: gatewayFields.PayloadHash, + } + + assert.Equal(t, + authn.BuildEventSigningInput(gatewayFields), + canon.BuildEventSigningInput(clientFields)) + }) +} + +// TestParityRequestSignedByUICoreAcceptedByGateway proves that a +// request the client signs with `keypair.Sign` is accepted by the +// gateway's `authn.VerifyRequestSignature`. This is the acceptance +// criterion from `ui/PLAN.md` Phase 3. +func TestParityRequestSignedByUICoreAcceptedByGateway(t *testing.T) { + t.Parallel() + + privateKey, publicKey, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + + clientFields := canon.RequestSigningFields{ + ProtocolVersion: "v1", + DeviceSessionID: "device-session-parity", + MessageType: "user.account.get", + TimestampMS: 1_700_000_000_000, + RequestID: "request-parity", + PayloadHash: sha256Of([]byte("payload")), + } + signature, err := keypair.Sign(privateKey, canon.BuildRequestSigningInput(clientFields)) + require.NoError(t, err) + + encodedKey, err := keypair.MarshalPublicKey(publicKey) + require.NoError(t, err) + + gatewayFields := authn.RequestSigningFields{ + ProtocolVersion: clientFields.ProtocolVersion, + DeviceSessionID: clientFields.DeviceSessionID, + MessageType: clientFields.MessageType, + TimestampMS: clientFields.TimestampMS, + RequestID: clientFields.RequestID, + PayloadHash: clientFields.PayloadHash, + } + + require.NoError(t, + authn.VerifyRequestSignature(encodedKey, signature, gatewayFields)) +} + +// TestParityResponseSignedByGatewayAcceptedByUICore proves that a +// response signed by the gateway's `Ed25519ResponseSigner` is +// accepted by the client's `canon.VerifyResponseSignature`. The +// reverse acceptance criterion from `ui/PLAN.md` Phase 3. +func TestParityResponseSignedByGatewayAcceptedByUICore(t *testing.T) { + t.Parallel() + + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + signer, err := authn.NewEd25519ResponseSigner(privateKey) + require.NoError(t, err) + + gatewayFields := authn.ResponseSigningFields{ + ProtocolVersion: "v1", + RequestID: "request-parity", + TimestampMS: 1_700_000_000_500, + ResultCode: "ok", + PayloadHash: sha256Of([]byte("response-payload")), + } + signature, err := signer.SignResponse(gatewayFields) + require.NoError(t, err) + + clientFields := canon.ResponseSigningFields{ + ProtocolVersion: gatewayFields.ProtocolVersion, + RequestID: gatewayFields.RequestID, + TimestampMS: gatewayFields.TimestampMS, + ResultCode: gatewayFields.ResultCode, + PayloadHash: gatewayFields.PayloadHash, + } + + require.NoError(t, + canon.VerifyResponseSignature(signer.PublicKey(), signature, clientFields)) +} + +// TestParityEventSignedByGatewayAcceptedByUICore proves that a +// stream event signed by the gateway's response signer (which signs +// both responses and events with the same key) is accepted by the +// client's `canon.VerifyEventSignature`. +func TestParityEventSignedByGatewayAcceptedByUICore(t *testing.T) { + t.Parallel() + + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + signer, err := authn.NewEd25519ResponseSigner(privateKey) + require.NoError(t, err) + + gatewayFields := authn.EventSigningFields{ + EventType: "gateway.server_time", + EventID: "evt-parity", + TimestampMS: 1_700_000_001_000, + RequestID: "request-parity", + TraceID: "trace-parity", + PayloadHash: sha256Of([]byte("event-payload")), + } + signature, err := signer.SignEvent(gatewayFields) + require.NoError(t, err) + + clientFields := canon.EventSigningFields{ + EventType: gatewayFields.EventType, + EventID: gatewayFields.EventID, + TimestampMS: gatewayFields.TimestampMS, + RequestID: gatewayFields.RequestID, + TraceID: gatewayFields.TraceID, + PayloadHash: gatewayFields.PayloadHash, + } + + require.NoError(t, + canon.VerifyEventSignature(signer.PublicKey(), signature, clientFields)) +} + +// TestParityClientPublicKeyEncodingMatchesBackend proves that the +// base64 encoding `keypair.MarshalPublicKey` produces is the exact +// string form `authn.VerifyRequestSignature` expects when the +// gateway reads a client public key out of session cache. +func TestParityClientPublicKeyEncodingMatchesBackend(t *testing.T) { + t.Parallel() + + _, publicKey, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + + encoded, err := keypair.MarshalPublicKey(publicKey) + require.NoError(t, err) + + expected := base64.StdEncoding.EncodeToString(publicKey) + require.Equal(t, expected, encoded) +} diff --git a/gateway/go.mod b/gateway/go.mod index 330b290..98131cc 100644 --- a/gateway/go.mod +++ b/gateway/go.mod @@ -5,6 +5,7 @@ go 1.26.1 require ( buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.11-20260209202127-80ab13bee0bf.1 buf.build/go/protovalidate v1.1.3 + galaxy/core v0.0.0-00010101000000-000000000000 galaxy/redisconn v0.0.0-00010101000000-000000000000 github.com/alicebob/miniredis/v2 v2.37.0 github.com/getkin/kin-openapi v0.135.0 @@ -102,3 +103,5 @@ require ( ) replace galaxy/redisconn => ../pkg/redisconn + +replace galaxy/core => ../ui/core diff --git a/go.work b/go.work index fd386f6..1bf0e01 100644 --- a/go.work +++ b/go.work @@ -18,11 +18,13 @@ use ( ./pkg/storage ./pkg/transcoder ./pkg/util + ./ui/core ) replace ( galaxy/calc v0.0.0 => ./pkg/calc galaxy/connector v0.0.0 => ./pkg/connector + galaxy/core v0.0.0 => ./ui/core galaxy/cronutil v0.0.0 => ./pkg/cronutil galaxy/error v0.0.0 => ./pkg/error galaxy/geoip v0.0.0 => ./pkg/geoip diff --git a/ui/PLAN.md b/ui/PLAN.md index f17df48..ff10e88 100644 --- a/ui/PLAN.md +++ b/ui/PLAN.md @@ -353,9 +353,9 @@ Targeted tests: in both `chromium-desktop` and `webkit-desktop` projects; - intentional failure produces a Playwright trace artefact in CI. -## Phase 3. Go Core: Canonical Bytes and Keypair +## ~~Phase 3. Go Core: Canonical Bytes and Keypair~~ -Status: pending. +Status: done. Goal: implement the canonical-bytes serializer and Ed25519 keypair management in pure Go, with bit-for-bit parity to the gateway-side @@ -363,41 +363,65 @@ implementation. No network, no UI. Artifacts: -- `ui/core/go.mod` module declared in the project Go workspace +- `ui/core/go.mod` module `galaxy/core` declared in the project Go + workspace (`go.work` `use` and `replace` directives) - `.gitea/workflows/ui-test.yaml` and `.gitea/workflows/ui-release.yaml` extended to add `./ui/core/...` to the Tier 1 / Tier 2 `go test` command list introduced in Phase 2 - `ui/core/canon/` canonical bytes for `galaxy-request-v1`, `galaxy-response-v1`, and `galaxy-event-v1`, matching - `docs/ARCHITECTURE.md` §15 byte-for-byte + `docs/ARCHITECTURE.md` §15 byte-for-byte. Server-only signers + (`Ed25519ResponseSigner`, PKCS#8 PEM loaders) intentionally stay + in `gateway/authn` — `ui/core` is verify-only on the server side - `ui/core/keypair/` Ed25519 generate, marshal, unmarshal helpers - returning opaque blobs to upper layers -- `ui/core/types/` envelope structs and result codes -- `ui/core/canon/testdata/` test vectors copied from gateway-side - canonicalisation fixtures + over opaque `[]byte` blobs; `Generate` accepts an injected + `io.Reader` so the WASM build can wire in `crypto.getRandomValues` +- `ui/core/types/` full v1 transport-envelope structs with + `SigningFields()` projection helpers; result-code and + protocol-version constants (`ProtocolVersionV1`, `ResultCodeOK`). + `TraceID` is part of the request envelope but deliberately + excluded from the request signing input (matches §15) +- `ui/core/canon/testdata/` golden JSON test vectors for the three + Phase-3 message types plus one response and one event - `ui/core/README.md` documenting the public API and the - network-free / storage-free invariant + network-free / storage-free / no-x509 / no-PEM / no-`os` invariant +- `gateway/authn/parity_with_ui_core_test.go` (cross-module test) + proving canonical-bytes parity and bidirectional sign/verify + acceptance between `gateway/authn` and `galaxy/core`. The test + adds `require galaxy/core` to `gateway/go.mod` (test-only in + practice — gateway production binary does not link `ui/core`) Dependencies: Phase 1. Acceptance criteria: -- canonical-bytes output matches gateway-side fixtures byte-for-byte - for at least three message types (`user.account.read`, - `user.lobby.list`, `user.games.command`); +- canonical-bytes output matches gateway-side output byte-for-byte + for the three Phase-3 message types (`user.account.get`, + `lobby.my.games.list`, `user.games.command`); - a request signed by `ui/core` is accepted by the gateway's own - verifier in a unit test; -- a response signed by gateway test fixtures is accepted by `ui/core`'s - verifier; -- freshness window violations and tampered hashes are rejected with - stable error codes. + verifier in a unit test (`TestParityRequestSignedByUICoreAcceptedByGateway`); +- a response signed by `gateway/authn`'s `Ed25519ResponseSigner` is + accepted by `ui/core`'s verifier + (`TestParityResponseSignedByGatewayAcceptedByUICore`); the same + applies to gateway-signed events; +- tampered `payload_hash`, mismatched `request_id`, mismatched + `timestamp_ms`, and invalid signature length are rejected with + stable error codes from `ui/core/canon`. Server-side freshness + enforcement (the symmetric ±5 minutes around server time) stays + in `gateway/internal/grpcapi/freshness_replay.go` and is not + duplicated in `ui/core`. Targeted tests: -- canonical-bytes equality tests on shared fixtures; +- canonical-bytes equality tests on golden JSON fixtures + (`testdata/`) for every envelope kind; - round-trip sign-then-verify across all three envelope kinds; -- negative tests: tampered `payload_hash`, wrong `request_id`, expired - timestamp, invalid signature length. +- negative tests: tampered `payload_hash`, mismatched `request_id`, + mismatched `timestamp_ms`, invalid signature lengths (too short, + too long, empty), bit-flipped signature, wrong public key, + malformed base64 public key; +- `gateway/authn` cross-module parity tests as listed under + Artifacts. ## Phase 4. ConnectRPC Support in Gateway diff --git a/ui/core/README.md b/ui/core/README.md new file mode 100644 index 0000000..67affe2 --- /dev/null +++ b/ui/core/README.md @@ -0,0 +1,146 @@ +# ui/core — Galaxy Client Compute Module + +`ui/core` (Go module `galaxy/core`) is the compute boundary of the +Galaxy cross-platform UI client. It carries v1 transport-envelope +canonical bytes, signature verification, and Ed25519 keypair +helpers. Network I/O and persistent storage live elsewhere on +purpose: this module compiles unchanged to WASM (Phase 5), +gomobile (Phase 32), and Wails-embedded native (Phase 31). + +The authoritative byte contract is defined in +[`docs/ARCHITECTURE.md` §15](../../docs/ARCHITECTURE.md). The gateway +mirrors this exact wire format in its own +[`gateway/authn`](../../gateway/authn) package; cross-module byte +parity and round-trip sign/verify are exercised by +[`gateway/authn/parity_with_ui_core_test.go`](../../gateway/authn/parity_with_ui_core_test.go). + +## Invariants + +- **No network.** No `net/http`, no `net/url`, no gRPC client. +- **No storage.** No `os` (outside `_test.go` fixtures), no SQL, no + filesystem, no keychain. +- **TinyGo-friendly.** Production files do not import + `crypto/x509`, `encoding/pem`, or any package not supported by + the WASM target. PKCS#8 PEM is server-only and stays in + `gateway/authn`. +- **No goroutines, no channels, no `sync` primitives** in + production files. Pure functions, deterministic outputs. +- **No re-export of `crypto/ed25519` types** in the public API. + Callers see opaque `[]byte` blobs and `string` representations + so the WASM bridge can hand them across the JS boundary as + `Uint8Array` and string primitives. +- **Randomness is injected.** `keypair.Generate(reader io.Reader)` + takes a caller-supplied reader. Production code passes + `crypto/rand.Reader`; tests use deterministic `bytes.NewReader`; + WASM later passes a `crypto.getRandomValues` adapter. + +## Layout + +```text +ui/core/ +├── go.mod module galaxy/core (Go 1.26.0) +├── canon/ canonical-bytes builders and verifiers +│ ├── canon.go length-prefix helpers +│ ├── request.go galaxy-request-v1 fields and signing input +│ ├── response.go galaxy-response-v1 fields and verifier +│ ├── event.go galaxy-event-v1 fields and verifier +│ ├── signature.go base64 client-key request verification +│ └── testdata/ committed JSON golden vectors +├── keypair/ Ed25519 generate / sign / verify / marshal +└── types/ full transport envelopes + result codes +``` + +## Public API + +### `galaxy/core/canon` + +- `RequestDomainMarkerV1`, `ResponseDomainMarkerV1`, `EventDomainMarkerV1` + — UTF-8 domain prefixes that bind a signature to a specific + envelope kind. +- `RequestSigningFields`, `ResponseSigningFields`, `EventSigningFields` + — exact subsets of envelope fields covered by the v1 signature. +- `BuildRequestSigningInput`, `BuildResponseSigningInput`, + `BuildEventSigningInput` — produce canonical bytes ready for + `ed25519.Sign` / `ed25519.Verify`. +- `VerifyRequestSignature(clientPublicKey string, signature []byte, + fields RequestSigningFields) error` — accepts the base64 + string form the backend stores in the device session. +- `VerifyResponseSignature(publicKey ed25519.PublicKey, signature []byte, + fields ResponseSigningFields) error`, + `VerifyEventSignature(publicKey ed25519.PublicKey, signature []byte, + fields EventSigningFields) error` — used by the client to + validate server output. +- `VerifyPayloadHash(payloadBytes, payloadHash []byte) error`. +- Sentinel errors: `ErrInvalidPayloadHash`, `ErrPayloadHashMismatch`, + `ErrInvalidClientPublicKey`, `ErrInvalidRequestSignature`, + `ErrInvalidResponseSignature`, `ErrInvalidEventSignature`. + +### `galaxy/core/keypair` + +- `Generate(reader io.Reader) (privateKey, publicKey []byte, err error)`. +- `Sign(privateKey, message []byte) ([]byte, error)` — returns a 64-byte + raw Ed25519 signature. +- `Verify(publicKey, message, signature []byte) bool`. +- `MarshalPublicKey(publicKey []byte) (string, error)` — base64 + StdEncoding, the wire format documented in §15. +- `UnmarshalPublicKey(value string) ([]byte, error)`. +- `PublicKeyFromPrivate(privateKey []byte) ([]byte, error)`. +- Sentinel errors: `ErrInvalidPrivateKey`, `ErrInvalidPublicKey`, + `ErrInvalidPublicKeyEncoding`. + +### `galaxy/core/types` + +- `RequestEnvelope`, `ResponseEnvelope`, `EventEnvelope` — full Go + envelope structs mirroring the protobuf messages in + `gateway/proto/galaxy/gateway/v1/`. Each exposes a + `SigningFields()` method to project onto the corresponding + `canon.*SigningFields`. +- `ProtocolVersionV1 = "v1"`, `ResultCodeOK = "ok"` — the only + result string that is part of the stable client contract; any + other `result_code` is downstream-opaque and must not be + hard-coded by clients. + +## Testing + +```sh +go test -count=1 ./ui/core/... +``` + +The `canon` test suite combines: + +- byte-equality on golden JSON fixtures under + `canon/testdata/` for three request types + (`user.account.get`, `lobby.my.games.list`, + `user.games.command`), one response (`ok`), and one event + (`gateway.server_time`); +- mutation tests proving every signed field is bound into the + signature; +- round-trip sign-then-verify across all three envelope kinds; +- negative tests for tampered hashes, mismatched timestamps and + request IDs, invalid signature lengths, and bad public-key + encodings. + +Cross-module parity (gateway accepts ui/core signatures and vice +versa) is enforced from +`gateway/authn/parity_with_ui_core_test.go`. + +## What this module is **not** + +- Not a network client. ConnectRPC over `@connectrpc/connect-web` + on the TypeScript side is the only network surface (Phase 5+). +- Not a key store. Per-platform secure storage lives in Phase 6. +- Not a freshness gate. Server-side `±5 min` freshness checks + remain in `gateway/internal/grpcapi/freshness_replay.go`. The + client is expected to stamp its own `timestamp_ms` accurately + via `time.Now`, but does not enforce a window. +- Not a FlatBuffers codec — that lands in a later phase, so the + module today is small on purpose. + +## Cross-references + +- [`../../docs/ARCHITECTURE.md` §15](../../docs/ARCHITECTURE.md) — + authoritative byte contract. +- [`../../gateway/authn`](../../gateway/authn) — server mirror of + the same canonical bytes. +- [`../PLAN.md`](../PLAN.md) Phase 3 — the staged plan that + describes how this module fits into the wider client. diff --git a/ui/core/canon/canon.go b/ui/core/canon/canon.go new file mode 100644 index 0000000..5144f09 --- /dev/null +++ b/ui/core/canon/canon.go @@ -0,0 +1,30 @@ +// Package canon implements the canonical-bytes serializer for the +// Galaxy v1 transport envelopes (galaxy-request-v1, galaxy-response-v1, +// galaxy-event-v1). The canonical-bytes contract is documented in +// `docs/ARCHITECTURE.md` §15 and mirrored byte-for-byte by the gateway +// in `gateway/authn`. Drift between the two implementations is caught +// by the parity test under `gateway/authn/parity_with_ui_core_test.go`. +// +// The package is network-free, storage-free, and TinyGo-friendly: it +// does not depend on `crypto/x509`, `encoding/pem`, or `os`. Random +// bytes are never read inside this package; the higher-level keypair +// API in `galaxy/core/keypair` accepts a caller-supplied io.Reader so +// the WASM build can inject `crypto.getRandomValues`. +package canon + +import "encoding/binary" + +// appendLengthPrefixedString encodes value as uvarint(len(value)) +// followed by the raw bytes of value. +func appendLengthPrefixedString(dst []byte, value string) []byte { + return appendLengthPrefixedBytes(dst, []byte(value)) +} + +// appendLengthPrefixedBytes encodes value as uvarint(len(value)) +// followed by the raw bytes of value. +func appendLengthPrefixedBytes(dst []byte, value []byte) []byte { + dst = binary.AppendUvarint(dst, uint64(len(value))) + dst = append(dst, value...) + + return dst +} diff --git a/ui/core/canon/event.go b/ui/core/canon/event.go new file mode 100644 index 0000000..9e9ba0e --- /dev/null +++ b/ui/core/canon/event.go @@ -0,0 +1,78 @@ +package canon + +import ( + "crypto/ed25519" + "encoding/binary" + "errors" +) + +const ( + // EventDomainMarkerV1 binds the v1 server event signature to the Galaxy + // gateway transport contract. + EventDomainMarkerV1 = "galaxy-event-v1" +) + +// ErrInvalidEventSignature reports that a gateway stream event signature is +// not a raw Ed25519 signature for the canonical event signing input. +var 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 +} diff --git a/ui/core/canon/event_test.go b/ui/core/canon/event_test.go new file mode 100644 index 0000000..eada954 --- /dev/null +++ b/ui/core/canon/event_test.go @@ -0,0 +1,162 @@ +package canon_test + +import ( + "bytes" + "crypto/ed25519" + "encoding/hex" + "testing" + + "galaxy/core/canon" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBuildEventSigningInputChangesWhenSignedFieldChanges(t *testing.T) { + t.Parallel() + + base := canon.EventSigningFields{ + EventType: "gateway.server_time", + EventID: "evt-123", + TimestampMS: 123456789, + RequestID: "request-123", + TraceID: "trace-123", + PayloadHash: sha256Sum([]byte("payload")), + } + + baseInput := canon.BuildEventSigningInput(base) + + tests := []struct { + name string + mutate func(canon.EventSigningFields) canon.EventSigningFields + }{ + { + name: "event type", + mutate: func(fields canon.EventSigningFields) canon.EventSigningFields { + fields.EventType = "gateway.other" + return fields + }, + }, + { + name: "event id", + mutate: func(fields canon.EventSigningFields) canon.EventSigningFields { + fields.EventID = "evt-456" + return fields + }, + }, + { + name: "timestamp", + mutate: func(fields canon.EventSigningFields) canon.EventSigningFields { + fields.TimestampMS++ + return fields + }, + }, + { + name: "request id", + mutate: func(fields canon.EventSigningFields) canon.EventSigningFields { + fields.RequestID = "request-456" + return fields + }, + }, + { + name: "trace id", + mutate: func(fields canon.EventSigningFields) canon.EventSigningFields { + fields.TraceID = "trace-456" + return fields + }, + }, + { + name: "payload hash", + mutate: func(fields canon.EventSigningFields) canon.EventSigningFields { + fields.PayloadHash = sha256Sum([]byte("other")) + return fields + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + mutated := canon.BuildEventSigningInput(tt.mutate(base)) + assert.False(t, bytes.Equal(baseInput, mutated)) + }) + } +} + +func TestSignAndVerifyEventSignature(t *testing.T) { + t.Parallel() + + seed := bytes.Repeat([]byte{0xBB}, ed25519.SeedSize) + privateKey := ed25519.NewKeyFromSeed(seed) + publicKey, _ := privateKey.Public().(ed25519.PublicKey) + + fields := canon.EventSigningFields{ + EventType: "gateway.server_time", + EventID: "evt-123", + TimestampMS: 123456789, + RequestID: "request-123", + TraceID: "trace-123", + PayloadHash: sha256Sum([]byte("payload")), + } + + signature := ed25519.Sign(privateKey, canon.BuildEventSigningInput(fields)) + require.NoError(t, canon.VerifyEventSignature(publicKey, signature, fields)) + + t.Run("rejects mutated trace id", func(t *testing.T) { + t.Parallel() + + mutated := fields + mutated.TraceID = "trace-other" + require.ErrorIs(t, + canon.VerifyEventSignature(publicKey, signature, mutated), + canon.ErrInvalidEventSignature) + }) + + t.Run("rejects invalid signature length", func(t *testing.T) { + t.Parallel() + + require.ErrorIs(t, + canon.VerifyEventSignature(publicKey, signature[:1], fields), + canon.ErrInvalidEventSignature) + }) + + t.Run("rejects invalid public key length", func(t *testing.T) { + t.Parallel() + + require.ErrorIs(t, + canon.VerifyEventSignature(publicKey[:8], signature, fields), + canon.ErrInvalidEventSignature) + }) +} + +func TestEventCanonicalBytesFixture(t *testing.T) { + t.Parallel() + + var fx eventFixture + loadJSONFixture(t, "event_gateway_server_time.json", &fx) + + fields := canon.EventSigningFields{ + EventType: fx.EventType, + EventID: fx.EventID, + TimestampMS: fx.TimestampMS, + RequestID: fx.RequestID, + TraceID: fx.TraceID, + PayloadHash: mustHex(t, fx.PayloadHashHex), + } + + require.NoError(t, + canon.VerifyPayloadHash([]byte(fx.Payload), fields.PayloadHash)) + + gotInput := canon.BuildEventSigningInput(fields) + assert.Equal(t, fx.ExpectedCanonicalBytesHex, hex.EncodeToString(gotInput)) + + seed := mustHex(t, fx.PrivateKeySeedHex) + require.Len(t, seed, ed25519.SeedSize) + privateKey := ed25519.NewKeyFromSeed(seed) + publicKey, _ := privateKey.Public().(ed25519.PublicKey) + signature := ed25519.Sign(privateKey, gotInput) + assert.Equal(t, fx.ExpectedSignatureHex, hex.EncodeToString(signature)) + + require.NoError(t, canon.VerifyEventSignature(publicKey, signature, fields)) +} diff --git a/ui/core/canon/request.go b/ui/core/canon/request.go new file mode 100644 index 0000000..c8d0eeb --- /dev/null +++ b/ui/core/canon/request.go @@ -0,0 +1,88 @@ +package canon + +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. The client populates this struct from a +// request envelope before signing; the server populates it from a received +// envelope before verification. +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. +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 +} diff --git a/ui/core/canon/request_test.go b/ui/core/canon/request_test.go new file mode 100644 index 0000000..50b1230 --- /dev/null +++ b/ui/core/canon/request_test.go @@ -0,0 +1,184 @@ +package canon_test + +import ( + "bytes" + "crypto/ed25519" + "crypto/sha256" + "encoding/hex" + "testing" + + "galaxy/core/canon" + + "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: canon.ErrInvalidPayloadHash, + }, + { + name: "rejects digest mismatch", + payload: []byte("payload"), + payloadHash: otherSum[:], + wantErr: canon.ErrPayloadHashMismatch, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := canon.VerifyPayloadHash(tt.payload, tt.payloadHash) + if tt.wantErr == nil { + require.NoError(t, err) + return + } + + require.ErrorIs(t, err, tt.wantErr) + }) + } +} + +func TestBuildRequestSigningInputChangesWhenSignedFieldChanges(t *testing.T) { + t.Parallel() + + base := canon.RequestSigningFields{ + ProtocolVersion: "v1", + DeviceSessionID: "device-session-123", + MessageType: "user.games.command", + TimestampMS: 123456789, + RequestID: "request-123", + PayloadHash: sha256Sum([]byte("payload")), + } + + baseInput := canon.BuildRequestSigningInput(base) + + tests := []struct { + name string + mutate func(canon.RequestSigningFields) canon.RequestSigningFields + }{ + { + name: "protocol version", + mutate: func(fields canon.RequestSigningFields) canon.RequestSigningFields { + fields.ProtocolVersion = "v2" + return fields + }, + }, + { + name: "device session id", + mutate: func(fields canon.RequestSigningFields) canon.RequestSigningFields { + fields.DeviceSessionID = "device-session-456" + return fields + }, + }, + { + name: "message type", + mutate: func(fields canon.RequestSigningFields) canon.RequestSigningFields { + fields.MessageType = "user.account.get" + return fields + }, + }, + { + name: "timestamp", + mutate: func(fields canon.RequestSigningFields) canon.RequestSigningFields { + fields.TimestampMS++ + return fields + }, + }, + { + name: "request id", + mutate: func(fields canon.RequestSigningFields) canon.RequestSigningFields { + fields.RequestID = "request-456" + return fields + }, + }, + { + name: "payload hash", + mutate: func(fields canon.RequestSigningFields) canon.RequestSigningFields { + fields.PayloadHash = sha256Sum([]byte("other")) + return fields + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + mutated := canon.BuildRequestSigningInput(tt.mutate(base)) + assert.False(t, bytes.Equal(baseInput, mutated)) + }) + } +} + +func TestRequestCanonicalBytesFixtures(t *testing.T) { + t.Parallel() + + fixtures := []string{ + "request_user_account_get.json", + "request_lobby_my_games_list.json", + "request_user_games_command.json", + } + + for _, name := range fixtures { + t.Run(name, func(t *testing.T) { + t.Parallel() + + var fx requestFixture + loadJSONFixture(t, name, &fx) + + fields := canon.RequestSigningFields{ + ProtocolVersion: fx.ProtocolVersion, + DeviceSessionID: fx.DeviceSessionID, + MessageType: fx.MessageType, + TimestampMS: fx.TimestampMS, + RequestID: fx.RequestID, + PayloadHash: mustHex(t, fx.PayloadHashHex), + } + + require.NoError(t, + canon.VerifyPayloadHash([]byte(fx.Payload), fields.PayloadHash), + "payload hash must match payload bytes") + + gotInput := canon.BuildRequestSigningInput(fields) + assert.Equal(t, fx.ExpectedCanonicalBytesHex, hex.EncodeToString(gotInput), + "canonical bytes drift from fixture") + + seed := mustHex(t, fx.PrivateKeySeedHex) + require.Len(t, seed, ed25519.SeedSize) + privateKey := ed25519.NewKeyFromSeed(seed) + signature := ed25519.Sign(privateKey, gotInput) + assert.Equal(t, fx.ExpectedSignatureHex, hex.EncodeToString(signature), + "signature drift from fixture") + + require.NoError(t, + canon.VerifyRequestSignature(fx.PublicKeyBase64, signature, fields)) + }) + } +} diff --git a/ui/core/canon/response.go b/ui/core/canon/response.go new file mode 100644 index 0000000..b08c5d4 --- /dev/null +++ b/ui/core/canon/response.go @@ -0,0 +1,74 @@ +package canon + +import ( + "crypto/ed25519" + "encoding/binary" + "errors" +) + +const ( + // ResponseDomainMarkerV1 binds the v1 server response signature to the + // Galaxy gateway transport contract. + ResponseDomainMarkerV1 = "galaxy-response-v1" +) + +// ErrInvalidResponseSignature reports that a server response signature is +// not a raw Ed25519 signature for the canonical response signing input. +var 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 +} + +// 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 +} diff --git a/ui/core/canon/response_test.go b/ui/core/canon/response_test.go new file mode 100644 index 0000000..a2a3342 --- /dev/null +++ b/ui/core/canon/response_test.go @@ -0,0 +1,153 @@ +package canon_test + +import ( + "bytes" + "crypto/ed25519" + "encoding/hex" + "testing" + + "galaxy/core/canon" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBuildResponseSigningInputChangesWhenSignedFieldChanges(t *testing.T) { + t.Parallel() + + base := canon.ResponseSigningFields{ + ProtocolVersion: "v1", + RequestID: "request-123", + TimestampMS: 123456789, + ResultCode: "ok", + PayloadHash: sha256Sum([]byte("payload")), + } + + baseInput := canon.BuildResponseSigningInput(base) + + tests := []struct { + name string + mutate func(canon.ResponseSigningFields) canon.ResponseSigningFields + }{ + { + name: "protocol version", + mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields { + fields.ProtocolVersion = "v2" + return fields + }, + }, + { + name: "request id", + mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields { + fields.RequestID = "request-456" + return fields + }, + }, + { + name: "timestamp", + mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields { + fields.TimestampMS++ + return fields + }, + }, + { + name: "result code", + mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields { + fields.ResultCode = "denied" + return fields + }, + }, + { + name: "payload hash", + mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields { + fields.PayloadHash = sha256Sum([]byte("other")) + return fields + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + mutated := canon.BuildResponseSigningInput(tt.mutate(base)) + assert.False(t, bytes.Equal(baseInput, mutated)) + }) + } +} + +func TestSignAndVerifyResponseSignature(t *testing.T) { + t.Parallel() + + seed := bytes.Repeat([]byte{0xAA}, ed25519.SeedSize) + privateKey := ed25519.NewKeyFromSeed(seed) + publicKey, _ := privateKey.Public().(ed25519.PublicKey) + + fields := canon.ResponseSigningFields{ + ProtocolVersion: "v1", + RequestID: "request-123", + TimestampMS: 123456789, + ResultCode: "ok", + PayloadHash: sha256Sum([]byte("payload")), + } + + signature := ed25519.Sign(privateKey, canon.BuildResponseSigningInput(fields)) + require.NoError(t, canon.VerifyResponseSignature(publicKey, signature, fields)) + + t.Run("rejects mutated field", func(t *testing.T) { + t.Parallel() + + mutated := fields + mutated.ResultCode = "denied" + require.ErrorIs(t, + canon.VerifyResponseSignature(publicKey, signature, mutated), + canon.ErrInvalidResponseSignature) + }) + + t.Run("rejects invalid public key length", func(t *testing.T) { + t.Parallel() + + shortKey := publicKey[:len(publicKey)-1] + require.ErrorIs(t, + canon.VerifyResponseSignature(shortKey, signature, fields), + canon.ErrInvalidResponseSignature) + }) + + t.Run("rejects invalid signature length", func(t *testing.T) { + t.Parallel() + + require.ErrorIs(t, + canon.VerifyResponseSignature(publicKey, signature[:len(signature)-1], fields), + canon.ErrInvalidResponseSignature) + }) +} + +func TestResponseCanonicalBytesFixture(t *testing.T) { + t.Parallel() + + var fx responseFixture + loadJSONFixture(t, "response_ok.json", &fx) + + fields := canon.ResponseSigningFields{ + ProtocolVersion: fx.ProtocolVersion, + RequestID: fx.RequestID, + TimestampMS: fx.TimestampMS, + ResultCode: fx.ResultCode, + PayloadHash: mustHex(t, fx.PayloadHashHex), + } + + require.NoError(t, + canon.VerifyPayloadHash([]byte(fx.Payload), fields.PayloadHash)) + + gotInput := canon.BuildResponseSigningInput(fields) + assert.Equal(t, fx.ExpectedCanonicalBytesHex, hex.EncodeToString(gotInput)) + + seed := mustHex(t, fx.PrivateKeySeedHex) + require.Len(t, seed, ed25519.SeedSize) + privateKey := ed25519.NewKeyFromSeed(seed) + publicKey, _ := privateKey.Public().(ed25519.PublicKey) + signature := ed25519.Sign(privateKey, gotInput) + assert.Equal(t, fx.ExpectedSignatureHex, hex.EncodeToString(signature)) + + require.NoError(t, canon.VerifyResponseSignature(publicKey, signature, fields)) +} diff --git a/ui/core/canon/signature.go b/ui/core/canon/signature.go new file mode 100644 index 0000000..7f46bc2 --- /dev/null +++ b/ui/core/canon/signature.go @@ -0,0 +1,51 @@ +package canon + +import ( + "crypto/ed25519" + "encoding/base64" + "errors" +) + +var ( + // ErrInvalidClientPublicKey reports that the provided client public key 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 decodes the base64-encoded raw Ed25519 client public +// key, builds the canonical v1 signing input from fields, and verifies that +// signature authenticates the request. +// +// The base64 string form matches how a backend hands the client public key +// back to the gateway after device-session resolution +// (see docs/ARCHITECTURE.md §15). +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 +} diff --git a/ui/core/canon/signature_test.go b/ui/core/canon/signature_test.go new file mode 100644 index 0000000..e958029 --- /dev/null +++ b/ui/core/canon/signature_test.go @@ -0,0 +1,145 @@ +package canon_test + +import ( + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "testing" + + "galaxy/core/canon" + + "github.com/stretchr/testify/require" +) + +func TestVerifyRequestSignature(t *testing.T) { + t.Parallel() + + clientPrivateKey := newTestPrivateKey("primary") + clientPublicKey, _ := clientPrivateKey.Public().(ed25519.PublicKey) + otherPrivateKey := newTestPrivateKey("other") + otherPublicKey, _ := otherPrivateKey.Public().(ed25519.PublicKey) + + fields := canon.RequestSigningFields{ + ProtocolVersion: "v1", + DeviceSessionID: "device-session-123", + MessageType: "user.games.command", + TimestampMS: 123456789, + RequestID: "request-123", + PayloadHash: sha256Sum([]byte("payload")), + } + + signature := ed25519.Sign(clientPrivateKey, canon.BuildRequestSigningInput(fields)) + + tests := []struct { + name string + clientPublicKey string + signature []byte + fields canon.RequestSigningFields + wantErr error + }{ + { + name: "valid signature", + clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey), + signature: signature, + fields: fields, + }, + { + name: "tampered payload hash rejects signature", + clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey), + signature: signature, + fields: func() canon.RequestSigningFields { + mutated := fields + mutated.PayloadHash = sha256Sum([]byte("other")) + return mutated + }(), + wantErr: canon.ErrInvalidRequestSignature, + }, + { + name: "mismatched request id rejects signature", + clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey), + signature: signature, + fields: func() canon.RequestSigningFields { + mutated := fields + mutated.RequestID = "request-456" + return mutated + }(), + wantErr: canon.ErrInvalidRequestSignature, + }, + { + name: "mismatched timestamp rejects signature", + clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey), + signature: signature, + fields: func() canon.RequestSigningFields { + mutated := fields + mutated.TimestampMS++ + return mutated + }(), + wantErr: canon.ErrInvalidRequestSignature, + }, + { + name: "wrong key rejects signature", + clientPublicKey: base64.StdEncoding.EncodeToString(otherPublicKey), + signature: signature, + fields: fields, + wantErr: canon.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: canon.ErrInvalidRequestSignature, + }, + { + name: "invalid signature length rejects", + clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey), + signature: signature[:len(signature)-1], + fields: fields, + wantErr: canon.ErrInvalidRequestSignature, + }, + { + name: "empty signature rejects", + clientPublicKey: base64.StdEncoding.EncodeToString(clientPublicKey), + signature: nil, + fields: fields, + wantErr: canon.ErrInvalidRequestSignature, + }, + { + name: "invalid base64 public key rejects", + clientPublicKey: "%%%not-base64%%%", + signature: signature, + fields: fields, + wantErr: canon.ErrInvalidClientPublicKey, + }, + { + name: "invalid public key length rejects", + clientPublicKey: base64.StdEncoding.EncodeToString([]byte("short")), + signature: signature, + fields: fields, + wantErr: canon.ErrInvalidClientPublicKey, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := canon.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("ui-core-canon-signature-test-" + label)) + return ed25519.NewKeyFromSeed(seed[:]) +} diff --git a/ui/core/canon/testdata/event_gateway_server_time.json b/ui/core/canon/testdata/event_gateway_server_time.json new file mode 100644 index 0000000..a1d25ea --- /dev/null +++ b/ui/core/canon/testdata/event_gateway_server_time.json @@ -0,0 +1,13 @@ +{ + "event_type": "gateway.server_time", + "event_id": "evt-server-time-1", + "timestamp_ms": 1700000003000, + "request_id": "req-stream-1", + "trace_id": "trace-server-time-1", + "payload": "event-payload", + "payload_hash_hex": "f484a64a69d92ecf6c00aa2a387a7cdcee3bcf3c5944659d1fd381f4c40852f3", + "expected_canonical_bytes_hex": "0f67616c6178792d6576656e742d763113676174657761792e7365727665725f74696d65116576742d7365727665722d74696d652d310000018bcfe573b80c7265712d73747265616d2d311374726163652d7365727665722d74696d652d3120f484a64a69d92ecf6c00aa2a387a7cdcee3bcf3c5944659d1fd381f4c40852f3", + "private_key_seed_hex": "0505050505050505050505050505050505050505050505050505050505050505", + "public_key_base64": "bnoc3Smwt4/ROvTFWY/v9O8qlxZuPKby5Pv8zYBQW/E=", + "expected_signature_hex": "5f25daad5758c7b0b25601c6b0639f6262e87a54272e01ccf5062e52b9eaef6a86f2eba96b5a94bf3ef81419d55d3e77d26a55110111465f97dbaaba8f3fb908" +} diff --git a/ui/core/canon/testdata/request_lobby_my_games_list.json b/ui/core/canon/testdata/request_lobby_my_games_list.json new file mode 100644 index 0000000..dccd471 --- /dev/null +++ b/ui/core/canon/testdata/request_lobby_my_games_list.json @@ -0,0 +1,13 @@ +{ + "message_type": "lobby.my.games.list", + "protocol_version": "v1", + "device_session_id": "device-session-1", + "timestamp_ms": 1700000000500, + "request_id": "req-lobby-1", + "payload": "lobby-payload", + "payload_hash_hex": "c1bf5b44b0254c7aca13830c1a85de8c7ac81d9989f41a82c44332ae040ab3f2", + "expected_canonical_bytes_hex": "1167616c6178792d726571756573742d7631027631106465766963652d73657373696f6e2d31136c6f6262792e6d792e67616d65732e6c6973740000018bcfe569f40b7265712d6c6f6262792d3120c1bf5b44b0254c7aca13830c1a85de8c7ac81d9989f41a82c44332ae040ab3f2", + "private_key_seed_hex": "0202020202020202020202020202020202020202020202020202020202020202", + "public_key_base64": "gTl3Dqh9F19Wo1Rmw0x+zMuNipG07jeiXfYPW4/Js5Q=", + "expected_signature_hex": "f8e1e382e8a95ae9d6bd297f4dd94ee252814d1fbbe62ae99859a1694c6ab1a0fc5e887d747ee1b9ba30d58d8986d7dd03af627be20f17edc5a37a495e8bc007" +} diff --git a/ui/core/canon/testdata/request_user_account_get.json b/ui/core/canon/testdata/request_user_account_get.json new file mode 100644 index 0000000..c036861 --- /dev/null +++ b/ui/core/canon/testdata/request_user_account_get.json @@ -0,0 +1,13 @@ +{ + "message_type": "user.account.get", + "protocol_version": "v1", + "device_session_id": "device-session-1", + "timestamp_ms": 1700000000000, + "request_id": "req-account-1", + "payload": "account-payload", + "payload_hash_hex": "c397741348585a420dafed41f7e809710bb09745889dcb699be827ed4d0f3fe8", + "expected_canonical_bytes_hex": "1167616c6178792d726571756573742d7631027631106465766963652d73657373696f6e2d3110757365722e6163636f756e742e6765740000018bcfe568000d7265712d6163636f756e742d3120c397741348585a420dafed41f7e809710bb09745889dcb699be827ed4d0f3fe8", + "private_key_seed_hex": "0101010101010101010101010101010101010101010101010101010101010101", + "public_key_base64": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w=", + "expected_signature_hex": "8fe30c4bb14e77e22e3c81a144fd03b53bba7e76664e36bdacbfa6b0575509279b5d97247eac25e104f09664e2e787f4c3e1a47af571d10c72a92a547c78f70d" +} diff --git a/ui/core/canon/testdata/request_user_games_command.json b/ui/core/canon/testdata/request_user_games_command.json new file mode 100644 index 0000000..cfd6512 --- /dev/null +++ b/ui/core/canon/testdata/request_user_games_command.json @@ -0,0 +1,13 @@ +{ + "message_type": "user.games.command", + "protocol_version": "v1", + "device_session_id": "device-session-1", + "timestamp_ms": 1700000001000, + "request_id": "req-games-1", + "payload": "games-payload", + "payload_hash_hex": "a8322c99bf424939cd3a1e5a41b5edb67e567bff87c49e8ff229be60976960e0", + "expected_canonical_bytes_hex": "1167616c6178792d726571756573742d7631027631106465766963652d73657373696f6e2d3112757365722e67616d65732e636f6d6d616e640000018bcfe56be80b7265712d67616d65732d3120a8322c99bf424939cd3a1e5a41b5edb67e567bff87c49e8ff229be60976960e0", + "private_key_seed_hex": "0303030303030303030303030303030303030303030303030303030303030303", + "public_key_base64": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY/k2NsFGFKyHN9E=", + "expected_signature_hex": "262d5480451560d9b2ca96468b0e962e4288eabb4dff29dbc66c491a37dd92b779d2b89853083a695317f8535e49c402dcfd49a11fd2926f3af42ceb745e2b0a" +} diff --git a/ui/core/canon/testdata/response_ok.json b/ui/core/canon/testdata/response_ok.json new file mode 100644 index 0000000..fa33469 --- /dev/null +++ b/ui/core/canon/testdata/response_ok.json @@ -0,0 +1,12 @@ +{ + "protocol_version": "v1", + "request_id": "req-response-1", + "timestamp_ms": 1700000002000, + "result_code": "ok", + "payload": "response-payload", + "payload_hash_hex": "2a9afa6f5873bca916cef860bf4902d5a665b1f01e832729eccccefe3424ea88", + "expected_canonical_bytes_hex": "1267616c6178792d726573706f6e73652d76310276310e7265712d726573706f6e73652d310000018bcfe56fd0026f6b202a9afa6f5873bca916cef860bf4902d5a665b1f01e832729eccccefe3424ea88", + "private_key_seed_hex": "0404040404040404040404040404040404040404040404040404040404040404", + "public_key_base64": "ypOsFwUYcHHWe4PH/w7+gQjo7EUwV113JoeTM9vavnw=", + "expected_signature_hex": "c9a1b79e602b7557c13d3554cd925be555ba0c5725d81c9baea75bee4693eb6f783e6654af9adfa589b93cf762417deaf7e5e3009d00ea8029c0de8996927b0e" +} diff --git a/ui/core/canon/testdata_test.go b/ui/core/canon/testdata_test.go new file mode 100644 index 0000000..06b01e1 --- /dev/null +++ b/ui/core/canon/testdata_test.go @@ -0,0 +1,80 @@ +package canon_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// requestFixture captures one stable canonical-bytes test vector for a v1 +// authenticated request. Fixture files live under testdata/ and are +// generated by hand using the canon package itself; they are committed as +// golden data so every change to the canonical-bytes contract surfaces as +// a hex diff in code review. +type requestFixture struct { + MessageType string `json:"message_type"` + ProtocolVersion string `json:"protocol_version"` + DeviceSessionID string `json:"device_session_id"` + TimestampMS int64 `json:"timestamp_ms"` + RequestID string `json:"request_id"` + Payload string `json:"payload"` + PayloadHashHex string `json:"payload_hash_hex"` + ExpectedCanonicalBytesHex string `json:"expected_canonical_bytes_hex"` + PrivateKeySeedHex string `json:"private_key_seed_hex"` + PublicKeyBase64 string `json:"public_key_base64"` + ExpectedSignatureHex string `json:"expected_signature_hex"` +} + +type responseFixture struct { + ProtocolVersion string `json:"protocol_version"` + RequestID string `json:"request_id"` + TimestampMS int64 `json:"timestamp_ms"` + ResultCode string `json:"result_code"` + Payload string `json:"payload"` + PayloadHashHex string `json:"payload_hash_hex"` + ExpectedCanonicalBytesHex string `json:"expected_canonical_bytes_hex"` + PrivateKeySeedHex string `json:"private_key_seed_hex"` + PublicKeyBase64 string `json:"public_key_base64"` + ExpectedSignatureHex string `json:"expected_signature_hex"` +} + +type eventFixture struct { + EventType string `json:"event_type"` + EventID string `json:"event_id"` + TimestampMS int64 `json:"timestamp_ms"` + RequestID string `json:"request_id"` + TraceID string `json:"trace_id"` + Payload string `json:"payload"` + PayloadHashHex string `json:"payload_hash_hex"` + ExpectedCanonicalBytesHex string `json:"expected_canonical_bytes_hex"` + PrivateKeySeedHex string `json:"private_key_seed_hex"` + PublicKeyBase64 string `json:"public_key_base64"` + ExpectedSignatureHex string `json:"expected_signature_hex"` +} + +func loadJSONFixture(t *testing.T, name string, into any) { + t.Helper() + + body, err := os.ReadFile(filepath.Join("testdata", name)) + require.NoError(t, err, "read %s", name) + require.NoError(t, json.Unmarshal(body, into), "decode %s", name) +} + +func mustHex(t *testing.T, value string) []byte { + t.Helper() + + decoded, err := hex.DecodeString(value) + require.NoError(t, err) + + return decoded +} + +func sha256Sum(payload []byte) []byte { + sum := sha256.Sum256(payload) + return sum[:] +} diff --git a/ui/core/go.mod b/ui/core/go.mod new file mode 100644 index 0000000..82efcaf --- /dev/null +++ b/ui/core/go.mod @@ -0,0 +1,11 @@ +module galaxy/core + +go 1.26.0 + +require github.com/stretchr/testify v1.11.1 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/ui/core/go.sum b/ui/core/go.sum new file mode 100644 index 0000000..c4c1710 --- /dev/null +++ b/ui/core/go.sum @@ -0,0 +1,10 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/ui/core/keypair/keypair.go b/ui/core/keypair/keypair.go new file mode 100644 index 0000000..b9f94ee --- /dev/null +++ b/ui/core/keypair/keypair.go @@ -0,0 +1,108 @@ +// Package keypair provides Ed25519 keypair generation and signing helpers +// over opaque []byte blobs. The package is network-free, storage-free, +// and TinyGo-friendly: it does not import `crypto/x509`, `encoding/pem`, +// or `os`. Random bytes are not read internally; callers pass an io.Reader +// (typically `crypto/rand.Reader` on host builds, or a `crypto.getRandomValues` +// adapter on WASM). +// +// Public APIs return raw byte blobs (32-byte public keys, 64-byte private +// keys, 64-byte signatures) so the WASM bridge in later phases can hand +// them back and forth across the JS boundary as Uint8Array. The package +// never re-exports `crypto/ed25519` types in its surface. +package keypair + +import ( + "bytes" + "crypto/ed25519" + "encoding/base64" + "errors" + "fmt" + "io" +) + +var ( + // ErrInvalidPrivateKey reports that a private key blob does not have the + // required Ed25519 private-key length. + ErrInvalidPrivateKey = errors.New("private_key must be a 64-byte Ed25519 private key") + + // ErrInvalidPublicKey reports that a public key blob does not have the + // required Ed25519 public-key length. + ErrInvalidPublicKey = errors.New("public_key must be a 32-byte Ed25519 public key") + + // ErrInvalidPublicKeyEncoding reports that a marshaled public key is not a + // strict base64 encoding of a 32-byte Ed25519 public key. + ErrInvalidPublicKeyEncoding = errors.New("public_key is not a valid base64-encoded Ed25519 public key") +) + +// Generate reads 32 seed bytes from reader and derives an Ed25519 keypair. +// The returned slices are independent copies; callers may retain or zero +// them without affecting subsequent calls. +func Generate(reader io.Reader) (privateKey, publicKey []byte, err error) { + if reader == nil { + return nil, nil, errors.New("keypair.Generate: reader must not be nil") + } + + pub, priv, err := ed25519.GenerateKey(reader) + if err != nil { + return nil, nil, fmt.Errorf("keypair.Generate: %w", err) + } + + return bytes.Clone(priv), bytes.Clone(pub), nil +} + +// Sign returns the raw 64-byte Ed25519 signature of message under privateKey. +func Sign(privateKey, message []byte) ([]byte, error) { + if len(privateKey) != ed25519.PrivateKeySize { + return nil, ErrInvalidPrivateKey + } + + signature := ed25519.Sign(ed25519.PrivateKey(privateKey), message) + return bytes.Clone(signature), nil +} + +// Verify reports whether signature authenticates message under publicKey. +// It returns false if any input has the wrong length. +func Verify(publicKey, message, signature []byte) bool { + if len(publicKey) != ed25519.PublicKeySize || len(signature) != ed25519.SignatureSize { + return false + } + + return ed25519.Verify(ed25519.PublicKey(publicKey), message, signature) +} + +// MarshalPublicKey returns the base64 (StdEncoding) representation of the raw +// 32-byte Ed25519 public key. The encoding matches docs/ARCHITECTURE.md §15: +// the backend stores client public keys in this exact form and the gateway +// reads them out of session cache as base64 strings. +func MarshalPublicKey(publicKey []byte) (string, error) { + if len(publicKey) != ed25519.PublicKeySize { + return "", ErrInvalidPublicKey + } + + return base64.StdEncoding.EncodeToString(publicKey), nil +} + +// UnmarshalPublicKey decodes a strict base64 (StdEncoding) representation of +// a raw 32-byte Ed25519 public key. +func UnmarshalPublicKey(value string) ([]byte, error) { + decoded, err := base64.StdEncoding.Strict().DecodeString(value) + if err != nil { + return nil, ErrInvalidPublicKeyEncoding + } + if len(decoded) != ed25519.PublicKeySize { + return nil, ErrInvalidPublicKey + } + + return decoded, nil +} + +// PublicKeyFromPrivate extracts the Ed25519 public key embedded in privateKey. +// The returned slice is an independent copy. +func PublicKeyFromPrivate(privateKey []byte) ([]byte, error) { + if len(privateKey) != ed25519.PrivateKeySize { + return nil, ErrInvalidPrivateKey + } + + pub, _ := ed25519.PrivateKey(privateKey).Public().(ed25519.PublicKey) + return bytes.Clone(pub), nil +} diff --git a/ui/core/keypair/keypair_test.go b/ui/core/keypair/keypair_test.go new file mode 100644 index 0000000..0b47de6 --- /dev/null +++ b/ui/core/keypair/keypair_test.go @@ -0,0 +1,143 @@ +package keypair_test + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "testing" + + "galaxy/core/keypair" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGenerateProducesIndependentCopies(t *testing.T) { + t.Parallel() + + priv, pub, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + require.Len(t, priv, ed25519.PrivateKeySize) + require.Len(t, pub, ed25519.PublicKeySize) + + // Mutating the returned slices must not affect a fresh call. + priv[0] ^= 0xFF + pub[0] ^= 0xFF + priv2, pub2, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + assert.NotEqual(t, priv[:8], priv2[:8]) + assert.NotEqual(t, pub[:8], pub2[:8]) +} + +func TestGenerateIsDeterministicForFixedSeed(t *testing.T) { + t.Parallel() + + seed := bytes.Repeat([]byte{0x42}, ed25519.SeedSize) + + priv1, pub1, err := keypair.Generate(bytes.NewReader(seed)) + require.NoError(t, err) + priv2, pub2, err := keypair.Generate(bytes.NewReader(seed)) + require.NoError(t, err) + + assert.Equal(t, priv1, priv2) + assert.Equal(t, pub1, pub2) +} + +func TestGenerateRejectsNilReader(t *testing.T) { + t.Parallel() + + _, _, err := keypair.Generate(nil) + require.Error(t, err) +} + +func TestSignRoundTrip(t *testing.T) { + t.Parallel() + + priv, pub, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + + message := []byte("ui-core-roundtrip") + signature, err := keypair.Sign(priv, message) + require.NoError(t, err) + assert.Len(t, signature, ed25519.SignatureSize) + + assert.True(t, keypair.Verify(pub, message, signature)) + assert.False(t, keypair.Verify(pub, []byte("tampered"), signature)) + tampered := append([]byte(nil), signature...) + tampered[0] ^= 0xFF + assert.False(t, keypair.Verify(pub, message, tampered)) +} + +func TestSignRejectsInvalidPrivateKey(t *testing.T) { + t.Parallel() + + _, err := keypair.Sign([]byte("short"), []byte("message")) + require.ErrorIs(t, err, keypair.ErrInvalidPrivateKey) +} + +func TestVerifyRejectsInvalidLengths(t *testing.T) { + t.Parallel() + + priv, pub, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + signature, err := keypair.Sign(priv, []byte("message")) + require.NoError(t, err) + + assert.False(t, keypair.Verify(pub[:8], []byte("message"), signature)) + assert.False(t, keypair.Verify(pub, []byte("message"), signature[:8])) +} + +func TestMarshalUnmarshalPublicKeyRoundTrip(t *testing.T) { + t.Parallel() + + _, pub, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + + encoded, err := keypair.MarshalPublicKey(pub) + require.NoError(t, err) + require.NotEmpty(t, encoded) + + // Encoding must be base64 StdEncoding to match docs/ARCHITECTURE.md §15. + expected := base64.StdEncoding.EncodeToString(pub) + assert.Equal(t, expected, encoded) + + decoded, err := keypair.UnmarshalPublicKey(encoded) + require.NoError(t, err) + assert.Equal(t, pub, decoded) +} + +func TestMarshalPublicKeyRejectsInvalidLength(t *testing.T) { + t.Parallel() + + _, err := keypair.MarshalPublicKey([]byte("short")) + require.ErrorIs(t, err, keypair.ErrInvalidPublicKey) +} + +func TestUnmarshalPublicKeyRejectsBadEncoding(t *testing.T) { + t.Parallel() + + _, err := keypair.UnmarshalPublicKey("%%%not-base64%%%") + require.ErrorIs(t, err, keypair.ErrInvalidPublicKeyEncoding) +} + +func TestUnmarshalPublicKeyRejectsWrongLength(t *testing.T) { + t.Parallel() + + _, err := keypair.UnmarshalPublicKey(base64.StdEncoding.EncodeToString([]byte("short"))) + require.ErrorIs(t, err, keypair.ErrInvalidPublicKey) +} + +func TestPublicKeyFromPrivate(t *testing.T) { + t.Parallel() + + priv, pub, err := keypair.Generate(rand.Reader) + require.NoError(t, err) + + derived, err := keypair.PublicKeyFromPrivate(priv) + require.NoError(t, err) + assert.Equal(t, pub, derived) + + _, err = keypair.PublicKeyFromPrivate([]byte("short")) + require.ErrorIs(t, err, keypair.ErrInvalidPrivateKey) +} diff --git a/ui/core/types/envelope.go b/ui/core/types/envelope.go new file mode 100644 index 0000000..38d129e --- /dev/null +++ b/ui/core/types/envelope.go @@ -0,0 +1,94 @@ +// Package types defines the v1 transport envelopes carried over the +// wire between the Galaxy client and gateway. Envelope shapes mirror +// the protobuf messages in `gateway/proto/galaxy/gateway/v1/`, but are +// kept as plain Go structs here so the UI client can read and produce +// them without depending on the protobuf runtime in WASM and gomobile +// builds. +// +// Each envelope exposes a SigningFields method that returns the subset +// of fields covered by the v1 signature (see canon.RequestSigningFields, +// canon.ResponseSigningFields, canon.EventSigningFields and +// docs/ARCHITECTURE.md §15). The TraceID field on a request envelope is +// intentionally not part of the request signing input. +package types + +import "galaxy/core/canon" + +// RequestEnvelope is the full client-side request envelope. PayloadBytes +// is hashed into PayloadHash; PayloadHash and the remaining envelope +// fields above Signature are bound by the v1 request signature. +type RequestEnvelope struct { + ProtocolVersion string + DeviceSessionID string + MessageType string + TimestampMS int64 + RequestID string + PayloadBytes []byte + PayloadHash []byte + Signature []byte + TraceID string +} + +// SigningFields projects the envelope onto the canonical request signing +// fields. TraceID is deliberately excluded: the v1 contract does not bind +// TraceID into the request signature. +func (e RequestEnvelope) SigningFields() canon.RequestSigningFields { + return canon.RequestSigningFields{ + ProtocolVersion: e.ProtocolVersion, + DeviceSessionID: e.DeviceSessionID, + MessageType: e.MessageType, + TimestampMS: e.TimestampMS, + RequestID: e.RequestID, + PayloadHash: e.PayloadHash, + } +} + +// ResponseEnvelope is the full server-side response envelope. PayloadBytes +// is hashed into PayloadHash; PayloadHash and the remaining envelope +// fields above Signature are bound by the v1 response signature. +type ResponseEnvelope struct { + ProtocolVersion string + RequestID string + TimestampMS int64 + ResultCode string + PayloadBytes []byte + PayloadHash []byte + Signature []byte +} + +// SigningFields projects the envelope onto the canonical response signing +// fields. +func (e ResponseEnvelope) SigningFields() canon.ResponseSigningFields { + return canon.ResponseSigningFields{ + ProtocolVersion: e.ProtocolVersion, + RequestID: e.RequestID, + TimestampMS: e.TimestampMS, + ResultCode: e.ResultCode, + PayloadHash: e.PayloadHash, + } +} + +// EventEnvelope is the full server-side push event envelope. +type EventEnvelope struct { + EventType string + EventID string + TimestampMS int64 + RequestID string + TraceID string + PayloadBytes []byte + PayloadHash []byte + Signature []byte +} + +// SigningFields projects the envelope onto the canonical event signing +// fields. +func (e EventEnvelope) SigningFields() canon.EventSigningFields { + return canon.EventSigningFields{ + EventType: e.EventType, + EventID: e.EventID, + TimestampMS: e.TimestampMS, + RequestID: e.RequestID, + TraceID: e.TraceID, + PayloadHash: e.PayloadHash, + } +} diff --git a/ui/core/types/envelope_test.go b/ui/core/types/envelope_test.go new file mode 100644 index 0000000..2cecb44 --- /dev/null +++ b/ui/core/types/envelope_test.go @@ -0,0 +1,81 @@ +package types_test + +import ( + "testing" + + "galaxy/core/canon" + "galaxy/core/types" + + "github.com/stretchr/testify/assert" +) + +func TestRequestEnvelopeSigningFieldsExcludesTraceID(t *testing.T) { + t.Parallel() + + envelope := types.RequestEnvelope{ + ProtocolVersion: types.ProtocolVersionV1, + DeviceSessionID: "device-session-1", + MessageType: "user.account.get", + TimestampMS: 1_700_000_000_000, + RequestID: "req-1", + PayloadBytes: []byte("payload"), + PayloadHash: []byte("01234567890123456789012345678901"), + Signature: []byte("ignored"), + TraceID: "trace-1", + } + + assert.Equal(t, canon.RequestSigningFields{ + ProtocolVersion: envelope.ProtocolVersion, + DeviceSessionID: envelope.DeviceSessionID, + MessageType: envelope.MessageType, + TimestampMS: envelope.TimestampMS, + RequestID: envelope.RequestID, + PayloadHash: envelope.PayloadHash, + }, envelope.SigningFields()) +} + +func TestResponseEnvelopeSigningFields(t *testing.T) { + t.Parallel() + + envelope := types.ResponseEnvelope{ + ProtocolVersion: types.ProtocolVersionV1, + RequestID: "req-1", + TimestampMS: 1_700_000_000_000, + ResultCode: types.ResultCodeOK, + PayloadBytes: []byte("payload"), + PayloadHash: []byte("01234567890123456789012345678901"), + Signature: []byte("ignored"), + } + + assert.Equal(t, canon.ResponseSigningFields{ + ProtocolVersion: envelope.ProtocolVersion, + RequestID: envelope.RequestID, + TimestampMS: envelope.TimestampMS, + ResultCode: envelope.ResultCode, + PayloadHash: envelope.PayloadHash, + }, envelope.SigningFields()) +} + +func TestEventEnvelopeSigningFieldsIncludesTraceID(t *testing.T) { + t.Parallel() + + envelope := types.EventEnvelope{ + EventType: "gateway.server_time", + EventID: "evt-1", + TimestampMS: 1_700_000_000_000, + RequestID: "req-1", + TraceID: "trace-1", + PayloadBytes: []byte("payload"), + PayloadHash: []byte("01234567890123456789012345678901"), + Signature: []byte("ignored"), + } + + assert.Equal(t, canon.EventSigningFields{ + EventType: envelope.EventType, + EventID: envelope.EventID, + TimestampMS: envelope.TimestampMS, + RequestID: envelope.RequestID, + TraceID: envelope.TraceID, + PayloadHash: envelope.PayloadHash, + }, envelope.SigningFields()) +} diff --git a/ui/core/types/result_codes.go b/ui/core/types/result_codes.go new file mode 100644 index 0000000..f8c681e --- /dev/null +++ b/ui/core/types/result_codes.go @@ -0,0 +1,11 @@ +package types + +const ( + // ProtocolVersionV1 is the only supported transport envelope version. + ProtocolVersionV1 = "v1" + + // ResultCodeOK is the stable success result code returned by the gateway + // for accepted authenticated commands. All other result_code strings are + // downstream-opaque and must not be hard-coded by clients. + ResultCodeOK = "ok" +)