diff --git a/crypto/encryptmegolm.go b/crypto/encryptmegolm.go index 2a7e744..7c78dc1 100644 --- a/crypto/encryptmegolm.go +++ b/crypto/encryptmegolm.go @@ -79,10 +79,15 @@ func getMentions(content any) *event.Mentions { return nil } +// Xessenger (QA-289): StateKey is omitzero, which keeps an empty state key in the plaintext and leaves out +// only a missing one (a message's), under encoding/json as under encoding/json/v2. canonicaljson marshals with +// v2 from Go 1.27 on, where omitempty also leaves out a pointer to "", as it encodes empty: the plaintext of +// encrypted state with the empty state key (MSC4362) then had none, which the receiving side refuses +// (matrix-sdk-crypto: the state key failed to validate) or reads as no state (mautrix-go). type rawMegolmEvent struct { RoomID id.RoomID `json:"room_id"` Type event.Type `json:"type"` - StateKey *string `json:"state_key,omitempty"` + StateKey *string `json:"state_key,omitzero"` Content any `json:"content"` } diff --git a/crypto/xessengertest/state_key_test.go b/crypto/xessengertest/state_key_test.go new file mode 100644 index 0000000..ec65736 --- /dev/null +++ b/crypto/xessengertest/state_key_test.go @@ -0,0 +1,179 @@ +// Copyright (c) 2026 Xessenger +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// From Go 1.27 on, as canonicaljson marshals with encoding/json/v2 (its jsonv2.go). +//go:build go1.27 + +package xessengertest + +import ( + "context" + jsonv1 "encoding/json" + jsonv2 "encoding/json/v2" + "fmt" + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "reflect" + "strconv" + "testing" + + "github.com/rs/zerolog" + + "maunium.net/go/mautrix" + "maunium.net/go/mautrix/crypto" + "maunium.net/go/mautrix/crypto/canonicaljson" + "maunium.net/go/mautrix/event" + "maunium.net/go/mautrix/id" +) + +// Encrypted state (MSC4362) carries its state key in the plaintext, the empty one too, and a message none, as +// the bridge encrypts it (canonicaljson, encoding/json/v2 from Go 1.27 on). A receiving mautrix-go reads each +// as it was sent: state under the outer key that packs it, with its own key, and the message as no state. +func TestXessengerEncryptedStateKeepsItsStateKey(t *testing.T) { + ctx := context.Background() + log := zerolog.Nop() + room := id.RoomID("!room:example.com") + bot := id.UserID("@bot:example.com") + store := crypto.NewMemoryStore(nil) + mach := crypto.NewOlmMachine(&mautrix.Client{UserID: bot, DeviceID: "BOTDEVICE", Log: log}, &log, store, mautrix.NewMemoryStateStore().(*mautrix.MemoryStateStore)) + mach.AllowEncryptedState = true + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(mach.Load(ctx)) + // The room's outbound session, and the inbound copy its sender keeps (as ShareGroupSession makes them), + // which decrypts as the sender's own: no device to look up. + session, err := crypto.NewOutboundGroupSession(room, &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1}, nil) + must(err) + session.Shared = true + must(store.AddOutboundGroupSession(ctx, session)) + own := mach.OwnIdentity() + inbound := func() *crypto.InboundGroupSession { + inbound, err := crypto.NewInboundGroupSession(own.IdentityKey, own.SigningKey, room, session.Internal.Key(), session.MaxAge, session.MaxMessages, nil, false) + must(err) + return inbound + } + must(store.PutGroupSession(ctx, inbound())) + reader := inbound() + empty, ghost := "", "@ghost:example.com" + for i, sent := range []struct { + eventType event.Type + stateKey *string + }{ + {event.Type{Type: "com.xessenger.room_meta", Class: event.StateEventType}, &empty}, + {event.Type{Type: "com.xessenger.member_profile", Class: event.StateEventType}, &ghost}, + {event.EventMessage, nil}, + } { + t.Run(sent.eventType.Type, func(t *testing.T) { + encrypted, err := mach.EncryptMegolmEventWithStateKey(ctx, room, sent.eventType, sent.stateKey, map[string]any{"v": 1}) + must(err) + // The plaintext as it was encrypted. + plaintext, _, err := reader.Internal.Decrypt(encrypted.MegolmCiphertext) + must(err) + var fields map[string]jsonv1.RawMessage + must(jsonv1.Unmarshal(plaintext, &fields)) + stateKey, has := fields["state_key"] + if sent.stateKey == nil && has { + t.Errorf("a message's plaintext has a state key: %s", plaintext) + } else if sent.stateKey != nil && (!has || string(stateKey) != strconv.Quote(*sent.stateKey)) { + t.Errorf("plaintext %s, want the state key %q in it", plaintext, *sent.stateKey) + } + // As a receiving mautrix-go decrypts it. + evt := &event.Event{ID: id.EventID(fmt.Sprintf("$event%d", i)), RoomID: room, Sender: bot, Type: event.EventEncrypted, Timestamp: 1, Content: event.Content{Parsed: encrypted}} + if sent.stateKey != nil { + outer := sent.eventType.Type + ":" + *sent.stateKey + evt.StateKey = &outer + } + decrypted, err := mach.DecryptMegolmEvent(ctx, evt) + must(err) + if sent.stateKey == nil && decrypted.StateKey != nil { + t.Errorf("a message decrypts as state with the key %q", *decrypted.StateKey) + } else if sent.stateKey != nil && (decrypted.StateKey == nil || *decrypted.StateKey != *sent.stateKey) { + t.Errorf("decrypted with the state key %v, want %q", decrypted.StateKey, *sent.stateKey) + } + }) + } +} + +// The tag rawMegolmEvent's state key has in encryptmegolm.go marshals the empty key and leaves out a missing one +// under both of Go's encoders: encoding/json, and encoding/json/v2, which canonicaljson uses from Go 1.27 on. +func TestXessengerStateKeyTagUnderBothEncoders(t *testing.T) { + tag := rawMegolmEventTag(t, "StateKey") + empty := "" + marshalers := []struct { + name string + marshal func(any) ([]byte, error) + }{ + {"encoding/json", jsonv1.Marshal}, + {"encoding/json/v2", func(v any) ([]byte, error) { return jsonv2.Marshal(v) }}, + {"canonicaljson", func(v any) ([]byte, error) { + out, err := canonicaljson.Marshal(v) + return []byte(out), err + }}, + } + marshal := func(t *testing.T, tag reflect.StructTag, marshal func(any) ([]byte, error), stateKey *string) string { + t.Helper() + value := reflect.New(reflect.StructOf([]reflect.StructField{{Name: "StateKey", Type: reflect.TypeFor[*string](), Tag: tag}})) + value.Elem().Field(0).Set(reflect.ValueOf(stateKey)) + out, err := marshal(value.Interface()) + if err != nil { + t.Fatal(err) + } + return string(out) + } + for _, encoder := range marshalers { + t.Run(encoder.name, func(t *testing.T) { + if got := marshal(t, tag, encoder.marshal, &empty); got != `{"state_key":""}` { + t.Errorf("the empty state key marshals as %s with %s", got, tag) + } + if got := marshal(t, tag, encoder.marshal, nil); got != `{}` { + t.Errorf("a missing state key marshals as %s with %s", got, tag) + } + }) + } + // Why: the tag before, omitempty, leaves the empty key out under encoding/json/v2. + if got := marshal(t, `json:"state_key,omitempty"`, marshalers[1].marshal, &empty); got != `{}` { + t.Errorf("omitempty marshals the empty state key as %s under encoding/json/v2", got) + } +} + +// rawMegolmEventTag reads the tag of a field of rawMegolmEvent from encryptmegolm.go, the crypto package being the +// folder above this one, where go test runs. +func rawMegolmEventTag(t *testing.T, field string) reflect.StructTag { + t.Helper() + file, err := parser.ParseFile(token.NewFileSet(), filepath.Join("..", "encryptmegolm.go"), nil, parser.SkipObjectResolution) + if err != nil { + t.Fatal(err) + } + for _, decl := range file.Decls { + types, ok := decl.(*ast.GenDecl) + if !ok || types.Tok != token.TYPE { + continue + } + for _, spec := range types.Specs { + if spec := spec.(*ast.TypeSpec); spec.Name.Name == "rawMegolmEvent" { + for _, each := range spec.Type.(*ast.StructType).Fields.List { + for _, name := range each.Names { + if name.Name == field && each.Tag != nil { + tag, err := strconv.Unquote(each.Tag.Value) + if err != nil { + t.Fatal(err) + } + return reflect.StructTag(tag) + } + } + } + } + } + } + t.Fatalf("encryptmegolm.go has no tag on rawMegolmEvent.%s", field) + return "" +}