Skip to content

Commit

Permalink
Move MakeJoin logic to GMSL (#3081)
Browse files Browse the repository at this point in the history
  • Loading branch information
devonh committed May 17, 2023
1 parent 0489d16 commit 67d6876
Show file tree
Hide file tree
Showing 80 changed files with 1,161 additions and 497 deletions.
6 changes: 4 additions & 2 deletions clientapi/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ func VerifyUserFromRequest(
}, &res)
if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("userAPI.QueryAccessToken failed")
jsonErr := spec.InternalServerError()
return nil, &jsonErr
return nil, &util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
if res.Err != "" {
if strings.HasPrefix(strings.ToLower(res.Err), "forbidden:") { // TODO: use actual error and no string comparison
Expand Down
14 changes: 7 additions & 7 deletions clientapi/auth/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,13 @@ func TestBadLoginFromJSONReader(t *testing.T) {
Name string
Body string

WantErrCode string
WantErrCode spec.MatrixErrorCode
}{
{Name: "empty", WantErrCode: "M_BAD_JSON"},
{Name: "empty", WantErrCode: spec.ErrorBadJSON},
{
Name: "badUnmarshal",
Body: `badsyntaxJSON`,
WantErrCode: "M_BAD_JSON",
WantErrCode: spec.ErrorBadJSON,
},
{
Name: "badPassword",
Expand All @@ -123,7 +123,7 @@ func TestBadLoginFromJSONReader(t *testing.T) {
"password": "invalidpassword",
"device_id": "adevice"
}`,
WantErrCode: "M_FORBIDDEN",
WantErrCode: spec.ErrorForbidden,
},
{
Name: "badToken",
Expand All @@ -132,15 +132,15 @@ func TestBadLoginFromJSONReader(t *testing.T) {
"token": "invalidtoken",
"device_id": "adevice"
}`,
WantErrCode: "M_FORBIDDEN",
WantErrCode: spec.ErrorForbidden,
},
{
Name: "badType",
Body: `{
"type": "m.login.invalid",
"device_id": "adevice"
}`,
WantErrCode: "M_INVALID_PARAM",
WantErrCode: spec.ErrorInvalidParam,
},
}
for _, tst := range tsts {
Expand All @@ -157,7 +157,7 @@ func TestBadLoginFromJSONReader(t *testing.T) {
if errRes == nil {
cleanup(ctx, nil)
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)
}
})
Expand Down
6 changes: 4 additions & 2 deletions clientapi/auth/login_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ func (t *LoginTypeToken) LoginFromJSON(ctx context.Context, reqBytes []byte) (*L
var res uapi.QueryLoginTokenResponse
if err := t.UserAPI.QueryLoginToken(ctx, &uapi.QueryLoginTokenRequest{Token: r.Token}, &res); err != nil {
util.GetLogger(ctx).WithError(err).Error("UserAPI.QueryLoginToken failed")
jsonErr := spec.InternalServerError()
return nil, nil, &jsonErr
return nil, nil, &util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
if res.Data == nil {
return nil, nil, &util.JSONResponse{
Expand Down
18 changes: 12 additions & 6 deletions clientapi/auth/user_interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,10 @@ func (u *UserInteractive) NewSession() *util.JSONResponse {
sessionID, err := GenerateAccessToken()
if err != nil {
logrus.WithError(err).Error("failed to generate session ID")
res := spec.InternalServerError()
return &res
return &util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
u.Lock()
u.Sessions[sessionID] = []string{}
Expand All @@ -193,15 +195,19 @@ func (u *UserInteractive) ResponseWithChallenge(sessionID string, response inter
mixedObjects := make(map[string]interface{})
b, err := json.Marshal(response)
if err != nil {
ise := spec.InternalServerError()
return &ise
return &util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
_ = json.Unmarshal(b, &mixedObjects)
challenge := u.challenge(sessionID)
b, err = json.Marshal(challenge.JSON)
if err != nil {
ise := spec.InternalServerError()
return &ise
return &util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
_ = json.Unmarshal(b, &mixedObjects)

Expand Down
3 changes: 2 additions & 1 deletion clientapi/clientapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
uapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util"
"github.com/stretchr/testify/assert"
"github.com/tidwall/gjson"
Expand Down Expand Up @@ -1105,7 +1106,7 @@ func Test3PID(t *testing.T) {
resp := threepid.GetValidatedResponse{}
switch r.URL.Query().Get("client_secret") {
case "fail":
resp.ErrCode = "M_SESSION_NOT_VALIDATED"
resp.ErrCode = string(spec.ErrorSessionNotValidated)
case "fail2":
resp.ErrCode = "some other error"
case "fail3":
Expand Down
6 changes: 4 additions & 2 deletions clientapi/httputil/httputil.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ func UnmarshalJSONRequest(req *http.Request, iface interface{}) *util.JSONRespon
body, err := io.ReadAll(req.Body)
if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("io.ReadAll failed")
resp := spec.InternalServerError()
return &resp
return &util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}

return UnmarshalJSON(body, iface)
Expand Down
10 changes: 8 additions & 2 deletions clientapi/routing/account_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ func SaveAccountData(
body, err := io.ReadAll(req.Body)
if err != nil {
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) {
Expand Down Expand Up @@ -157,7 +160,10 @@ func SaveReadMarker(
if r.FullyRead != "" {
data, err := json.Marshal(fullyReadEvent{EventID: r.FullyRead})
if err != nil {
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}

dataReq := api.InputAccountDataRequest{
Expand Down
13 changes: 8 additions & 5 deletions clientapi/routing/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func AdminEvacuateRoom(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAP
}

affected, err := rsAPI.PerformAdminEvacuateRoom(req.Context(), vars["roomID"])
switch err {
switch err.(type) {
case nil:
case eventutil.ErrRoomNoExists:
return util.JSONResponse{
Expand Down Expand Up @@ -113,7 +113,7 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
}, accAvailableResp); err != nil {
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(),
JSON: spec.InternalServerError{},
}
}
if accAvailableResp.Available {
Expand Down Expand Up @@ -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)
if err != nil {
logrus.WithError(err).Error("failed to publish nats message")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
return util.JSONResponse{
Code: http.StatusOK,
Expand Down Expand Up @@ -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 errors.Is(err, eventutil.ErrRoomNoExists) {
if errors.Is(err, eventutil.ErrRoomNoExists{}) {
return util.JSONResponse{
Code: 200,
JSON: spec.NotFound(eventutil.ErrRoomNoExists.Error()),
JSON: spec.NotFound(err.Error()),
}
}
logrus.WithError(err).WithFields(logrus.Fields{
Expand Down
5 changes: 4 additions & 1 deletion clientapi/routing/admin_whois.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,10 @@ func GetAdminWhois(
}, &queryRes)
if err != nil {
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)
Expand Down
5 changes: 4 additions & 1 deletion clientapi/routing/aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ func GetAliases(
var queryRes api.QueryMembershipForUserResponse
if err := rsAPI.QueryMembershipForUser(req.Context(), &queryReq, &queryRes); err != nil {
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 {
return util.JSONResponse{
Expand Down
57 changes: 45 additions & 12 deletions clientapi/routing/createroom.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ func createRoom(
_, userDomain, err := gomatrixserverlib.SplitID('@', device.UserID)
if err != nil {
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) {
return util.JSONResponse{
Expand Down Expand Up @@ -218,7 +221,10 @@ func createRoom(
profile, err := appserviceAPI.RetrieveUserProfile(ctx, userID, asAPI, profileAPI)
if err != nil {
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{}{}
Expand Down Expand Up @@ -342,7 +348,10 @@ func createRoom(
err = rsAPI.GetRoomIDForAlias(ctx, &hasAliasReq, &aliasResp)
if err != nil {
util.GetLogger(ctx).WithError(err).Error("aliasAPI.GetRoomIDForAlias failed")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
if aliasResp.RoomID != "" {
return util.JSONResponse{
Expand Down Expand Up @@ -455,33 +464,48 @@ func createRoom(
err = builder.SetContent(e.Content)
if err != nil {
util.GetLogger(ctx).WithError(err).Error("builder.SetContent failed")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
if i > 0 {
builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}
}
var ev gomatrixserverlib.PDU
if err = builder.AddAuthEvents(&authEvents); err != nil {
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)
if err != nil {
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 {
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
builtEvents = append(builtEvents, &types.HeaderedEvent{PDU: ev})
err = authEvents.AddEvent(ev)
if err != nil {
util.GetLogger(ctx).WithError(err).Error("authEvents.AddEvent failed")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
}

Expand All @@ -496,7 +520,10 @@ func createRoom(
}
if err = roomserverAPI.SendInputRoomEvents(ctx, rsAPI, device.UserDomain(), inputs, false); err != nil {
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
Expand All @@ -513,7 +540,10 @@ func createRoom(
err = rsAPI.SetRoomAlias(ctx, &aliasReq, &aliasResp)
if err != nil {
util.GetLogger(ctx).WithError(err).Error("aliasAPI.SetRoomAlias failed")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}

if aliasResp.AliasExists {
Expand Down Expand Up @@ -596,7 +626,7 @@ func createRoom(
sentry.CaptureException(err)
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError(),
JSON: spec.InternalServerError{},
}
}
}
Expand All @@ -609,7 +639,10 @@ func createRoom(
Visibility: spec.Public,
}); err != nil {
util.GetLogger(ctx).WithError(err).Error("failed to publish room")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
}

Expand Down
10 changes: 8 additions & 2 deletions clientapi/routing/deactivate.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ func Deactivate(
localpart, serverName, err := gomatrixserverlib.SplitID('@', login.Username())
if err != nil {
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
Expand All @@ -46,7 +49,10 @@ func Deactivate(
}, &res)
if err != nil {
util.GetLogger(ctx).WithError(err).Error("userAPI.PerformAccountDeactivation failed")
return spec.InternalServerError()
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}

return util.JSONResponse{
Expand Down
Loading

0 comments on commit 67d6876

Please sign in to comment.