Move MakeJoin logic to GMSL (#3081)

This commit is contained in:
devonh 2023-05-17 00:33:27 +00:00 committed by GitHub
parent 0489d16f95
commit 67d6876857
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
80 changed files with 1158 additions and 494 deletions

View File

@ -68,8 +68,10 @@ func VerifyUserFromRequest(
}, &res) }, &res)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("userAPI.QueryAccessToken failed") util.GetLogger(req.Context()).WithError(err).Error("userAPI.QueryAccessToken failed")
jsonErr := spec.InternalServerError() return nil, &util.JSONResponse{
return nil, &jsonErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if res.Err != "" { if res.Err != "" {
if strings.HasPrefix(strings.ToLower(res.Err), "forbidden:") { // TODO: use actual error and no string comparison if strings.HasPrefix(strings.ToLower(res.Err), "forbidden:") { // TODO: use actual error and no string comparison

View File

@ -107,13 +107,13 @@ func TestBadLoginFromJSONReader(t *testing.T) {
Name string Name string
Body string Body string
WantErrCode string WantErrCode spec.MatrixErrorCode
}{ }{
{Name: "empty", WantErrCode: "M_BAD_JSON"}, {Name: "empty", WantErrCode: spec.ErrorBadJSON},
{ {
Name: "badUnmarshal", Name: "badUnmarshal",
Body: `badsyntaxJSON`, Body: `badsyntaxJSON`,
WantErrCode: "M_BAD_JSON", WantErrCode: spec.ErrorBadJSON,
}, },
{ {
Name: "badPassword", Name: "badPassword",
@ -123,7 +123,7 @@ func TestBadLoginFromJSONReader(t *testing.T) {
"password": "invalidpassword", "password": "invalidpassword",
"device_id": "adevice" "device_id": "adevice"
}`, }`,
WantErrCode: "M_FORBIDDEN", WantErrCode: spec.ErrorForbidden,
}, },
{ {
Name: "badToken", Name: "badToken",
@ -132,7 +132,7 @@ func TestBadLoginFromJSONReader(t *testing.T) {
"token": "invalidtoken", "token": "invalidtoken",
"device_id": "adevice" "device_id": "adevice"
}`, }`,
WantErrCode: "M_FORBIDDEN", WantErrCode: spec.ErrorForbidden,
}, },
{ {
Name: "badType", Name: "badType",
@ -140,7 +140,7 @@ func TestBadLoginFromJSONReader(t *testing.T) {
"type": "m.login.invalid", "type": "m.login.invalid",
"device_id": "adevice" "device_id": "adevice"
}`, }`,
WantErrCode: "M_INVALID_PARAM", WantErrCode: spec.ErrorInvalidParam,
}, },
} }
for _, tst := range tsts { for _, tst := range tsts {
@ -157,7 +157,7 @@ func TestBadLoginFromJSONReader(t *testing.T) {
if errRes == nil { if errRes == nil {
cleanup(ctx, nil) cleanup(ctx, nil)
t.Fatalf("LoginFromJSONReader err: got %+v, want code %q", errRes, tst.WantErrCode) t.Fatalf("LoginFromJSONReader err: got %+v, want code %q", errRes, tst.WantErrCode)
} else if merr, ok := errRes.JSON.(*spec.MatrixError); ok && merr.ErrCode != tst.WantErrCode { } else if merr, ok := errRes.JSON.(spec.MatrixError); ok && merr.ErrCode != tst.WantErrCode {
t.Fatalf("LoginFromJSONReader err: got %+v, want code %q", errRes, tst.WantErrCode) t.Fatalf("LoginFromJSONReader err: got %+v, want code %q", errRes, tst.WantErrCode)
} }
}) })

View File

@ -48,8 +48,10 @@ func (t *LoginTypeToken) LoginFromJSON(ctx context.Context, reqBytes []byte) (*L
var res uapi.QueryLoginTokenResponse var res uapi.QueryLoginTokenResponse
if err := t.UserAPI.QueryLoginToken(ctx, &uapi.QueryLoginTokenRequest{Token: r.Token}, &res); err != nil { if err := t.UserAPI.QueryLoginToken(ctx, &uapi.QueryLoginTokenRequest{Token: r.Token}, &res); err != nil {
util.GetLogger(ctx).WithError(err).Error("UserAPI.QueryLoginToken failed") util.GetLogger(ctx).WithError(err).Error("UserAPI.QueryLoginToken failed")
jsonErr := spec.InternalServerError() return nil, nil, &util.JSONResponse{
return nil, nil, &jsonErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if res.Data == nil { if res.Data == nil {
return nil, nil, &util.JSONResponse{ return nil, nil, &util.JSONResponse{

View File

@ -178,8 +178,10 @@ func (u *UserInteractive) NewSession() *util.JSONResponse {
sessionID, err := GenerateAccessToken() sessionID, err := GenerateAccessToken()
if err != nil { if err != nil {
logrus.WithError(err).Error("failed to generate session ID") logrus.WithError(err).Error("failed to generate session ID")
res := spec.InternalServerError() return &util.JSONResponse{
return &res Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
u.Lock() u.Lock()
u.Sessions[sessionID] = []string{} u.Sessions[sessionID] = []string{}
@ -193,15 +195,19 @@ func (u *UserInteractive) ResponseWithChallenge(sessionID string, response inter
mixedObjects := make(map[string]interface{}) mixedObjects := make(map[string]interface{})
b, err := json.Marshal(response) b, err := json.Marshal(response)
if err != nil { if err != nil {
ise := spec.InternalServerError() return &util.JSONResponse{
return &ise Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
_ = json.Unmarshal(b, &mixedObjects) _ = json.Unmarshal(b, &mixedObjects)
challenge := u.challenge(sessionID) challenge := u.challenge(sessionID)
b, err = json.Marshal(challenge.JSON) b, err = json.Marshal(challenge.JSON)
if err != nil { if err != nil {
ise := spec.InternalServerError() return &util.JSONResponse{
return &ise Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
_ = json.Unmarshal(b, &mixedObjects) _ = json.Unmarshal(b, &mixedObjects)

View File

@ -33,6 +33,7 @@ import (
uapi "github.com/matrix-org/dendrite/userapi/api" uapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
@ -1105,7 +1106,7 @@ func Test3PID(t *testing.T) {
resp := threepid.GetValidatedResponse{} resp := threepid.GetValidatedResponse{}
switch r.URL.Query().Get("client_secret") { switch r.URL.Query().Get("client_secret") {
case "fail": case "fail":
resp.ErrCode = "M_SESSION_NOT_VALIDATED" resp.ErrCode = string(spec.ErrorSessionNotValidated)
case "fail2": case "fail2":
resp.ErrCode = "some other error" resp.ErrCode = "some other error"
case "fail3": case "fail3":

View File

@ -32,8 +32,10 @@ func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONRespon
body, err := io.ReadAll(req.Body) body, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("io.ReadAll failed") util.GetLogger(req.Context()).WithError(err).Error("io.ReadAll failed")
resp := spec.InternalServerError() return &util.JSONResponse{
return &resp Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return UnmarshalJSON(body, iface) return UnmarshalJSON(body, iface)

View File

@ -104,7 +104,10 @@ func SaveAccountData(
body, err := io.ReadAll(req.Body) body, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("io.ReadAll failed") util.GetLogger(req.Context()).WithError(err).Error("io.ReadAll failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !json.Valid(body) { if !json.Valid(body) {
@ -157,7 +160,10 @@ func SaveReadMarker(
if r.FullyRead != "" { if r.FullyRead != "" {
data, err := json.Marshal(fullyReadEvent{EventID: r.FullyRead}) data, err := json.Marshal(fullyReadEvent{EventID: r.FullyRead})
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
dataReq := api.InputAccountDataRequest{ dataReq := api.InputAccountDataRequest{

View File

@ -31,7 +31,7 @@ func AdminEvacuateRoom(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAP
} }
affected, err := rsAPI.PerformAdminEvacuateRoom(req.Context(), vars["roomID"]) affected, err := rsAPI.PerformAdminEvacuateRoom(req.Context(), vars["roomID"])
switch err { switch err.(type) {
case nil: case nil:
case eventutil.ErrRoomNoExists: case eventutil.ErrRoomNoExists:
return util.JSONResponse{ return util.JSONResponse{
@ -113,7 +113,7 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
}, accAvailableResp); err != nil { }, accAvailableResp); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
if accAvailableResp.Available { if accAvailableResp.Available {
@ -169,7 +169,10 @@ func AdminReindex(req *http.Request, cfg *config.ClientAPI, device *api.Device,
_, err := natsClient.RequestMsg(nats.NewMsg(cfg.Matrix.JetStream.Prefixed(jetstream.InputFulltextReindex)), time.Second*10) _, err := natsClient.RequestMsg(nats.NewMsg(cfg.Matrix.JetStream.Prefixed(jetstream.InputFulltextReindex)), time.Second*10)
if err != nil { if err != nil {
logrus.WithError(err).Error("failed to publish nats message") logrus.WithError(err).Error("failed to publish nats message")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -231,10 +234,10 @@ func AdminDownloadState(req *http.Request, device *api.Device, rsAPI roomserverA
} }
} }
if err = rsAPI.PerformAdminDownloadState(req.Context(), roomID, device.UserID, spec.ServerName(serverName)); err != nil { if err = rsAPI.PerformAdminDownloadState(req.Context(), roomID, device.UserID, spec.ServerName(serverName)); err != nil {
if errors.Is(err, eventutil.ErrRoomNoExists) { if errors.Is(err, eventutil.ErrRoomNoExists{}) {
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,
JSON: spec.NotFound(eventutil.ErrRoomNoExists.Error()), JSON: spec.NotFound(err.Error()),
} }
} }
logrus.WithError(err).WithFields(logrus.Fields{ logrus.WithError(err).WithFields(logrus.Fields{

View File

@ -61,7 +61,10 @@ func GetAdminWhois(
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("GetAdminWhois failed to query user devices") util.GetLogger(req.Context()).WithError(err).Error("GetAdminWhois failed to query user devices")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
devices := make(map[string]deviceInfo) devices := make(map[string]deviceInfo)

View File

@ -62,7 +62,10 @@ func GetAliases(
var queryRes api.QueryMembershipForUserResponse var queryRes api.QueryMembershipForUserResponse
if err := rsAPI.QueryMembershipForUser(req.Context(), &queryReq, &queryRes); err != nil { if err := rsAPI.QueryMembershipForUser(req.Context(), &queryReq, &queryRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryMembershipsForRoom failed") util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryMembershipsForRoom failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !queryRes.IsInRoom { if !queryRes.IsInRoom {
return util.JSONResponse{ return util.JSONResponse{

View File

@ -174,7 +174,10 @@ func createRoom(
_, userDomain, err := gomatrixserverlib.SplitID('@', device.UserID) _, userDomain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !cfg.Matrix.IsLocalServerName(userDomain) { if !cfg.Matrix.IsLocalServerName(userDomain) {
return util.JSONResponse{ return util.JSONResponse{
@ -218,7 +221,10 @@ func createRoom(
profile, err := appserviceAPI.RetrieveUserProfile(ctx, userID, asAPI, profileAPI) profile, err := appserviceAPI.RetrieveUserProfile(ctx, userID, asAPI, profileAPI)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("appserviceAPI.RetrieveUserProfile failed") util.GetLogger(ctx).WithError(err).Error("appserviceAPI.RetrieveUserProfile failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
createContent := map[string]interface{}{} createContent := map[string]interface{}{}
@ -342,7 +348,10 @@ func createRoom(
err = rsAPI.GetRoomIDForAlias(ctx, &hasAliasReq, &aliasResp) err = rsAPI.GetRoomIDForAlias(ctx, &hasAliasReq, &aliasResp)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("aliasAPI.GetRoomIDForAlias failed") util.GetLogger(ctx).WithError(err).Error("aliasAPI.GetRoomIDForAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if aliasResp.RoomID != "" { if aliasResp.RoomID != "" {
return util.JSONResponse{ return util.JSONResponse{
@ -455,7 +464,10 @@ func createRoom(
err = builder.SetContent(e.Content) err = builder.SetContent(e.Content)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("builder.SetContent failed") util.GetLogger(ctx).WithError(err).Error("builder.SetContent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if i > 0 { if i > 0 {
builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()} builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}
@ -463,17 +475,26 @@ func createRoom(
var ev gomatrixserverlib.PDU var ev gomatrixserverlib.PDU
if err = builder.AddAuthEvents(&authEvents); err != nil { if err = builder.AddAuthEvents(&authEvents); err != nil {
util.GetLogger(ctx).WithError(err).Error("AddAuthEvents failed") util.GetLogger(ctx).WithError(err).Error("AddAuthEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
ev, err = builder.Build(evTime, userDomain, cfg.Matrix.KeyID, cfg.Matrix.PrivateKey) ev, err = builder.Build(evTime, userDomain, cfg.Matrix.KeyID, cfg.Matrix.PrivateKey)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("buildEvent failed") util.GetLogger(ctx).WithError(err).Error("buildEvent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if err = gomatrixserverlib.Allowed(ev, &authEvents); err != nil { if err = gomatrixserverlib.Allowed(ev, &authEvents); err != nil {
util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.Allowed failed") util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.Allowed failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Add the event to the list of auth events // Add the event to the list of auth events
@ -481,7 +502,10 @@ func createRoom(
err = authEvents.AddEvent(ev) err = authEvents.AddEvent(ev)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("authEvents.AddEvent failed") util.GetLogger(ctx).WithError(err).Error("authEvents.AddEvent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
@ -496,7 +520,10 @@ func createRoom(
} }
if err = roomserverAPI.SendInputRoomEvents(ctx, rsAPI, device.UserDomain(), inputs, false); err != nil { if err = roomserverAPI.SendInputRoomEvents(ctx, rsAPI, device.UserDomain(), inputs, false); err != nil {
util.GetLogger(ctx).WithError(err).Error("roomserverAPI.SendInputRoomEvents failed") util.GetLogger(ctx).WithError(err).Error("roomserverAPI.SendInputRoomEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// TODO(#269): Reserve room alias while we create the room. This stops us // TODO(#269): Reserve room alias while we create the room. This stops us
@ -513,7 +540,10 @@ func createRoom(
err = rsAPI.SetRoomAlias(ctx, &aliasReq, &aliasResp) err = rsAPI.SetRoomAlias(ctx, &aliasReq, &aliasResp)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("aliasAPI.SetRoomAlias failed") util.GetLogger(ctx).WithError(err).Error("aliasAPI.SetRoomAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if aliasResp.AliasExists { if aliasResp.AliasExists {
@ -596,7 +626,7 @@ func createRoom(
sentry.CaptureException(err) sentry.CaptureException(err)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
} }
@ -609,7 +639,10 @@ func createRoom(
Visibility: spec.Public, Visibility: spec.Public,
}); err != nil { }); err != nil {
util.GetLogger(ctx).WithError(err).Error("failed to publish room") util.GetLogger(ctx).WithError(err).Error("failed to publish room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }

View File

@ -36,7 +36,10 @@ func Deactivate(
localpart, serverName, err := gomatrixserverlib.SplitID('@', login.Username()) localpart, serverName, err := gomatrixserverlib.SplitID('@', login.Username())
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var res api.PerformAccountDeactivationResponse var res api.PerformAccountDeactivationResponse
@ -46,7 +49,10 @@ func Deactivate(
}, &res) }, &res)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("userAPI.PerformAccountDeactivation failed") util.GetLogger(ctx).WithError(err).Error("userAPI.PerformAccountDeactivation failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -60,7 +60,10 @@ func GetDeviceByID(
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed") util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var targetDevice *api.Device var targetDevice *api.Device
for _, device := range queryRes.Devices { for _, device := range queryRes.Devices {
@ -97,7 +100,10 @@ func GetDevicesByLocalpart(
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed") util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res := devicesJSON{} res := devicesJSON{}
@ -139,7 +145,10 @@ func UpdateDeviceByID(
}, &performRes) }, &performRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceUpdate failed") util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceUpdate failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !performRes.DeviceExists { if !performRes.DeviceExists {
return util.JSONResponse{ return util.JSONResponse{
@ -206,7 +215,10 @@ func DeleteDeviceById(
localpart, _, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, _, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// make sure that the access token being used matches the login creds used for user interactive auth, else // make sure that the access token being used matches the login creds used for user interactive auth, else
@ -224,7 +236,10 @@ func DeleteDeviceById(
DeviceIDs: []string{deviceID}, DeviceIDs: []string{deviceID},
}, &res); err != nil { }, &res); err != nil {
util.GetLogger(ctx).WithError(err).Error("userAPI.PerformDeviceDeletion failed") util.GetLogger(ctx).WithError(err).Error("userAPI.PerformDeviceDeletion failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
deleteOK = true deleteOK = true
@ -266,7 +281,10 @@ func DeleteDevices(
payload := devicesDeleteJSON{} payload := devicesDeleteJSON{}
if err = json.Unmarshal(bodyBytes, &payload); err != nil { if err = json.Unmarshal(bodyBytes, &payload); err != nil {
util.GetLogger(ctx).WithError(err).Error("unable to unmarshal device deletion request") util.GetLogger(ctx).WithError(err).Error("unable to unmarshal device deletion request")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var res api.PerformDeviceDeletionResponse var res api.PerformDeviceDeletionResponse
@ -275,7 +293,10 @@ func DeleteDevices(
DeviceIDs: payload.Devices, DeviceIDs: payload.Devices,
}, &res); err != nil { }, &res); err != nil {
util.GetLogger(ctx).WithError(err).Error("userAPI.PerformDeviceDeletion failed") util.GetLogger(ctx).WithError(err).Error("userAPI.PerformDeviceDeletion failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -69,7 +69,10 @@ func DirectoryRoom(
queryRes := &roomserverAPI.GetRoomIDForAliasResponse{} queryRes := &roomserverAPI.GetRoomIDForAliasResponse{}
if err = rsAPI.GetRoomIDForAlias(req.Context(), queryReq, queryRes); err != nil { if err = rsAPI.GetRoomIDForAlias(req.Context(), queryReq, queryRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("rsAPI.GetRoomIDForAlias failed") util.GetLogger(req.Context()).WithError(err).Error("rsAPI.GetRoomIDForAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res.RoomID = queryRes.RoomID res.RoomID = queryRes.RoomID
@ -83,7 +86,10 @@ func DirectoryRoom(
// TODO: Return 502 if the remote server errored. // TODO: Return 502 if the remote server errored.
// TODO: Return 504 if the remote server timed out. // TODO: Return 504 if the remote server timed out.
util.GetLogger(req.Context()).WithError(fedErr).Error("federation.LookupRoomAlias failed") util.GetLogger(req.Context()).WithError(fedErr).Error("federation.LookupRoomAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res.RoomID = fedRes.RoomID res.RoomID = fedRes.RoomID
res.fillServers(fedRes.Servers) res.fillServers(fedRes.Servers)
@ -102,7 +108,10 @@ func DirectoryRoom(
var joinedHostsRes federationAPI.QueryJoinedHostServerNamesInRoomResponse var joinedHostsRes federationAPI.QueryJoinedHostServerNamesInRoomResponse
if err = fedSenderAPI.QueryJoinedHostServerNamesInRoom(req.Context(), &joinedHostsReq, &joinedHostsRes); err != nil { if err = fedSenderAPI.QueryJoinedHostServerNamesInRoom(req.Context(), &joinedHostsReq, &joinedHostsRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("fedSenderAPI.QueryJoinedHostServerNamesInRoom failed") util.GetLogger(req.Context()).WithError(err).Error("fedSenderAPI.QueryJoinedHostServerNamesInRoom failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res.fillServers(joinedHostsRes.ServerNames) res.fillServers(joinedHostsRes.ServerNames)
} }
@ -180,7 +189,10 @@ func SetLocalAlias(
var queryRes roomserverAPI.SetRoomAliasResponse var queryRes roomserverAPI.SetRoomAliasResponse
if err := rsAPI.SetRoomAlias(req.Context(), &queryReq, &queryRes); err != nil { if err := rsAPI.SetRoomAlias(req.Context(), &queryReq, &queryRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("aliasAPI.SetRoomAlias failed") util.GetLogger(req.Context()).WithError(err).Error("aliasAPI.SetRoomAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if queryRes.AliasExists { if queryRes.AliasExists {
@ -210,7 +222,10 @@ func RemoveLocalAlias(
var queryRes roomserverAPI.RemoveRoomAliasResponse var queryRes roomserverAPI.RemoveRoomAliasResponse
if err := rsAPI.RemoveRoomAlias(req.Context(), &queryReq, &queryRes); err != nil { if err := rsAPI.RemoveRoomAlias(req.Context(), &queryReq, &queryRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("aliasAPI.RemoveRoomAlias failed") util.GetLogger(req.Context()).WithError(err).Error("aliasAPI.RemoveRoomAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !queryRes.Found { if !queryRes.Found {
@ -248,7 +263,10 @@ func GetVisibility(
}, &res) }, &res)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryPublishedRooms failed") util.GetLogger(req.Context()).WithError(err).Error("QueryPublishedRooms failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var v roomVisibility var v roomVisibility
@ -286,7 +304,10 @@ func SetVisibility(
err := rsAPI.QueryLatestEventsAndState(req.Context(), &queryEventsReq, &queryEventsRes) err := rsAPI.QueryLatestEventsAndState(req.Context(), &queryEventsReq, &queryEventsRes)
if err != nil || len(queryEventsRes.StateEvents) == 0 { if err != nil || len(queryEventsRes.StateEvents) == 0 {
util.GetLogger(req.Context()).WithError(err).Error("could not query events from room") util.GetLogger(req.Context()).WithError(err).Error("could not query events from room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// NOTSPEC: Check if the user's power is greater than power required to change m.room.canonical_alias event // NOTSPEC: Check if the user's power is greater than power required to change m.room.canonical_alias event
@ -308,7 +329,10 @@ func SetVisibility(
Visibility: v.Visibility, Visibility: v.Visibility,
}); err != nil { }); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("failed to publish room") util.GetLogger(req.Context()).WithError(err).Error("failed to publish room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -344,7 +368,10 @@ func SetVisibilityAS(
AppserviceID: dev.AppserviceID, AppserviceID: dev.AppserviceID,
}); err != nil { }); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("failed to publish room") util.GetLogger(req.Context()).WithError(err).Error("failed to publish room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -81,7 +81,10 @@ func GetPostPublicRooms(
) )
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("failed to get public rooms") util.GetLogger(req.Context()).WithError(err).Error("failed to get public rooms")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -92,7 +95,10 @@ func GetPostPublicRooms(
response, err := publicRooms(req.Context(), request, rsAPI, extRoomsProvider) response, err := publicRooms(req.Context(), request, rsAPI, extRoomsProvider)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Errorf("failed to work out public rooms") util.GetLogger(req.Context()).WithError(err).Errorf("failed to work out public rooms")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,

View File

@ -40,7 +40,10 @@ func GetJoinedRooms(
}, &res) }, &res)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryRoomsForUser failed") util.GetLogger(req.Context()).WithError(err).Error("QueryRoomsForUser failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if res.RoomIDs == nil { if res.RoomIDs == nil {
res.RoomIDs = []string{} res.RoomIDs = []string{}

View File

@ -16,7 +16,6 @@ package routing
import ( import (
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"time" "time"
@ -114,16 +113,15 @@ func JoinRoomByIDOrAlias(
Code: e.Code, Code: e.Code,
JSON: json.RawMessage(e.Message), JSON: json.RawMessage(e.Message),
} }
default: case eventutil.ErrRoomNoExists:
response = util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(),
}
if errors.Is(err, eventutil.ErrRoomNoExists) {
response = util.JSONResponse{ response = util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: spec.NotFound(e.Error()), JSON: spec.NotFound(e.Error()),
} }
default:
response = util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
} }
} }
done <- response done <- response

View File

@ -128,7 +128,7 @@ func ModifyKeyBackupVersionAuthData(req *http.Request, userAPI userapi.ClientUse
Algorithm: kb.Algorithm, Algorithm: kb.Algorithm,
}) })
switch e := err.(type) { switch e := err.(type) {
case *spec.ErrRoomKeysVersion: case spec.ErrRoomKeysVersion:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: e, JSON: e,
@ -182,7 +182,7 @@ func UploadBackupKeys(
}) })
switch e := err.(type) { switch e := err.(type) {
case *spec.ErrRoomKeysVersion: case spec.ErrRoomKeysVersion:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: e, JSON: e,

View File

@ -67,7 +67,10 @@ func UploadKeys(req *http.Request, keyAPI api.ClientKeyAPI, device *api.Device)
} }
if uploadRes.Error != nil { if uploadRes.Error != nil {
util.GetLogger(req.Context()).WithError(uploadRes.Error).Error("Failed to PerformUploadKeys") util.GetLogger(req.Context()).WithError(uploadRes.Error).Error("Failed to PerformUploadKeys")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if len(uploadRes.KeyErrors) > 0 { if len(uploadRes.KeyErrors) > 0 {
util.GetLogger(req.Context()).WithField("key_errors", uploadRes.KeyErrors).Error("Failed to upload one or more keys") util.GetLogger(req.Context()).WithField("key_errors", uploadRes.KeyErrors).Error("Failed to upload one or more keys")
@ -156,7 +159,10 @@ func ClaimKeys(req *http.Request, keyAPI api.ClientKeyAPI) util.JSONResponse {
}, &claimRes) }, &claimRes)
if claimRes.Error != nil { if claimRes.Error != nil {
util.GetLogger(req.Context()).WithError(claimRes.Error).Error("failed to PerformClaimKeys") util.GetLogger(req.Context()).WithError(claimRes.Error).Error("failed to PerformClaimKeys")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,

View File

@ -83,13 +83,19 @@ func completeAuth(
token, err := auth.GenerateAccessToken() token, err := auth.GenerateAccessToken()
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("auth.GenerateAccessToken failed") util.GetLogger(ctx).WithError(err).Error("auth.GenerateAccessToken failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
localpart, serverName, err := userutil.ParseUsernameParam(login.Username(), cfg) localpart, serverName, err := userutil.ParseUsernameParam(login.Username(), cfg)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("auth.ParseUsernameParam failed") util.GetLogger(ctx).WithError(err).Error("auth.ParseUsernameParam failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var performRes userapi.PerformDeviceCreationResponse var performRes userapi.PerformDeviceCreationResponse

View File

@ -33,7 +33,10 @@ func Logout(
}, &performRes) }, &performRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed") util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -53,7 +56,10 @@ func LogoutAll(
}, &performRes) }, &performRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed") util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -85,7 +85,10 @@ func sendMembership(ctx context.Context, profileAPI userapi.ClientUserAPI, devic
) )
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("buildMembershipEvent failed") util.GetLogger(ctx).WithError(err).Error("buildMembershipEvent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
serverName := device.UserDomain() serverName := device.UserDomain()
@ -100,7 +103,10 @@ func sendMembership(ctx context.Context, profileAPI userapi.ClientUserAPI, devic
false, false,
); err != nil { ); err != nil {
util.GetLogger(ctx).WithError(err).Error("SendEvents failed") util.GetLogger(ctx).WithError(err).Error("SendEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -262,7 +268,10 @@ func sendInvite(
) )
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("buildMembershipEvent failed") util.GetLogger(ctx).WithError(err).Error("buildMembershipEvent failed")
return spec.InternalServerError(), err return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}, err
} }
err = rsAPI.PerformInvite(ctx, &api.PerformInviteRequest{ err = rsAPI.PerformInvite(ctx, &api.PerformInviteRequest{
@ -289,7 +298,7 @@ func sendInvite(
sentry.CaptureException(err) sentry.CaptureException(err)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
}, err }, err
} }
@ -398,31 +407,38 @@ func checkAndProcessThreepid(
req.Context(), device, body, cfg, rsAPI, profileAPI, req.Context(), device, body, cfg, rsAPI, profileAPI,
roomID, evTime, roomID, evTime,
) )
if err == threepid.ErrMissingParameter { switch e := err.(type) {
case nil:
case threepid.ErrMissingParameter:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed")
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
} else if err == threepid.ErrNotTrusted { case threepid.ErrNotTrusted:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed")
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.NotTrusted(body.IDServer), JSON: spec.NotTrusted(body.IDServer),
} }
} else if err == eventutil.ErrRoomNoExists { case eventutil.ErrRoomNoExists:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed")
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: spec.NotFound(err.Error()), JSON: spec.NotFound(err.Error()),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { case gomatrixserverlib.BadJSONError:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed")
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} default:
if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed")
er := spec.InternalServerError() return inviteStored, &util.JSONResponse{
return inviteStored, &er Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return return
} }
@ -435,8 +451,10 @@ func checkMemberInRoom(ctx context.Context, rsAPI roomserverAPI.ClientRoomserver
}, &membershipRes) }, &membershipRes)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("QueryMembershipForUser: could not query membership for user") util.GetLogger(ctx).WithError(err).Error("QueryMembershipForUser: could not query membership for user")
e := spec.InternalServerError() return &util.JSONResponse{
return &e Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !membershipRes.IsInRoom { if !membershipRes.IsInRoom {
return &util.JSONResponse{ return &util.JSONResponse{
@ -461,7 +479,10 @@ func SendForget(
err := rsAPI.QueryMembershipForUser(ctx, &membershipReq, &membershipRes) err := rsAPI.QueryMembershipForUser(ctx, &membershipReq, &membershipRes)
if err != nil { if err != nil {
logger.WithError(err).Error("QueryMembershipForUser: could not query membership for user") logger.WithError(err).Error("QueryMembershipForUser: could not query membership for user")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !membershipRes.RoomExists { if !membershipRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
@ -483,7 +504,10 @@ func SendForget(
response := roomserverAPI.PerformForgetResponse{} response := roomserverAPI.PerformForgetResponse{}
if err := rsAPI.PerformForget(ctx, &request, &response); err != nil { if err := rsAPI.PerformForget(ctx, &request, &response); err != nil {
logger.WithError(err).Error("PerformForget: unable to forget room") logger.WithError(err).Error("PerformForget: unable to forget room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,

View File

@ -35,7 +35,10 @@ func GetNotifications(
limit, err = strconv.ParseInt(limitStr, 10, 64) limit, err = strconv.ParseInt(limitStr, 10, 64)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("ParseInt(limit) failed") util.GetLogger(req.Context()).WithError(err).Error("ParseInt(limit) failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
@ -43,7 +46,10 @@ func GetNotifications(
localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
err = userAPI.QueryNotifications(req.Context(), &userapi.QueryNotificationsRequest{ err = userAPI.QueryNotifications(req.Context(), &userapi.QueryNotificationsRequest{
Localpart: localpart, Localpart: localpart,
@ -54,7 +60,10 @@ func GetNotifications(
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryNotifications failed") util.GetLogger(req.Context()).WithError(err).Error("QueryNotifications failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
util.GetLogger(req.Context()).WithField("from", req.URL.Query().Get("from")).WithField("limit", limit).WithField("only", req.URL.Query().Get("only")).WithField("next", queryRes.NextToken).Infof("QueryNotifications: len %d", len(queryRes.Notifications)) util.GetLogger(req.Context()).WithField("from", req.URL.Query().Get("from")).WithField("limit", limit).WithField("only", req.URL.Query().Get("only")).WithField("next", queryRes.NextToken).Infof("QueryNotifications: len %d", len(queryRes.Notifications))
return util.JSONResponse{ return util.JSONResponse{

View File

@ -55,7 +55,10 @@ func CreateOpenIDToken(
err := userAPI.PerformOpenIDTokenCreation(req.Context(), &request, &response) err := userAPI.PerformOpenIDTokenCreation(req.Context(), &request, &response)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("userAPI.CreateOpenIDToken failed") util.GetLogger(req.Context()).WithError(err).Error("userAPI.CreateOpenIDToken failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -90,7 +90,10 @@ func Password(
localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Ask the user API to perform the password change. // Ask the user API to perform the password change.
@ -102,11 +105,17 @@ func Password(
passwordRes := &api.PerformPasswordUpdateResponse{} passwordRes := &api.PerformPasswordUpdateResponse{}
if err := userAPI.PerformPasswordUpdate(req.Context(), passwordReq, passwordRes); err != nil { if err := userAPI.PerformPasswordUpdate(req.Context(), passwordReq, passwordRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformPasswordUpdate failed") util.GetLogger(req.Context()).WithError(err).Error("PerformPasswordUpdate failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !passwordRes.PasswordUpdated { if !passwordRes.PasswordUpdated {
util.GetLogger(req.Context()).Error("Expected password to have been updated but wasn't") util.GetLogger(req.Context()).Error("Expected password to have been updated but wasn't")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// If the request asks us to log out all other devices then // If the request asks us to log out all other devices then
@ -120,7 +129,10 @@ func Password(
logoutRes := &api.PerformDeviceDeletionResponse{} logoutRes := &api.PerformDeviceDeletionResponse{}
if err := userAPI.PerformDeviceDeletion(req.Context(), logoutReq, logoutRes); err != nil { if err := userAPI.PerformDeviceDeletion(req.Context(), logoutReq, logoutRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed") util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
pushersReq := &api.PerformPusherDeletionRequest{ pushersReq := &api.PerformPusherDeletionRequest{
@ -130,7 +142,10 @@ func Password(
} }
if err := userAPI.PerformPusherDeletion(req.Context(), pushersReq, &struct{}{}); err != nil { if err := userAPI.PerformPusherDeletion(req.Context(), pushersReq, &struct{}{}); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformPusherDeletion failed") util.GetLogger(req.Context()).WithError(err).Error("PerformPusherDeletion failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }

View File

@ -75,7 +75,10 @@ func PeekRoomByIDOrAlias(
case nil: case nil:
default: default:
logrus.WithError(err).WithField("roomID", roomIDOrAlias).Errorf("Failed to peek room") logrus.WithError(err).WithField("roomID", roomIDOrAlias).Errorf("Failed to peek room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// if this user is already joined to the room, we let them peek anyway // if this user is already joined to the room, we let them peek anyway
@ -111,7 +114,10 @@ func UnpeekRoomByID(
case nil: case nil:
default: default:
logrus.WithError(err).WithField("roomID", roomID).Errorf("Failed to un-peek room") logrus.WithError(err).WithField("roomID", roomID).Errorf("Failed to un-peek room")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -74,7 +74,7 @@ func SetPresence(
log.WithError(err).Errorf("failed to update presence") log.WithError(err).Errorf("failed to update presence")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
@ -99,7 +99,7 @@ func GetPresence(
log.WithError(err).Errorf("unable to get presence") log.WithError(err).Errorf("unable to get presence")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
@ -118,7 +118,7 @@ func GetPresence(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }

View File

@ -52,7 +52,10 @@ func GetProfile(
} }
util.GetLogger(req.Context()).WithError(err).Error("getProfile failed") util.GetLogger(req.Context()).WithError(err).Error("getProfile failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -111,7 +114,10 @@ func SetAvatarURL(
localpart, domain, err := gomatrixserverlib.SplitID('@', userID) localpart, domain, err := gomatrixserverlib.SplitID('@', userID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !cfg.Matrix.IsLocalServerName(domain) { if !cfg.Matrix.IsLocalServerName(domain) {
@ -132,7 +138,10 @@ func SetAvatarURL(
profile, changed, err := profileAPI.SetAvatarURL(req.Context(), localpart, domain, r.AvatarURL) profile, changed, err := profileAPI.SetAvatarURL(req.Context(), localpart, domain, r.AvatarURL)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("profileAPI.SetAvatarURL failed") util.GetLogger(req.Context()).WithError(err).Error("profileAPI.SetAvatarURL failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// No need to build new membership events, since nothing changed // No need to build new membership events, since nothing changed
if !changed { if !changed {
@ -200,7 +209,10 @@ func SetDisplayName(
localpart, domain, err := gomatrixserverlib.SplitID('@', userID) localpart, domain, err := gomatrixserverlib.SplitID('@', userID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !cfg.Matrix.IsLocalServerName(domain) { if !cfg.Matrix.IsLocalServerName(domain) {
@ -221,7 +233,10 @@ func SetDisplayName(
profile, changed, err := profileAPI.SetDisplayName(req.Context(), localpart, domain, r.DisplayName) profile, changed, err := profileAPI.SetDisplayName(req.Context(), localpart, domain, r.DisplayName)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("profileAPI.SetDisplayName failed") util.GetLogger(req.Context()).WithError(err).Error("profileAPI.SetDisplayName failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// No need to build new membership events, since nothing changed // No need to build new membership events, since nothing changed
if !changed { if !changed {
@ -254,13 +269,19 @@ func updateProfile(
}, &res) }, &res)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("QueryRoomsForUser failed") util.GetLogger(ctx).WithError(err).Error("QueryRoomsForUser failed")
return spec.InternalServerError(), err return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}, err
} }
_, domain, err := gomatrixserverlib.SplitID('@', userID) _, domain, err := gomatrixserverlib.SplitID('@', userID)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(ctx).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError(), err return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}, err
} }
events, err := buildMembershipEvents( events, err := buildMembershipEvents(
@ -275,12 +296,18 @@ func updateProfile(
}, e }, e
default: default:
util.GetLogger(ctx).WithError(err).Error("buildMembershipEvents failed") util.GetLogger(ctx).WithError(err).Error("buildMembershipEvents failed")
return spec.InternalServerError(), e return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}, e
} }
if err := api.SendEvents(ctx, rsAPI, api.KindNew, events, device.UserDomain(), domain, domain, nil, true); err != nil { if err := api.SendEvents(ctx, rsAPI, api.KindNew, events, device.UserDomain(), domain, domain, nil, true); err != nil {
util.GetLogger(ctx).WithError(err).Error("SendEvents failed") util.GetLogger(ctx).WithError(err).Error("SendEvents failed")
return spec.InternalServerError(), err return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}, err
} }
return util.JSONResponse{}, nil return util.JSONResponse{}, nil
} }

View File

@ -34,7 +34,10 @@ func GetPushers(
localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
err = userAPI.QueryPushers(req.Context(), &userapi.QueryPushersRequest{ err = userAPI.QueryPushers(req.Context(), &userapi.QueryPushersRequest{
Localpart: localpart, Localpart: localpart,
@ -42,7 +45,10 @@ func GetPushers(
}, &queryRes) }, &queryRes)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("QueryPushers failed") util.GetLogger(req.Context()).WithError(err).Error("QueryPushers failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
for i := range queryRes.Pushers { for i := range queryRes.Pushers {
queryRes.Pushers[i].SessionID = 0 queryRes.Pushers[i].SessionID = 0
@ -63,7 +69,10 @@ func SetPusher(
localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
body := userapi.PerformPusherSetRequest{} body := userapi.PerformPusherSetRequest{}
if resErr := httputil.UnmarshalJSONRequest(req, &body); resErr != nil { if resErr := httputil.UnmarshalJSONRequest(req, &body); resErr != nil {
@ -99,7 +108,10 @@ func SetPusher(
err = userAPI.PerformPusherSet(req.Context(), &body, &struct{}{}) err = userAPI.PerformPusherSet(req.Context(), &body, &struct{}{})
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("PerformPusherSet failed") util.GetLogger(req.Context()).WithError(err).Error("PerformPusherSet failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -14,20 +14,23 @@ import (
) )
func errorResponse(ctx context.Context, err error, msg string, args ...interface{}) util.JSONResponse { func errorResponse(ctx context.Context, err error, msg string, args ...interface{}) util.JSONResponse {
if eerr, ok := err.(*spec.MatrixError); ok { if eerr, ok := err.(spec.MatrixError); ok {
var status int var status int
switch eerr.ErrCode { switch eerr.ErrCode {
case "M_INVALID_PARAM": case spec.ErrorInvalidParam:
status = http.StatusBadRequest status = http.StatusBadRequest
case "M_NOT_FOUND": case spec.ErrorNotFound:
status = http.StatusNotFound status = http.StatusNotFound
default: default:
status = http.StatusInternalServerError status = http.StatusInternalServerError
} }
return util.MatrixErrorResponse(status, eerr.ErrCode, eerr.Err) return util.MatrixErrorResponse(status, string(eerr.ErrCode), eerr.Err)
} }
util.GetLogger(ctx).WithError(err).Errorf(msg, args...) util.GetLogger(ctx).WithError(err).Errorf(msg, args...)
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
func GetAllPushRules(ctx context.Context, device *userapi.Device, userAPI userapi.ClientUserAPI) util.JSONResponse { func GetAllPushRules(ctx context.Context, device *userapi.Device, userAPI userapi.ClientUserAPI) util.JSONResponse {

View File

@ -48,7 +48,10 @@ func SetReceipt(req *http.Request, userAPI api.ClientUserAPI, syncProducer *prod
case "m.fully_read": case "m.fully_read":
data, err := json.Marshal(fullyReadEvent{EventID: eventID}) data, err := json.Marshal(fullyReadEvent{EventID: eventID})
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
dataReq := api.InputAccountDataRequest{ dataReq := api.InputAccountDataRequest{

View File

@ -16,6 +16,7 @@ package routing
import ( import (
"context" "context"
"errors"
"net/http" "net/http"
"time" "time"
@ -121,17 +122,23 @@ func SendRedaction(
err := proto.SetContent(r) err := proto.SetContent(r)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("proto.SetContent failed") util.GetLogger(req.Context()).WithError(err).Error("proto.SetContent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain()) identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain())
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var queryRes roomserverAPI.QueryLatestEventsAndStateResponse var queryRes roomserverAPI.QueryLatestEventsAndStateResponse
e, err := eventutil.QueryAndBuildEvent(req.Context(), &proto, cfg.Matrix, identity, time.Now(), rsAPI, &queryRes) e, err := eventutil.QueryAndBuildEvent(req.Context(), &proto, cfg.Matrix, identity, time.Now(), rsAPI, &queryRes)
if err == eventutil.ErrRoomNoExists { if errors.Is(err, eventutil.ErrRoomNoExists{}) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: spec.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
@ -140,7 +147,10 @@ func SendRedaction(
domain := device.UserDomain() domain := device.UserDomain()
if err = roomserverAPI.SendEvents(context.Background(), rsAPI, roomserverAPI.KindNew, []*types.HeaderedEvent{e}, device.UserDomain(), domain, domain, nil, false); err != nil { if err = roomserverAPI.SendEvents(context.Background(), rsAPI, roomserverAPI.KindNew, []*types.HeaderedEvent{e}, device.UserDomain(), domain, domain, nil, false); err != nil {
util.GetLogger(req.Context()).WithError(err).Errorf("failed to SendEvents") util.GetLogger(req.Context()).WithError(err).Errorf("failed to SendEvents")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res := util.JSONResponse{ res := util.JSONResponse{

View File

@ -528,7 +528,10 @@ func Register(
nres := &userapi.QueryNumericLocalpartResponse{} nres := &userapi.QueryNumericLocalpartResponse{}
if err = userAPI.QueryNumericLocalpart(req.Context(), nreq, nres); err != nil { if err = userAPI.QueryNumericLocalpart(req.Context(), nreq, nres); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("userAPI.QueryNumericLocalpart failed") util.GetLogger(req.Context()).WithError(err).Error("userAPI.QueryNumericLocalpart failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
r.Username = strconv.FormatInt(nres.ID, 10) r.Username = strconv.FormatInt(nres.ID, 10)
} }
@ -713,7 +716,7 @@ func handleRegistrationFlow(
case nil: case nil:
default: default:
util.GetLogger(req.Context()).WithError(err).Error("failed to validate recaptcha") util.GetLogger(req.Context()).WithError(err).Error("failed to validate recaptcha")
return util.JSONResponse{Code: http.StatusInternalServerError, JSON: spec.InternalServerError()} return util.JSONResponse{Code: http.StatusInternalServerError, JSON: spec.InternalServerError{}}
} }
// Add Recaptcha to the list of completed registration stages // Add Recaptcha to the list of completed registration stages

View File

@ -402,7 +402,7 @@ func Test_register(t *testing.T) {
enableRecaptcha: true, enableRecaptcha: true,
loginType: authtypes.LoginTypeRecaptcha, loginType: authtypes.LoginTypeRecaptcha,
captchaBody: `i should fail for other reasons`, captchaBody: `i should fail for other reasons`,
wantResponse: util.JSONResponse{Code: http.StatusInternalServerError, JSON: spec.InternalServerError()}, wantResponse: util.JSONResponse{Code: http.StatusInternalServerError, JSON: spec.InternalServerError{}},
}, },
} }
@ -484,7 +484,7 @@ func Test_register(t *testing.T) {
if !reflect.DeepEqual(r.Flows, cfg.Derived.Registration.Flows) { if !reflect.DeepEqual(r.Flows, cfg.Derived.Registration.Flows) {
t.Fatalf("unexpected registration flows: %+v, want %+v", r.Flows, cfg.Derived.Registration.Flows) t.Fatalf("unexpected registration flows: %+v, want %+v", r.Flows, cfg.Derived.Registration.Flows)
} }
case *spec.MatrixError: case spec.MatrixError:
if !reflect.DeepEqual(tc.wantResponse, resp) { if !reflect.DeepEqual(tc.wantResponse, resp) {
t.Fatalf("(%s), unexpected response: %+v, want: %+v", tc.name, resp, tc.wantResponse) t.Fatalf("(%s), unexpected response: %+v, want: %+v", tc.name, resp, tc.wantResponse)
} }
@ -541,7 +541,12 @@ func Test_register(t *testing.T) {
resp = Register(req, userAPI, &cfg.ClientAPI) resp = Register(req, userAPI, &cfg.ClientAPI)
switch resp.JSON.(type) { switch resp.JSON.(type) {
case *spec.MatrixError: case spec.InternalServerError:
if !reflect.DeepEqual(tc.wantResponse, resp) {
t.Fatalf("unexpected response: %+v, want: %+v", resp, tc.wantResponse)
}
return
case spec.MatrixError:
if !reflect.DeepEqual(tc.wantResponse, resp) { if !reflect.DeepEqual(tc.wantResponse, resp) {
t.Fatalf("unexpected response: %+v, want: %+v", resp, tc.wantResponse) t.Fatalf("unexpected response: %+v, want: %+v", resp, tc.wantResponse)
} }

View File

@ -46,7 +46,10 @@ func GetTags(
tagContent, err := obtainSavedTags(req, userID, roomID, userAPI) tagContent, err := obtainSavedTags(req, userID, roomID, userAPI)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("obtainSavedTags failed") util.GetLogger(req.Context()).WithError(err).Error("obtainSavedTags failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -83,7 +86,10 @@ func PutTag(
tagContent, err := obtainSavedTags(req, userID, roomID, userAPI) tagContent, err := obtainSavedTags(req, userID, roomID, userAPI)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("obtainSavedTags failed") util.GetLogger(req.Context()).WithError(err).Error("obtainSavedTags failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if tagContent.Tags == nil { if tagContent.Tags == nil {
@ -93,7 +99,10 @@ func PutTag(
if err = saveTagData(req, userID, roomID, userAPI, tagContent); err != nil { if err = saveTagData(req, userID, roomID, userAPI, tagContent); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("saveTagData failed") util.GetLogger(req.Context()).WithError(err).Error("saveTagData failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -125,7 +134,10 @@ func DeleteTag(
tagContent, err := obtainSavedTags(req, userID, roomID, userAPI) tagContent, err := obtainSavedTags(req, userID, roomID, userAPI)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("obtainSavedTags failed") util.GetLogger(req.Context()).WithError(err).Error("obtainSavedTags failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Check whether the tag to be deleted exists // Check whether the tag to be deleted exists
@ -141,7 +153,10 @@ func DeleteTag(
if err = saveTagData(req, userID, roomID, userAPI, tagContent); err != nil { if err = saveTagData(req, userID, roomID, userAPI, tagContent); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("saveTagData failed") util.GetLogger(req.Context()).WithError(err).Error("saveTagData failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -149,7 +149,10 @@ func SendEvent(
} }
aliasRes := &api.GetAliasesForRoomIDResponse{} aliasRes := &api.GetAliasesForRoomIDResponse{}
if err = rsAPI.GetAliasesForRoomID(req.Context(), &api.GetAliasesForRoomIDRequest{RoomID: roomID}, aliasRes); err != nil { if err = rsAPI.GetAliasesForRoomID(req.Context(), &api.GetAliasesForRoomIDRequest{RoomID: roomID}, aliasRes); err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var found int var found int
requestAliases := append(aliasReq.AltAliases, aliasReq.Alias) requestAliases := append(aliasReq.AltAliases, aliasReq.Alias)
@ -193,7 +196,10 @@ func SendEvent(
false, false,
); err != nil { ); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("SendEvents failed") util.GetLogger(req.Context()).WithError(err).Error("SendEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
timeToSubmitEvent := time.Since(startedSubmittingEvent) timeToSubmitEvent := time.Since(startedSubmittingEvent)
util.GetLogger(req.Context()).WithFields(logrus.Fields{ util.GetLogger(req.Context()).WithFields(logrus.Fields{
@ -272,43 +278,51 @@ func generateSendEvent(
err := proto.SetContent(r) err := proto.SetContent(r)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("proto.SetContent failed") util.GetLogger(ctx).WithError(err).Error("proto.SetContent failed")
resErr := spec.InternalServerError() return nil, &util.JSONResponse{
return nil, &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain()) identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain())
if err != nil { if err != nil {
resErr := spec.InternalServerError() return nil, &util.JSONResponse{
return nil, &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var queryRes api.QueryLatestEventsAndStateResponse var queryRes api.QueryLatestEventsAndStateResponse
e, err := eventutil.QueryAndBuildEvent(ctx, &proto, cfg.Matrix, identity, evTime, rsAPI, &queryRes) e, err := eventutil.QueryAndBuildEvent(ctx, &proto, cfg.Matrix, identity, evTime, rsAPI, &queryRes)
if err == eventutil.ErrRoomNoExists { switch specificErr := err.(type) {
case nil:
case eventutil.ErrRoomNoExists:
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: spec.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { case gomatrixserverlib.BadJSONError:
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.BadJSON(e.Error()), JSON: spec.BadJSON(specificErr.Error()),
} }
} else if e, ok := err.(gomatrixserverlib.EventValidationError); ok { case gomatrixserverlib.EventValidationError:
if e.Code == gomatrixserverlib.EventValidationTooLarge { if specificErr.Code == gomatrixserverlib.EventValidationTooLarge {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusRequestEntityTooLarge, Code: http.StatusRequestEntityTooLarge,
JSON: spec.BadJSON(e.Error()), JSON: spec.BadJSON(specificErr.Error()),
} }
} }
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.BadJSON(e.Error()), JSON: spec.BadJSON(specificErr.Error()),
} }
} else if err != nil { default:
util.GetLogger(ctx).WithError(err).Error("eventutil.BuildEvent failed") util.GetLogger(ctx).WithError(err).Error("eventutil.BuildEvent failed")
resErr := spec.InternalServerError() return nil, &util.JSONResponse{
return nil, &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// check to see if this user can perform this operation // check to see if this user can perform this operation

View File

@ -53,7 +53,10 @@ func SendToDevice(
req.Context(), device.UserID, userID, deviceID, eventType, message, req.Context(), device.UserID, userID, deviceID, eventType, message,
); err != nil { ); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("eduProducer.SendToDevice failed") util.GetLogger(req.Context()).WithError(err).Error("eduProducer.SendToDevice failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
} }

View File

@ -58,7 +58,10 @@ func SendTyping(
if err := syncProducer.SendTyping(req.Context(), userID, roomID, r.Typing, r.Timeout); err != nil { if err := syncProducer.SendTyping(req.Context(), userID, roomID, r.Typing, r.Timeout); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("eduProducer.Send failed") util.GetLogger(req.Context()).WithError(err).Error("eduProducer.Send failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -175,7 +175,10 @@ func SendServerNotice(
}} }}
if err = saveTagData(req, r.UserID, roomID, userAPI, serverAlertTag); err != nil { if err = saveTagData(req, r.UserID, roomID, userAPI, serverAlertTag); err != nil {
util.GetLogger(ctx).WithError(err).Error("saveTagData failed") util.GetLogger(ctx).WithError(err).Error("saveTagData failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
default: default:
@ -189,7 +192,10 @@ func SendServerNotice(
err := rsAPI.QueryMembershipForUser(ctx, &api.QueryMembershipForUserRequest{UserID: r.UserID, RoomID: roomID}, &membershipRes) err := rsAPI.QueryMembershipForUser(ctx, &api.QueryMembershipForUserRequest{UserID: r.UserID, RoomID: roomID}, &membershipRes)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("unable to query membership for user") util.GetLogger(ctx).WithError(err).Error("unable to query membership for user")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !membershipRes.IsInRoom { if !membershipRes.IsInRoom {
// re-invite the user // re-invite the user
@ -237,7 +243,10 @@ func SendServerNotice(
false, false,
); err != nil { ); err != nil {
util.GetLogger(ctx).WithError(err).Error("SendEvents failed") util.GetLogger(ctx).WithError(err).Error("SendEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
util.GetLogger(ctx).WithFields(logrus.Fields{ util.GetLogger(ctx).WithFields(logrus.Fields{
"event_id": e.EventID(), "event_id": e.EventID(),

View File

@ -56,7 +56,10 @@ func OnIncomingStateRequest(ctx context.Context, device *userapi.Device, rsAPI a
StateToFetch: []gomatrixserverlib.StateKeyTuple{}, StateToFetch: []gomatrixserverlib.StateKeyTuple{},
}, &stateRes); err != nil { }, &stateRes); err != nil {
util.GetLogger(ctx).WithError(err).Error("queryAPI.QueryLatestEventsAndState failed") util.GetLogger(ctx).WithError(err).Error("queryAPI.QueryLatestEventsAndState failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !stateRes.RoomExists { if !stateRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
@ -73,7 +76,10 @@ func OnIncomingStateRequest(ctx context.Context, device *userapi.Device, rsAPI a
content := map[string]string{} content := map[string]string{}
if err := json.Unmarshal(ev.Content(), &content); err != nil { if err := json.Unmarshal(ev.Content(), &content); err != nil {
util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed") util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if visibility, ok := content["history_visibility"]; ok { if visibility, ok := content["history_visibility"]; ok {
worldReadable = visibility == "world_readable" worldReadable = visibility == "world_readable"
@ -99,7 +105,10 @@ func OnIncomingStateRequest(ctx context.Context, device *userapi.Device, rsAPI a
}, &membershipRes) }, &membershipRes)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser") util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// If the user has never been in the room then stop at this point. // If the user has never been in the room then stop at this point.
// We won't tell the user about a room they have never joined. // We won't tell the user about a room they have never joined.
@ -147,7 +156,10 @@ func OnIncomingStateRequest(ctx context.Context, device *userapi.Device, rsAPI a
}, &stateAfterRes) }, &stateAfterRes)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser") util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
for _, ev := range stateAfterRes.StateEvents { for _, ev := range stateAfterRes.StateEvents {
stateEvents = append( stateEvents = append(
@ -202,7 +214,10 @@ func OnIncomingStateTypeRequest(
StateToFetch: stateToFetch, StateToFetch: stateToFetch,
}, &stateRes); err != nil { }, &stateRes); err != nil {
util.GetLogger(ctx).WithError(err).Error("queryAPI.QueryLatestEventsAndState failed") util.GetLogger(ctx).WithError(err).Error("queryAPI.QueryLatestEventsAndState failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Look at the room state and see if we have a history visibility event // Look at the room state and see if we have a history visibility event
@ -213,7 +228,10 @@ func OnIncomingStateTypeRequest(
content := map[string]string{} content := map[string]string{}
if err := json.Unmarshal(ev.Content(), &content); err != nil { if err := json.Unmarshal(ev.Content(), &content); err != nil {
util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed") util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if visibility, ok := content["history_visibility"]; ok { if visibility, ok := content["history_visibility"]; ok {
worldReadable = visibility == "world_readable" worldReadable = visibility == "world_readable"
@ -239,7 +257,10 @@ func OnIncomingStateTypeRequest(
}, &membershipRes) }, &membershipRes)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser") util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// If the user has never been in the room then stop at this point. // If the user has never been in the room then stop at this point.
// We won't tell the user about a room they have never joined. // We won't tell the user about a room they have never joined.
@ -294,7 +315,10 @@ func OnIncomingStateTypeRequest(
}, &stateAfterRes) }, &stateAfterRes)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser") util.GetLogger(ctx).WithError(err).Error("Failed to QueryMembershipForUser")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if len(stateAfterRes.StateEvents) > 0 { if len(stateAfterRes.StateEvents) > 0 {
event = stateAfterRes.StateEvents[0] event = stateAfterRes.StateEvents[0]

View File

@ -33,7 +33,10 @@ func Protocols(req *http.Request, asAPI appserviceAPI.AppServiceInternalAPI, dev
resp := &appserviceAPI.ProtocolResponse{} resp := &appserviceAPI.ProtocolResponse{}
if err := asAPI.Protocols(req.Context(), &appserviceAPI.ProtocolRequest{Protocol: protocol}, resp); err != nil { if err := asAPI.Protocols(req.Context(), &appserviceAPI.ProtocolRequest{Protocol: protocol}, resp); err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !resp.Exists { if !resp.Exists {
if protocol != "" { if protocol != "" {
@ -71,7 +74,10 @@ func User(req *http.Request, asAPI appserviceAPI.AppServiceInternalAPI, device *
Protocol: protocol, Protocol: protocol,
Params: params.Encode(), Params: params.Encode(),
}, resp); err != nil { }, resp); err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !resp.Exists { if !resp.Exists {
return util.JSONResponse{ return util.JSONResponse{
@ -97,7 +103,10 @@ func Location(req *http.Request, asAPI appserviceAPI.AppServiceInternalAPI, devi
Protocol: protocol, Protocol: protocol,
Params: params.Encode(), Params: params.Encode(),
}, resp); err != nil { }, resp); err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !resp.Exists { if !resp.Exists {
return util.JSONResponse{ return util.JSONResponse{

View File

@ -60,28 +60,37 @@ func RequestEmailToken(req *http.Request, threePIDAPI api.ClientUserAPI, cfg *co
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threePIDAPI.QueryLocalpartForThreePID failed") util.GetLogger(req.Context()).WithError(err).Error("threePIDAPI.QueryLocalpartForThreePID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if len(res.Localpart) > 0 { if len(res.Localpart) > 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.MatrixError{ JSON: spec.MatrixError{
ErrCode: "M_THREEPID_IN_USE", ErrCode: spec.ErrorThreePIDInUse,
Err: userdb.Err3PIDInUse.Error(), Err: userdb.Err3PIDInUse.Error(),
}, },
} }
} }
resp.SID, err = threepid.CreateSession(req.Context(), body, cfg, client) resp.SID, err = threepid.CreateSession(req.Context(), body, cfg, client)
if err == threepid.ErrNotTrusted { switch err.(type) {
case nil:
case threepid.ErrNotTrusted:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CreateSession failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.NotTrusted(body.IDServer), JSON: spec.NotTrusted(body.IDServer),
} }
} else if err != nil { default:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CreateSession failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.CreateSession failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -102,21 +111,27 @@ func CheckAndSave3PIDAssociation(
// Check if the association has been validated // Check if the association has been validated
verified, address, medium, err := threepid.CheckAssociation(req.Context(), body.Creds, cfg, client) verified, address, medium, err := threepid.CheckAssociation(req.Context(), body.Creds, cfg, client)
if err == threepid.ErrNotTrusted { switch err.(type) {
case nil:
case threepid.ErrNotTrusted:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAssociation failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.NotTrusted(body.Creds.IDServer), JSON: spec.NotTrusted(body.Creds.IDServer),
} }
} else if err != nil { default:
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAssociation failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAssociation failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !verified { if !verified {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.MatrixError{ JSON: spec.MatrixError{
ErrCode: "M_THREEPID_AUTH_FAILED", ErrCode: spec.ErrorThreePIDAuthFailed,
Err: "Failed to auth 3pid", Err: "Failed to auth 3pid",
}, },
} }
@ -127,7 +142,10 @@ func CheckAndSave3PIDAssociation(
err = threepid.PublishAssociation(req.Context(), body.Creds, device.UserID, cfg, client) err = threepid.PublishAssociation(req.Context(), body.Creds, device.UserID, cfg, client)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepid.PublishAssociation failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.PublishAssociation failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
@ -135,7 +153,10 @@ func CheckAndSave3PIDAssociation(
localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if err = threePIDAPI.PerformSaveThreePIDAssociation(req.Context(), &api.PerformSaveThreePIDAssociationRequest{ if err = threePIDAPI.PerformSaveThreePIDAssociation(req.Context(), &api.PerformSaveThreePIDAssociationRequest{
@ -145,7 +166,10 @@ func CheckAndSave3PIDAssociation(
Medium: medium, Medium: medium,
}, &struct{}{}); err != nil { }, &struct{}{}); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threePIDAPI.PerformSaveThreePIDAssociation failed") util.GetLogger(req.Context()).WithError(err).Error("threePIDAPI.PerformSaveThreePIDAssociation failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -161,7 +185,10 @@ func GetAssociated3PIDs(
localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID) localpart, domain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res := &api.QueryThreePIDsForLocalpartResponse{} res := &api.QueryThreePIDsForLocalpartResponse{}
@ -171,7 +198,10 @@ func GetAssociated3PIDs(
}, res) }, res)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepidAPI.QueryThreePIDsForLocalpart failed") util.GetLogger(req.Context()).WithError(err).Error("threepidAPI.QueryThreePIDsForLocalpart failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -192,7 +222,10 @@ func Forget3PID(req *http.Request, threepidAPI api.ClientUserAPI) util.JSONRespo
Medium: body.Medium, Medium: body.Medium,
}, &struct{}{}); err != nil { }, &struct{}{}); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepidAPI.PerformForgetThreePID failed") util.GetLogger(req.Context()).WithError(err).Error("threepidAPI.PerformForgetThreePID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -68,13 +68,16 @@ func UpgradeRoom(
JSON: spec.Forbidden(e.Error()), JSON: spec.Forbidden(e.Error()),
} }
default: default:
if errors.Is(err, eventutil.ErrRoomNoExists) { if errors.Is(err, eventutil.ErrRoomNoExists{}) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: spec.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} }
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -60,7 +60,10 @@ func RequestTurnServer(req *http.Request, device *api.Device, cfg *config.Client
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("mac.Write failed") util.GetLogger(req.Context()).WithError(err).Error("mac.Write failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
resp.Password = base64.StdEncoding.EncodeToString(mac.Sum(nil)) resp.Password = base64.StdEncoding.EncodeToString(mac.Sum(nil))

View File

@ -64,13 +64,33 @@ type idServerStoreInviteResponse struct {
} }
var ( var (
errMissingParameter = fmt.Errorf("'address', 'id_server' and 'medium' must all be supplied")
errNotTrusted = fmt.Errorf("untrusted server")
)
// ErrMissingParameter is the error raised if a request for 3PID invite has // ErrMissingParameter is the error raised if a request for 3PID invite has
// an incomplete body // an incomplete body
ErrMissingParameter = errors.New("'address', 'id_server' and 'medium' must all be supplied") type ErrMissingParameter struct{}
func (e ErrMissingParameter) Error() string {
return errMissingParameter.Error()
}
func (e ErrMissingParameter) Unwrap() error {
return errMissingParameter
}
// ErrNotTrusted is the error raised if an identity server isn't in the list // ErrNotTrusted is the error raised if an identity server isn't in the list
// of trusted servers in the configuration file. // of trusted servers in the configuration file.
ErrNotTrusted = errors.New("untrusted server") type ErrNotTrusted struct{}
)
func (e ErrNotTrusted) Error() string {
return errNotTrusted.Error()
}
func (e ErrNotTrusted) Unwrap() error {
return errNotTrusted
}
// CheckAndProcessInvite analyses the body of an incoming membership request. // CheckAndProcessInvite analyses the body of an incoming membership request.
// If the fields relative to a third-party-invite are all supplied, lookups the // If the fields relative to a third-party-invite are all supplied, lookups the
@ -99,7 +119,7 @@ func CheckAndProcessInvite(
} else if body.Address == "" || body.IDServer == "" || body.Medium == "" { } else if body.Address == "" || body.IDServer == "" || body.Medium == "" {
// If at least one of the 3PID-specific fields is supplied but not all // If at least one of the 3PID-specific fields is supplied but not all
// of them, return an error // of them, return an error
err = ErrMissingParameter err = ErrMissingParameter{}
return return
} }

View File

@ -26,6 +26,7 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// EmailAssociationRequest represents the request defined at https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-register-email-requesttoken // EmailAssociationRequest represents the request defined at https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-register-email-requesttoken
@ -133,7 +134,7 @@ func CheckAssociation(
return false, "", "", err return false, "", "", err
} }
if respBody.ErrCode == "M_SESSION_NOT_VALIDATED" { if respBody.ErrCode == string(spec.ErrorSessionNotValidated) {
return false, "", "", nil return false, "", "", nil
} else if len(respBody.ErrCode) > 0 { } else if len(respBody.ErrCode) > 0 {
return false, "", "", errors.New(respBody.Error) return false, "", "", errors.New(respBody.Error)
@ -186,5 +187,5 @@ func isTrusted(idServer string, cfg *config.ClientAPI) error {
return nil return nil
} }
} }
return ErrNotTrusted return ErrNotTrusted{}
} }

View File

@ -98,7 +98,10 @@ func Backfill(
// Query the roomserver. // Query the roomserver.
if err = rsAPI.PerformBackfill(httpReq.Context(), &req, &res); err != nil { if err = rsAPI.PerformBackfill(httpReq.Context(), &req, &res); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("query.PerformBackfill failed") util.GetLogger(httpReq.Context()).WithError(err).Error("query.PerformBackfill failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Filter any event that's not from the requested room out. // Filter any event that's not from the requested room out.

View File

@ -38,7 +38,10 @@ func GetUserDevices(
} }
if res.Error != nil { if res.Error != nil {
util.GetLogger(req.Context()).WithError(res.Error).Error("keyAPI.QueryDeviceMessages failed") util.GetLogger(req.Context()).WithError(res.Error).Error("keyAPI.QueryDeviceMessages failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
sigReq := &api.QuerySignaturesRequest{ sigReq := &api.QuerySignaturesRequest{

View File

@ -183,7 +183,10 @@ func processInvite(
verifyResults, err := keys.VerifyJSONs(ctx, verifyRequests) verifyResults, err := keys.VerifyJSONs(ctx, verifyRequests)
if err != nil { if err != nil {
util.GetLogger(ctx).WithError(err).Error("keys.VerifyJSONs failed") util.GetLogger(ctx).WithError(err).Error("keys.VerifyJSONs failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if verifyResults[0].Error != nil { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
@ -211,7 +214,7 @@ func processInvite(
util.GetLogger(ctx).WithError(err).Error("PerformInvite failed") util.GetLogger(ctx).WithError(err).Error("PerformInvite failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
@ -232,7 +235,7 @@ func processInvite(
sentry.CaptureException(err) sentry.CaptureException(err)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }

View File

@ -15,6 +15,7 @@
package routing package routing
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
@ -33,153 +34,187 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
) )
type JoinRoomQuerier struct {
roomserver api.FederationRoomserverAPI
}
func (rq *JoinRoomQuerier) CurrentStateEvent(ctx context.Context, roomID spec.RoomID, eventType string, stateKey string) (gomatrixserverlib.PDU, error) {
return rq.roomserver.CurrentStateEvent(ctx, roomID, eventType, stateKey)
}
func (rq *JoinRoomQuerier) InvitePending(ctx context.Context, roomID spec.RoomID, userID spec.UserID) (bool, error) {
return rq.roomserver.InvitePending(ctx, roomID, userID)
}
func (rq *JoinRoomQuerier) RestrictedRoomJoinInfo(ctx context.Context, roomID spec.RoomID, userID spec.UserID, localServerName spec.ServerName) (*gomatrixserverlib.RestrictedRoomJoinInfo, error) {
roomInfo, err := rq.roomserver.QueryRoomInfo(ctx, roomID)
if err != nil || roomInfo == nil || roomInfo.IsStub() {
return nil, err
}
req := api.QueryServerJoinedToRoomRequest{
ServerName: localServerName,
RoomID: roomID.String(),
}
res := api.QueryServerJoinedToRoomResponse{}
if err = rq.roomserver.QueryServerJoinedToRoom(ctx, &req, &res); err != nil {
util.GetLogger(ctx).WithError(err).Error("rsAPI.QueryServerJoinedToRoom failed")
return nil, fmt.Errorf("InternalServerError: Failed to query room: %w", err)
}
userJoinedToRoom, err := rq.roomserver.UserJoinedToRoom(ctx, types.RoomNID(roomInfo.RoomNID), userID)
if err != nil {
util.GetLogger(ctx).WithError(err).Error("rsAPI.UserJoinedToRoom failed")
return nil, fmt.Errorf("InternalServerError: %w", err)
}
locallyJoinedUsers, err := rq.roomserver.LocallyJoinedUsers(ctx, roomInfo.RoomVersion, types.RoomNID(roomInfo.RoomNID))
if err != nil {
util.GetLogger(ctx).WithError(err).Error("rsAPI.GetLocallyJoinedUsers failed")
return nil, fmt.Errorf("InternalServerError: %w", err)
}
return &gomatrixserverlib.RestrictedRoomJoinInfo{
LocalServerInRoom: res.RoomExists && res.IsInRoom,
UserJoinedToRoom: userJoinedToRoom,
JoinedUsers: locallyJoinedUsers,
}, nil
}
// MakeJoin implements the /make_join API // MakeJoin implements the /make_join API
func MakeJoin( func MakeJoin(
httpReq *http.Request, httpReq *http.Request,
request *fclient.FederationRequest, request *fclient.FederationRequest,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID, userID string, roomID spec.RoomID, userID spec.UserID,
remoteVersions []gomatrixserverlib.RoomVersion, remoteVersions []gomatrixserverlib.RoomVersion,
) util.JSONResponse { ) util.JSONResponse {
roomVersion, err := rsAPI.QueryRoomVersionForRoom(httpReq.Context(), roomID) roomVersion, err := rsAPI.QueryRoomVersionForRoom(httpReq.Context(), roomID.String())
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("failed obtaining room version")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
// Check that the room that the remote side is trying to join is actually req := api.QueryServerJoinedToRoomRequest{
// one of the room versions that they listed in their supported ?ver= in
// the make_join URL.
// https://matrix.org/docs/spec/server_server/r0.1.3#get-matrix-federation-v1-make-join-roomid-userid
remoteSupportsVersion := false
for _, v := range remoteVersions {
if v == roomVersion {
remoteSupportsVersion = true
break
}
}
// If it isn't, stop trying to join the room.
if !remoteSupportsVersion {
return util.JSONResponse{
Code: http.StatusBadRequest,
JSON: spec.IncompatibleRoomVersion(string(roomVersion)),
}
}
_, domain, err := gomatrixserverlib.SplitID('@', userID)
if err != nil {
return util.JSONResponse{
Code: http.StatusBadRequest,
JSON: spec.BadJSON("Invalid UserID"),
}
}
if domain != request.Origin() {
return util.JSONResponse{
Code: http.StatusForbidden,
JSON: spec.Forbidden("The join must be sent by the server of the user"),
}
}
// Check if we think we are still joined to the room
inRoomReq := &api.QueryServerJoinedToRoomRequest{
ServerName: cfg.Matrix.ServerName, ServerName: cfg.Matrix.ServerName,
RoomID: roomID, RoomID: roomID.String(),
} }
inRoomRes := &api.QueryServerJoinedToRoomResponse{} res := api.QueryServerJoinedToRoomResponse{}
if err = rsAPI.QueryServerJoinedToRoom(httpReq.Context(), inRoomReq, inRoomRes); err != nil { if err := rsAPI.QueryServerJoinedToRoom(httpReq.Context(), &req, &res); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryServerJoinedToRoom failed") util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryServerJoinedToRoom failed")
return spec.InternalServerError()
}
if !inRoomRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusInternalServerError,
JSON: spec.NotFound(fmt.Sprintf("Room ID %q was not found on this server", roomID)), JSON: spec.InternalServerError{},
}
}
if !inRoomRes.IsInRoom {
return util.JSONResponse{
Code: http.StatusNotFound,
JSON: spec.NotFound(fmt.Sprintf("Room ID %q has no remaining users on this server", roomID)),
} }
} }
// Check if the restricted join is allowed. If the room doesn't createJoinTemplate := func(proto *gomatrixserverlib.ProtoEvent) (gomatrixserverlib.PDU, []gomatrixserverlib.PDU, error) {
// support restricted joins then this is effectively a no-op.
res, authorisedVia, err := checkRestrictedJoin(httpReq, rsAPI, roomVersion, roomID, userID)
if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("checkRestrictedJoin failed")
return spec.InternalServerError()
} else if res != nil {
return *res
}
// Try building an event for the server
proto := gomatrixserverlib.ProtoEvent{
Sender: userID,
RoomID: roomID,
Type: "m.room.member",
StateKey: &userID,
}
content := gomatrixserverlib.MemberContent{
Membership: spec.Join,
AuthorisedVia: authorisedVia,
}
if err = proto.SetContent(content); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("builder.SetContent failed")
return spec.InternalServerError()
}
identity, err := cfg.Matrix.SigningIdentityFor(request.Destination()) identity, err := cfg.Matrix.SigningIdentityFor(request.Destination())
if err != nil { if err != nil {
return util.JSONResponse{ util.GetLogger(httpReq.Context()).WithError(err).Errorf("obtaining signing identity for %s failed", request.Destination())
Code: http.StatusNotFound, return nil, nil, spec.NotFound(fmt.Sprintf("Server name %q does not exist", request.Destination()))
JSON: spec.NotFound(
fmt.Sprintf("Server name %q does not exist", request.Destination()),
),
}
} }
queryRes := api.QueryLatestEventsAndStateResponse{ queryRes := api.QueryLatestEventsAndStateResponse{
RoomVersion: roomVersion, RoomVersion: roomVersion,
} }
event, err := eventutil.QueryAndBuildEvent(httpReq.Context(), &proto, cfg.Matrix, identity, time.Now(), rsAPI, &queryRes) event, err := eventutil.QueryAndBuildEvent(httpReq.Context(), proto, cfg.Matrix, identity, time.Now(), rsAPI, &queryRes)
if err == eventutil.ErrRoomNoExists { switch e := err.(type) {
return util.JSONResponse{ case nil:
Code: http.StatusNotFound, case eventutil.ErrRoomNoExists:
JSON: spec.NotFound("Room does not exist"), util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return nil, nil, spec.NotFound("Room does not exist")
case gomatrixserverlib.BadJSONError:
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return nil, nil, spec.BadJSON(e.Error())
default:
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return nil, nil, spec.InternalServerError{}
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok {
stateEvents := make([]gomatrixserverlib.PDU, len(queryRes.StateEvents))
for i, stateEvent := range queryRes.StateEvents {
stateEvents[i] = stateEvent.PDU
}
return event, stateEvents, nil
}
roomQuerier := JoinRoomQuerier{
roomserver: rsAPI,
}
input := gomatrixserverlib.HandleMakeJoinInput{
Context: httpReq.Context(),
UserID: userID,
RoomID: roomID,
RoomVersion: roomVersion,
RemoteVersions: remoteVersions,
RequestOrigin: request.Origin(),
LocalServerName: cfg.Matrix.ServerName,
LocalServerInRoom: res.RoomExists && res.IsInRoom,
RoomQuerier: &roomQuerier,
BuildEventTemplate: createJoinTemplate,
}
response, internalErr := gomatrixserverlib.HandleMakeJoin(input)
if internalErr != nil {
switch e := internalErr.(type) {
case nil:
case spec.InternalServerError:
util.GetLogger(httpReq.Context()).WithError(internalErr)
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
case spec.MatrixError:
util.GetLogger(httpReq.Context()).WithError(internalErr)
code := http.StatusInternalServerError
switch e.ErrCode {
case spec.ErrorForbidden:
code = http.StatusForbidden
case spec.ErrorNotFound:
code = http.StatusNotFound
case spec.ErrorUnableToAuthoriseJoin:
code = http.StatusBadRequest
case spec.ErrorBadJSON:
code = http.StatusBadRequest
}
return util.JSONResponse{
Code: code,
JSON: e,
}
case spec.IncompatibleRoomVersionError:
util.GetLogger(httpReq.Context()).WithError(internalErr)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.BadJSON(e.Error()), JSON: e,
} }
} else if err != nil { default:
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed") util.GetLogger(httpReq.Context()).WithError(internalErr)
return spec.InternalServerError()
}
// Check that the join is allowed or not
stateEvents := make([]gomatrixserverlib.PDU, len(queryRes.StateEvents))
for i := range queryRes.StateEvents {
stateEvents[i] = queryRes.StateEvents[i].PDU
}
provider := gomatrixserverlib.NewAuthEvents(stateEvents)
if err = gomatrixserverlib.Allowed(event.PDU, &provider); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusBadRequest,
JSON: spec.Forbidden(err.Error()), JSON: spec.Unknown("unknown error"),
}
}
}
if response == nil {
util.GetLogger(httpReq.Context()).Error("gmsl.HandleMakeJoin returned invalid response")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
JSON: map[string]interface{}{ JSON: map[string]interface{}{
"event": proto, "event": response.JoinTemplateEvent,
"room_version": roomVersion, "room_version": response.RoomVersion,
}, },
} }
} }
@ -201,7 +236,7 @@ func SendJoin(
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryRoomVersionForRoom failed") util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryRoomVersionForRoom failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion) verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
@ -311,7 +346,10 @@ func SendJoin(
verifyResults, err := keys.VerifyJSONs(httpReq.Context(), verifyRequests) verifyResults, err := keys.VerifyJSONs(httpReq.Context(), verifyRequests)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("keys.VerifyJSONs failed") util.GetLogger(httpReq.Context()).WithError(err).Error("keys.VerifyJSONs failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if verifyResults[0].Error != nil { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
@ -331,7 +369,10 @@ func SendJoin(
}, &stateAndAuthChainResponse) }, &stateAndAuthChainResponse)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryStateAndAuthChain failed") util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryStateAndAuthChain failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !stateAndAuthChainResponse.RoomExists { if !stateAndAuthChainResponse.RoomExists {
@ -427,7 +468,10 @@ func SendJoin(
JSON: spec.Forbidden(response.ErrMsg), JSON: spec.Forbidden(response.ErrMsg),
} }
} }
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
@ -449,74 +493,6 @@ func SendJoin(
} }
} }
// checkRestrictedJoin finds out whether or not we can assist in processing
// a restricted room join. If the room version does not support restricted
// joins then this function returns with no side effects. This returns three
// values:
// - an optional JSON response body (i.e. M_UNABLE_TO_AUTHORISE_JOIN) which
// should always be sent back to the client if one is specified
// - a user ID of an authorising user, typically a user that has power to
// issue invites in the room, if one has been found
// - an error if there was a problem finding out if this was allowable,
// like if the room version isn't known or a problem happened talking to
// the roomserver
func checkRestrictedJoin(
httpReq *http.Request,
rsAPI api.FederationRoomserverAPI,
roomVersion gomatrixserverlib.RoomVersion,
roomID, userID string,
) (*util.JSONResponse, string, error) {
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil {
return nil, "", err
}
if !verImpl.MayAllowRestrictedJoinsInEventAuth() {
return nil, "", nil
}
req := &api.QueryRestrictedJoinAllowedRequest{
RoomID: roomID,
UserID: userID,
}
res := &api.QueryRestrictedJoinAllowedResponse{}
if err := rsAPI.QueryRestrictedJoinAllowed(httpReq.Context(), req, res); err != nil {
return nil, "", err
}
switch {
case !res.Restricted:
// The join rules for the room don't restrict membership.
return nil, "", nil
case !res.Resident:
// The join rules restrict membership but our server isn't currently
// joined to all of the allowed rooms, so we can't actually decide
// whether or not to allow the user to join. This error code should
// tell the joining server to try joining via another resident server
// instead.
return &util.JSONResponse{
Code: http.StatusBadRequest,
JSON: spec.UnableToAuthoriseJoin("This server cannot authorise the join."),
}, "", nil
case !res.Allowed:
// The join rules restrict membership, our server is in the relevant
// rooms and the user wasn't joined to join any of the allowed rooms
// and therefore can't join this room.
return &util.JSONResponse{
Code: http.StatusForbidden,
JSON: spec.Forbidden("You are not joined to any matching rooms."),
}, "", nil
default:
// The join rules restrict membership, our server is in the relevant
// rooms and the user was allowed to join because they belong to one
// of the allowed rooms. We now need to pick one of our own local users
// from within the room to use as the authorising user ID, so that it
// can be referred to from within the membership content.
return nil, res.AuthorisedVia, nil
}
}
type eventsByDepth []*types.HeaderedEvent type eventsByDepth []*types.HeaderedEvent
func (e eventsByDepth) Len() int { func (e eventsByDepth) Len() int {

View File

@ -67,7 +67,10 @@ func QueryDeviceKeys(
}, &queryRes) }, &queryRes)
if queryRes.Error != nil { if queryRes.Error != nil {
util.GetLogger(httpReq.Context()).WithError(queryRes.Error).Error("Failed to QueryKeys") util.GetLogger(httpReq.Context()).WithError(queryRes.Error).Error("Failed to QueryKeys")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,
@ -119,7 +122,10 @@ func ClaimOneTimeKeys(
}, &claimRes) }, &claimRes)
if claimRes.Error != nil { if claimRes.Error != nil {
util.GetLogger(httpReq.Context()).WithError(claimRes.Error).Error("Failed to PerformClaimKeys") util.GetLogger(httpReq.Context()).WithError(claimRes.Error).Error("Failed to PerformClaimKeys")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,
@ -243,7 +249,10 @@ func NotaryKeys(
j, err := json.Marshal(keys) j, err := json.Marshal(keys)
if err != nil { if err != nil {
logrus.WithError(err).Errorf("Failed to marshal %q response", serverName) logrus.WithError(err).Errorf("Failed to marshal %q response", serverName)
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
js, err := gomatrixserverlib.SignJSON( js, err := gomatrixserverlib.SignJSON(
@ -251,7 +260,10 @@ func NotaryKeys(
) )
if err != nil { if err != nil {
logrus.WithError(err).Errorf("Failed to sign %q response", serverName) logrus.WithError(err).Errorf("Failed to sign %q response", serverName)
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
response.ServerKeys = append(response.ServerKeys, js) response.ServerKeys = append(response.ServerKeys, js)

View File

@ -60,7 +60,10 @@ func MakeLeave(
err = proto.SetContent(map[string]interface{}{"membership": spec.Leave}) err = proto.SetContent(map[string]interface{}{"membership": spec.Leave})
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("proto.SetContent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("proto.SetContent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
identity, err := cfg.Matrix.SigningIdentityFor(request.Destination()) identity, err := cfg.Matrix.SigningIdentityFor(request.Destination())
@ -75,19 +78,26 @@ func MakeLeave(
var queryRes api.QueryLatestEventsAndStateResponse var queryRes api.QueryLatestEventsAndStateResponse
event, err := eventutil.QueryAndBuildEvent(httpReq.Context(), &proto, cfg.Matrix, identity, time.Now(), rsAPI, &queryRes) event, err := eventutil.QueryAndBuildEvent(httpReq.Context(), &proto, cfg.Matrix, identity, time.Now(), rsAPI, &queryRes)
if err == eventutil.ErrRoomNoExists { switch e := err.(type) {
case nil:
case eventutil.ErrRoomNoExists:
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: spec.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { case gomatrixserverlib.BadJSONError:
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: spec.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} else if err != nil { default:
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// If the user has already left then just return their last leave // If the user has already left then just return their last leave
@ -233,7 +243,10 @@ func SendLeave(
err = rsAPI.QueryLatestEventsAndState(httpReq.Context(), queryReq, queryRes) err = rsAPI.QueryLatestEventsAndState(httpReq.Context(), queryReq, queryRes)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryLatestEventsAndState failed") util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryLatestEventsAndState failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// The room doesn't exist or we weren't ever joined to it. Might as well // The room doesn't exist or we weren't ever joined to it. Might as well
// no-op here. // no-op here.
@ -279,7 +292,10 @@ func SendLeave(
verifyResults, err := keys.VerifyJSONs(httpReq.Context(), verifyRequests) verifyResults, err := keys.VerifyJSONs(httpReq.Context(), verifyRequests)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("keys.VerifyJSONs failed") util.GetLogger(httpReq.Context()).WithError(err).Error("keys.VerifyJSONs failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if verifyResults[0].Error != nil { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
@ -327,7 +343,10 @@ func SendLeave(
JSON: spec.Forbidden(response.ErrMsg), JSON: spec.Forbidden(response.ErrMsg),
} }
} }
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -63,7 +63,10 @@ func GetMissingEvents(
&eventsResponse, &eventsResponse,
); err != nil { ); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("query.QueryMissingEvents failed") util.GetLogger(httpReq.Context()).WithError(err).Error("query.QueryMissingEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
eventsResponse.Events = filterEvents(eventsResponse.Events, roomID) eventsResponse.Events = filterEvents(eventsResponse.Events, roomID)

View File

@ -40,7 +40,7 @@ func Peek(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }

View File

@ -53,7 +53,10 @@ func GetProfile(
profile, err := userAPI.QueryProfile(httpReq.Context(), userID) profile, err := userAPI.QueryProfile(httpReq.Context(), userID)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("userAPI.QueryProfile failed") util.GetLogger(httpReq.Context()).WithError(err).Error("userAPI.QueryProfile failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var res interface{} var res interface{}

View File

@ -39,7 +39,10 @@ func GetPostPublicRooms(req *http.Request, rsAPI roomserverAPI.FederationRoomser
} }
response, err := publicRooms(req.Context(), request, rsAPI) response, err := publicRooms(req.Context(), request, rsAPI)
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -106,8 +109,10 @@ func fillPublicRoomsReq(httpReq *http.Request, request *PublicRoomReq) *util.JSO
// In that case, we want to assign 0 so we ignore the error // In that case, we want to assign 0 so we ignore the error
if err != nil && len(httpReq.FormValue("limit")) > 0 { if err != nil && len(httpReq.FormValue("limit")) > 0 {
util.GetLogger(httpReq.Context()).WithError(err).Error("strconv.Atoi failed") util.GetLogger(httpReq.Context()).WithError(err).Error("strconv.Atoi failed")
reqErr := spec.InternalServerError() return &util.JSONResponse{
return &reqErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
request.Limit = int16(limit) request.Limit = int16(limit)
request.Since = httpReq.FormValue("since") request.Since = httpReq.FormValue("since")

View File

@ -61,7 +61,10 @@ func RoomAliasToID(
queryRes := &roomserverAPI.GetRoomIDForAliasResponse{} queryRes := &roomserverAPI.GetRoomIDForAliasResponse{}
if err = rsAPI.GetRoomIDForAlias(httpReq.Context(), queryReq, queryRes); err != nil { if err = rsAPI.GetRoomIDForAlias(httpReq.Context(), queryReq, queryRes); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("aliasAPI.GetRoomIDForAlias failed") util.GetLogger(httpReq.Context()).WithError(err).Error("aliasAPI.GetRoomIDForAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if queryRes.RoomID != "" { if queryRes.RoomID != "" {
@ -69,7 +72,10 @@ func RoomAliasToID(
var serverQueryRes federationAPI.QueryJoinedHostServerNamesInRoomResponse var serverQueryRes federationAPI.QueryJoinedHostServerNamesInRoomResponse
if err = senderAPI.QueryJoinedHostServerNamesInRoom(httpReq.Context(), &serverQueryReq, &serverQueryRes); err != nil { if err = senderAPI.QueryJoinedHostServerNamesInRoom(httpReq.Context(), &serverQueryReq, &serverQueryRes); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("senderAPI.QueryJoinedHostServerNamesInRoom failed") util.GetLogger(httpReq.Context()).WithError(err).Error("senderAPI.QueryJoinedHostServerNamesInRoom failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
resp = fclient.RespDirectory{ resp = fclient.RespDirectory{
@ -98,7 +104,10 @@ func RoomAliasToID(
// TODO: Return 502 if the remote server errored. // TODO: Return 502 if the remote server errored.
// TODO: Return 504 if the remote server timed out. // TODO: Return 504 if the remote server timed out.
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.LookupRoomAlias failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.LookupRoomAlias failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }

View File

@ -312,8 +312,6 @@ func Setup(
JSON: spec.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"]
userID := vars["userID"]
queryVars := httpReq.URL.Query() queryVars := httpReq.URL.Query()
remoteVersions := []gomatrixserverlib.RoomVersion{} remoteVersions := []gomatrixserverlib.RoomVersion{}
if vers, ok := queryVars["ver"]; ok { if vers, ok := queryVars["ver"]; ok {
@ -328,8 +326,25 @@ func Setup(
// https://matrix.org/docs/spec/server_server/r0.1.3#get-matrix-federation-v1-make-join-roomid-userid // https://matrix.org/docs/spec/server_server/r0.1.3#get-matrix-federation-v1-make-join-roomid-userid
remoteVersions = append(remoteVersions, gomatrixserverlib.RoomVersionV1) remoteVersions = append(remoteVersions, gomatrixserverlib.RoomVersionV1)
} }
userID, err := spec.NewUserID(vars["userID"], true)
if err != nil {
return util.JSONResponse{
Code: http.StatusBadRequest,
JSON: spec.BadJSON("Invalid UserID"),
}
}
roomID, err := spec.NewRoomID(vars["roomID"])
if err != nil {
return util.JSONResponse{
Code: http.StatusBadRequest,
JSON: spec.BadJSON("Invalid RoomID"),
}
}
logrus.Debugf("Processing make_join for user %s, room %s", userID.String(), roomID.String())
return MakeJoin( return MakeJoin(
httpReq, request, cfg, rsAPI, roomID, userID, remoteVersions, httpReq, request, cfg, rsAPI, *roomID, *userID, remoteVersions,
) )
}, },
)).Methods(http.MethodGet) )).Methods(http.MethodGet)
@ -353,7 +368,7 @@ func Setup(
body = []interface{}{ body = []interface{}{
res.Code, res.JSON, res.Code, res.JSON,
} }
jerr, ok := res.JSON.(*spec.MatrixError) jerr, ok := res.JSON.(spec.MatrixError)
if ok { if ok {
body = jerr body = jerr
} }
@ -419,7 +434,7 @@ func Setup(
body = []interface{}{ body = []interface{}{
res.Code, res.JSON, res.Code, res.JSON,
} }
jerr, ok := res.JSON.(*spec.MatrixError) jerr, ok := res.JSON.(spec.MatrixError)
if ok { if ok {
body = jerr body = jerr
} }
@ -566,7 +581,7 @@ func MakeFedAPI(
go wakeup.Wakeup(req.Context(), fedReq.Origin()) go wakeup.Wakeup(req.Context(), fedReq.Origin())
vars, err := httputil.URLDecodeMapValues(mux.Vars(req)) vars, err := httputil.URLDecodeMapValues(mux.Vars(req))
if err != nil { if err != nil {
return util.MatrixErrorResponse(400, "M_UNRECOGNISED", "badly encoded query params") return util.MatrixErrorResponse(400, string(spec.ErrorUnrecognized), "badly encoded query params")
} }
jsonRes := f(req, fedReq, vars) jsonRes := f(req, fedReq, vars)

View File

@ -80,7 +80,10 @@ func CreateInvitesFrom3PIDInvites(
) )
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("createInviteFrom3PIDInvite failed") util.GetLogger(req.Context()).WithError(err).Error("createInviteFrom3PIDInvite failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if event != nil { if event != nil {
evs = append(evs, &types.HeaderedEvent{PDU: event}) evs = append(evs, &types.HeaderedEvent{PDU: event})
@ -100,7 +103,10 @@ func CreateInvitesFrom3PIDInvites(
false, false,
); err != nil { ); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("SendEvents failed") util.GetLogger(req.Context()).WithError(err).Error("SendEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{
@ -176,7 +182,10 @@ func ExchangeThirdPartyInvite(
} }
} else if err != nil { } else if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("buildMembershipEvent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("buildMembershipEvent failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Ask the requesting server to sign the newly created event so we know it // Ask the requesting server to sign the newly created event so we know it
@ -184,22 +193,34 @@ func ExchangeThirdPartyInvite(
inviteReq, err := fclient.NewInviteV2Request(event, nil) inviteReq, err := fclient.NewInviteV2Request(event, nil)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("failed to make invite v2 request") util.GetLogger(httpReq.Context()).WithError(err).Error("failed to make invite v2 request")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
signedEvent, err := federation.SendInviteV2(httpReq.Context(), senderDomain, request.Origin(), inviteReq) signedEvent, err := federation.SendInviteV2(httpReq.Context(), senderDomain, request.Origin(), inviteReq)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion) verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Errorf("unknown room version: %s", roomVersion) util.GetLogger(httpReq.Context()).WithError(err).Errorf("unknown room version: %s", roomVersion)
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
inviteEvent, err := verImpl.NewEventFromUntrustedJSON(signedEvent.Event) inviteEvent, err := verImpl.NewEventFromUntrustedJSON(signedEvent.Event)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Send the event to the roomserver // Send the event to the roomserver
@ -216,7 +237,10 @@ func ExchangeThirdPartyInvite(
false, false,
); err != nil { ); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("SendEvents failed") util.GetLogger(httpReq.Context()).WithError(err).Error("SendEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

4
go.mod
View File

@ -22,7 +22,7 @@ require (
github.com/matrix-org/dugong v0.0.0-20210921133753-66e6b1c67e2e github.com/matrix-org/dugong v0.0.0-20210921133753-66e6b1c67e2e
github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91 github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91
github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530
github.com/matrix-org/gomatrixserverlib v0.0.0-20230509222610-6fd532036ab6 github.com/matrix-org/gomatrixserverlib v0.0.0-20230517000105-1ff06fc8a6a2
github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a
github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 github.com/matrix-org/util v0.0.0-20221111132719-399730281e66
github.com/mattn/go-sqlite3 v1.14.16 github.com/mattn/go-sqlite3 v1.14.16
@ -34,7 +34,7 @@ require (
github.com/patrickmn/go-cache v2.1.0+incompatible github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.13.0 github.com/prometheus/client_golang v1.13.0
github.com/sirupsen/logrus v1.9.0 github.com/sirupsen/logrus v1.9.1
github.com/stretchr/testify v1.8.2 github.com/stretchr/testify v1.8.2
github.com/tidwall/gjson v1.14.4 github.com/tidwall/gjson v1.14.4
github.com/tidwall/sjson v1.2.5 github.com/tidwall/sjson v1.2.5

8
go.sum
View File

@ -323,8 +323,8 @@ github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91 h1:s7fexw
github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91/go.mod h1:e+cg2q7C7yE5QnAXgzo512tgFh1RbQLC0+jozuegKgo= github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91/go.mod h1:e+cg2q7C7yE5QnAXgzo512tgFh1RbQLC0+jozuegKgo=
github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 h1:kHKxCOLcHH8r4Fzarl4+Y3K5hjothkVW5z7T1dUM11U= 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/gomatrix v0.0.0-20220926102614-ceba4d9f7530/go.mod h1:/gBX06Kw0exX1HrwmoBibFA98yBk/jxKpGVeyQbff+s=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230509222610-6fd532036ab6 h1:cF6fNfxC73fU9zT3pgzDXI9NDihAdnilqqGcpDWgNP4= github.com/matrix-org/gomatrixserverlib v0.0.0-20230517000105-1ff06fc8a6a2 h1:V36yCWt2CoSfI1xr6WYJ9Mb3eyl95SknMRLGFvEuYak=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230509222610-6fd532036ab6/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU= github.com/matrix-org/gomatrixserverlib v0.0.0-20230517000105-1ff06fc8a6a2/go.mod h1:H9V9N3Uqn1bBJqYJNGK1noqtgJTaCEhtTdcH/mp50uU=
github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a h1:awrPDf9LEFySxTLKYBMCiObelNx/cBuv/wzllvCCH3A= github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a h1:awrPDf9LEFySxTLKYBMCiObelNx/cBuv/wzllvCCH3A=
github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a/go.mod h1:HchJX9oKMXaT2xYFs0Ha/6Zs06mxLU8k6F1ODnrGkeQ= github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a/go.mod h1:HchJX9oKMXaT2xYFs0Ha/6Zs06mxLU8k6F1ODnrGkeQ=
github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 h1:6z4KxomXSIGWqhHcfzExgkH3Z3UkIXry4ibJS4Aqz2Y= github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 h1:6z4KxomXSIGWqhHcfzExgkH3Z3UkIXry4ibJS4Aqz2Y=
@ -444,8 +444,8 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 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.1 h1:Ou41VVR3nMWWmTiEUnj0OlsgOSCUFgsPAOl6jRIcVtQ=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sirupsen/logrus v1.9.1/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=

View File

@ -31,7 +31,17 @@ import (
// ErrRoomNoExists is returned when trying to lookup the state of a room that // ErrRoomNoExists is returned when trying to lookup the state of a room that
// doesn't exist // doesn't exist
var ErrRoomNoExists = errors.New("room does not exist") var errRoomNoExists = fmt.Errorf("room does not exist")
type ErrRoomNoExists struct{}
func (e ErrRoomNoExists) Error() string {
return errRoomNoExists.Error()
}
func (e ErrRoomNoExists) Unwrap() error {
return errRoomNoExists
}
// QueryAndBuildEvent builds a Matrix event using the event builder and roomserver query // QueryAndBuildEvent builds a Matrix event using the event builder and roomserver query
// API client provided. If also fills roomserver query API response (if provided) // API client provided. If also fills roomserver query API response (if provided)
@ -116,7 +126,7 @@ func addPrevEventsToEvent(
queryRes *api.QueryLatestEventsAndStateResponse, queryRes *api.QueryLatestEventsAndStateResponse,
) error { ) error {
if !queryRes.RoomExists { if !queryRes.RoomExists {
return ErrRoomNoExists return ErrRoomNoExists{}
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(queryRes.RoomVersion) verImpl, err := gomatrixserverlib.GetRoomVersion(queryRes.RoomVersion)

View File

@ -15,10 +15,12 @@
package httputil package httputil
import ( import (
"encoding/json"
"net/http" "net/http"
"net/url" "net/url"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// URLDecodeMapValues is a function that iterates through each of the items in a // URLDecodeMapValues is a function that iterates through each of the items in a
@ -66,13 +68,15 @@ func NewRouters() Routers {
var NotAllowedHandler = WrapHandlerInCORS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var NotAllowedHandler = WrapHandlerInCORS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed) w.WriteHeader(http.StatusMethodNotAllowed)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}`)) // nolint:misspell unrecognizedErr, _ := json.Marshal(spec.Unrecognized("Unrecognized request")) // nolint:misspell
_, _ = w.Write(unrecognizedErr) // nolint:misspell
})) }))
var NotFoundCORSHandler = WrapHandlerInCORS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var NotFoundCORSHandler = WrapHandlerInCORS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}`)) // nolint:misspell unrecognizedErr, _ := json.Marshal(spec.Unrecognized("Unrecognized request")) // nolint:misspell
_, _ = w.Write(unrecognizedErr) // nolint:misspell
})) }))
func (r *Routers) configureHTTPErrors() { func (r *Routers) configureHTTPErrors() {

View File

@ -184,8 +184,10 @@ func (r *uploadRequest) doUpload(
if err != nil { if err != nil {
fileutils.RemoveDir(tmpDir, r.Logger) fileutils.RemoveDir(tmpDir, r.Logger)
r.Logger.WithError(err).Error("Error querying the database by hash.") r.Logger.WithError(err).Error("Error querying the database by hash.")
resErr := spec.InternalServerError() return &util.JSONResponse{
return &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if existingMetadata != nil { if existingMetadata != nil {
// The file already exists, delete the uploaded temporary file. // The file already exists, delete the uploaded temporary file.
@ -194,8 +196,10 @@ func (r *uploadRequest) doUpload(
mediaID, merr := r.generateMediaID(ctx, db) mediaID, merr := r.generateMediaID(ctx, db)
if merr != nil { if merr != nil {
r.Logger.WithError(merr).Error("Failed to generate media ID for existing file") r.Logger.WithError(merr).Error("Failed to generate media ID for existing file")
resErr := spec.InternalServerError() return &util.JSONResponse{
return &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// Then amend the upload metadata. // Then amend the upload metadata.
@ -217,8 +221,10 @@ func (r *uploadRequest) doUpload(
if err != nil { if err != nil {
fileutils.RemoveDir(tmpDir, r.Logger) fileutils.RemoveDir(tmpDir, r.Logger)
r.Logger.WithError(err).Error("Failed to generate media ID for new upload") r.Logger.WithError(err).Error("Failed to generate media ID for new upload")
resErr := spec.InternalServerError() return &util.JSONResponse{
return &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }

View File

@ -122,7 +122,7 @@ func MakeRelayAPI(
}() }()
vars, err := httputil.URLDecodeMapValues(mux.Vars(req)) vars, err := httputil.URLDecodeMapValues(mux.Vars(req))
if err != nil { if err != nil {
return util.MatrixErrorResponse(400, "M_UNRECOGNISED", "badly encoded query params") return util.MatrixErrorResponse(400, string(spec.ErrorUnrecognized), "badly encoded query params")
} }
jsonRes := f(req, fedReq, vars) jsonRes := f(req, fedReq, vars)

View File

@ -8,6 +8,7 @@ import (
asAPI "github.com/matrix-org/dendrite/appservice/api" asAPI "github.com/matrix-org/dendrite/appservice/api"
fsAPI "github.com/matrix-org/dendrite/federationapi/api" fsAPI "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/dendrite/roomserver/types"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
) )
@ -224,6 +225,12 @@ type FederationRoomserverAPI interface {
PerformInvite(ctx context.Context, req *PerformInviteRequest) error PerformInvite(ctx context.Context, req *PerformInviteRequest) error
// Query a given amount (or less) of events prior to a given set of events. // Query a given amount (or less) of events prior to a given set of events.
PerformBackfill(ctx context.Context, req *PerformBackfillRequest, res *PerformBackfillResponse) error PerformBackfill(ctx context.Context, req *PerformBackfillRequest, res *PerformBackfillResponse) error
CurrentStateEvent(ctx context.Context, roomID spec.RoomID, eventType string, stateKey string) (gomatrixserverlib.PDU, error)
InvitePending(ctx context.Context, roomID spec.RoomID, userID spec.UserID) (bool, error)
QueryRoomInfo(ctx context.Context, roomID spec.RoomID) (*types.RoomInfo, error)
UserJoinedToRoom(ctx context.Context, roomID types.RoomNID, userID spec.UserID) (bool, error)
LocallyJoinedUsers(ctx context.Context, roomVersion gomatrixserverlib.RoomVersion, roomNID types.RoomNID) ([]gomatrixserverlib.PDU, error)
} }
type KeyserverRoomserverAPI interface { type KeyserverRoomserverAPI interface {

View File

@ -52,7 +52,7 @@ func (r *Admin) PerformAdminEvacuateRoom(
return nil, err return nil, err
} }
if roomInfo == nil || roomInfo.IsStub() { if roomInfo == nil || roomInfo.IsStub() {
return nil, eventutil.ErrRoomNoExists return nil, eventutil.ErrRoomNoExists{}
} }
memberNIDs, err := r.DB.GetMembershipEventNIDsForRoom(ctx, roomInfo.RoomNID, true, true) memberNIDs, err := r.DB.GetMembershipEventNIDsForRoom(ctx, roomInfo.RoomNID, true, true)
@ -240,7 +240,7 @@ func (r *Admin) PerformAdminDownloadState(
} }
if roomInfo == nil || roomInfo.IsStub() { if roomInfo == nil || roomInfo.IsStub() {
return eventutil.ErrRoomNoExists return eventutil.ErrRoomNoExists{}
} }
fwdExtremities, _, depth, err := r.DB.LatestEventIDs(ctx, roomInfo.RoomNID) fwdExtremities, _, depth, err := r.DB.LatestEventIDs(ctx, roomInfo.RoomNID)

View File

@ -145,7 +145,7 @@ func (r *Joiner) performJoinRoomByAlias(
return r.performJoinRoomByID(ctx, req) return r.performJoinRoomByID(ctx, req)
} }
// TODO: Break this function up a bit // TODO: Break this function up a bit & move to GMSL
// nolint:gocyclo // nolint:gocyclo
func (r *Joiner) performJoinRoomByID( func (r *Joiner) performJoinRoomByID(
ctx context.Context, ctx context.Context,
@ -286,7 +286,7 @@ func (r *Joiner) performJoinRoomByID(
} }
event, err := eventutil.QueryAndBuildEvent(ctx, &proto, r.Cfg.Matrix, identity, time.Now(), r.RSAPI, &buildRes) event, err := eventutil.QueryAndBuildEvent(ctx, &proto, r.Cfg.Matrix, identity, time.Now(), r.RSAPI, &buildRes)
switch err { switch err.(type) {
case nil: case nil:
// The room join is local. Send the new join event into the // The room join is local. Send the new join event into the
// roomserver. First of all check that the user isn't already // roomserver. First of all check that the user isn't already
@ -328,7 +328,7 @@ func (r *Joiner) performJoinRoomByID(
// Otherwise we'll try a federated join as normal, since it's quite // Otherwise we'll try a federated join as normal, since it's quite
// possible that the room still exists on other servers. // possible that the room still exists on other servers.
if len(req.ServerNames) == 0 { if len(req.ServerNames) == 0 {
return "", "", eventutil.ErrRoomNoExists return "", "", eventutil.ErrRoomNoExists{}
} }
} }

View File

@ -274,7 +274,7 @@ func publishNewRoomAndUnpublishOldRoom(
func (r *Upgrader) validateRoomExists(ctx context.Context, roomID string) error { func (r *Upgrader) validateRoomExists(ctx context.Context, roomID string) error {
if _, err := r.URSAPI.QueryRoomVersionForRoom(ctx, roomID); err != nil { if _, err := r.URSAPI.QueryRoomVersionForRoom(ctx, roomID); err != nil {
return eventutil.ErrRoomNoExists return eventutil.ErrRoomNoExists{}
} }
return nil return nil
} }
@ -556,15 +556,18 @@ func (r *Upgrader) makeHeaderedEvent(ctx context.Context, evTime time.Time, user
} }
var queryRes api.QueryLatestEventsAndStateResponse var queryRes api.QueryLatestEventsAndStateResponse
headeredEvent, err := eventutil.QueryAndBuildEvent(ctx, &proto, r.Cfg.Matrix, identity, evTime, r.URSAPI, &queryRes) headeredEvent, err := eventutil.QueryAndBuildEvent(ctx, &proto, r.Cfg.Matrix, identity, evTime, r.URSAPI, &queryRes)
if err == eventutil.ErrRoomNoExists { switch e := err.(type) {
return nil, err case nil:
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { case eventutil.ErrRoomNoExists:
return nil, e return nil, e
} else if e, ok := err.(gomatrixserverlib.EventValidationError); ok { case gomatrixserverlib.BadJSONError:
return nil, e return nil, e
} else if err != nil { case gomatrixserverlib.EventValidationError:
return nil, e
default:
return nil, fmt.Errorf("failed to build new %q event: %w", proto.Type, err) return nil, fmt.Errorf("failed to build new %q event: %w", proto.Type, err)
} }
// check to see if this user can perform this operation // check to see if this user can perform this operation
stateEvents := make([]gomatrixserverlib.PDU, len(queryRes.StateEvents)) stateEvents := make([]gomatrixserverlib.PDU, len(queryRes.StateEvents))
for i := range queryRes.StateEvents { for i := range queryRes.StateEvents {

View File

@ -858,6 +858,49 @@ func (r *Queryer) QueryAuthChain(ctx context.Context, req *api.QueryAuthChainReq
return nil return nil
} }
func (r *Queryer) InvitePending(ctx context.Context, roomID spec.RoomID, userID spec.UserID) (bool, error) {
pending, _, _, _, err := helpers.IsInvitePending(ctx, r.DB, roomID.String(), userID.String())
return pending, err
}
func (r *Queryer) QueryRoomInfo(ctx context.Context, roomID spec.RoomID) (*types.RoomInfo, error) {
return r.DB.RoomInfo(ctx, roomID.String())
}
func (r *Queryer) CurrentStateEvent(ctx context.Context, roomID spec.RoomID, eventType string, stateKey string) (gomatrixserverlib.PDU, error) {
return r.DB.GetStateEvent(ctx, roomID.String(), string(eventType), "")
}
func (r *Queryer) UserJoinedToRoom(ctx context.Context, roomNID types.RoomNID, userID spec.UserID) (bool, error) {
_, isIn, _, err := r.DB.GetMembership(ctx, roomNID, userID.String())
return isIn, err
}
func (r *Queryer) LocallyJoinedUsers(ctx context.Context, roomVersion gomatrixserverlib.RoomVersion, roomNID types.RoomNID) ([]gomatrixserverlib.PDU, error) {
joinNIDs, err := r.DB.GetMembershipEventNIDsForRoom(ctx, roomNID, true, true)
if err != nil {
return nil, err
}
events, err := r.DB.Events(ctx, roomVersion, joinNIDs)
if err != nil {
return nil, err
}
// For each of the joined users, let's see if we can get a valid
// membership event.
joinedUsers := []gomatrixserverlib.PDU{}
for _, event := range events {
if event.Type() != spec.MRoomMember || event.StateKey() == nil {
continue // shouldn't happen
}
joinedUsers = append(joinedUsers, event)
}
return joinedUsers, nil
}
// nolint:gocyclo // nolint:gocyclo
func (r *Queryer) QueryRestrictedJoinAllowed(ctx context.Context, req *api.QueryRestrictedJoinAllowedRequest, res *api.QueryRestrictedJoinAllowedResponse) error { func (r *Queryer) QueryRestrictedJoinAllowed(ctx context.Context, req *api.QueryRestrictedJoinAllowedRequest, res *api.QueryRestrictedJoinAllowedResponse) error {
// Look up if we know anything about the room. If it doesn't exist // Look up if we know anything about the room. If it doesn't exist

View File

@ -427,8 +427,10 @@ func (rc *reqCtx) includeChildren(db Database, parentID string, limit int, recen
children, err := db.ChildrenForParent(rc.ctx, parentID, constRelType, recentFirst) children, err := db.ChildrenForParent(rc.ctx, parentID, constRelType, recentFirst)
if err != nil { if err != nil {
util.GetLogger(rc.ctx).WithError(err).Error("failed to get ChildrenForParent") util.GetLogger(rc.ctx).WithError(err).Error("failed to get ChildrenForParent")
resErr := spec.InternalServerError() return nil, &util.JSONResponse{
return nil, &resErr Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var childEvents []*types.HeaderedEvent var childEvents []*types.HeaderedEvent
for _, child := range children { for _, child := range children {

View File

@ -56,7 +56,10 @@ func Context(
) util.JSONResponse { ) util.JSONResponse {
snapshot, err := syncDB.NewDatabaseSnapshot(req.Context()) snapshot, err := syncDB.NewDatabaseSnapshot(req.Context())
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)
@ -87,7 +90,10 @@ func Context(
membershipReq := roomserver.QueryMembershipForUserRequest{UserID: device.UserID, RoomID: roomID} membershipReq := roomserver.QueryMembershipForUserRequest{UserID: device.UserID, RoomID: roomID}
if err = rsAPI.QueryMembershipForUser(ctx, &membershipReq, &membershipRes); err != nil { if err = rsAPI.QueryMembershipForUser(ctx, &membershipReq, &membershipRes); err != nil {
logrus.WithError(err).Error("unable to query membership") logrus.WithError(err).Error("unable to query membership")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !membershipRes.RoomExists { if !membershipRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
@ -117,7 +123,10 @@ func Context(
} }
} }
logrus.WithError(err).WithField("eventID", eventID).Error("unable to find requested event") logrus.WithError(err).WithField("eventID", eventID).Error("unable to find requested event")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// verify the user is allowed to see the context for this room/event // verify the user is allowed to see the context for this room/event
@ -125,7 +134,10 @@ func Context(
filteredEvents, err := internal.ApplyHistoryVisibilityFilter(ctx, snapshot, rsAPI, []*rstypes.HeaderedEvent{&requestedEvent}, nil, device.UserID, "context") filteredEvents, err := internal.ApplyHistoryVisibilityFilter(ctx, snapshot, rsAPI, []*rstypes.HeaderedEvent{&requestedEvent}, nil, device.UserID, "context")
if err != nil { if err != nil {
logrus.WithError(err).Error("unable to apply history visibility filter") logrus.WithError(err).Error("unable to apply history visibility filter")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
"duration": time.Since(startTime), "duration": time.Since(startTime),
@ -141,20 +153,29 @@ func Context(
eventsBefore, err := snapshot.SelectContextBeforeEvent(ctx, id, roomID, filter) eventsBefore, err := snapshot.SelectContextBeforeEvent(ctx, id, roomID, filter)
if err != nil && err != sql.ErrNoRows { if err != nil && err != sql.ErrNoRows {
logrus.WithError(err).Error("unable to fetch before events") logrus.WithError(err).Error("unable to fetch before events")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
_, eventsAfter, err := snapshot.SelectContextAfterEvent(ctx, id, roomID, filter) _, eventsAfter, err := snapshot.SelectContextAfterEvent(ctx, id, roomID, filter)
if err != nil && err != sql.ErrNoRows { if err != nil && err != sql.ErrNoRows {
logrus.WithError(err).Error("unable to fetch after events") logrus.WithError(err).Error("unable to fetch after events")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
startTime = time.Now() startTime = time.Now()
eventsBeforeFiltered, eventsAfterFiltered, err := applyHistoryVisibilityOnContextEvents(ctx, snapshot, rsAPI, eventsBefore, eventsAfter, device.UserID) eventsBeforeFiltered, eventsAfterFiltered, err := applyHistoryVisibilityOnContextEvents(ctx, snapshot, rsAPI, eventsBefore, eventsAfter, device.UserID)
if err != nil { if err != nil {
logrus.WithError(err).Error("unable to apply history visibility filter") logrus.WithError(err).Error("unable to apply history visibility filter")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
@ -166,7 +187,10 @@ func Context(
state, err := snapshot.CurrentState(ctx, roomID, &stateFilter, nil) state, err := snapshot.CurrentState(ctx, roomID, &stateFilter, nil)
if err != nil { if err != nil {
logrus.WithError(err).Error("unable to fetch current room state") logrus.WithError(err).Error("unable to fetch current room state")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
eventsBeforeClient := synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(eventsBeforeFiltered), synctypes.FormatAll) eventsBeforeClient := synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(eventsBeforeFiltered), synctypes.FormatAll)
@ -180,7 +204,10 @@ func Context(
newState, err = applyLazyLoadMembers(ctx, device, snapshot, roomID, evs, lazyLoadCache) newState, err = applyLazyLoadMembers(ctx, device, snapshot, roomID, evs, lazyLoadCache)
if err != nil { if err != nil {
logrus.WithError(err).Error("unable to load membership events") logrus.WithError(err).Error("unable to load membership events")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }

View File

@ -43,7 +43,10 @@ func GetFilter(
localpart, _, err := gomatrixserverlib.SplitID('@', userID) localpart, _, err := gomatrixserverlib.SplitID('@', userID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
filter := synctypes.DefaultFilter() filter := synctypes.DefaultFilter()
@ -83,7 +86,10 @@ func PutFilter(
localpart, _, err := gomatrixserverlib.SplitID('@', userID) localpart, _, err := gomatrixserverlib.SplitID('@', userID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(req.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var filter synctypes.Filter var filter synctypes.Filter
@ -122,7 +128,10 @@ func PutFilter(
filterID, err := syncDB.PutFilter(req.Context(), localpart, &filter) filterID, err := syncDB.PutFilter(req.Context(), localpart, &filter)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("syncDB.PutFilter failed") util.GetLogger(req.Context()).WithError(err).Error("syncDB.PutFilter failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
return util.JSONResponse{ return util.JSONResponse{

View File

@ -51,13 +51,19 @@ func GetEvent(
}) })
if err != nil { if err != nil {
logger.WithError(err).Error("GetEvent: syncDB.NewDatabaseTransaction failed") logger.WithError(err).Error("GetEvent: syncDB.NewDatabaseTransaction failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
events, err := db.Events(ctx, []string{eventID}) events, err := db.Events(ctx, []string{eventID})
if err != nil { if err != nil {
logger.WithError(err).Error("GetEvent: syncDB.Events failed") logger.WithError(err).Error("GetEvent: syncDB.Events failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
// The requested event does not exist in our database // The requested event does not exist in our database
@ -81,7 +87,7 @@ func GetEvent(
logger.WithError(err).Error("GetEvent: internal.ApplyHistoryVisibilityFilter failed") logger.WithError(err).Error("GetEvent: internal.ApplyHistoryVisibilityFilter failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(), JSON: spec.InternalServerError{},
} }
} }

View File

@ -67,7 +67,10 @@ func GetMemberships(
var queryRes api.QueryMembershipForUserResponse var queryRes api.QueryMembershipForUserResponse
if err := rsAPI.QueryMembershipForUser(req.Context(), &queryReq, &queryRes); err != nil { if err := rsAPI.QueryMembershipForUser(req.Context(), &queryReq, &queryRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryMembershipsForRoom failed") util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryMembershipsForRoom failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !queryRes.HasBeenInRoom { if !queryRes.HasBeenInRoom {
@ -86,7 +89,10 @@ func GetMemberships(
db, err := syncDB.NewDatabaseSnapshot(req.Context()) db, err := syncDB.NewDatabaseSnapshot(req.Context())
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
defer db.Rollback() // nolint: errcheck defer db.Rollback() // nolint: errcheck
@ -98,7 +104,10 @@ func GetMemberships(
atToken, err = db.EventPositionInTopology(req.Context(), queryRes.EventID) atToken, err = db.EventPositionInTopology(req.Context(), queryRes.EventID)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("unable to get 'atToken'") util.GetLogger(req.Context()).WithError(err).Error("unable to get 'atToken'")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
} }
@ -106,13 +115,19 @@ func GetMemberships(
eventIDs, err := db.SelectMemberships(req.Context(), roomID, atToken, membership, notMembership) eventIDs, err := db.SelectMemberships(req.Context(), roomID, atToken, membership, notMembership)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("db.SelectMemberships failed") util.GetLogger(req.Context()).WithError(err).Error("db.SelectMemberships failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
qryRes := &api.QueryEventsByIDResponse{} qryRes := &api.QueryEventsByIDResponse{}
if err := rsAPI.QueryEventsByID(req.Context(), &api.QueryEventsByIDRequest{EventIDs: eventIDs, RoomID: roomID}, qryRes); err != nil { if err := rsAPI.QueryEventsByID(req.Context(), &api.QueryEventsByIDRequest{EventIDs: eventIDs, RoomID: roomID}, qryRes); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryEventsByID failed") util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryEventsByID failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
result := qryRes.Events result := qryRes.Events
@ -124,7 +139,10 @@ func GetMemberships(
var content databaseJoinedMember var content databaseJoinedMember
if err := json.Unmarshal(ev.Content(), &content); err != nil { if err := json.Unmarshal(ev.Content(), &content); err != nil {
util.GetLogger(req.Context()).WithError(err).Error("failed to unmarshal event content") util.GetLogger(req.Context()).WithError(err).Error("failed to unmarshal event content")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res.Joined[ev.Sender()] = joinedMember(content) res.Joined[ev.Sender()] = joinedMember(content)
} }

View File

@ -81,7 +81,10 @@ func OnIncomingMessagesRequest(
// request that requires backfilling from the roomserver or federation. // request that requires backfilling from the roomserver or federation.
snapshot, err := db.NewDatabaseTransaction(req.Context()) snapshot, err := db.NewDatabaseTransaction(req.Context())
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)
@ -89,7 +92,10 @@ func OnIncomingMessagesRequest(
// check if the user has already forgotten about this room // check if the user has already forgotten about this room
membershipResp, err := getMembershipForUser(req.Context(), roomID, device.UserID, rsAPI) membershipResp, err := getMembershipForUser(req.Context(), roomID, device.UserID, rsAPI)
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if !membershipResp.RoomExists { if !membershipResp.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
@ -151,7 +157,10 @@ func OnIncomingMessagesRequest(
from, err = snapshot.StreamToTopologicalPosition(req.Context(), roomID, streamToken.PDUPosition, backwardOrdering) from, err = snapshot.StreamToTopologicalPosition(req.Context(), roomID, streamToken.PDUPosition, backwardOrdering)
if err != nil { if err != nil {
logrus.WithError(err).Errorf("Failed to get topological position for streaming token %v", streamToken) logrus.WithError(err).Errorf("Failed to get topological position for streaming token %v", streamToken)
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
} }
@ -173,7 +182,10 @@ func OnIncomingMessagesRequest(
to, err = snapshot.StreamToTopologicalPosition(req.Context(), roomID, streamToken.PDUPosition, !backwardOrdering) to, err = snapshot.StreamToTopologicalPosition(req.Context(), roomID, streamToken.PDUPosition, !backwardOrdering)
if err != nil { if err != nil {
logrus.WithError(err).Errorf("Failed to get topological position for streaming token %v", streamToken) logrus.WithError(err).Errorf("Failed to get topological position for streaming token %v", streamToken)
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
} }
@ -232,7 +244,10 @@ func OnIncomingMessagesRequest(
clientEvents, start, end, err := mReq.retrieveEvents() clientEvents, start, end, err := mReq.retrieveEvents()
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("mreq.retrieveEvents failed") util.GetLogger(req.Context()).WithError(err).Error("mreq.retrieveEvents failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
util.GetLogger(req.Context()).WithFields(logrus.Fields{ util.GetLogger(req.Context()).WithFields(logrus.Fields{
@ -253,7 +268,10 @@ func OnIncomingMessagesRequest(
membershipEvents, err := applyLazyLoadMembers(req.Context(), device, snapshot, roomID, clientEvents, lazyLoadCache) membershipEvents, err := applyLazyLoadMembers(req.Context(), device, snapshot, roomID, clientEvents, lazyLoadCache)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("failed to apply lazy loading") util.GetLogger(req.Context()).WithError(err).Error("failed to apply lazy loading")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
res.State = append(res.State, synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(membershipEvents), synctypes.FormatAll)...) res.State = append(res.State, synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(membershipEvents), synctypes.FormatAll)...)
} }

View File

@ -80,7 +80,10 @@ func Relations(
snapshot, err := syncDB.NewDatabaseSnapshot(req.Context()) snapshot, err := syncDB.NewDatabaseSnapshot(req.Context())
if err != nil { if err != nil {
logrus.WithError(err).Error("Failed to get snapshot for relations") logrus.WithError(err).Error("Failed to get snapshot for relations")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)

View File

@ -162,7 +162,10 @@ func Setup(
} }
var nextBatch *string var nextBatch *string
if err := req.ParseForm(); err != nil { if err := req.ParseForm(); err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if req.Form.Has("next_batch") { if req.Form.Has("next_batch") {
nb := req.FormValue("next_batch") nb := req.FormValue("next_batch")

View File

@ -55,7 +55,10 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
if from != nil && *from != "" { if from != nil && *from != "" {
nextBatch, err = strconv.Atoi(*from) nextBatch, err = strconv.Atoi(*from)
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
} }
@ -65,7 +68,10 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
snapshot, err := syncDB.NewDatabaseSnapshot(req.Context()) snapshot, err := syncDB.NewDatabaseSnapshot(req.Context())
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)
@ -73,7 +79,10 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
// only search rooms the user is actually joined to // only search rooms the user is actually joined to
joinedRooms, err := snapshot.RoomIDsWithMembership(ctx, device.UserID, "join") joinedRooms, err := snapshot.RoomIDsWithMembership(ctx, device.UserID, "join")
if err != nil { if err != nil {
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
if len(joinedRooms) == 0 { if len(joinedRooms) == 0 {
return util.JSONResponse{ return util.JSONResponse{
@ -115,7 +124,10 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
) )
if err != nil { if err != nil {
logrus.WithError(err).Error("failed to search fulltext") logrus.WithError(err).Error("failed to search fulltext")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
logrus.Debugf("Search took %s", result.Took) logrus.Debugf("Search took %s", result.Took)
@ -155,7 +167,10 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
evs, err := syncDB.Events(ctx, wantEvents) evs, err := syncDB.Events(ctx, wantEvents)
if err != nil { if err != nil {
logrus.WithError(err).Error("failed to get events from database") logrus.WithError(err).Error("failed to get events from database")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
groups := make(map[string]RoomResult) groups := make(map[string]RoomResult)
@ -173,12 +188,18 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
eventsBefore, eventsAfter, err := contextEvents(ctx, snapshot, event, roomFilter, searchReq) eventsBefore, eventsAfter, err := contextEvents(ctx, snapshot, event, roomFilter, searchReq)
if err != nil { if err != nil {
logrus.WithError(err).Error("failed to get context events") logrus.WithError(err).Error("failed to get context events")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
startToken, endToken, err := getStartEnd(ctx, snapshot, eventsBefore, eventsAfter) startToken, endToken, err := getStartEnd(ctx, snapshot, eventsBefore, eventsAfter)
if err != nil { if err != nil {
logrus.WithError(err).Error("failed to get start/end") logrus.WithError(err).Error("failed to get start/end")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
profileInfos := make(map[string]ProfileInfoResponse) profileInfos := make(map[string]ProfileInfoResponse)
@ -221,7 +242,10 @@ func Search(req *http.Request, device *api.Device, syncDB storage.Database, fts
state, err := snapshot.CurrentState(ctx, event.RoomID(), &stateFilter, nil) state, err := snapshot.CurrentState(ctx, event.RoomID(), &stateFilter, nil)
if err != nil { if err != nil {
logrus.WithError(err).Error("unable to get current state") logrus.WithError(err).Error("unable to get current state")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
stateForRooms[event.RoomID()] = synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(state), synctypes.FormatSync) stateForRooms[event.RoomID()] = synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(state), synctypes.FormatSync)
} }

View File

@ -536,12 +536,18 @@ func (rp *RequestPool) OnIncomingKeyChangeRequest(req *http.Request, device *use
syncReq, err := newSyncRequest(req, *device, rp.db) syncReq, err := newSyncRequest(req, *device, rp.db)
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("newSyncRequest failed") util.GetLogger(req.Context()).WithError(err).Error("newSyncRequest failed")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
snapshot, err := rp.db.NewDatabaseSnapshot(req.Context()) snapshot, err := rp.db.NewDatabaseSnapshot(req.Context())
if err != nil { if err != nil {
logrus.WithError(err).Error("Failed to acquire database snapshot for key change") logrus.WithError(err).Error("Failed to acquire database snapshot for key change")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)
@ -552,7 +558,10 @@ func (rp *RequestPool) OnIncomingKeyChangeRequest(req *http.Request, device *use
) )
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("Failed to DeviceListCatchup info") util.GetLogger(req.Context()).WithError(err).Error("Failed to DeviceListCatchup info")
return spec.InternalServerError() return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} }
succeeded = true succeeded = true
return util.JSONResponse{ return util.JSONResponse{