Skip to content

Commit

Permalink
RespUserDevices intermediate decoding (#342)
Browse files Browse the repository at this point in the history
This should fix cases where Synapse users can upload absolute nonsense
into their device keys and then that causes the entire devices response
to fail to unmarshal.

This has happened both in the `"devices"` and `"stream_id"` keys that I
can see.
  • Loading branch information
neilalexander authored Sep 29, 2022
1 parent 759a8ee commit b0edbe0
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions federationtypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,34 @@ type RespUserDevices struct {
SelfSigningKey *CrossSigningKey `json:"self_signing_key"`
}

// UnmarshalJSON is used here because people on Synapses can apparently upload
// nonsense into their device keys in types that don't match the expected and
// that can cause the entire response to fail to unmarshal. This simply skips
// anything that fails to unmarshal and returns the rest.
func (r *RespUserDevices) UnmarshalJSON(data []byte) error {
intermediate := struct {
UserID json.RawMessage `json:"user_id"`
StreamID json.RawMessage `json:"stream_id"`
Devices []json.RawMessage `json:"devices"`
MasterKey json.RawMessage `json:"master_key"`
SelfSigningKey json.RawMessage `json:"self_signing_key"`
}{}
if err := json.Unmarshal(data, &intermediate); err != nil {
return err
}
_ = json.Unmarshal(intermediate.UserID, &r.UserID)
_ = json.Unmarshal(intermediate.StreamID, &r.StreamID)
_ = json.Unmarshal(intermediate.MasterKey, &r.MasterKey)
_ = json.Unmarshal(intermediate.SelfSigningKey, &r.SelfSigningKey)
for _, deviceJSON := range intermediate.Devices {
var device RespUserDevice
if err := json.Unmarshal(deviceJSON, &device); err == nil {
r.Devices = append(r.Devices, device)
}
}
return nil
}

// RespUserDevice are embedded in RespUserDevices
// https://matrix.org/docs/spec/server_server/latest#get-matrix-federation-v1-user-devices-userid
type RespUserDevice struct {
Expand Down

0 comments on commit b0edbe0

Please sign in to comment.