diff --git a/go.mod b/go.mod index 89275817..ce52cfd6 100644 --- a/go.mod +++ b/go.mod @@ -12,17 +12,17 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/gorilla/mux v1.8.0 github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 - github.com/matrix-org/gomatrixserverlib v0.0.0-20230113181222-67e060196d05 + github.com/matrix-org/gomatrixserverlib v0.0.0-20230921171121-0466775328c7 github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 github.com/moby/term v0.0.0-20210610120745-9d4ed1856297 // indirect github.com/morikuni/aec v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799 // indirect - github.com/sirupsen/logrus v1.9.0 - github.com/tidwall/gjson v1.14.4 + github.com/sirupsen/logrus v1.9.3 + github.com/tidwall/gjson v1.16.0 github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 - golang.org/x/crypto v0.5.0 // indirect + golang.org/x/crypto v0.13.0 // indirect golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 // indirect golang.org/x/image v0.5.0 // indirect golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect diff --git a/go.sum b/go.sum index aa4f34b5..a3e2ea9b 100644 --- a/go.sum +++ b/go.sum @@ -78,8 +78,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/matrix-org/gomatrix v0.0.0-20210324163249-be2af5ef2e16/go.mod h1:/gBX06Kw0exX1HrwmoBibFA98yBk/jxKpGVeyQbff+s= github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 h1:kHKxCOLcHH8r4Fzarl4+Y3K5hjothkVW5z7T1dUM11U= github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530/go.mod h1:/gBX06Kw0exX1HrwmoBibFA98yBk/jxKpGVeyQbff+s= -github.com/matrix-org/gomatrixserverlib v0.0.0-20230113181222-67e060196d05 h1:b0bSn6mQXKC0rktS5CZS/4imu643NYccnpSCv/w6xWc= -github.com/matrix-org/gomatrixserverlib v0.0.0-20230113181222-67e060196d05/go.mod h1:Mtifyr8q8htcBeugvlDnkBcNUy5LO8OzUoplAf1+mb4= +github.com/matrix-org/gomatrixserverlib v0.0.0-20230921171121-0466775328c7 h1:NhPNNFLHwdDb/upeicBh1GkxX/sFinEp5HF1WBqPtiY= +github.com/matrix-org/gomatrixserverlib v0.0.0-20230921171121-0466775328c7/go.mod h1:H9V9N3Uqn1bBJqYJNGK1noqtgJTaCEhtTdcH/mp50uU= github.com/matrix-org/util v0.0.0-20200807132607-55161520e1d4/go.mod h1:vVQlW/emklohkZnOPwD3LrZUBqdfsbiyO3p1lNV8F6U= github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 h1:6z4KxomXSIGWqhHcfzExgkH3Z3UkIXry4ibJS4Aqz2Y= github.com/matrix-org/util v0.0.0-20221111132719-399730281e66/go.mod h1:iBI1foelCqA09JJgPV0FYz4qA5dUXYOxMi57FxKBdd4= @@ -108,8 +108,9 @@ github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfF github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -123,8 +124,8 @@ github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vl github.com/tidwall/gjson v1.14.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.14.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= -github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.16.0 h1:SyXa+dsSPpUlcwEDuKuEBJEz5vzTvOea+9rjyYodQFg= +github.com/tidwall/gjson v1.16.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= @@ -147,8 +148,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220513210258-46612604a0f9/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= -golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -179,8 +180,9 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -193,15 +195,17 @@ golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220513224357-95641704303c/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.0.0-20220919232410-f2f64ebce3c1/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= -golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw= -golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220907140024-f12130a52804/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -225,21 +229,24 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= -golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -254,8 +261,9 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= -golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/federation/handle.go b/internal/federation/handle.go index c6374495..0261879a 100644 --- a/internal/federation/handle.go +++ b/internal/federation/handle.go @@ -10,6 +10,8 @@ import ( "github.com/gorilla/mux" "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/util" ) @@ -17,8 +19,8 @@ import ( // HandleMakeSendJoinRequests. func MakeJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request) { // Check federation signature - fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest( - req, time.Now(), gomatrixserverlib.ServerName(s.serverName), nil, s.keyRing, + fedReq, errResp := fclient.VerifyHTTPRequest( + req, time.Now(), spec.ServerName(s.serverName), nil, s.keyRing, ) if fedReq == nil { w.WriteHeader(errResp.Code) @@ -53,62 +55,62 @@ func MakeJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request // MakeRespMakeJoin makes the response for a /make_join request, without verifying any signatures // or dealing with HTTP responses itself. -func MakeRespMakeJoin(s *Server, room *ServerRoom, userID string) (resp gomatrixserverlib.RespMakeJoin, err error) { +func MakeRespMakeJoin(s *Server, room *ServerRoom, userID string) (resp fclient.RespMakeJoin, err error) { // Generate a join event - builder := gomatrixserverlib.EventBuilder{ - Sender: userID, + proto := gomatrixserverlib.ProtoEvent{ + SenderID: userID, RoomID: room.RoomID, Type: "m.room.member", StateKey: &userID, PrevEvents: []string{room.Timeline[len(room.Timeline)-1].EventID()}, Depth: room.Timeline[len(room.Timeline)-1].Depth() + 1, } - err = builder.SetContent(map[string]interface{}{"membership": gomatrixserverlib.Join}) + err = proto.SetContent(map[string]interface{}{"membership": spec.Join}) if err != nil { err = fmt.Errorf("make_join cannot set membership content: %w", err) return } - stateNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(&builder) + stateNeeded, err := gomatrixserverlib.StateNeededForProtoEvent(&proto) if err != nil { err = fmt.Errorf("make_join cannot calculate auth_events: %w", err) return } - builder.AuthEvents = room.AuthEvents(stateNeeded) + proto.AuthEvents = room.AuthEvents(stateNeeded) - resp = gomatrixserverlib.RespMakeJoin{ + resp = fclient.RespMakeJoin{ RoomVersion: room.Version, - JoinEvent: builder, + JoinEvent: proto, } return } // MakeRespMakeKnock makes the response for a /make_knock request, without verifying any signatures // or dealing with HTTP responses itself. -func MakeRespMakeKnock(s *Server, room *ServerRoom, userID string) (resp gomatrixserverlib.RespMakeKnock, err error) { +func MakeRespMakeKnock(s *Server, room *ServerRoom, userID string) (resp fclient.RespMakeKnock, err error) { // Generate a knock event - builder := gomatrixserverlib.EventBuilder{ - Sender: userID, + proto := gomatrixserverlib.ProtoEvent{ + SenderID: userID, RoomID: room.RoomID, Type: "m.room.member", StateKey: &userID, PrevEvents: []string{room.Timeline[len(room.Timeline)-1].EventID()}, Depth: room.Timeline[len(room.Timeline)-1].Depth() + 1, } - err = builder.SetContent(map[string]interface{}{"membership": gomatrixserverlib.Join}) + err = proto.SetContent(map[string]interface{}{"membership": spec.Join}) if err != nil { err = fmt.Errorf("make_knock cannot set membership content: %w", err) return } - stateNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(&builder) + stateNeeded, err := gomatrixserverlib.StateNeededForProtoEvent(&proto) if err != nil { err = fmt.Errorf("make_knock cannot calculate auth_events: %w", err) return } - builder.AuthEvents = room.AuthEvents(stateNeeded) + proto.AuthEvents = room.AuthEvents(stateNeeded) - resp = gomatrixserverlib.RespMakeKnock{ + resp = fclient.RespMakeKnock{ RoomVersion: room.Version, - KnockEvent: builder, + KnockEvent: proto, } return } @@ -124,8 +126,8 @@ func MakeRespMakeKnock(s *Server, room *ServerRoom, userID string) (resp gomatri // servers in the room. When omitServersInRoom is true, a misbehaving server is simulated and only // the current server is returned to the joining server. func SendJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request, expectPartialState bool, omitServersInRoom bool) { - fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest( - req, time.Now(), gomatrixserverlib.ServerName(s.serverName), nil, s.keyRing, + fedReq, errResp := fclient.VerifyHTTPRequest( + req, time.Now(), spec.ServerName(s.serverName), nil, s.keyRing, ) if fedReq == nil { w.WriteHeader(errResp.Code) @@ -154,7 +156,13 @@ func SendJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request w.Write([]byte("complement: HandleMakeSendJoinRequests send_join unexpected room ID: " + roomID)) return } - event, err := gomatrixserverlib.NewEventFromUntrustedJSON(fedReq.Content(), room.Version) + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + if err != nil { + w.WriteHeader(500) + w.Write([]byte("complement: HandleMakeSendJoinRequests send_join unexpected room version: " + err.Error())) + return + } + event, err := verImpl.NewEventFromUntrustedJSON(fedReq.Content()) if err != nil { w.WriteHeader(500) w.Write([]byte("complement: HandleMakeSendJoinRequests send_join cannot parse event JSON: " + err.Error())) @@ -162,7 +170,7 @@ func SendJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request } // build the state list *before* we insert the new event - var stateEvents []*gomatrixserverlib.Event + var stateEvents []gomatrixserverlib.PDU room.StateMutex.RLock() for _, ev := range room.State { // filter out non-critical memberships if this is a partial-state join @@ -188,8 +196,8 @@ func SendJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request log.Printf("Received send-join of event %s", event.EventID()) // return state and auth chain - b, err := json.Marshal(gomatrixserverlib.RespSendJoin{ - Origin: gomatrixserverlib.ServerName(s.serverName), + b, err := json.Marshal(fclient.RespSendJoin{ + Origin: spec.ServerName(s.serverName), AuthEvents: gomatrixserverlib.NewEventJSONsFromEvents(authEvents), StateEvents: gomatrixserverlib.NewEventJSONsFromEvents(stateEvents), MembersOmitted: expectPartialState, @@ -235,12 +243,12 @@ func HandlePartialStateMakeSendJoinRequests() func(*Server) { // HandleInviteRequests is an option which makes the server process invite requests. // // inviteCallback is a callback function that if non-nil will be called and passed the incoming invite event -func HandleInviteRequests(inviteCallback func(*gomatrixserverlib.Event)) func(*Server) { +func HandleInviteRequests(inviteCallback func(gomatrixserverlib.PDU)) func(*Server) { return func(s *Server) { // https://matrix.org/docs/spec/server_server/r0.1.4#put-matrix-federation-v2-invite-roomid-eventid s.mux.Handle("/_matrix/federation/v2/invite/{roomID}/{eventID}", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest( - req, time.Now(), gomatrixserverlib.ServerName(s.serverName), nil, s.keyRing, + fedReq, errResp := fclient.VerifyHTTPRequest( + req, time.Now(), spec.ServerName(s.serverName), nil, s.keyRing, ) if fedReq == nil { w.WriteHeader(errResp.Code) @@ -249,7 +257,7 @@ func HandleInviteRequests(inviteCallback func(*gomatrixserverlib.Event)) func(*S return } - var inviteRequest gomatrixserverlib.InviteV2Request + var inviteRequest fclient.InviteV2Request if err := json.Unmarshal(fedReq.Content(), &inviteRequest); err != nil { log.Printf( "complement: Unable to unmarshal incoming /invite request: %s", @@ -291,10 +299,10 @@ func HandleDirectoryLookups() func(*Server) { s.mux.Handle("/_matrix/federation/v1/query/directory", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { alias := req.URL.Query().Get("room_alias") if roomID, ok := s.aliases[alias]; ok { - b, err := json.Marshal(gomatrixserverlib.RespDirectory{ + b, err := json.Marshal(fclient.RespDirectory{ RoomID: roomID, - Servers: []gomatrixserverlib.ServerName{ - gomatrixserverlib.ServerName(s.serverName), + Servers: []spec.ServerName{ + spec.ServerName(s.serverName), }, }) if err != nil { @@ -321,7 +329,7 @@ func HandleEventRequests() func(*Server) { srv.mux.Handle("/_matrix/federation/v1/event/{eventID}", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) eventID := vars["eventID"] - var event *gomatrixserverlib.Event + var event gomatrixserverlib.PDU // find the event RoomLoop: for _, room := range srv.rooms { @@ -340,8 +348,8 @@ func HandleEventRequests() func(*Server) { } txn := gomatrixserverlib.Transaction{ - Origin: gomatrixserverlib.ServerName(srv.serverName), - OriginServerTS: gomatrixserverlib.AsTimestamp(time.Now()), + Origin: spec.ServerName(srv.serverName), + OriginServerTS: spec.AsTimestamp(time.Now()), PDUs: []json.RawMessage{ event.JSON(), }, @@ -376,7 +384,7 @@ func HandleEventAuthRequests() func(*Server) { } // find the event - var event *gomatrixserverlib.Event + var event gomatrixserverlib.PDU for _, ev := range room.Timeline { if ev.EventID() == eventID { event = ev @@ -391,8 +399,8 @@ func HandleEventAuthRequests() func(*Server) { return } - authEvents := room.AuthChainForEvents([]*gomatrixserverlib.Event{event}) - resp := gomatrixserverlib.RespEventAuth{ + authEvents := room.AuthChainForEvents([]gomatrixserverlib.PDU{event}) + resp := fclient.RespEventAuth{ gomatrixserverlib.NewEventJSONsFromEvents(authEvents), } respJSON, err := json.Marshal(resp) @@ -413,15 +421,15 @@ func HandleKeyRequests() func(*Server) { keymux := srv.mux.PathPrefix("/_matrix/key/v2").Subrouter() keyFn := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { k := gomatrixserverlib.ServerKeys{} - k.ServerName = gomatrixserverlib.ServerName(srv.serverName) + k.ServerName = spec.ServerName(srv.serverName) publicKey := srv.Priv.Public().(ed25519.PublicKey) k.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{ srv.KeyID: { - Key: gomatrixserverlib.Base64Bytes(publicKey), + Key: spec.Base64Bytes(publicKey), }, } k.OldVerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.OldVerifyKey{} - k.ValidUntilTS = gomatrixserverlib.AsTimestamp(time.Now().Add(24 * time.Hour)) + k.ValidUntilTS = spec.AsTimestamp(time.Now().Add(24 * time.Hour)) toSign, err := json.Marshal(k.ServerKeyFields) if err != nil { w.WriteHeader(500) @@ -484,7 +492,7 @@ func HandleMediaRequests(mediaIds map[string]func(w http.ResponseWriter)) func(* // HandleTransactionRequests is an option which will process GET /_matrix/federation/v1/send/{transactionID} requests universally when requested. // pduCallback and eduCallback are functions that if non-nil will be called and passed each PDU or EDU event received in the transaction. // Callbacks will be fired AFTER the event has been stored onto the respective ServerRoom. -func HandleTransactionRequests(pduCallback func(*gomatrixserverlib.Event), eduCallback func(gomatrixserverlib.EDU)) func(*Server) { +func HandleTransactionRequests(pduCallback func(gomatrixserverlib.PDU), eduCallback func(gomatrixserverlib.EDU)) func(*Server) { return func(srv *Server) { srv.mux.Handle("/_matrix/federation/v1/send/{transactionID}", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Extract the transaction ID from the request vars @@ -492,8 +500,8 @@ func HandleTransactionRequests(pduCallback func(*gomatrixserverlib.Event), eduCa transactionID := vars["transactionID"] // Check federation signature - fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest( - req, time.Now(), gomatrixserverlib.ServerName(srv.serverName), nil, srv.keyRing, + fedReq, errResp := fclient.VerifyHTTPRequest( + req, time.Now(), spec.ServerName(srv.serverName), nil, srv.keyRing, ) if fedReq == nil { log.Printf( @@ -540,8 +548,8 @@ func HandleTransactionRequests(pduCallback func(*gomatrixserverlib.Event), eduCa } // Construct a response and fill as we process each PDU - response := gomatrixserverlib.RespSend{} - response.PDUs = make(map[string]gomatrixserverlib.PDUResult) + response := fclient.RespSend{} + response.PDUs = make(map[string]fclient.PDUResult) for _, pdu := range transaction.PDUs { var header struct { RoomID string `json:"room_id"` @@ -561,10 +569,18 @@ func HandleTransactionRequests(pduCallback func(*gomatrixserverlib.Event), eduCa log.Printf("complement: Transaction '%s': Failed to find local room: %s", transaction.TransactionID, header.RoomID) continue } - roomVersion := gomatrixserverlib.RoomVersion(room.Version) - var event *gomatrixserverlib.Event - event, err = gomatrixserverlib.NewEventFromUntrustedJSON(pdu, roomVersion) + var event gomatrixserverlib.PDU + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + if err != nil { + log.Printf( + "complement: Transaction '%s': Failed to get room version '%s': %s", + transaction.TransactionID, event.EventID(), err.Error(), + ) + continue + } + + event, err = verImpl.NewEventFromUntrustedJSON(pdu) if err != nil { // We were unable to verify or process this event. log.Printf( @@ -580,7 +596,7 @@ func HandleTransactionRequests(pduCallback func(*gomatrixserverlib.Event), eduCa room.AddEvent(event) // Add this PDU as a success to the response - response.PDUs[event.EventID()] = gomatrixserverlib.PDUResult{} + response.PDUs[event.EventID()] = fclient.PDUResult{} // Run the PDU callback function with this event if pduCallback != nil { diff --git a/internal/federation/server.go b/internal/federation/server.go index 7959619d..e9159253 100644 --- a/internal/federation/server.go +++ b/internal/federation/server.go @@ -21,6 +21,8 @@ import ( "time" "github.com/matrix-org/gomatrix" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/gorilla/mux" "github.com/matrix-org/gomatrixserverlib" @@ -76,9 +78,11 @@ func NewServer(t *testing.T, deployment *docker.Deployment, opts ...func(*Server } fetcher := &basicKeyFetcher{ KeyFetcher: &gomatrixserverlib.DirectKeyFetcher{ - Client: gomatrixserverlib.NewClient( - gomatrixserverlib.WithTransport(&docker.RoundTripper{Deployment: deployment}), + Client: fclient.NewClient( + fclient.WithTransport(&docker.RoundTripper{Deployment: deployment}), ), + IsLocalServerName: func(s spec.ServerName) bool { return s == spec.ServerName(deployment.Config.HostnameRunningComplement) }, + LocalPublicKey: []byte(pub), }, srv: srv, } @@ -182,18 +186,18 @@ func (s *Server) MustMakeRoom(t *testing.T, roomVer gomatrixserverlib.RoomVersio // FederationClient returns a client which will sign requests using this server's key. // // The requests will be routed according to the deployment map in `deployment`. -func (s *Server) FederationClient(deployment *docker.Deployment) *gomatrixserverlib.FederationClient { +func (s *Server) FederationClient(deployment *docker.Deployment) fclient.FederationClient { if !s.listening { s.t.Fatalf("FederationClient() called before Listen() - this is not supported because Listen() chooses a high-numbered port and thus changes the server name and thus changes the way federation requests are signed. Ensure you Listen() first!") } - identity := gomatrixserverlib.SigningIdentity{ - ServerName: gomatrixserverlib.ServerName(s.ServerName()), + identity := fclient.SigningIdentity{ + ServerName: spec.ServerName(s.ServerName()), KeyID: s.KeyID, PrivateKey: s.Priv, } - f := gomatrixserverlib.NewFederationClient( - []*gomatrixserverlib.SigningIdentity{&identity}, - gomatrixserverlib.WithTransport(&docker.RoundTripper{Deployment: deployment}), + f := fclient.NewFederationClient( + []*fclient.SigningIdentity{&identity}, + fclient.WithTransport(&docker.RoundTripper{Deployment: deployment}), ) return f } @@ -207,8 +211,8 @@ func (s *Server) MustSendTransaction(t *testing.T, deployment *docker.Deployment defer cancel() resp, err := cli.SendTransaction(ctx, gomatrixserverlib.Transaction{ TransactionID: gomatrixserverlib.TransactionID(fmt.Sprintf("complement-%d", time.Now().Nanosecond())), - Origin: gomatrixserverlib.ServerName(s.ServerName()), - Destination: gomatrixserverlib.ServerName(destination), + Origin: spec.ServerName(s.ServerName()), + Destination: spec.ServerName(destination), PDUs: pdus, EDUs: edus, }) @@ -229,10 +233,10 @@ func (s *Server) SendFederationRequest( ctx context.Context, t *testing.T, deployment *docker.Deployment, - req gomatrixserverlib.FederationRequest, + req fclient.FederationRequest, resBody interface{}, ) error { - if err := req.Sign(gomatrixserverlib.ServerName(s.serverName), s.KeyID, s.Priv); err != nil { + if err := req.Sign(spec.ServerName(s.serverName), s.KeyID, s.Priv); err != nil { return err } @@ -241,7 +245,7 @@ func (s *Server) SendFederationRequest( return err } - httpClient := gomatrixserverlib.NewClient(gomatrixserverlib.WithTransport(&docker.RoundTripper{Deployment: deployment})) + httpClient := fclient.NewClient(fclient.WithTransport(&docker.RoundTripper{Deployment: deployment})) start := time.Now() err = httpClient.DoRequestAndParseResponse(ctx, httpReq, resBody) @@ -260,8 +264,8 @@ func (s *Server) DoFederationRequest( ctx context.Context, t *testing.T, deployment *docker.Deployment, - req gomatrixserverlib.FederationRequest) (*http.Response, error) { - if err := req.Sign(gomatrixserverlib.ServerName(s.serverName), s.KeyID, s.Priv); err != nil { + req fclient.FederationRequest) (*http.Response, error) { + if err := req.Sign(spec.ServerName(s.serverName), s.KeyID, s.Priv); err != nil { return nil, err } @@ -270,7 +274,7 @@ func (s *Server) DoFederationRequest( return nil, err } - httpClient := gomatrixserverlib.NewClient(gomatrixserverlib.WithTransport(&docker.RoundTripper{Deployment: deployment})) + httpClient := fclient.NewClient(fclient.WithTransport(&docker.RoundTripper{Deployment: deployment})) start := time.Now() var resp *http.Response @@ -286,7 +290,7 @@ func (s *Server) DoFederationRequest( // MustCreateEvent will create and sign a new latest event for the given room. // It does not insert this event into the room however. See ServerRoom.AddEvent for that. -func (s *Server) MustCreateEvent(t *testing.T, room *ServerRoom, ev b.Event) *gomatrixserverlib.Event { +func (s *Server) MustCreateEvent(t *testing.T, room *ServerRoom, ev b.Event) gomatrixserverlib.PDU { t.Helper() content, err := json.Marshal(ev.Content) if err != nil { @@ -310,8 +314,8 @@ func (s *Server) MustCreateEvent(t *testing.T, room *ServerRoom, ev b.Event) *go // the usual behaviour. prevEvents = room.ForwardExtremities } - eb := gomatrixserverlib.EventBuilder{ - Sender: ev.Sender, + proto := gomatrixserverlib.ProtoEvent{ + SenderID: ev.Sender, Depth: int64(room.Depth + 1), // depth starts at 1 Type: ev.Type, StateKey: ev.StateKey, @@ -322,15 +326,20 @@ func (s *Server) MustCreateEvent(t *testing.T, room *ServerRoom, ev b.Event) *go AuthEvents: ev.AuthEvents, Redacts: ev.Redacts, } - if eb.AuthEvents == nil { + if proto.AuthEvents == nil { var stateNeeded gomatrixserverlib.StateNeeded - stateNeeded, err = gomatrixserverlib.StateNeededForEventBuilder(&eb) + stateNeeded, err = gomatrixserverlib.StateNeededForProtoEvent(&proto) if err != nil { t.Fatalf("MustCreateEvent: failed to work out auth_events : %s", err) } - eb.AuthEvents = room.AuthEvents(stateNeeded) + proto.AuthEvents = room.AuthEvents(stateNeeded) } - signedEvent, err := eb.Build(time.Now(), gomatrixserverlib.ServerName(s.serverName), s.KeyID, s.Priv, room.Version) + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + if err != nil { + t.Fatalf("MustCreateEvent: invalid room version: %s", err) + } + eb := verImpl.NewEventBuilderFromProtoEvent(&proto) + signedEvent, err := eb.Build(time.Now(), spec.ServerName(s.serverName), s.KeyID, s.Priv) if err != nil { t.Fatalf("MustCreateEvent: failed to sign event: %s", err) } @@ -339,20 +348,25 @@ func (s *Server) MustCreateEvent(t *testing.T, room *ServerRoom, ev b.Event) *go // MustJoinRoom will make the server send a make_join and a send_join to join a room // It returns the resultant room. -func (s *Server) MustJoinRoom(t *testing.T, deployment *docker.Deployment, remoteServer gomatrixserverlib.ServerName, roomID string, userID string, partialState ...bool) *ServerRoom { +func (s *Server) MustJoinRoom(t *testing.T, deployment *docker.Deployment, remoteServer spec.ServerName, roomID string, userID string, partialState ...bool) *ServerRoom { t.Helper() - origin := gomatrixserverlib.ServerName(s.serverName) + origin := spec.ServerName(s.serverName) fedClient := s.FederationClient(deployment) - makeJoinResp, err := fedClient.MakeJoin(context.Background(), origin, remoteServer, roomID, userID, SupportedRoomVersions()) + makeJoinResp, err := fedClient.MakeJoin(context.Background(), origin, remoteServer, roomID, userID) if err != nil { t.Fatalf("MustJoinRoom: make_join failed: %v", err) } roomVer := makeJoinResp.RoomVersion - joinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), origin, s.KeyID, s.Priv, roomVer) + verImpl, err := gomatrixserverlib.GetRoomVersion(makeJoinResp.RoomVersion) + if err != nil { + t.Fatalf("MustJoinRoom: invalid room version: %v", err) + } + eb := verImpl.NewEventBuilderFromProtoEvent(&makeJoinResp.JoinEvent) + joinEvent, err := eb.Build(time.Now(), origin, s.KeyID, s.Priv) if err != nil { t.Fatalf("MustJoinRoom: failed to sign event: %v", err) } - var sendJoinResp gomatrixserverlib.RespSendJoin + var sendJoinResp fclient.RespSendJoin if len(partialState) == 0 || !partialState[0] { // Default to doing a regular join. sendJoinResp, err = fedClient.SendJoin(context.Background(), origin, remoteServer, joinEvent) @@ -376,11 +390,11 @@ func (s *Server) MustJoinRoom(t *testing.T, deployment *docker.Deployment, remot } // Leaves a room. If this is rejecting an invite then a make_leave request is made first, before send_leave. -func (s *Server) MustLeaveRoom(t *testing.T, deployment *docker.Deployment, remoteServer gomatrixserverlib.ServerName, roomID string, userID string) { +func (s *Server) MustLeaveRoom(t *testing.T, deployment *docker.Deployment, remoteServer spec.ServerName, roomID string, userID string) { t.Helper() - origin := gomatrixserverlib.ServerName(s.serverName) + origin := spec.ServerName(s.serverName) fedClient := s.FederationClient(deployment) - var leaveEvent *gomatrixserverlib.Event + var leaveEvent gomatrixserverlib.PDU room := s.rooms[roomID] if room == nil { // e.g rejecting an invite @@ -388,8 +402,12 @@ func (s *Server) MustLeaveRoom(t *testing.T, deployment *docker.Deployment, remo if err != nil { t.Fatalf("MustLeaveRoom: (rejecting invite) make_leave failed: %v", err) } - roomVer := makeLeaveResp.RoomVersion - leaveEvent, err = makeLeaveResp.LeaveEvent.Build(time.Now(), origin, s.KeyID, s.Priv, roomVer) + verImpl, err := gomatrixserverlib.GetRoomVersion(makeLeaveResp.RoomVersion) + if err != nil { + t.Fatalf("MustLeaveRoom: invalid room version: %v", err) + } + eb := verImpl.NewEventBuilderFromProtoEvent(&makeLeaveResp.LeaveEvent) + leaveEvent, err = eb.Build(time.Now(), origin, s.KeyID, s.Priv) if err != nil { t.Fatalf("MustLeaveRoom: (rejecting invite) failed to sign event: %v", err) } @@ -416,11 +434,11 @@ func (s *Server) MustLeaveRoom(t *testing.T, deployment *docker.Deployment, remo // ValidFederationRequest is a wrapper around http.HandlerFunc which automatically validates the incoming // federation request and supports sending back JSON. Fails the test if the request is not valid. -func (s *Server) ValidFederationRequest(t *testing.T, handler func(fr *gomatrixserverlib.FederationRequest, pathParams map[string]string) util.JSONResponse) http.HandlerFunc { +func (s *Server) ValidFederationRequest(t *testing.T, handler func(fr *fclient.FederationRequest, pathParams map[string]string) util.JSONResponse) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { // Check federation signature - fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest( - req, time.Now(), gomatrixserverlib.ServerName(s.serverName), nil, s.keyRing, + fedReq, errResp := fclient.VerifyHTTPRequest( + req, time.Now(), spec.ServerName(s.serverName), nil, s.keyRing, ) if fedReq == nil { t.Errorf( @@ -575,7 +593,7 @@ func (d *nopKeyDatabase) StoreKeys(ctx context.Context, results map[gomatrixserv } func (f *nopKeyDatabase) FetchKeys( ctx context.Context, - requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp) ( + requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp) ( map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error, ) { return nil, nil @@ -591,7 +609,7 @@ type basicKeyFetcher struct { func (f *basicKeyFetcher) FetchKeys( ctx context.Context, - requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp) ( + requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp) ( map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error, ) { result := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, len(requests)) @@ -599,10 +617,10 @@ func (f *basicKeyFetcher) FetchKeys( if string(req.ServerName) == f.srv.serverName && req.KeyID == f.srv.KeyID { publicKey := f.srv.Priv.Public().(ed25519.PublicKey) result[req] = gomatrixserverlib.PublicKeyLookupResult{ - ValidUntilTS: gomatrixserverlib.AsTimestamp(time.Now().Add(24 * time.Hour)), + ValidUntilTS: spec.AsTimestamp(time.Now().Add(24 * time.Hour)), ExpiredTS: gomatrixserverlib.PublicKeyNotExpired, VerifyKey: gomatrixserverlib.VerifyKey{ - Key: gomatrixserverlib.Base64Bytes(publicKey), + Key: spec.Base64Bytes(publicKey), }, } } else { @@ -619,7 +637,7 @@ func (f *basicKeyFetcher) FetcherName() string { // SupportedRoomVersions is a convenience method which returns a list of the room versions supported by gomatrixserverlib. func SupportedRoomVersions() []gomatrixserverlib.RoomVersion { supportedRoomVersions := make([]gomatrixserverlib.RoomVersion, 0, 10) - for v := range gomatrixserverlib.SupportedRoomVersions() { + for v := range gomatrixserverlib.StableRoomVersions() { supportedRoomVersions = append(supportedRoomVersions, v) } return supportedRoomVersions diff --git a/internal/federation/server_room.go b/internal/federation/server_room.go index c17d94ab..82e1ef7f 100644 --- a/internal/federation/server_room.go +++ b/internal/federation/server_room.go @@ -15,9 +15,9 @@ import ( type ServerRoom struct { Version gomatrixserverlib.RoomVersion RoomID string - State map[string]*gomatrixserverlib.Event + State map[string]gomatrixserverlib.PDU StateMutex sync.RWMutex - Timeline []*gomatrixserverlib.Event + Timeline []gomatrixserverlib.PDU TimelineMutex sync.RWMutex ForwardExtremities []string Depth int64 @@ -28,14 +28,14 @@ func newRoom(roomVer gomatrixserverlib.RoomVersion, roomId string) *ServerRoom { return &ServerRoom{ RoomID: roomId, Version: roomVer, - State: make(map[string]*gomatrixserverlib.Event), + State: make(map[string]gomatrixserverlib.PDU), ForwardExtremities: make([]string, 0), } } // AddEvent adds a new event to the timeline, updating current state if it is a state event. // Updates depth and forward extremities. -func (r *ServerRoom) AddEvent(ev *gomatrixserverlib.Event) { +func (r *ServerRoom) AddEvent(ev gomatrixserverlib.PDU) { if ev.StateKey() != nil { r.replaceCurrentState(ev) } @@ -78,7 +78,7 @@ func (r *ServerRoom) AuthEvents(sn gomatrixserverlib.StateNeeded) (eventIDs []st // replaceCurrentState inserts a new state event for this room or replaces current state depending // on the (type, state_key) provided. -func (r *ServerRoom) replaceCurrentState(ev *gomatrixserverlib.Event) { +func (r *ServerRoom) replaceCurrentState(ev gomatrixserverlib.PDU) { tuple := fmt.Sprintf("%s\x1f%s", ev.Type(), *ev.StateKey()) r.StateMutex.Lock() r.State[tuple] = ev @@ -86,7 +86,7 @@ func (r *ServerRoom) replaceCurrentState(ev *gomatrixserverlib.Event) { } // CurrentState returns the state event for the given (type, state_key) or nil. -func (r *ServerRoom) CurrentState(evType, stateKey string) *gomatrixserverlib.Event { +func (r *ServerRoom) CurrentState(evType, stateKey string) gomatrixserverlib.PDU { tuple := fmt.Sprintf("%s\x1f%s", evType, stateKey) r.StateMutex.RLock() state := r.State[tuple] @@ -95,7 +95,7 @@ func (r *ServerRoom) CurrentState(evType, stateKey string) *gomatrixserverlib.Ev } // AllCurrentState returns all the current state events -func (r *ServerRoom) AllCurrentState() (events []*gomatrixserverlib.Event) { +func (r *ServerRoom) AllCurrentState() (events []gomatrixserverlib.PDU) { r.StateMutex.RLock() for _, ev := range r.State { events = append(events, ev) @@ -105,17 +105,17 @@ func (r *ServerRoom) AllCurrentState() (events []*gomatrixserverlib.Event) { } // AuthChain returns all auth events for all events in the current state TODO: recursively -func (r *ServerRoom) AuthChain() (chain []*gomatrixserverlib.Event) { +func (r *ServerRoom) AuthChain() (chain []gomatrixserverlib.PDU) { return r.AuthChainForEvents(r.AllCurrentState()) } // AuthChainForEvents returns all auth events for all events in the given state -func (r *ServerRoom) AuthChainForEvents(events []*gomatrixserverlib.Event) (chain []*gomatrixserverlib.Event) { +func (r *ServerRoom) AuthChainForEvents(events []gomatrixserverlib.PDU) (chain []gomatrixserverlib.PDU) { chainMap := make(map[string]bool) // build a map of all events in the room // Timeline and State contain different sets of events, so check them both. - eventsByID := map[string]*gomatrixserverlib.Event{} + eventsByID := map[string]gomatrixserverlib.PDU{} r.TimelineMutex.RLock() for _, ev := range r.Timeline { eventsByID[ev.EventID()] = ev @@ -128,7 +128,7 @@ func (r *ServerRoom) AuthChainForEvents(events []*gomatrixserverlib.Event) (chai r.StateMutex.RUnlock() // a queue of events whose auth events are to be included in the auth chain - queue := []*gomatrixserverlib.Event{} + queue := []gomatrixserverlib.PDU{} queue = append(queue, events...) // get all the auth events recursively @@ -255,16 +255,10 @@ func InitialRoomEvents(roomVer gomatrixserverlib.RoomVersion, creator string) [] // EventIDsOrReferences converts a list of events into a list of EventIDs or EventReferences, // depending on the room version -func (r *ServerRoom) EventIDsOrReferences(events []*gomatrixserverlib.Event) (refs []interface{}) { +func (r *ServerRoom) EventIDsOrReferences(events []gomatrixserverlib.PDU) (refs []interface{}) { refs = make([]interface{}, len(events)) - eventFormat, _ := r.Version.EventFormat() for i, ev := range events { - switch eventFormat { - case gomatrixserverlib.EventFormatV1: - refs[i] = ev.EventReference() - default: - refs[i] = ev.EventID() - } + refs[i] = ev.EventID() } return } diff --git a/internal/must/must.go b/internal/must/must.go index d7cd9c33..4b218c00 100644 --- a/internal/must/must.go +++ b/internal/must/must.go @@ -12,7 +12,7 @@ import ( "github.com/tidwall/gjson" - "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/complement/internal/match" ) @@ -118,7 +118,7 @@ func MatchResponse(t *testing.T, res *http.Response, m match.HTTPResponse) []byt } // MatchFederationRequest performs JSON assertions on incoming federation requests. -func MatchFederationRequest(t *testing.T, fedReq *gomatrixserverlib.FederationRequest, matchers ...match.JSON) { +func MatchFederationRequest(t *testing.T, fedReq *fclient.FederationRequest, matchers ...match.JSON) { t.Helper() content := fedReq.Content() if !gjson.ValidBytes(content) { diff --git a/tests/direct_messaging_test.go b/tests/direct_messaging_test.go index 6b310a03..44b8b8af 100644 --- a/tests/direct_messaging_test.go +++ b/tests/direct_messaging_test.go @@ -11,6 +11,8 @@ import ( "github.com/matrix-org/complement/internal/federation" "github.com/matrix-org/complement/internal/match" "github.com/matrix-org/complement/internal/must" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib" "github.com/tidwall/gjson" @@ -132,13 +134,13 @@ func TestIsDirectFlagFederation(t *testing.T) { "membership": "invite", "is_direct": true, }, - }).Headered(roomVer) - inviteReq, err := gomatrixserverlib.NewInviteV2Request(dmInviteEvent, []gomatrixserverlib.InviteV2StrippedState{}) + }) + inviteReq, err := fclient.NewInviteV2Request(dmInviteEvent, []gomatrixserverlib.InviteStrippedState{}) if err != nil { t.Fatalf("failed to make invite request: %s", err) } _, since := alice.MustSync(t, client.SyncReq{}) - _, err = srv.FederationClient(deployment).SendInviteV2(context.Background(), gomatrixserverlib.ServerName(srv.ServerName()), "hs1", inviteReq) + _, err = srv.FederationClient(deployment).SendInviteV2(context.Background(), spec.ServerName(srv.ServerName()), "hs1", inviteReq) if err != nil { t.Fatalf("failed to send invite v2: %s", err) } diff --git a/tests/federation_event_auth_test.go b/tests/federation_event_auth_test.go index cbad14ea..395b131d 100644 --- a/tests/federation_event_auth_test.go +++ b/tests/federation_event_auth_test.go @@ -8,6 +8,7 @@ import ( "github.com/matrix-org/complement/internal/b" "github.com/matrix-org/complement/internal/federation" "github.com/matrix-org/complement/internal/must" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib" ) @@ -21,10 +22,10 @@ import ( // - Charlie on Complement joins the room over federation, then leaves, then rejoins // - Alice updates join rules for the room (test waits until it sees this event over federation) // At this point we can then test: -// - /event_auth for the join rules event just returns the chain for the join rules event, which -// just means it returns the auth_events as that is equal to the auth chain for this event. -// - /event_auth for the latest join event returns the complete auth chain for Charlie (all the -// joins and leaves are included), without any extraneous events. +// - /event_auth for the join rules event just returns the chain for the join rules event, which +// just means it returns the auth_events as that is equal to the auth chain for this event. +// - /event_auth for the latest join event returns the complete auth chain for Charlie (all the +// joins and leaves are included), without any extraneous events. func TestEventAuth(t *testing.T) { deployment := Deploy(t, b.BlueprintOneToOneRoom) defer deployment.Destroy(t) @@ -32,14 +33,14 @@ func TestEventAuth(t *testing.T) { alice := deployment.Client(t, "hs1", "@alice:hs1") // create a remote homeserver which will make the /event_auth request - var joinRuleEvent *gomatrixserverlib.Event + var joinRuleEvent gomatrixserverlib.PDU waiter := NewWaiter() srv := federation.NewServer(t, deployment, federation.HandleKeyRequests(), federation.HandleMakeSendJoinRequests(), federation.HandleTransactionRequests( // listen for the new join rule event - func(ev *gomatrixserverlib.Event) { + func(ev gomatrixserverlib.PDU) { if jr, _ := ev.JoinRule(); jr == "invite" { joinRuleEvent = ev waiter.Finish() @@ -77,7 +78,7 @@ func TestEventAuth(t *testing.T) { getEventAuth := func(t *testing.T, eventID string, wantAuthEventIDs []string) { t.Helper() t.Logf("/event_auth for %s - want %v", eventID, wantAuthEventIDs) - eventAuthResp, err := srv.FederationClient(deployment).GetEventAuth(context.Background(), gomatrixserverlib.ServerName(srv.ServerName()), "hs1", room.Version, roomID, eventID) + eventAuthResp, err := srv.FederationClient(deployment).GetEventAuth(context.Background(), spec.ServerName(srv.ServerName()), "hs1", room.Version, roomID, eventID) must.NotError(t, "failed to /event_auth", err) if len(eventAuthResp.AuthEvents) == 0 { t.Fatalf("/event_auth returned 0 auth events") diff --git a/tests/federation_query_profile_test.go b/tests/federation_query_profile_test.go index 91a1d102..35e07edd 100644 --- a/tests/federation_query_profile_test.go +++ b/tests/federation_query_profile_test.go @@ -6,7 +6,8 @@ import ( "net/http" "testing" - "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/complement/internal/b" "github.com/matrix-org/complement/internal/client" @@ -79,11 +80,11 @@ func TestInboundFederationProfile(t *testing.T) { ) cancel := srv.Listen() defer cancel() - origin := gomatrixserverlib.ServerName(srv.ServerName()) + origin := spec.ServerName(srv.ServerName()) // sytest: Non-numeric ports in server names are rejected t.Run("Non-numeric ports in server names are rejected", func(t *testing.T) { - fedReq := gomatrixserverlib.NewFederationRequest( + fedReq := fclient.NewFederationRequest( "GET", origin, "hs1", @@ -114,7 +115,7 @@ func TestInboundFederationProfile(t *testing.T) { }), ) - fedReq := gomatrixserverlib.NewFederationRequest( + fedReq := fclient.NewFederationRequest( "GET", origin, "hs1", diff --git a/tests/federation_redaction_test.go b/tests/federation_redaction_test.go index 22765d76..ef9a89a6 100644 --- a/tests/federation_redaction_test.go +++ b/tests/federation_redaction_test.go @@ -27,7 +27,7 @@ func TestFederationRedactSendsWithoutEvent(t *testing.T) { federation.HandleMakeSendJoinRequests(), federation.HandleTransactionRequests( // listen for PDU events in transactions - func(ev *gomatrixserverlib.Event) { + func(ev gomatrixserverlib.PDU) { defer waiter.Finish() if ev.Type() != wantEventType { diff --git a/tests/federation_room_event_auth_test.go b/tests/federation_room_event_auth_test.go index 0292f411..b469edc8 100644 --- a/tests/federation_room_event_auth_test.go +++ b/tests/federation_room_event_auth_test.go @@ -13,6 +13,8 @@ import ( "github.com/gorilla/mux" "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/tidwall/gjson" "github.com/matrix-org/complement/internal/b" @@ -87,7 +89,7 @@ func TestInboundFederationRejectsEventsWithRejectedAuthEvents(t *testing.T) { /* Create a handler for /event_auth */ // a map from event ID to events to be returned by /event_auth - eventAuthMap := make(map[string][]*gomatrixserverlib.Event) + eventAuthMap := make(map[string][]gomatrixserverlib.PDU) srv.Mux().HandleFunc("/_matrix/federation/v1/event_auth/{roomID}/{eventID}", func(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) eventID := vars["eventID"] @@ -98,7 +100,7 @@ func TestInboundFederationRejectsEventsWithRejectedAuthEvents(t *testing.T) { _, _ = w.Write([]byte("{}")) return } - res := gomatrixserverlib.RespEventAuth{AuthEvents: gomatrixserverlib.NewEventJSONsFromEvents(authEvents)} + res := fclient.RespEventAuth{AuthEvents: gomatrixserverlib.NewEventJSONsFromEvents(authEvents)} responseBytes, _ := json.Marshal(&res) w.WriteHeader(200) _, _ = w.Write(responseBytes) @@ -126,9 +128,9 @@ func TestInboundFederationRejectsEventsWithRejectedAuthEvents(t *testing.T) { }) _, err := fedClient.SendTransaction(context.Background(), gomatrixserverlib.Transaction{ TransactionID: "complement1", - Origin: gomatrixserverlib.ServerName(srv.ServerName()), + Origin: spec.ServerName(srv.ServerName()), Destination: "hs1", - OriginServerTS: gomatrixserverlib.AsTimestamp(time.Now()), + OriginServerTS: spec.AsTimestamp(time.Now()), PDUs: []json.RawMessage{ rejectedEvent.JSON(), }, @@ -157,7 +159,7 @@ func TestInboundFederationRejectsEventsWithRejectedAuthEvents(t *testing.T) { // create a regular event which refers to the outlier event in its auth events, // so that the outlier gets pulled in. - sentEventAuthEvents := []*gomatrixserverlib.Event{ + sentEventAuthEvents := []gomatrixserverlib.PDU{ room.CurrentState("m.room.create", ""), room.CurrentState("m.room.join_rules", ""), room.CurrentState("m.room.power_levels", ""), @@ -197,9 +199,9 @@ func TestInboundFederationRejectsEventsWithRejectedAuthEvents(t *testing.T) { _, err = fedClient.SendTransaction(context.Background(), gomatrixserverlib.Transaction{ TransactionID: "complement2", - Origin: gomatrixserverlib.ServerName(srv.ServerName()), + Origin: spec.ServerName(srv.ServerName()), Destination: "hs1", - OriginServerTS: gomatrixserverlib.AsTimestamp(time.Now()), + OriginServerTS: spec.AsTimestamp(time.Now()), PDUs: []json.RawMessage{ sentEvent1.JSON(), sentEvent2.JSON(), diff --git a/tests/federation_room_get_missing_events_test.go b/tests/federation_room_get_missing_events_test.go index 1aeeb791..0c74ee92 100644 --- a/tests/federation_room_get_missing_events_test.go +++ b/tests/federation_room_get_missing_events_test.go @@ -9,6 +9,8 @@ import ( "time" "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/util" "github.com/tidwall/gjson" @@ -96,7 +98,7 @@ func TestGetMissingEventsGapFilling(t *testing.T) { // 4) Respond to /get_missing_events with the missing events if the request is well-formed. srv.Mux().HandleFunc( "/_matrix/federation/v1/get_missing_events/{roomID}", - srv.ValidFederationRequest(t, func(fr *gomatrixserverlib.FederationRequest, pathParams map[string]string) util.JSONResponse { + srv.ValidFederationRequest(t, func(fr *fclient.FederationRequest, pathParams map[string]string) util.JSONResponse { if pathParams["roomID"] != roomID { t.Errorf("Received /get_missing_events for the wrong room: %s", roomID) return util.JSONResponse{ @@ -205,8 +207,9 @@ func TestOutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6(t *test if err != nil { t.Fatalf("failed to marshal badEvent content %+v", badEvent.Content) } - eb := gomatrixserverlib.EventBuilder{ - Sender: badEvent.Sender, + + proto := gomatrixserverlib.ProtoEvent{ + SenderID: badEvent.Sender, Depth: int64(room.Depth + 1), // depth starts at 1 Type: badEvent.Type, StateKey: badEvent.StateKey, @@ -214,13 +217,20 @@ func TestOutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6(t *test RoomID: room.RoomID, PrevEvents: room.ForwardExtremities, } - stateNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(&eb) + var stateNeeded gomatrixserverlib.StateNeeded + stateNeeded, err = gomatrixserverlib.StateNeededForProtoEvent(&proto) if err != nil { - t.Fatalf("failed to work out auth_events : %s", err) + t.Fatalf("failed to create event: failed to work out auth_events : %s", err) } - eb.AuthEvents = room.AuthEvents(stateNeeded) + proto.AuthEvents = room.AuthEvents(stateNeeded) + // we have to create this event as a v5 event which doesn't assert floats yet - signedBadEvent, err := eb.Build(time.Now(), gomatrixserverlib.ServerName(srv.ServerName()), srv.KeyID, srv.Priv, gomatrixserverlib.RoomVersionV5) + verImpl, err := gomatrixserverlib.GetRoomVersion(gomatrixserverlib.RoomVersionV5) + if err != nil { + t.Fatalf("failed to create event: invalid room version: %s", err) + } + eb := verImpl.NewEventBuilderFromProtoEvent(&proto) + signedBadEvent, err := eb.Build(time.Now(), spec.ServerName(srv.ServerName()), srv.KeyID, srv.Priv) if err != nil { t.Fatalf("failed to sign event: %s", err) } @@ -248,9 +258,9 @@ func TestOutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6(t *test // return the bad event, which should result in the transaction failing. w.WriteHeader(200) res := struct { - Events []*gomatrixserverlib.Event `json:"events"` + Events []gomatrixserverlib.PDU `json:"events"` }{ - Events: []*gomatrixserverlib.Event{signedBadEvent}, + Events: []gomatrixserverlib.PDU{signedBadEvent}, } var responseBytes []byte responseBytes, err = json.Marshal(&res) @@ -261,8 +271,8 @@ func TestOutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6(t *test fedClient := srv.FederationClient(deployment) resp, err := fedClient.SendTransaction(context.Background(), gomatrixserverlib.Transaction{ TransactionID: "wut", - Origin: gomatrixserverlib.ServerName(srv.ServerName()), - Destination: gomatrixserverlib.ServerName("hs1"), + Origin: spec.ServerName(srv.ServerName()), + Destination: spec.ServerName("hs1"), PDUs: []json.RawMessage{ sentEvent.JSON(), }, @@ -307,8 +317,8 @@ func TestOutboundFederationIgnoresMissingEventWithBadJSONForRoomVersion6(t *test resp, err = fedClient.SendTransaction(context.Background(), gomatrixserverlib.Transaction{ TransactionID: "t2", - Origin: gomatrixserverlib.ServerName(srv.ServerName()), - Destination: gomatrixserverlib.ServerName("hs1"), + Origin: spec.ServerName(srv.ServerName()), + Destination: spec.ServerName("hs1"), PDUs: []json.RawMessage{ message3.JSON(), }, @@ -350,7 +360,7 @@ func TestInboundCanReturnMissingEvents(t *testing.T) { stateKey := "" // Set the history visibility for this room alice.SendEventSynced(t, roomID, b.Event{ - Type: gomatrixserverlib.MRoomHistoryVisibility, + Type: spec.MRoomHistoryVisibility, Content: map[string]interface{}{ "history_visibility": visibility, }, @@ -369,9 +379,9 @@ func TestInboundCanReturnMissingEvents(t *testing.T) { room := srv.MustJoinRoom(t, deployment, "hs1", roomID, charlie) alice.MustSyncUntil(t, client.SyncReq{}, client.SyncJoinedTo(charlie, roomID)) - req := gomatrixserverlib.NewFederationRequest( + req := fclient.NewFederationRequest( "POST", - gomatrixserverlib.ServerName(srv.ServerName()), + spec.ServerName(srv.ServerName()), "hs1", fmt.Sprintf("/_matrix/federation/v1/get_missing_events/%s", roomID), ) @@ -390,7 +400,7 @@ func TestInboundCanReturnMissingEvents(t *testing.T) { }) must.NotError(t, "failed to set content", err) - result := gomatrixserverlib.RespMissingEvents{} + result := fclient.RespMissingEvents{} err = srv.SendFederationRequest(context.Background(), t, deployment, req, &result) must.NotError(t, "get_missing_events failed", err) if len(result.Events) == 0 { @@ -406,7 +416,7 @@ func TestInboundCanReturnMissingEvents(t *testing.T) { // * the message events := result.Events.UntrustedEvents(roomVersion) - verifyMsgEvent := func(ev *gomatrixserverlib.Event) { + verifyMsgEvent := func(ev gomatrixserverlib.PDU) { must.EqualStr(t, ev.Type(), "m.room.message", "not a message event") // if the history vis is 'joined' or 'invite', we should get redacted // copies of the events before we joined. @@ -424,20 +434,20 @@ func TestInboundCanReturnMissingEvents(t *testing.T) { } for i, ev := range events { - must.EqualStr(t, ev.RoomID(), roomID, "unexpected roomID") + must.EqualStr(t, ev.RoomID().String(), roomID, "unexpected roomID") switch i { case 0: must.EqualStr(t, ev.Type(), "m.room.member", "not a membership event") must.EqualStr(t, *ev.StateKey(), alice.UserID, "unexpected creator") case 1: - must.EqualStr(t, ev.Type(), gomatrixserverlib.MRoomPowerLevels, "not a powerlevel event") + must.EqualStr(t, ev.Type(), spec.MRoomPowerLevels, "not a powerlevel event") case 2: - must.EqualStr(t, ev.Type(), gomatrixserverlib.MRoomJoinRules, "not a join_rules event") + must.EqualStr(t, ev.Type(), spec.MRoomJoinRules, "not a join_rules event") case 3: - must.EqualStr(t, ev.Type(), gomatrixserverlib.MRoomHistoryVisibility, "not a history_visiblity event") + must.EqualStr(t, ev.Type(), spec.MRoomHistoryVisibility, "not a history_visiblity event") case 4: if visibility != gomatrixserverlib.HistoryVisibilityShared { // shared -> shared no-ops - must.EqualStr(t, ev.Type(), gomatrixserverlib.MRoomHistoryVisibility, "not a history_visiblity event") + must.EqualStr(t, ev.Type(), spec.MRoomHistoryVisibility, "not a history_visiblity event") } else { verifyMsgEvent(ev) } diff --git a/tests/federation_room_invite_test.go b/tests/federation_room_invite_test.go index a66f7b8c..b277480d 100644 --- a/tests/federation_room_invite_test.go +++ b/tests/federation_room_invite_test.go @@ -15,7 +15,6 @@ import ( // We start with two users in a room - alice@hs1, and 'delia' on the Complement test server. // alice sends an invite to charlie@hs2, which he rejects. // We check that delia sees the rejection. -// func TestFederationRejectInvite(t *testing.T) { deployment := Deploy(t, b.BlueprintFederationTwoLocalOneRemote) defer deployment.Destroy(t) @@ -27,7 +26,7 @@ func TestFederationRejectInvite(t *testing.T) { srv := federation.NewServer(t, deployment, federation.HandleKeyRequests(), - federation.HandleTransactionRequests(func(ev *gomatrixserverlib.Event) { + federation.HandleTransactionRequests(func(ev gomatrixserverlib.PDU) { sk := "" if ev.StateKey() != nil { sk = *ev.StateKey() diff --git a/tests/federation_room_join_partial_state_test.go b/tests/federation_room_join_partial_state_test.go index 0562cea7..c3cbd36d 100644 --- a/tests/federation_room_join_partial_state_test.go +++ b/tests/federation_room_join_partial_state_test.go @@ -10,7 +10,6 @@ import ( "context" "encoding/json" "fmt" - "github.com/matrix-org/complement/runtime" "io/ioutil" "net" "net/http" @@ -21,11 +20,15 @@ import ( "testing" "time" + "github.com/matrix-org/complement/runtime" + "github.com/gorilla/mux" "github.com/tidwall/gjson" "github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/complement/internal/b" "github.com/matrix-org/complement/internal/client" @@ -38,7 +41,7 @@ import ( type server struct { *federation.Server - pduHandlers map[int]func(*gomatrixserverlib.Event) bool + pduHandlers map[int]func(gomatrixserverlib.PDU) bool eduHandlers map[int]func(gomatrixserverlib.EDU) bool nextPDUHandlerKey int @@ -53,7 +56,7 @@ func createTestServer(t *testing.T, deployment *docker.Deployment, opts ...func( t.Helper() server := &server{ - pduHandlers: map[int]func(*gomatrixserverlib.Event) bool{}, + pduHandlers: map[int]func(gomatrixserverlib.PDU) bool{}, eduHandlers: map[int]func(gomatrixserverlib.EDU) bool{}, nextPDUHandlerKey: 0, nextEDUHandlerKey: 0, @@ -65,7 +68,7 @@ func createTestServer(t *testing.T, deployment *docker.Deployment, opts ...func( federation.HandlePartialStateMakeSendJoinRequests(), federation.HandleEventRequests(), federation.HandleTransactionRequests( - func(e *gomatrixserverlib.Event) { + func(e gomatrixserverlib.PDU) { expected := false for _, pduHandler := range server.pduHandlers { expected = pduHandler(e) || expected @@ -98,7 +101,7 @@ func createTestServer(t *testing.T, deployment *docker.Deployment, opts ...func( // AddPDUHandler adds a PDU callback that returns `true` if it expected the given PDU. // When a PDU is received which is not expected by any PDU callback, the ongoing test is failed. // Returns a function to remove the PDU callback. -func (s *server) AddPDUHandler(pduHandler func(*gomatrixserverlib.Event) bool) func() { +func (s *server) AddPDUHandler(pduHandler func(gomatrixserverlib.PDU) bool) func() { pduHandlerKey := s.nextPDUHandlerKey s.nextPDUHandlerKey++ s.pduHandlers[pduHandlerKey] = pduHandler @@ -125,9 +128,9 @@ func (s *server) AddEDUHandler(eduHandler func(gomatrixserverlib.EDU) bool) func func (s *server) WithWaitForLeave( t *testing.T, room *federation.ServerRoom, userID string, leaveAction func(), ) { - leaveChannel := make(chan *gomatrixserverlib.Event, 10) + leaveChannel := make(chan gomatrixserverlib.PDU, 10) removePDUHandler := s.AddPDUHandler( - func(e *gomatrixserverlib.Event) bool { + func(e gomatrixserverlib.PDU) bool { if membership, _ := e.Membership(); e.Type() == "m.room.member" && *e.StateKey() == userID && membership == "leave" { @@ -164,7 +167,7 @@ func TestPartialStateJoin(t *testing.T) { createMembershipEvent := func( t *testing.T, signingServer *server, room *federation.ServerRoom, userId string, membership string, - ) *gomatrixserverlib.Event { + ) gomatrixserverlib.PDU { t.Helper() return signingServer.MustCreateEvent(t, room, b.Event{ @@ -180,7 +183,7 @@ func TestPartialStateJoin(t *testing.T) { // createJoinEvent creates a join event for the given user createJoinEvent := func( t *testing.T, signingServer *server, room *federation.ServerRoom, userId string, - ) *gomatrixserverlib.Event { + ) gomatrixserverlib.PDU { t.Helper() return createMembershipEvent(t, signingServer, room, userId, "join") @@ -189,7 +192,7 @@ func TestPartialStateJoin(t *testing.T) { // createLeaveEvent creates a leave event for the given user createLeaveEvent := func( t *testing.T, signingServer *server, room *federation.ServerRoom, userId string, - ) *gomatrixserverlib.Event { + ) gomatrixserverlib.PDU { t.Helper() return createMembershipEvent(t, signingServer, room, userId, "leave") @@ -300,7 +303,7 @@ func TestPartialStateJoin(t *testing.T) { ) t.Log("4. Have Alice send a message to the remote room.") - removePDUHandler := server.AddPDUHandler(func(*gomatrixserverlib.Event) bool { return true }) + removePDUHandler := server.AddPDUHandler(func(gomatrixserverlib.PDU) bool { return true }) defer removePDUHandler() messageId := alice.SendEventUnsynced(t, serverRoom.RoomID, b.Event{ Type: "m.room.message", @@ -463,9 +466,9 @@ func TestPartialStateJoin(t *testing.T) { psjResult := beginPartialStateJoin(t, server, serverRoom, alice) defer psjResult.Destroy(t) - pdusChannel := make(chan *gomatrixserverlib.Event) + pdusChannel := make(chan gomatrixserverlib.PDU) removePDUHandler := server.AddPDUHandler( - func(e *gomatrixserverlib.Event) bool { + func(e gomatrixserverlib.PDU) bool { pdusChannel <- e return true @@ -858,7 +861,7 @@ func TestPartialStateJoin(t *testing.T) { // the HS will make a /get_missing_events request for the missing prev events of event B handleGetMissingEventsRequests(t, server, serverRoom, - []string{eventB.EventID()}, []*gomatrixserverlib.Event{eventA}) + []string{eventB.EventID()}, []gomatrixserverlib.PDU{eventA}) // send event B to hs1 testReceiveEventDuringPartialStateJoin(t, deployment, alice, psjResult, eventB, syncToken) @@ -898,7 +901,7 @@ func TestPartialStateJoin(t *testing.T) { // the HS will make a /get_missing_events request for the missing prev event of event B handleGetMissingEventsRequests(t, server, serverRoom, - []string{eventB.EventID()}, []*gomatrixserverlib.Event{eventA}) + []string{eventB.EventID()}, []gomatrixserverlib.PDU{eventA}) // send event B to hs1 testReceiveEventDuringPartialStateJoin(t, deployment, alice, psjResult, eventB, syncToken) @@ -939,7 +942,7 @@ func TestPartialStateJoin(t *testing.T) { // the HS will make a /get_missing_events request for the missing prev event of event C, // to which we respond with event B only. handleGetMissingEventsRequests(t, server, serverRoom, - []string{eventC.EventID()}, []*gomatrixserverlib.Event{eventB}) + []string{eventC.EventID()}, []gomatrixserverlib.PDU{eventB}) // dedicated state_ids and state handlers for event A handleStateIdsRequests(t, server, serverRoom, eventA.EventID(), serverRoom.AllCurrentState(), nil, nil) @@ -981,10 +984,10 @@ func TestPartialStateJoin(t *testing.T) { ) err := client.SyncStateHas(serverRoom.RoomID, func(ev gjson.Result) bool { - return ev.Get("type").Str == "m.room.member" && ev.Get("state_key").Str == event.Sender() + return ev.Get("type").Str == "m.room.member" && ev.Get("state_key").Str == string(event.SenderID()) })(alice.UserID, syncRes) if err != nil { - t.Errorf("Did not find %s's m.room.member event in lazy-loading /sync response: %s", event.Sender(), err) + t.Errorf("Did not find %s's m.room.member event in lazy-loading /sync response: %s", event.SenderID(), err) } }) @@ -1051,10 +1054,10 @@ func TestPartialStateJoin(t *testing.T) { } err = client.SyncStateHas(serverRoom.RoomID, func(ev gjson.Result) bool { - return ev.Get("type").Str == "m.room.member" && ev.Get("state_key").Str == event2.Sender() + return ev.Get("type").Str == "m.room.member" && ev.Get("state_key").Str == string(event2.SenderID()) })(alice.UserID, syncRes) if err != nil { - t.Errorf("Did not find %s's m.room.member event in lazy-loading /sync response: %s", event2.Sender(), err) + t.Errorf("Did not find %s's m.room.member event in lazy-loading /sync response: %s", event2.SenderID(), err) } }) @@ -1099,10 +1102,10 @@ func TestPartialStateJoin(t *testing.T) { ) err := client.SyncStateHas(serverRoom.RoomID, func(ev gjson.Result) bool { - return ev.Get("type").Str == "m.room.member" && ev.Get("state_key").Str == event.Sender() + return ev.Get("type").Str == "m.room.member" && ev.Get("state_key").Str == string(event.SenderID()) })(alice.UserID, syncRes) if err != nil { - t.Errorf("Did not find %s's m.room.member event in lazy-loading /sync response: %s", event.Sender(), err) + t.Errorf("Did not find %s's m.room.member event in lazy-loading /sync response: %s", event.SenderID(), err) } }) @@ -1409,7 +1412,7 @@ func TestPartialStateJoin(t *testing.T) { // next, we want to create 100 outliers. So, charlie creates 100 state events, and // then persuades the system under test to create a backwards extremity using those events as // part of the room state. - outliers := make([]*gomatrixserverlib.Event, 100) + outliers := make([]gomatrixserverlib.PDU, 100) outlierEventIDs := make([]string, len(outliers)) for i := range outliers { body := fmt.Sprintf("outlier event %d", i) @@ -1432,7 +1435,7 @@ func TestPartialStateJoin(t *testing.T) { // dedicated get_missing_event handler for timelineEvent2. // we grudgingly return a single event. handleGetMissingEventsRequests(t, server, serverRoom, - []string{timelineEvent2.EventID()}, []*gomatrixserverlib.Event{timelineEvent1}, + []string{timelineEvent2.EventID()}, []gomatrixserverlib.PDU{timelineEvent1}, ) // dedicated state_ids and state handlers for timelineEvent1's prev event (ie, the last outlier event) @@ -1612,7 +1615,7 @@ func TestPartialStateJoin(t *testing.T) { Content: map[string]interface{}{ "body": "bad state event", }, - AuthEvents: serverRoom.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: serverRoom.EventIDsOrReferences([]gomatrixserverlib.PDU{ serverRoom.CurrentState("m.room.create", ""), serverRoom.CurrentState("m.room.power_levels", ""), derekJoinEvent, @@ -1693,7 +1696,7 @@ func TestPartialStateJoin(t *testing.T) { StateKey: &elsie, Sender: derek, Content: map[string]interface{}{"membership": "leave"}, - AuthEvents: serverRoom.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: serverRoom.EventIDsOrReferences([]gomatrixserverlib.PDU{ serverRoom.CurrentState("m.room.create", ""), serverRoom.CurrentState("m.room.power_levels", ""), derekJoinEvent, @@ -1713,7 +1716,7 @@ func TestPartialStateJoin(t *testing.T) { StateKey: b.Ptr(""), Sender: elsie, Content: map[string]interface{}{"body": "rejected state"}, - AuthEvents: serverRoom.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: serverRoom.EventIDsOrReferences([]gomatrixserverlib.PDU{ serverRoom.CurrentState("m.room.create", ""), serverRoom.CurrentState("m.room.power_levels", ""), elsieJoinEvent, @@ -1793,7 +1796,7 @@ func TestPartialStateJoin(t *testing.T) { fedClient2 := testServer2.FederationClient(deployment) // charlie sends a make_join - _, err := fedClient2.MakeJoin(context.Background(), gomatrixserverlib.ServerName(testServer2.ServerName()), "hs1", roomID, testServer2.UserID("charlie"), federation.SupportedRoomVersions()) + _, err := fedClient2.MakeJoin(context.Background(), spec.ServerName(testServer2.ServerName()), "hs1", roomID, testServer2.UserID("charlie")) if err == nil { t.Errorf("MakeJoin returned 200, want 404") @@ -1855,12 +1858,17 @@ func TestPartialStateJoin(t *testing.T) { } // daniel then tries to /send_join via the homeserver under test - joinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), gomatrixserverlib.ServerName(testServer2.ServerName()), testServer2.KeyID, testServer2.Priv, makeJoinResp.RoomVersion) + verImpl, err := gomatrixserverlib.GetRoomVersion(serverRoom.Version) + if err != nil { + t.Fatalf("MakeRespMakeJoin: invalid room version: %s", err) + } + eb := verImpl.NewEventBuilderFromProtoEvent(&makeJoinResp.JoinEvent) + joinEvent, err := eb.Build(time.Now(), spec.ServerName(testServer2.ServerName()), testServer2.KeyID, testServer2.Priv) must.NotError(t, "JoinEvent.Build", err) // SendJoin should return a 404 because the homeserver under test has not // finished its partial join. - _, err = fedClient2.SendJoin(context.Background(), gomatrixserverlib.ServerName(testServer2.ServerName()), "hs1", joinEvent) + _, err = fedClient2.SendJoin(context.Background(), spec.ServerName(testServer2.ServerName()), "hs1", joinEvent) if err == nil { t.Errorf("SendJoin returned 200, want 404") } else if httpError, ok := err.(gomatrix.HTTPError); ok { @@ -1966,7 +1974,7 @@ func TestPartialStateJoin(t *testing.T) { fedClient2 := testServer2.FederationClient(deployment) // charlie sends a make_knock - _, err := fedClient2.MakeKnock(context.Background(), gomatrixserverlib.ServerName(testServer2.ServerName()), "hs1", roomID, testServer2.UserID("charlie"), federation.SupportedRoomVersions()) + _, err := fedClient2.MakeKnock(context.Background(), spec.ServerName(testServer2.ServerName()), "hs1", roomID, testServer2.UserID("charlie"), federation.SupportedRoomVersions()) if err == nil { t.Errorf("MakeKnock returned 200, want 404") @@ -2028,12 +2036,17 @@ func TestPartialStateJoin(t *testing.T) { } // daniel then tries to /send_knock via the homeserver under test - knockEvent, err := makeKnockResp.KnockEvent.Build(time.Now(), gomatrixserverlib.ServerName(testServer2.ServerName()), testServer2.KeyID, testServer2.Priv, makeKnockResp.RoomVersion) + verImpl, err := gomatrixserverlib.GetRoomVersion(serverRoom.Version) + if err != nil { + t.Fatalf("MakeRespMakeJoin: invalid room version: %s", err) + } + eb := verImpl.NewEventBuilderFromProtoEvent(&makeKnockResp.KnockEvent) + knockEvent, err := eb.Build(time.Now(), spec.ServerName(testServer2.ServerName()), testServer2.KeyID, testServer2.Priv) must.NotError(t, "KnockEvent.Build", err) // SendKnock should return a 404 because the homeserver under test has not // finished its partial join. - _, err = fedClient2.SendKnock(context.Background(), gomatrixserverlib.ServerName(testServer2.ServerName()), "hs1", knockEvent) + _, err = fedClient2.SendKnock(context.Background(), spec.ServerName(testServer2.ServerName()), "hs1", knockEvent) if err == nil { t.Errorf("SendKnock returned 200, want 404") } else if httpError, ok := err.(gomatrix.HTTPError); ok { @@ -2173,7 +2186,7 @@ func TestPartialStateJoin(t *testing.T) { server2Room := server2.MustJoinRoom( t, deployment, - gomatrixserverlib.ServerName(server1.ServerName()), + spec.ServerName(server1.ServerName()), room.RoomID, server2.UserID("elsie"), true, @@ -2221,7 +2234,7 @@ func TestPartialStateJoin(t *testing.T) { server2Room := server2.MustJoinRoom( t, deployment, - gomatrixserverlib.ServerName(server1.ServerName()), + spec.ServerName(server1.ServerName()), room.RoomID, server2.UserID("elsie"), true, @@ -2263,7 +2276,7 @@ func TestPartialStateJoin(t *testing.T) { server2.MustJoinRoom( t, deployment, - gomatrixserverlib.ServerName(server1.ServerName()), + spec.ServerName(server1.ServerName()), room.RoomID, server2.UserID("elsie"), true, @@ -2337,7 +2350,7 @@ func TestPartialStateJoin(t *testing.T) { server2Room = server2.MustJoinRoom( t, deployment, - gomatrixserverlib.ServerName(server1.ServerName()), + spec.ServerName(server1.ServerName()), room.RoomID, elsie, true, @@ -2358,7 +2371,7 @@ func TestPartialStateJoin(t *testing.T) { StateKey: b.Ptr(elsie), Sender: derek, Content: map[string]interface{}{"membership": "leave"}, - AuthEvents: room.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: room.EventIDsOrReferences([]gomatrixserverlib.PDU{ room.CurrentState("m.room.create", ""), room.CurrentState("m.room.power_levels", ""), derekJoinEvent, @@ -2519,7 +2532,7 @@ func TestPartialStateJoin(t *testing.T) { server2Room := server2.MustJoinRoom( t, deployment, - gomatrixserverlib.ServerName(server1.ServerName()), + spec.ServerName(server1.ServerName()), room.RoomID, server2.UserID("elsie"), true, @@ -2550,7 +2563,7 @@ func TestPartialStateJoin(t *testing.T) { server2.MustJoinRoom( t, deployment, - gomatrixserverlib.ServerName(server1.ServerName()), + spec.ServerName(server1.ServerName()), room.RoomID, server2.UserID("elsie"), true, @@ -2591,17 +2604,17 @@ func TestPartialStateJoin(t *testing.T) { makeRespUserDeviceKeys := func( userID string, deviceID string, - ) gomatrixserverlib.RespUserDeviceKeys { - return gomatrixserverlib.RespUserDeviceKeys{ + ) fclient.RespUserDeviceKeys { + return fclient.RespUserDeviceKeys{ UserID: userID, DeviceID: deviceID, Algorithms: []string{ "m.megolm.v1.aes-sha2", }, - Keys: map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{ + Keys: map[gomatrixserverlib.KeyID]spec.Base64Bytes{ "ed25519:JLAFKJWSCS": []byte("lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI"), }, - Signatures: map[string]map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{ + Signatures: map[string]map[gomatrixserverlib.KeyID]spec.Base64Bytes{ userID: { "ed25519:JLAFKJWSCS": []byte("dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/a+myXS367WT6NAIcBA"), }, @@ -2624,10 +2637,10 @@ func TestPartialStateJoin(t *testing.T) { userDevicesQueryChannel <- userID // Make up a device list for the user. - responseBytes, _ := json.Marshal(gomatrixserverlib.RespUserDevices{ + responseBytes, _ := json.Marshal(fclient.RespUserDevices{ UserID: userID, StreamID: lastDeviceStreamID, - Devices: []gomatrixserverlib.RespUserDevice{ + Devices: []fclient.RespUserDevice{ { DeviceID: deviceID, DisplayName: fmt.Sprintf("%s's device", userID), @@ -2658,19 +2671,19 @@ func TestPartialStateJoin(t *testing.T) { } // Make up keys for every device requested. - deviceKeys := make(map[string]map[string]gomatrixserverlib.DeviceKeys) + deviceKeys := make(map[string]map[string]fclient.DeviceKeys) for userID := range queryKeysRequest.DeviceKeys { userDevicesQueryChannel <- userID deviceID := fmt.Sprintf("%s_device", userID) - deviceKeys[userID] = map[string]gomatrixserverlib.DeviceKeys{ + deviceKeys[userID] = map[string]fclient.DeviceKeys{ deviceID: { RespUserDeviceKeys: makeRespUserDeviceKeys(userID, deviceID), }, } } - responseBytes, _ := json.Marshal(gomatrixserverlib.RespQueryKeys{ + responseBytes, _ := json.Marshal(fclient.RespQueryKeys{ DeviceKeys: deviceKeys, }) w.WriteHeader(200) @@ -3160,7 +3173,7 @@ func TestPartialStateJoin(t *testing.T) { StateKey: b.Ptr(derek), Sender: fred, Content: map[string]interface{}{"membership": "ban"}, - AuthEvents: room.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: room.EventIDsOrReferences([]gomatrixserverlib.PDU{ room.CurrentState("m.room.create", ""), room.CurrentState("m.room.power_levels", ""), fredJoinEvent, @@ -3473,7 +3486,7 @@ func TestPartialStateJoin(t *testing.T) { psjResult := beginPartialStateJoin(t, server, serverRoom, alice) defer psjResult.Destroy(t) - server.AddPDUHandler(func(e *gomatrixserverlib.Event) bool { return true }) + server.AddPDUHandler(func(e gomatrixserverlib.PDU) bool { return true }) bob.JoinRoom(t, serverRoom.RoomID, []string{server.ServerName()}) alice.MustSyncUntil(t, client.SyncReq{ @@ -3505,9 +3518,9 @@ func TestPartialStateJoin(t *testing.T) { psjResult := beginPartialStateJoin(t, server, serverRoom, alice) defer psjResult.Destroy(t) - pdusChannel := make(chan *gomatrixserverlib.Event) + pdusChannel := make(chan gomatrixserverlib.PDU) removePDUHandler := server.AddPDUHandler( - func(e *gomatrixserverlib.Event) bool { + func(e gomatrixserverlib.PDU) bool { pdusChannel <- e return true @@ -3562,7 +3575,7 @@ func TestPartialStateJoin(t *testing.T) { leaveCompleted := NewWaiter() t.Log("Alice starts a leave request") - server.AddPDUHandler(func(e *gomatrixserverlib.Event) bool { return true }) + server.AddPDUHandler(func(e gomatrixserverlib.PDU) bool { return true }) go func() { alice.LeaveRoom(t, serverRoom.RoomID) t.Log("Alice's leave request completed") @@ -3605,9 +3618,9 @@ func TestPartialStateJoin(t *testing.T) { // Prepare to listen for leave events from the HS under test. // We're only expecting one leave event, but give the channel extra capacity // to avoid deadlock if the HS does something silly. - leavesChannel := make(chan *gomatrixserverlib.Event, 10) + leavesChannel := make(chan gomatrixserverlib.PDU, 10) server.AddPDUHandler( - func(e *gomatrixserverlib.Event) bool { + func(e gomatrixserverlib.PDU) bool { if e.Type() == "m.room.member" { if ok := gjson.ValidBytes(e.Content()); !ok { t.Fatalf("Received event %s with invalid content: %v", e.EventID(), e.Content()) @@ -3634,8 +3647,8 @@ func TestPartialStateJoin(t *testing.T) { case <-time.After(1 * time.Second): t.Fatal("Resident server did not receive Alice's leave") case e := <-leavesChannel: - if e.Sender() != alice.UserID { - t.Errorf("Unexpected leave event %s for %s", e.EventID(), e.Sender()) + if string(e.SenderID()) != alice.UserID { + t.Errorf("Unexpected leave event %s for %s", e.EventID(), e.SenderID()) } } }) @@ -3674,7 +3687,7 @@ func TestPartialStateJoin(t *testing.T) { ) t.Log("Alice leaves the room") - server.AddPDUHandler(func(e *gomatrixserverlib.Event) bool { return true }) + server.AddPDUHandler(func(e gomatrixserverlib.PDU) bool { return true }) alice.LeaveRoom(t, serverRoom.RoomID) t.Log("Alice sees Alice's leave") @@ -3711,7 +3724,7 @@ func TestPartialStateJoin(t *testing.T) { ) t.Log("Alice leaves the room") - server.AddPDUHandler(func(e *gomatrixserverlib.Event) bool { return true }) + server.AddPDUHandler(func(e gomatrixserverlib.PDU) bool { return true }) alice.LeaveRoom(t, serverRoom.RoomID) t.Log("Alice sees Alice's leave") @@ -3755,7 +3768,7 @@ func TestPartialStateJoin(t *testing.T) { ) t.Log("Alice leaves the room") - server.AddPDUHandler(func(e *gomatrixserverlib.Event) bool { return true }) + server.AddPDUHandler(func(e gomatrixserverlib.PDU) bool { return true }) alice.LeaveRoom(t, serverRoom.RoomID) t.Log("Alice sees Alice's leave") @@ -3801,7 +3814,7 @@ func TestPartialStateJoin(t *testing.T) { StateKey: b.Ptr(alice.UserID), Sender: server.UserID("charlie"), Content: map[string]interface{}{"membership": "leave"}, - AuthEvents: serverRoom.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: serverRoom.EventIDsOrReferences([]gomatrixserverlib.PDU{ serverRoom.CurrentState("m.room.create", ""), serverRoom.CurrentState("m.room.power_levels", ""), serverRoom.CurrentState("m.room.member", alice.UserID), @@ -3853,7 +3866,7 @@ func TestPartialStateJoin(t *testing.T) { StateKey: b.Ptr(alice.UserID), Sender: server.UserID("charlie"), Content: map[string]interface{}{"membership": "ban"}, - AuthEvents: serverRoom.EventIDsOrReferences([]*gomatrixserverlib.Event{ + AuthEvents: serverRoom.EventIDsOrReferences([]gomatrixserverlib.PDU{ serverRoom.CurrentState("m.room.create", ""), serverRoom.CurrentState("m.room.power_levels", ""), serverRoom.CurrentState("m.room.member", alice.UserID), @@ -4038,7 +4051,7 @@ func TestPartialStateJoin(t *testing.T) { t.Log("Alice purges that room") // Ignore PDUs (leaves from shutting down the room). - server.AddPDUHandler(func(e *gomatrixserverlib.Event) bool { return true }) + server.AddPDUHandler(func(e gomatrixserverlib.PDU) bool { return true }) alice.MustDoFunc(t, "DELETE", []string{"_synapse", "admin", "v1", "rooms", serverRoom.RoomID}, client.WithJSONBody(t, map[string]interface{}{})) // Note: clients don't get told about purged rooms. No leave event for you! @@ -4077,7 +4090,7 @@ func TestPartialStateJoin(t *testing.T) { // sends the given event to the homeserver under test, checks that a client can see it and checks // the state at the event. returns the new sync token after the event. func testReceiveEventDuringPartialStateJoin( - t *testing.T, deployment *docker.Deployment, alice *client.CSAPI, psjResult partialStateJoinResult, event *gomatrixserverlib.Event, syncToken string, + t *testing.T, deployment *docker.Deployment, alice *client.CSAPI, psjResult partialStateJoinResult, event gomatrixserverlib.PDU, syncToken string, ) string { // send the event to the homeserver psjResult.Server.MustSendTransaction(t, deployment, "hs1", []json.RawMessage{event.JSON()}, nil) @@ -4093,13 +4106,13 @@ func testReceiveEventDuringPartialStateJoin( // is resolved. For now, we use this to check whether Synapse has calculated the partial state // flag for the last event correctly. - stateReq := gomatrixserverlib.NewFederationRequest("GET", gomatrixserverlib.ServerName(psjResult.Server.ServerName()), "hs1", + stateReq := fclient.NewFederationRequest("GET", spec.ServerName(psjResult.Server.ServerName()), "hs1", fmt.Sprintf("/_matrix/federation/v1/state_ids/%s?event_id=%s", url.PathEscape(psjResult.ServerRoom.RoomID), url.QueryEscape(event.EventID()), ), ) - var respStateIDs gomatrixserverlib.RespStateIDs + var respStateIDs fclient.RespStateIDs ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() err := psjResult.Server.SendFederationRequest(ctx, t, deployment, stateReq, &respStateIDs) @@ -4137,7 +4150,7 @@ func testReceiveEventDuringPartialStateJoin( ) // check the server's idea of the state at the event. We do this by making a `state_ids` request over federation - stateReq = gomatrixserverlib.NewFederationRequest("GET", gomatrixserverlib.ServerName(psjResult.Server.ServerName()), "hs1", + stateReq = fclient.NewFederationRequest("GET", spec.ServerName(psjResult.Server.ServerName()), "hs1", fmt.Sprintf("/_matrix/federation/v1/state_ids/%s?event_id=%s", url.PathEscape(psjResult.ServerRoom.RoomID), url.QueryEscape(event.EventID()), @@ -4329,7 +4342,7 @@ func (psj *partialStateJoinResult) Destroy(t *testing.T) { } // send a message into the room without letting the homeserver under test know about it. -func (psj *partialStateJoinResult) CreateMessageEvent(t *testing.T, senderLocalpart string, prevEventIDs []string) *gomatrixserverlib.Event { +func (psj *partialStateJoinResult) CreateMessageEvent(t *testing.T, senderLocalpart string, prevEventIDs []string) gomatrixserverlib.PDU { var prevEvents interface{} if prevEventIDs == nil { prevEvents = nil @@ -4368,7 +4381,7 @@ func (psj *partialStateJoinResult) FinishStateRequest() { // if sendResponseWaiter is not nil, we will Wait() for it to finish before sending the response. func handleStateIdsRequests( t *testing.T, srv *server, serverRoom *federation.ServerRoom, - eventID string, roomState []*gomatrixserverlib.Event, + eventID string, roomState []gomatrixserverlib.PDU, requestReceivedWaiter *Waiter, sendResponseWaiter *Waiter, ) { srv.Mux().NewRoute().Methods("GET").Path( @@ -4385,7 +4398,7 @@ func handleStateIdsRequests( } t.Logf("Replying to /state_ids request for event %s", queryParams["event_id"]) - res := gomatrixserverlib.RespStateIDs{ + res := fclient.RespStateIDs{ AuthEventIDs: eventIDsFromEvents(serverRoom.AuthChainForEvents(roomState)), StateEventIDs: eventIDsFromEvents(roomState), } @@ -4408,7 +4421,7 @@ func handleStateIdsRequests( // if sendResponseWaiter is not nil, we will Wait() for it to finish before sending the response. func handleStateRequests( t *testing.T, srv *server, serverRoom *federation.ServerRoom, - eventID string, roomState []*gomatrixserverlib.Event, + eventID string, roomState []gomatrixserverlib.PDU, requestReceivedWaiter *Waiter, sendResponseWaiter *Waiter, ) { srv.Mux().NewRoute().Methods("GET").Path( @@ -4426,7 +4439,7 @@ func handleStateRequests( t.Logf("Replying to /state request for event %s", queryParams["event_id"]) - res := gomatrixserverlib.RespState{ + res := fclient.RespState{ AuthEvents: gomatrixserverlib.NewEventJSONsFromEvents(serverRoom.AuthChainForEvents(roomState)), StateEvents: gomatrixserverlib.NewEventJSONsFromEvents(roomState), } @@ -4447,14 +4460,14 @@ func handleStateRequests( // must match those listed in "expectedLatestEvents" (otherwise the test is failed). func handleGetMissingEventsRequests( t *testing.T, srv *server, serverRoom *federation.ServerRoom, - expectedLatestEvents []string, eventsToReturn []*gomatrixserverlib.Event, + expectedLatestEvents []string, eventsToReturn []gomatrixserverlib.PDU, ) { srv.Mux().HandleFunc(fmt.Sprintf("/_matrix/federation/v1/get_missing_events/%s", serverRoom.RoomID), func(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) if err != nil { t.Fatalf("unable to read /get_missing_events request body: %s", err) } - var getMissingEventsRequest gomatrixserverlib.MissingEvents + var getMissingEventsRequest fclient.MissingEvents err = json.Unmarshal(body, &getMissingEventsRequest) if err != nil { t.Fatalf("unable to unmarshall /get_missing_events request body: %s", err) @@ -4465,7 +4478,7 @@ func handleGetMissingEventsRequests( t.Fatalf("getMissingEventsRequest.LatestEvents: got %v, wanted %v", getMissingEventsRequest, expectedLatestEvents) } - responseBytes, _ := json.Marshal(gomatrixserverlib.RespMissingEvents{ + responseBytes, _ := json.Marshal(fclient.RespMissingEvents{ Events: gomatrixserverlib.NewEventJSONsFromEvents(eventsToReturn), }) w.WriteHeader(200) @@ -4473,7 +4486,7 @@ func handleGetMissingEventsRequests( }).Methods("POST") } -func eventIDsFromEvents(he []*gomatrixserverlib.Event) []string { +func eventIDsFromEvents(he []gomatrixserverlib.PDU) []string { eventIDs := make([]string, len(he)) for i := range he { eventIDs[i] = he[i].EventID() diff --git a/tests/federation_room_join_test.go b/tests/federation_room_join_test.go index 5c302f94..5cdc7b1a 100644 --- a/tests/federation_room_join_test.go +++ b/tests/federation_room_join_test.go @@ -11,6 +11,8 @@ import ( "time" "github.com/matrix-org/gomatrix" + "github.com/matrix-org/gomatrixserverlib/fclient" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib" @@ -167,7 +169,9 @@ func TestJoinFederatedRoomWithUnverifiableEvents(t *testing.T) { raw := signedEvent.JSON() raw, err := sjson.SetRawBytes(raw, "signatures", []byte(`{}`)) must.NotError(t, "failed to strip signatures key from event", err) - unsignedEvent, err := gomatrixserverlib.NewEventFromTrustedJSON(raw, false, ver) + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + must.NotError(t, "failed to get room version", err) + unsignedEvent, err := verImpl.NewEventFromTrustedJSON(raw, false) must.NotError(t, "failed to make Event from unsigned event JSON", err) room.AddEvent(unsignedEvent) alice.JoinRoom(t, roomAlias, nil) @@ -195,7 +199,9 @@ func TestJoinFederatedRoomWithUnverifiableEvents(t *testing.T) { raw := signedEvent.JSON() raw, err = sjson.SetRawBytes(raw, "signatures", rawSig) must.NotError(t, "failed to modify signatures key from event", err) - unsignedEvent, err := gomatrixserverlib.NewEventFromTrustedJSON(raw, false, ver) + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + must.NotError(t, "failed to get room version", err) + unsignedEvent, err := verImpl.NewEventFromTrustedJSON(raw, false) must.NotError(t, "failed to make Event from unsigned event JSON", err) room.AddEvent(unsignedEvent) alice.JoinRoom(t, roomAlias, nil) @@ -224,7 +230,9 @@ func TestJoinFederatedRoomWithUnverifiableEvents(t *testing.T) { raw := signedEvent.JSON() raw, err = sjson.SetRawBytes(raw, "signatures", rawSig) must.NotError(t, "failed to modify signatures key from event", err) - unsignedEvent, err := gomatrixserverlib.NewEventFromTrustedJSON(raw, false, ver) + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + must.NotError(t, "failed to get room version", err) + unsignedEvent, err := verImpl.NewEventFromTrustedJSON(raw, false) must.NotError(t, "failed to make Event from unsigned event JSON", err) room.AddEvent(unsignedEvent) alice.JoinRoom(t, roomAlias, nil) @@ -255,7 +263,9 @@ func TestJoinFederatedRoomWithUnverifiableEvents(t *testing.T) { must.NotError(t, "failed to marshal bad signature block", err) rawEvent, err = sjson.SetRawBytes(rawEvent, "signatures", rawSig) must.NotError(t, "failed to modify signatures key from event", err) - badlySignedEvent, err := gomatrixserverlib.NewEventFromTrustedJSON(rawEvent, false, ver) + verImpl, err := gomatrixserverlib.GetRoomVersion(room.Version) + must.NotError(t, "failed to get room version", err) + badlySignedEvent, err := verImpl.NewEventFromTrustedJSON(rawEvent, false) must.NotError(t, "failed to make Event from badly signed event JSON", err) room.AddEvent(badlySignedEvent) t.Logf("Created badly signed auth event %s", badlySignedEvent.EventID()) @@ -297,7 +307,7 @@ func TestBannedUserCannotSendJoin(t *testing.T) { federation.HandleTransactionRequests(nil, nil), ) cancel := srv.Listen() - origin := gomatrixserverlib.ServerName(srv.ServerName()) + origin := spec.ServerName(srv.ServerName()) defer cancel() fedClient := srv.FederationClient(deployment) @@ -320,13 +330,17 @@ func TestBannedUserCannotSendJoin(t *testing.T) { }) // charlie sends a make_join for a different user - makeJoinResp, err := fedClient.MakeJoin(context.Background(), origin, "hs1", roomID, srv.UserID("charlie2"), federation.SupportedRoomVersions()) + makeJoinResp, err := fedClient.MakeJoin(context.Background(), origin, "hs1", roomID, srv.UserID("charlie2")) must.NotError(t, "MakeJoin", err) // ... and does a switcheroo to turn it into a join for himself - makeJoinResp.JoinEvent.Sender = charlie + makeJoinResp.JoinEvent.SenderID = charlie makeJoinResp.JoinEvent.StateKey = &charlie - joinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), gomatrixserverlib.ServerName(srv.ServerName()), srv.KeyID, srv.Priv, makeJoinResp.RoomVersion) + + verImpl, err := gomatrixserverlib.GetRoomVersion(makeJoinResp.RoomVersion) + must.NotError(t, "JoinEvent.GetRoomVersion", err) + eb := verImpl.NewEventBuilderFromProtoEvent(&makeJoinResp.JoinEvent) + joinEvent, err := eb.Build(time.Now(), spec.ServerName(srv.ServerName()), srv.KeyID, srv.Priv) must.NotError(t, "JoinEvent.Build", err) // SendJoin should return a 403. @@ -404,14 +418,14 @@ func testValidationForSendMembershipEndpoint(t *testing.T, baseApiPath, expected // a helper function which makes a send_* request to the given path and checks // that it fails with a 400 error - assertRequestFails := func(t *testing.T, event *gomatrixserverlib.Event) { + assertRequestFails := func(t *testing.T, event gomatrixserverlib.PDU) { path := fmt.Sprintf("%s/%s/%s", baseApiPath, - url.PathEscape(event.RoomID()), + url.PathEscape(event.RoomID().String()), url.PathEscape(event.EventID()), ) t.Logf("PUT %s", path) - req := gomatrixserverlib.NewFederationRequest("PUT", gomatrixserverlib.ServerName(srv.ServerName()), "hs1", path) + req := fclient.NewFederationRequest("PUT", spec.ServerName(srv.ServerName()), "hs1", path) if err := req.SetContent(event); err != nil { t.Errorf("req.SetContent: %v", err) return @@ -500,7 +514,7 @@ func TestSendJoinPartialStateResponse(t *testing.T) { ) cancel := srv.Listen() defer cancel() - origin := gomatrixserverlib.ServerName(srv.ServerName()) + origin := spec.ServerName(srv.ServerName()) // annoyingly we can't get to the room that alice and bob already share (see https://github.com/matrix-org/complement/issues/254) // so we have to create a new one. @@ -513,14 +527,16 @@ func TestSendJoinPartialStateResponse(t *testing.T) { // now we send a make_join... charlie := srv.UserID("charlie") fedClient := srv.FederationClient(deployment) - makeJoinResp, err := fedClient.MakeJoin(context.Background(), origin, "hs1", roomID, charlie, federation.SupportedRoomVersions()) + makeJoinResp, err := fedClient.MakeJoin(context.Background(), origin, "hs1", roomID, charlie) if err != nil { t.Fatalf("make_join failed: %v", err) } // ... construct a signed join event ... - roomVer := makeJoinResp.RoomVersion - joinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), origin, srv.KeyID, srv.Priv, roomVer) + verImpl, err := gomatrixserverlib.GetRoomVersion(makeJoinResp.RoomVersion) + must.NotError(t, "JoinEvent.GetRoomVersion", err) + eb := verImpl.NewEventBuilderFromProtoEvent(&makeJoinResp.JoinEvent) + joinEvent, err := eb.Build(time.Now(), spec.ServerName(srv.ServerName()), srv.KeyID, srv.Priv) if err != nil { t.Fatalf("failed to sign join event: %v", err) } diff --git a/tests/federation_room_send_test.go b/tests/federation_room_send_test.go index fc4ed33a..f9993640 100644 --- a/tests/federation_room_send_test.go +++ b/tests/federation_room_send_test.go @@ -32,7 +32,7 @@ func TestOutboundFederationSend(t *testing.T) { federation.HandleMakeSendJoinRequests(), federation.HandleTransactionRequests( // listen for PDU events in transactions - func(ev *gomatrixserverlib.Event) { + func(ev gomatrixserverlib.PDU) { defer waiter.Finish() if ev.Type() != wantEventType { diff --git a/tests/federation_rooms_invite_test.go b/tests/federation_rooms_invite_test.go index 0bdd688d..e33c1b76 100644 --- a/tests/federation_rooms_invite_test.go +++ b/tests/federation_rooms_invite_test.go @@ -3,7 +3,7 @@ package tests import ( "testing" - "github.com/matrix-org/gomatrixserverlib" + "github.com/matrix-org/gomatrixserverlib/spec" "github.com/tidwall/gjson" "github.com/matrix-org/complement/internal/b" @@ -96,7 +96,7 @@ func TestFederationRoomsInvite(t *testing.T) { bob.MustSyncUntil(t, client.SyncReq{}, client.SyncTimelineHas(roomID, func(result gjson.Result) bool { // We expect a membership event .. - if result.Get("type").Str != gomatrixserverlib.MRoomMember { + if result.Get("type").Str != spec.MRoomMember { return false } // .. for Bob diff --git a/tests/knocking_test.go b/tests/knocking_test.go index e84f7ca8..fb1fd18a 100644 --- a/tests/knocking_test.go +++ b/tests/knocking_test.go @@ -57,7 +57,7 @@ func doTestKnocking(t *testing.T, roomVersion string, joinRule string) { inviteWaiter := NewWaiter() srv := federation.NewServer(t, deployment, federation.HandleKeyRequests(), - federation.HandleInviteRequests(func(ev *gomatrixserverlib.Event) { + federation.HandleInviteRequests(func(ev gomatrixserverlib.PDU) { inviteWaiter.Finish() }), federation.HandleTransactionRequests(nil, nil), @@ -146,7 +146,7 @@ func knockingBetweenTwoUsersTest(t *testing.T, roomID string, inRoomUser, knocki // wait for the membership to arrive over federation start := time.Now() knockerState := serverRoom.CurrentState("m.room.member", knockingUser.UserID) - for knockerState == nil && time.Since(start) < 5 * time.Second { + for knockerState == nil && time.Since(start) < 5*time.Second { time.Sleep(100 * time.Millisecond) knockerState = serverRoom.CurrentState("m.room.member", knockingUser.UserID) }