Move json errors over to gmsl (#3080)

This commit is contained in:
devonh 2023-05-09 22:46:49 +00:00 committed by GitHub
parent a49c9f01e2
commit 0489d16f95
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
109 changed files with 808 additions and 1217 deletions

View file

@ -23,8 +23,8 @@ import (
"net/http" "net/http"
"strings" "strings"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -58,7 +58,7 @@ func VerifyUserFromRequest(
if err != nil { if err != nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.MissingToken(err.Error()), JSON: spec.MissingToken(err.Error()),
} }
} }
var res api.QueryAccessTokenResponse var res api.QueryAccessTokenResponse
@ -68,21 +68,21 @@ 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 := jsonerror.InternalServerError() jsonErr := spec.InternalServerError()
return nil, &jsonErr return nil, &jsonErr
} }
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
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(res.Err), JSON: spec.Forbidden(res.Err),
} }
} }
} }
if res.Device == nil { if res.Device == nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.UnknownToken("Unknown token"), JSON: spec.UnknownToken("Unknown token"),
} }
} }
return res.Device, nil return res.Device, nil

View file

@ -21,9 +21,9 @@ import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
uapi "github.com/matrix-org/dendrite/userapi/api" uapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -37,7 +37,7 @@ func LoginFromJSONReader(ctx context.Context, r io.Reader, useraccountAPI uapi.U
if err != nil { if err != nil {
err := &util.JSONResponse{ err := &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Reading request body failed: " + err.Error()), JSON: spec.BadJSON("Reading request body failed: " + err.Error()),
} }
return nil, nil, err return nil, nil, err
} }
@ -48,7 +48,7 @@ func LoginFromJSONReader(ctx context.Context, r io.Reader, useraccountAPI uapi.U
if err := json.Unmarshal(reqBytes, &header); err != nil { if err := json.Unmarshal(reqBytes, &header); err != nil {
err := &util.JSONResponse{ err := &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Reading request body failed: " + err.Error()), JSON: spec.BadJSON("Reading request body failed: " + err.Error()),
} }
return nil, nil, err return nil, nil, err
} }
@ -68,7 +68,7 @@ func LoginFromJSONReader(ctx context.Context, r io.Reader, useraccountAPI uapi.U
default: default:
err := util.JSONResponse{ err := util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("unhandled login type: " + header.Type), JSON: spec.InvalidParam("unhandled login type: " + header.Type),
} }
return nil, nil, &err return nil, nil, &err
} }

View file

@ -21,11 +21,11 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/userutil" "github.com/matrix-org/dendrite/clientapi/userutil"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
uapi "github.com/matrix-org/dendrite/userapi/api" uapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -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_ARGUMENT_VALUE", WantErrCode: "M_INVALID_PARAM",
}, },
} }
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.(*jsonerror.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

@ -20,9 +20,9 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
uapi "github.com/matrix-org/dendrite/userapi/api" uapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -48,13 +48,13 @@ 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 := jsonerror.InternalServerError() jsonErr := spec.InternalServerError()
return nil, nil, &jsonErr return nil, nil, &jsonErr
} }
if res.Data == nil { if res.Data == nil {
return nil, nil, &util.JSONResponse{ return nil, nil, &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("invalid login token"), JSON: spec.Forbidden("invalid login token"),
} }
} }

View file

@ -21,10 +21,10 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/userutil" "github.com/matrix-org/dendrite/clientapi/userutil"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -65,26 +65,26 @@ func (t *LoginTypePassword) Login(ctx context.Context, req interface{}) (*Login,
if username == "" { if username == "" {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.BadJSON("A username must be supplied."), JSON: spec.BadJSON("A username must be supplied."),
} }
} }
if len(r.Password) == 0 { if len(r.Password) == 0 {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.BadJSON("A password must be supplied."), JSON: spec.BadJSON("A password must be supplied."),
} }
} }
localpart, domain, err := userutil.ParseUsernameParam(username, t.Config.Matrix) localpart, domain, err := userutil.ParseUsernameParam(username, t.Config.Matrix)
if err != nil { if err != nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.InvalidUsername(err.Error()), JSON: spec.InvalidUsername(err.Error()),
} }
} }
if !t.Config.Matrix.IsLocalServerName(domain) { if !t.Config.Matrix.IsLocalServerName(domain) {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.InvalidUsername("The server name is not known."), JSON: spec.InvalidUsername("The server name is not known."),
} }
} }
// Squash username to all lowercase letters // Squash username to all lowercase letters
@ -97,7 +97,7 @@ func (t *LoginTypePassword) Login(ctx context.Context, req interface{}) (*Login,
if err != nil { if err != nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("Unable to fetch account by password."), JSON: spec.Unknown("Unable to fetch account by password."),
} }
} }
@ -112,7 +112,7 @@ func (t *LoginTypePassword) Login(ctx context.Context, req interface{}) (*Login,
if err != nil { if err != nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("Unable to fetch account by password."), JSON: spec.Unknown("Unable to fetch account by password."),
} }
} }
// Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows // Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows
@ -120,7 +120,7 @@ func (t *LoginTypePassword) Login(ctx context.Context, req interface{}) (*Login,
if !res.Exists { if !res.Exists {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The username or password was incorrect or the account does not exist."), JSON: spec.Forbidden("The username or password was incorrect or the account does not exist."),
} }
} }
} }

View file

@ -20,9 +20,9 @@ import (
"net/http" "net/http"
"sync" "sync"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
@ -178,7 +178,7 @@ 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 := jsonerror.InternalServerError() res := spec.InternalServerError()
return &res return &res
} }
u.Lock() u.Lock()
@ -193,14 +193,14 @@ 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 := jsonerror.InternalServerError() ise := spec.InternalServerError()
return &ise return &ise
} }
_ = 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 := jsonerror.InternalServerError() ise := spec.InternalServerError()
return &ise return &ise
} }
_ = json.Unmarshal(b, &mixedObjects) _ = json.Unmarshal(b, &mixedObjects)
@ -234,7 +234,7 @@ func (u *UserInteractive) Verify(ctx context.Context, bodyBytes []byte, device *
if !ok { if !ok {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Unknown auth.type: " + authType), JSON: spec.BadJSON("Unknown auth.type: " + authType),
} }
} }
@ -250,7 +250,7 @@ func (u *UserInteractive) Verify(ctx context.Context, bodyBytes []byte, device *
if !u.IsSingleStageFlow(authType) { if !u.IsSingleStageFlow(authType) {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("The auth.session is missing or unknown."), JSON: spec.Unknown("The auth.session is missing or unknown."),
} }
} }
} }

View file

@ -20,7 +20,7 @@ import (
"net/http" "net/http"
"unicode/utf8" "unicode/utf8"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -32,7 +32,7 @@ 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 := jsonerror.InternalServerError() resp := spec.InternalServerError()
return &resp return &resp
} }
@ -43,7 +43,7 @@ func UnmarshalJSON(body []byte, iface interface{}) *util.JSONResponse {
if !utf8.Valid(body) { if !utf8.Valid(body) {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("Body contains invalid UTF-8"), JSON: spec.NotJSON("Body contains invalid UTF-8"),
} }
} }
@ -53,7 +53,7 @@ func UnmarshalJSON(body []byte, iface interface{}) *util.JSONResponse {
// valid JSON with incorrect types for values. // valid JSON with incorrect types for values.
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
return nil return nil

View file

@ -1,246 +0,0 @@
// Copyright 2017 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jsonerror
import (
"context"
"fmt"
"net/http"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util"
"github.com/sirupsen/logrus"
)
// MatrixError represents the "standard error response" in Matrix.
// http://matrix.org/docs/spec/client_server/r0.2.0.html#api-standards
type MatrixError struct {
ErrCode string `json:"errcode"`
Err string `json:"error"`
}
func (e MatrixError) Error() string {
return fmt.Sprintf("%s: %s", e.ErrCode, e.Err)
}
// InternalServerError returns a 500 Internal Server Error in a matrix-compliant
// format.
func InternalServerError() util.JSONResponse {
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: Unknown("Internal Server Error"),
}
}
// Unknown is an unexpected error
func Unknown(msg string) *MatrixError {
return &MatrixError{"M_UNKNOWN", msg}
}
// Forbidden is an error when the client tries to access a resource
// they are not allowed to access.
func Forbidden(msg string) *MatrixError {
return &MatrixError{"M_FORBIDDEN", msg}
}
// BadJSON is an error when the client supplies malformed JSON.
func BadJSON(msg string) *MatrixError {
return &MatrixError{"M_BAD_JSON", msg}
}
// BadAlias is an error when the client supplies a bad alias.
func BadAlias(msg string) *MatrixError {
return &MatrixError{"M_BAD_ALIAS", msg}
}
// NotJSON is an error when the client supplies something that is not JSON
// to a JSON endpoint.
func NotJSON(msg string) *MatrixError {
return &MatrixError{"M_NOT_JSON", msg}
}
// NotFound is an error when the client tries to access an unknown resource.
func NotFound(msg string) *MatrixError {
return &MatrixError{"M_NOT_FOUND", msg}
}
// MissingArgument is an error when the client tries to access a resource
// without providing an argument that is required.
func MissingArgument(msg string) *MatrixError {
return &MatrixError{"M_MISSING_ARGUMENT", msg}
}
// InvalidArgumentValue is an error when the client tries to provide an
// invalid value for a valid argument
func InvalidArgumentValue(msg string) *MatrixError {
return &MatrixError{"M_INVALID_ARGUMENT_VALUE", msg}
}
// MissingToken is an error when the client tries to access a resource which
// requires authentication without supplying credentials.
func MissingToken(msg string) *MatrixError {
return &MatrixError{"M_MISSING_TOKEN", msg}
}
// UnknownToken is an error when the client tries to access a resource which
// requires authentication and supplies an unrecognised token
func UnknownToken(msg string) *MatrixError {
return &MatrixError{"M_UNKNOWN_TOKEN", msg}
}
// WeakPassword is an error which is returned when the client tries to register
// using a weak password. http://matrix.org/docs/spec/client_server/r0.2.0.html#password-based
func WeakPassword(msg string) *MatrixError {
return &MatrixError{"M_WEAK_PASSWORD", msg}
}
// InvalidUsername is an error returned when the client tries to register an
// invalid username
func InvalidUsername(msg string) *MatrixError {
return &MatrixError{"M_INVALID_USERNAME", msg}
}
// UserInUse is an error returned when the client tries to register an
// username that already exists
func UserInUse(msg string) *MatrixError {
return &MatrixError{"M_USER_IN_USE", msg}
}
// RoomInUse is an error returned when the client tries to make a room
// that already exists
func RoomInUse(msg string) *MatrixError {
return &MatrixError{"M_ROOM_IN_USE", msg}
}
// ASExclusive is an error returned when an application service tries to
// register an username that is outside of its registered namespace, or if a
// user attempts to register a username or room alias within an exclusive
// namespace.
func ASExclusive(msg string) *MatrixError {
return &MatrixError{"M_EXCLUSIVE", msg}
}
// GuestAccessForbidden is an error which is returned when the client is
// forbidden from accessing a resource as a guest.
func GuestAccessForbidden(msg string) *MatrixError {
return &MatrixError{"M_GUEST_ACCESS_FORBIDDEN", msg}
}
// InvalidSignature is an error which is returned when the client tries
// to upload invalid signatures.
func InvalidSignature(msg string) *MatrixError {
return &MatrixError{"M_INVALID_SIGNATURE", msg}
}
// InvalidParam is an error that is returned when a parameter was invalid,
// traditionally with cross-signing.
func InvalidParam(msg string) *MatrixError {
return &MatrixError{"M_INVALID_PARAM", msg}
}
// MissingParam is an error that is returned when a parameter was incorrect,
// traditionally with cross-signing.
func MissingParam(msg string) *MatrixError {
return &MatrixError{"M_MISSING_PARAM", msg}
}
// UnableToAuthoriseJoin is an error that is returned when a server can't
// determine whether to allow a restricted join or not.
func UnableToAuthoriseJoin(msg string) *MatrixError {
return &MatrixError{"M_UNABLE_TO_AUTHORISE_JOIN", msg}
}
// LeaveServerNoticeError is an error returned when trying to reject an invite
// for a server notice room.
func LeaveServerNoticeError() *MatrixError {
return &MatrixError{
ErrCode: "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM",
Err: "You cannot reject this invite",
}
}
// ErrRoomKeysVersion is an error returned by `PUT /room_keys/keys`
type ErrRoomKeysVersion struct {
MatrixError
CurrentVersion string `json:"current_version"`
}
// WrongBackupVersionError is an error returned by `PUT /room_keys/keys`
func WrongBackupVersionError(currentVersion string) *ErrRoomKeysVersion {
return &ErrRoomKeysVersion{
MatrixError: MatrixError{
ErrCode: "M_WRONG_ROOM_KEYS_VERSION",
Err: "Wrong backup version.",
},
CurrentVersion: currentVersion,
}
}
type IncompatibleRoomVersionError struct {
RoomVersion string `json:"room_version"`
Error string `json:"error"`
Code string `json:"errcode"`
}
// IncompatibleRoomVersion is an error which is returned when the client
// requests a room with a version that is unsupported.
func IncompatibleRoomVersion(roomVersion gomatrixserverlib.RoomVersion) *IncompatibleRoomVersionError {
return &IncompatibleRoomVersionError{
Code: "M_INCOMPATIBLE_ROOM_VERSION",
RoomVersion: string(roomVersion),
Error: "Your homeserver does not support the features required to join this room",
}
}
// UnsupportedRoomVersion is an error which is returned when the client
// requests a room with a version that is unsupported.
func UnsupportedRoomVersion(msg string) *MatrixError {
return &MatrixError{"M_UNSUPPORTED_ROOM_VERSION", msg}
}
// LimitExceededError is a rate-limiting error.
type LimitExceededError struct {
MatrixError
RetryAfterMS int64 `json:"retry_after_ms,omitempty"`
}
// LimitExceeded is an error when the client tries to send events too quickly.
func LimitExceeded(msg string, retryAfterMS int64) *LimitExceededError {
return &LimitExceededError{
MatrixError: MatrixError{"M_LIMIT_EXCEEDED", msg},
RetryAfterMS: retryAfterMS,
}
}
// NotTrusted is an error which is returned when the client asks the server to
// proxy a request (e.g. 3PID association) to a server that isn't trusted
func NotTrusted(serverName string) *MatrixError {
return &MatrixError{
ErrCode: "M_SERVER_NOT_TRUSTED",
Err: fmt.Sprintf("Untrusted server '%s'", serverName),
}
}
// InternalAPIError is returned when Dendrite failed to reach an internal API.
func InternalAPIError(ctx context.Context, err error) util.JSONResponse {
logrus.WithContext(ctx).WithError(err).Error("Error reaching an internal API")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: &MatrixError{
ErrCode: "M_INTERNAL_SERVER_ERROR",
Err: "Dendrite encountered an error reaching an internal API.",
},
}
}

View file

@ -1,44 +0,0 @@
// Copyright 2017 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jsonerror
import (
"encoding/json"
"testing"
)
func TestLimitExceeded(t *testing.T) {
e := LimitExceeded("too fast", 5000)
jsonBytes, err := json.Marshal(&e)
if err != nil {
t.Fatalf("TestLimitExceeded: Failed to marshal LimitExceeded error. %s", err.Error())
}
want := `{"errcode":"M_LIMIT_EXCEEDED","error":"too fast","retry_after_ms":5000}`
if string(jsonBytes) != want {
t.Errorf("TestLimitExceeded: want %s, got %s", want, string(jsonBytes))
}
}
func TestForbidden(t *testing.T) {
e := Forbidden("you shall not pass")
jsonBytes, err := json.Marshal(&e)
if err != nil {
t.Fatalf("TestForbidden: Failed to marshal Forbidden error. %s", err.Error())
}
want := `{"errcode":"M_FORBIDDEN","error":"you shall not pass"}`
if string(jsonBytes) != want {
t.Errorf("TestForbidden: want %s, got %s", want, string(jsonBytes))
}
}

View file

@ -21,11 +21,11 @@ import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -38,7 +38,7 @@ func GetAccountData(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: spec.Forbidden("userID does not match the current user"),
} }
} }
@ -69,7 +69,7 @@ func GetAccountData(
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("data not found"), JSON: spec.NotFound("data not found"),
} }
} }
@ -81,7 +81,7 @@ func SaveAccountData(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: spec.Forbidden("userID does not match the current user"),
} }
} }
@ -90,27 +90,27 @@ func SaveAccountData(
if req.Body == http.NoBody { if req.Body == http.NoBody {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("Content not JSON"), JSON: spec.NotJSON("Content not JSON"),
} }
} }
if dataType == "m.fully_read" || dataType == "m.push_rules" { if dataType == "m.fully_read" || dataType == "m.push_rules" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(fmt.Sprintf("Unable to modify %q using this API", dataType)), JSON: spec.Forbidden(fmt.Sprintf("Unable to modify %q using this API", dataType)),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !json.Valid(body) { if !json.Valid(body) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Bad JSON content"), JSON: spec.BadJSON("Bad JSON content"),
} }
} }
@ -157,7 +157,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
dataReq := api.InputAccountDataRequest{ dataReq := api.InputAccountDataRequest{

View file

@ -17,7 +17,6 @@ import (
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/httputil" "github.com/matrix-org/dendrite/internal/httputil"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
@ -37,7 +36,7 @@ func AdminEvacuateRoom(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAP
case eventutil.ErrRoomNoExists: case eventutil.ErrRoomNoExists:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(err.Error()), JSON: spec.NotFound(err.Error()),
} }
default: default:
logrus.WithError(err).WithField("roomID", vars["roomID"]).Error("Failed to evacuate room") logrus.WithError(err).WithField("roomID", vars["roomID"]).Error("Failed to evacuate room")
@ -91,7 +90,7 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
if req.Body == nil { if req.Body == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Missing request body"), JSON: spec.Unknown("Missing request body"),
} }
} }
vars, err := httputil.URLDecodeMapValues(mux.Vars(req)) vars, err := httputil.URLDecodeMapValues(mux.Vars(req))
@ -104,7 +103,7 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
} }
accAvailableResp := &api.QueryAccountAvailabilityResponse{} accAvailableResp := &api.QueryAccountAvailabilityResponse{}
@ -114,13 +113,13 @@ 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: jsonerror.InternalAPIError(req.Context(), err), JSON: spec.InternalServerError(),
} }
} }
if accAvailableResp.Available { if accAvailableResp.Available {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.Unknown("User does not exist"), JSON: spec.Unknown("User does not exist"),
} }
} }
request := struct { request := struct {
@ -129,13 +128,13 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
if err = json.NewDecoder(req.Body).Decode(&request); err != nil { if err = json.NewDecoder(req.Body).Decode(&request); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to decode request body: " + err.Error()), JSON: spec.Unknown("Failed to decode request body: " + err.Error()),
} }
} }
if request.Password == "" { if request.Password == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Expecting non-empty password."), JSON: spec.MissingParam("Expecting non-empty password."),
} }
} }
@ -153,7 +152,7 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
if err := userAPI.PerformPasswordUpdate(req.Context(), updateReq, updateRes); err != nil { if err := userAPI.PerformPasswordUpdate(req.Context(), updateReq, updateRes); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to perform password update: " + err.Error()), JSON: spec.Unknown("Failed to perform password update: " + err.Error()),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -170,7 +169,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -192,7 +191,7 @@ func AdminMarkAsStale(req *http.Request, cfg *config.ClientAPI, keyAPI api.Clien
if cfg.Matrix.IsLocalServerName(domain) { if cfg.Matrix.IsLocalServerName(domain) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam("Can not mark local device list as stale"), JSON: spec.InvalidParam("Can not mark local device list as stale"),
} }
} }
@ -203,7 +202,7 @@ func AdminMarkAsStale(req *http.Request, cfg *config.ClientAPI, keyAPI api.Clien
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown(fmt.Sprintf("Failed to mark device list as stale: %s", err)), JSON: spec.Unknown(fmt.Sprintf("Failed to mark device list as stale: %s", err)),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -221,21 +220,21 @@ func AdminDownloadState(req *http.Request, device *api.Device, rsAPI roomserverA
if !ok { if !ok {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Expecting room ID."), JSON: spec.MissingParam("Expecting room ID."),
} }
} }
serverName, ok := vars["serverName"] serverName, ok := vars["serverName"]
if !ok { if !ok {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Expecting remote server name."), JSON: spec.MissingParam("Expecting remote server name."),
} }
} }
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: jsonerror.NotFound(eventutil.ErrRoomNoExists.Error()), JSON: spec.NotFound(eventutil.ErrRoomNoExists.Error()),
} }
} }
logrus.WithError(err).WithFields(logrus.Fields{ logrus.WithError(err).WithFields(logrus.Fields{

View file

@ -17,8 +17,8 @@ package routing
import ( import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -51,7 +51,7 @@ func GetAdminWhois(
if !allowed { if !allowed {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: spec.Forbidden("userID does not match the current user"),
} }
} }
@ -61,7 +61,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
devices := make(map[string]deviceInfo) devices := make(map[string]deviceInfo)

View file

@ -19,12 +19,10 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -64,12 +62,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !queryRes.IsInRoom { if !queryRes.IsInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You aren't a member of this room."), JSON: spec.Forbidden("You aren't a member of this room."),
} }
} }
} }

View file

@ -32,7 +32,6 @@ import (
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
@ -75,7 +74,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse {
if strings.ContainsAny(r.RoomAliasName, whitespace+":") { if strings.ContainsAny(r.RoomAliasName, whitespace+":") {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("room_alias_name cannot contain whitespace or ':'"), JSON: spec.BadJSON("room_alias_name cannot contain whitespace or ':'"),
} }
} }
for _, userID := range r.Invite { for _, userID := range r.Invite {
@ -87,7 +86,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse {
if _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil { if _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"), JSON: spec.BadJSON("user id must be in the form @localpart:domain"),
} }
} }
} }
@ -96,7 +95,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse {
default: default:
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'"), JSON: spec.BadJSON("preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'"),
} }
} }
@ -108,7 +107,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse {
if err != nil { if err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("malformed creation_content"), JSON: spec.BadJSON("malformed creation_content"),
} }
} }
@ -117,7 +116,7 @@ func (r createRoomRequest) Validate() *util.JSONResponse {
if err != nil { if err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("malformed creation_content"), JSON: spec.BadJSON("malformed creation_content"),
} }
} }
@ -156,7 +155,7 @@ func CreateRoom(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
} }
return createRoom(req.Context(), r, device, cfg, profileAPI, rsAPI, asAPI, evTime) return createRoom(req.Context(), r, device, cfg, profileAPI, rsAPI, asAPI, evTime)
@ -175,12 +174,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !cfg.Matrix.IsLocalServerName(userDomain) { if !cfg.Matrix.IsLocalServerName(userDomain) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(fmt.Sprintf("User domain %q not configured locally", userDomain)), JSON: spec.Forbidden(fmt.Sprintf("User domain %q not configured locally", userDomain)),
} }
} }
@ -200,7 +199,7 @@ func createRoom(
if roomVersionError != nil { if roomVersionError != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion(roomVersionError.Error()), JSON: spec.UnsupportedRoomVersion(roomVersionError.Error()),
} }
} }
roomVersion = candidateVersion roomVersion = candidateVersion
@ -219,7 +218,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
createContent := map[string]interface{}{} createContent := map[string]interface{}{}
@ -228,7 +227,7 @@ func createRoom(
util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for creation_content failed") util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for creation_content failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("invalid create content"), JSON: spec.BadJSON("invalid create content"),
} }
} }
} }
@ -249,7 +248,7 @@ func createRoom(
util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for power_level_content_override failed") util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for power_level_content_override failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("malformed power_level_content_override"), JSON: spec.BadJSON("malformed power_level_content_override"),
} }
} }
} }
@ -343,12 +342,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if aliasResp.RoomID != "" { if aliasResp.RoomID != "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.RoomInUse("Room ID already exists."), JSON: spec.RoomInUse("Room ID already exists."),
} }
} }
@ -437,7 +436,7 @@ func createRoom(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("unknown room version"), JSON: spec.BadJSON("unknown room version"),
} }
} }
@ -456,7 +455,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if i > 0 { if i > 0 {
builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()} builder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}
@ -464,17 +463,17 @@ 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
// Add the event to the list of auth events // Add the event to the list of auth events
@ -482,7 +481,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
@ -497,7 +496,7 @@ 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 jsonerror.InternalServerError() return 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
@ -514,13 +513,13 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if aliasResp.AliasExists { if aliasResp.AliasExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.RoomInUse("Room alias already exists."), JSON: spec.RoomInUse("Room alias already exists."),
} }
} }
} }
@ -584,12 +583,12 @@ func createRoom(
case roomserverAPI.ErrInvalidID: case roomserverAPI.ErrInvalidID:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(e.Error()), JSON: spec.Unknown(e.Error()),
} }
case roomserverAPI.ErrNotAllowed: case roomserverAPI.ErrNotAllowed:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(e.Error()), JSON: spec.Forbidden(e.Error()),
} }
case nil: case nil:
default: default:
@ -597,7 +596,7 @@ func createRoom(
sentry.CaptureException(err) sentry.CaptureException(err)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
} }
@ -610,7 +609,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }

View file

@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"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"
) )
@ -24,7 +24,7 @@ func Deactivate(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be read: " + err.Error()), JSON: spec.BadJSON("The request body could not be read: " + err.Error()),
} }
} }
@ -36,7 +36,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var res api.PerformAccountDeactivationResponse var res api.PerformAccountDeactivationResponse
@ -46,7 +46,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -22,9 +22,9 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"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/tidwall/gjson" "github.com/tidwall/gjson"
) )
@ -60,7 +60,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var targetDevice *api.Device var targetDevice *api.Device
for _, device := range queryRes.Devices { for _, device := range queryRes.Devices {
@ -72,7 +72,7 @@ func GetDeviceByID(
if targetDevice == nil { if targetDevice == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Unknown device"), JSON: spec.NotFound("Unknown device"),
} }
} }
@ -97,7 +97,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res := devicesJSON{} res := devicesJSON{}
@ -139,12 +139,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !performRes.DeviceExists { if !performRes.DeviceExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.Forbidden("device does not exist"), JSON: spec.Forbidden("device does not exist"),
} }
} }
@ -174,7 +174,7 @@ func DeleteDeviceById(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be read: " + err.Error()), JSON: spec.BadJSON("The request body could not be read: " + err.Error()),
} }
} }
@ -184,7 +184,7 @@ func DeleteDeviceById(
if dev != deviceID { if dev != deviceID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("session and device mismatch"), JSON: spec.Forbidden("session and device mismatch"),
} }
} }
} }
@ -206,7 +206,7 @@ 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 jsonerror.InternalServerError() return 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
@ -214,7 +214,7 @@ func DeleteDeviceById(
if login.Username() != localpart && login.Username() != device.UserID { if login.Username() != localpart && login.Username() != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden("Cannot delete another user's device"), JSON: spec.Forbidden("Cannot delete another user's device"),
} }
} }
@ -224,7 +224,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
deleteOK = true deleteOK = true
@ -245,7 +245,7 @@ func DeleteDevices(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be read: " + err.Error()), JSON: spec.BadJSON("The request body could not be read: " + err.Error()),
} }
} }
defer req.Body.Close() // nolint:errcheck defer req.Body.Close() // nolint:errcheck
@ -259,14 +259,14 @@ func DeleteDevices(
if login.Username() != device.UserID { if login.Username() != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("unable to delete devices for other user"), JSON: spec.Forbidden("unable to delete devices for other user"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var res api.PerformDeviceDeletionResponse var res api.PerformDeviceDeletionResponse
@ -275,7 +275,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -24,7 +24,6 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
federationAPI "github.com/matrix-org/dendrite/federationapi/api" federationAPI "github.com/matrix-org/dendrite/federationapi/api"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
@ -56,7 +55,7 @@ func DirectoryRoom(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), JSON: spec.BadJSON("Room alias must be in the form '#localpart:domain'"),
} }
} }
@ -70,7 +69,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res.RoomID = queryRes.RoomID res.RoomID = queryRes.RoomID
@ -84,7 +83,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res.RoomID = fedRes.RoomID res.RoomID = fedRes.RoomID
res.fillServers(fedRes.Servers) res.fillServers(fedRes.Servers)
@ -93,7 +92,7 @@ func DirectoryRoom(
if res.RoomID == "" { if res.RoomID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound( JSON: spec.NotFound(
fmt.Sprintf("Room alias %s not found", roomAlias), fmt.Sprintf("Room alias %s not found", roomAlias),
), ),
} }
@ -103,7 +102,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res.fillServers(joinedHostsRes.ServerNames) res.fillServers(joinedHostsRes.ServerNames)
} }
@ -126,14 +125,14 @@ func SetLocalAlias(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), JSON: spec.BadJSON("Room alias must be in the form '#localpart:domain'"),
} }
} }
if !cfg.Matrix.IsLocalServerName(domain) { if !cfg.Matrix.IsLocalServerName(domain) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Alias must be on local homeserver"), JSON: spec.Forbidden("Alias must be on local homeserver"),
} }
} }
@ -146,7 +145,7 @@ func SetLocalAlias(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("User ID must be in the form '@localpart:domain'"), JSON: spec.BadJSON("User ID must be in the form '@localpart:domain'"),
} }
} }
for _, appservice := range cfg.Derived.ApplicationServices { for _, appservice := range cfg.Derived.ApplicationServices {
@ -158,7 +157,7 @@ func SetLocalAlias(
if namespace.Exclusive && namespace.RegexpObject.MatchString(alias) { if namespace.Exclusive && namespace.RegexpObject.MatchString(alias) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.ASExclusive("Alias is reserved by an application service"), JSON: spec.ASExclusive("Alias is reserved by an application service"),
} }
} }
} }
@ -181,13 +180,13 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if queryRes.AliasExists { if queryRes.AliasExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusConflict, Code: http.StatusConflict,
JSON: jsonerror.Unknown("The alias " + alias + " already exists."), JSON: spec.Unknown("The alias " + alias + " already exists."),
} }
} }
@ -211,20 +210,20 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !queryRes.Found { if !queryRes.Found {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("The alias does not exist."), JSON: spec.NotFound("The alias does not exist."),
} }
} }
if !queryRes.Removed { if !queryRes.Removed {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You do not have permission to remove this alias."), JSON: spec.Forbidden("You do not have permission to remove this alias."),
} }
} }
@ -249,7 +248,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var v roomVisibility var v roomVisibility
@ -287,7 +286,7 @@ 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 jsonerror.InternalServerError() return 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
@ -295,7 +294,7 @@ func SetVisibility(
if power.UserLevel(dev.UserID) < power.EventLevel(spec.MRoomCanonicalAlias, true) { if power.UserLevel(dev.UserID) < power.EventLevel(spec.MRoomCanonicalAlias, true) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID doesn't have power level to change visibility"), JSON: spec.Forbidden("userID doesn't have power level to change visibility"),
} }
} }
@ -309,7 +308,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -325,7 +324,7 @@ func SetVisibilityAS(
if dev.AccountType != userapi.AccountTypeAppService { if dev.AccountType != userapi.AccountTypeAppService {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Only appservice may use this endpoint"), JSON: spec.Forbidden("Only appservice may use this endpoint"),
} }
} }
var v roomVisibility var v roomVisibility
@ -345,7 +344,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -29,7 +29,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/api" "github.com/matrix-org/dendrite/clientapi/api"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
) )
@ -68,7 +67,7 @@ func GetPostPublicRooms(
if request.IncludeAllNetworks && request.NetworkID != "" { if request.IncludeAllNetworks && request.NetworkID != "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam("include_all_networks and third_party_instance_id can not be used together"), JSON: spec.InvalidParam("include_all_networks and third_party_instance_id can not be used together"),
} }
} }
@ -82,7 +81,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -93,7 +92,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -173,7 +172,7 @@ func fillPublicRoomsReq(httpReq *http.Request, request *PublicRoomReq) *util.JSO
if httpReq.Method != "GET" && httpReq.Method != "POST" { if httpReq.Method != "GET" && httpReq.Method != "POST" {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusMethodNotAllowed, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: spec.NotFound("Bad method"),
} }
} }
if httpReq.Method == "GET" { if httpReq.Method == "GET" {
@ -184,7 +183,7 @@ func fillPublicRoomsReq(httpReq *http.Request, request *PublicRoomReq) *util.JSO
util.GetLogger(httpReq.Context()).WithError(err).Error("strconv.Atoi failed") util.GetLogger(httpReq.Context()).WithError(err).Error("strconv.Atoi failed")
return &util.JSONResponse{ return &util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.BadJSON("limit param is not a number"), JSON: spec.BadJSON("limit param is not a number"),
} }
} }
request.Limit = int64(limit) request.Limit = int64(limit)

View file

@ -19,9 +19,9 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
type getJoinedRoomsResponse struct { type getJoinedRoomsResponse struct {
@ -40,7 +40,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if res.RoomIDs == nil { if res.RoomIDs == nil {
res.RoomIDs = []string{} res.RoomIDs = []string{}

View file

@ -22,7 +22,6 @@ import (
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
@ -75,7 +74,7 @@ func JoinRoomByIDOrAlias(
util.GetLogger(req.Context()).Error("Unable to query user profile, no profile found.") util.GetLogger(req.Context()).Error("Unable to query user profile, no profile found.")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("Unable to query user profile, no profile found."), JSON: spec.Unknown("Unable to query user profile, no profile found."),
} }
default: default:
} }
@ -99,12 +98,12 @@ func JoinRoomByIDOrAlias(
case roomserverAPI.ErrInvalidID: case roomserverAPI.ErrInvalidID:
response = util.JSONResponse{ response = util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(e.Error()), JSON: spec.Unknown(e.Error()),
} }
case roomserverAPI.ErrNotAllowed: case roomserverAPI.ErrNotAllowed:
jsonErr := jsonerror.Forbidden(e.Error()) jsonErr := spec.Forbidden(e.Error())
if device.AccountType == api.AccountTypeGuest { if device.AccountType == api.AccountTypeGuest {
jsonErr = jsonerror.GuestAccessForbidden(e.Error()) jsonErr = spec.GuestAccessForbidden(e.Error())
} }
response = util.JSONResponse{ response = util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -118,12 +117,12 @@ func JoinRoomByIDOrAlias(
default: default:
response = util.JSONResponse{ response = util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
if errors.Is(err, eventutil.ErrRoomNoExists) { if errors.Is(err, eventutil.ErrRoomNoExists) {
response = util.JSONResponse{ response = util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(e.Error()), JSON: spec.NotFound(e.Error()),
} }
} }
} }
@ -137,7 +136,7 @@ func JoinRoomByIDOrAlias(
case <-timer.C: case <-timer.C:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusAccepted, Code: http.StatusAccepted,
JSON: jsonerror.Unknown("The room join will continue in the background."), JSON: spec.Unknown("The room join will continue in the background."),
} }
case result := <-done: case result := <-done:
// Stop and drain the timer // Stop and drain the timer

View file

@ -20,8 +20,8 @@ import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -64,7 +64,7 @@ func CreateKeyBackupVersion(req *http.Request, userAPI userapi.ClientUserAPI, de
if len(kb.AuthData) == 0 { if len(kb.AuthData) == 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing auth_data"), JSON: spec.BadJSON("missing auth_data"),
} }
} }
version, err := userAPI.PerformKeyBackup(req.Context(), &userapi.PerformKeyBackupRequest{ version, err := userAPI.PerformKeyBackup(req.Context(), &userapi.PerformKeyBackupRequest{
@ -98,7 +98,7 @@ func KeyBackupVersion(req *http.Request, userAPI userapi.ClientUserAPI, device *
if !queryResp.Exists { if !queryResp.Exists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("version not found"), JSON: spec.NotFound("version not found"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -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 *jsonerror.ErrRoomKeysVersion: case *spec.ErrRoomKeysVersion:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: e, JSON: e,
@ -141,7 +141,7 @@ func ModifyKeyBackupVersionAuthData(req *http.Request, userAPI userapi.ClientUse
if !performKeyBackupResp.Exists { if !performKeyBackupResp.Exists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("backup version not found"), JSON: spec.NotFound("backup version not found"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -162,7 +162,7 @@ func DeleteKeyBackupVersion(req *http.Request, userAPI userapi.ClientUserAPI, de
if !exists { if !exists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("backup version not found"), JSON: spec.NotFound("backup version not found"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -182,7 +182,7 @@ func UploadBackupKeys(
}) })
switch e := err.(type) { switch e := err.(type) {
case *jsonerror.ErrRoomKeysVersion: case *spec.ErrRoomKeysVersion:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: e, JSON: e,
@ -194,7 +194,7 @@ func UploadBackupKeys(
if !performKeyBackupResp.Exists { if !performKeyBackupResp.Exists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("backup version not found"), JSON: spec.NotFound("backup version not found"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -223,7 +223,7 @@ func GetBackupKeys(
if !queryResp.Exists { if !queryResp.Exists {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("version not found"), JSON: spec.NotFound("version not found"),
} }
} }
if sessionID != "" { if sessionID != "" {
@ -274,6 +274,6 @@ func GetBackupKeys(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("keys not found"), JSON: spec.NotFound("keys not found"),
} }
} }

View file

@ -20,9 +20,9 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -71,31 +71,29 @@ func UploadCrossSigningDeviceKeys(
sessions.addCompletedSessionStage(sessionID, authtypes.LoginTypePassword) sessions.addCompletedSessionStage(sessionID, authtypes.LoginTypePassword)
uploadReq.UserID = device.UserID uploadReq.UserID = device.UserID
if err := keyserverAPI.PerformUploadDeviceKeys(req.Context(), &uploadReq.PerformUploadDeviceKeysRequest, uploadRes); err != nil { keyserverAPI.PerformUploadDeviceKeys(req.Context(), &uploadReq.PerformUploadDeviceKeysRequest, uploadRes)
return jsonerror.InternalAPIError(req.Context(), err)
}
if err := uploadRes.Error; err != nil { if err := uploadRes.Error; err != nil {
switch { switch {
case err.IsInvalidSignature: case err.IsInvalidSignature:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidSignature(err.Error()), JSON: spec.InvalidSignature(err.Error()),
} }
case err.IsMissingParam: case err.IsMissingParam:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingParam(err.Error()), JSON: spec.MissingParam(err.Error()),
} }
case err.IsInvalidParam: case err.IsInvalidParam:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(err.Error()), JSON: spec.Unknown(err.Error()),
} }
} }
} }
@ -115,31 +113,29 @@ func UploadCrossSigningDeviceSignatures(req *http.Request, keyserverAPI api.Clie
} }
uploadReq.UserID = device.UserID uploadReq.UserID = device.UserID
if err := keyserverAPI.PerformUploadDeviceSignatures(req.Context(), uploadReq, uploadRes); err != nil { keyserverAPI.PerformUploadDeviceSignatures(req.Context(), uploadReq, uploadRes)
return jsonerror.InternalAPIError(req.Context(), err)
}
if err := uploadRes.Error; err != nil { if err := uploadRes.Error; err != nil {
switch { switch {
case err.IsInvalidSignature: case err.IsInvalidSignature:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidSignature(err.Error()), JSON: spec.InvalidSignature(err.Error()),
} }
case err.IsMissingParam: case err.IsMissingParam:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingParam(err.Error()), JSON: spec.MissingParam(err.Error()),
} }
case err.IsInvalidParam: case err.IsInvalidParam:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(err.Error()), JSON: spec.Unknown(err.Error()),
} }
} }
} }

View file

@ -22,8 +22,8 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
type uploadKeysRequest struct { type uploadKeysRequest struct {
@ -67,7 +67,7 @@ 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 jsonerror.InternalServerError() return 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")
@ -112,14 +112,12 @@ func QueryKeys(req *http.Request, keyAPI api.ClientKeyAPI, device *api.Device) u
return *resErr return *resErr
} }
queryRes := api.QueryKeysResponse{} queryRes := api.QueryKeysResponse{}
if err := keyAPI.QueryKeys(req.Context(), &api.QueryKeysRequest{ keyAPI.QueryKeys(req.Context(), &api.QueryKeysRequest{
UserID: device.UserID, UserID: device.UserID,
UserToDevices: r.DeviceKeys, UserToDevices: r.DeviceKeys,
Timeout: r.GetTimeout(), Timeout: r.GetTimeout(),
// TODO: Token? // TODO: Token?
}, &queryRes); err != nil { }, &queryRes)
return util.ErrorResponse(err)
}
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,
JSON: map[string]interface{}{ JSON: map[string]interface{}{
@ -152,15 +150,13 @@ func ClaimKeys(req *http.Request, keyAPI api.ClientKeyAPI) util.JSONResponse {
return *resErr return *resErr
} }
claimRes := api.PerformClaimKeysResponse{} claimRes := api.PerformClaimKeysResponse{}
if err := keyAPI.PerformClaimKeys(req.Context(), &api.PerformClaimKeysRequest{ keyAPI.PerformClaimKeys(req.Context(), &api.PerformClaimKeysRequest{
OneTimeKeys: r.OneTimeKeys, OneTimeKeys: r.OneTimeKeys,
Timeout: r.GetTimeout(), Timeout: r.GetTimeout(),
}, &claimRes); err != nil { }, &claimRes)
return jsonerror.InternalAPIError(req.Context(), err)
}
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,

View file

@ -17,9 +17,9 @@ package routing
import ( import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -41,12 +41,12 @@ func LeaveRoomByID(
if leaveRes.Code != 0 { if leaveRes.Code != 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: leaveRes.Code, Code: leaveRes.Code,
JSON: jsonerror.LeaveServerNoticeError(), JSON: spec.LeaveServerNoticeError(),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(err.Error()), JSON: spec.Unknown(err.Error()),
} }
} }

View file

@ -19,10 +19,10 @@ import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/userutil" "github.com/matrix-org/dendrite/clientapi/userutil"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -72,7 +72,7 @@ func Login(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusMethodNotAllowed, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: spec.NotFound("Bad method"),
} }
} }
@ -83,13 +83,13 @@ 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var performRes userapi.PerformDeviceCreationResponse var performRes userapi.PerformDeviceCreationResponse
@ -105,7 +105,7 @@ func completeAuth(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create device: " + err.Error()), JSON: spec.Unknown("failed to create device: " + err.Error()),
} }
} }

View file

@ -17,8 +17,8 @@ package routing
import ( import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -33,7 +33,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -53,7 +53,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -27,7 +27,6 @@ import (
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/threepid" "github.com/matrix-org/dendrite/clientapi/threepid"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
@ -52,7 +51,7 @@ func SendBan(
if body.UserID == "" { if body.UserID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing user_id"), JSON: spec.BadJSON("missing user_id"),
} }
} }
@ -69,7 +68,7 @@ func SendBan(
if !allowedToBan { if !allowedToBan {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You don't have permission to ban this user, power level too low."), JSON: spec.Forbidden("You don't have permission to ban this user, power level too low."),
} }
} }
@ -86,7 +85,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
serverName := device.UserDomain() serverName := device.UserDomain()
@ -101,7 +100,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -122,7 +121,7 @@ func SendKick(
if body.UserID == "" { if body.UserID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing user_id"), JSON: spec.BadJSON("missing user_id"),
} }
} }
@ -139,7 +138,7 @@ func SendKick(
if !allowedToKick { if !allowedToKick {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You don't have permission to kick this user, power level too low."), JSON: spec.Forbidden("You don't have permission to kick this user, power level too low."),
} }
} }
@ -155,7 +154,7 @@ func SendKick(
if queryRes.Membership != spec.Join && queryRes.Membership != spec.Invite { if queryRes.Membership != spec.Join && queryRes.Membership != spec.Invite {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Unknown("cannot /kick banned or left users"), JSON: spec.Unknown("cannot /kick banned or left users"),
} }
} }
// TODO: should we be using SendLeave instead? // TODO: should we be using SendLeave instead?
@ -174,7 +173,7 @@ func SendUnban(
if body.UserID == "" { if body.UserID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing user_id"), JSON: spec.BadJSON("missing user_id"),
} }
} }
@ -196,7 +195,7 @@ func SendUnban(
if queryRes.Membership != spec.Ban { if queryRes.Membership != spec.Ban {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("can only /unban users that are banned"), JSON: spec.Unknown("can only /unban users that are banned"),
} }
} }
// TODO: should we be using SendLeave instead? // TODO: should we be using SendLeave instead?
@ -233,7 +232,7 @@ func SendInvite(
if body.UserID == "" { if body.UserID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing user_id"), JSON: spec.BadJSON("missing user_id"),
} }
} }
@ -263,7 +262,7 @@ 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 jsonerror.InternalServerError(), err return spec.InternalServerError(), err
} }
err = rsAPI.PerformInvite(ctx, &api.PerformInviteRequest{ err = rsAPI.PerformInvite(ctx, &api.PerformInviteRequest{
@ -277,12 +276,12 @@ func sendInvite(
case roomserverAPI.ErrInvalidID: case roomserverAPI.ErrInvalidID:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(e.Error()), JSON: spec.Unknown(e.Error()),
}, e }, e
case roomserverAPI.ErrNotAllowed: case roomserverAPI.ErrNotAllowed:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(e.Error()), JSON: spec.Forbidden(e.Error()),
}, e }, e
case nil: case nil:
default: default:
@ -290,7 +289,7 @@ func sendInvite(
sentry.CaptureException(err) sentry.CaptureException(err)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
}, err }, err
} }
@ -377,7 +376,7 @@ func extractRequestData(req *http.Request) (body *threepid.MembershipRequest, ev
if err != nil { if err != nil {
resErr = &util.JSONResponse{ resErr = &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
return return
} }
@ -402,27 +401,27 @@ func checkAndProcessThreepid(
if err == threepid.ErrMissingParameter { if err == threepid.ErrMissingParameter {
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
} else if err == threepid.ErrNotTrusted { } else if err == threepid.ErrNotTrusted {
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.IDServer), JSON: spec.NotTrusted(body.IDServer),
} }
} else if err == eventutil.ErrRoomNoExists { } else if err == eventutil.ErrRoomNoExists {
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(err.Error()), JSON: spec.NotFound(err.Error()),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { } else if e, ok := err.(gomatrixserverlib.BadJSONError); ok {
return inviteStored, &util.JSONResponse{ return inviteStored, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} }
if err != nil { if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAndProcessInvite failed")
er := jsonerror.InternalServerError() er := spec.InternalServerError()
return inviteStored, &er return inviteStored, &er
} }
return return
@ -436,13 +435,13 @@ 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 := jsonerror.InternalServerError() e := spec.InternalServerError()
return &e return &e
} }
if !membershipRes.IsInRoom { if !membershipRes.IsInRoom {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("user does not belong to room"), JSON: spec.Forbidden("user does not belong to room"),
} }
} }
return nil return nil
@ -462,18 +461,18 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !membershipRes.RoomExists { if !membershipRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("room does not exist"), JSON: spec.Forbidden("room does not exist"),
} }
} }
if membershipRes.IsInRoom { if membershipRes.IsInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(fmt.Sprintf("User %s is in room %s", device.UserID, roomID)), JSON: spec.Unknown(fmt.Sprintf("User %s is in room %s", device.UserID, roomID)),
} }
} }
@ -484,7 +483,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -500,14 +499,14 @@ func getPowerlevels(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAPI,
if plEvent == nil { if plEvent == nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You don't have permission to perform this action, no power_levels event in this room."), JSON: spec.Forbidden("You don't have permission to perform this action, no power_levels event in this room."),
} }
} }
pl, err := plEvent.PowerLevels() pl, err := plEvent.PowerLevels()
if err != nil { if err != nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You don't have permission to perform this action, the power_levels event for this room is malformed so auth checks cannot be performed."), JSON: spec.Forbidden("You don't have permission to perform this action, the power_levels event for this room is malformed so auth checks cannot be performed."),
} }
} }
return pl, nil return pl, nil

View file

@ -18,9 +18,9 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"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"
) )
@ -35,7 +35,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
@ -43,7 +43,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
err = userAPI.QueryNotifications(req.Context(), &userapi.QueryNotificationsRequest{ err = userAPI.QueryNotifications(req.Context(), &userapi.QueryNotificationsRequest{
Localpart: localpart, Localpart: localpart,
@ -54,7 +54,7 @@ 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 jsonerror.InternalServerError() return 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

@ -17,9 +17,9 @@ package routing
import ( import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -43,7 +43,7 @@ func CreateOpenIDToken(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot request tokens for other users"), JSON: spec.Forbidden("Cannot request tokens for other users"),
} }
} }
@ -55,7 +55,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -6,11 +6,11 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"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/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -90,7 +90,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
// Ask the user API to perform the password change. // Ask the user API to perform the password change.
@ -102,11 +102,11 @@ 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return 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 +120,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
pushersReq := &api.PerformPusherDeletionRequest{ pushersReq := &api.PerformPusherDeletionRequest{
@ -130,7 +130,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }

View file

@ -18,7 +18,6 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
@ -61,12 +60,12 @@ func PeekRoomByIDOrAlias(
case roomserverAPI.ErrInvalidID: case roomserverAPI.ErrInvalidID:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(e.Error()), JSON: spec.Unknown(e.Error()),
} }
case roomserverAPI.ErrNotAllowed: case roomserverAPI.ErrNotAllowed:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(e.Error()), JSON: spec.Forbidden(e.Error()),
} }
case *gomatrix.HTTPError: case *gomatrix.HTTPError:
return util.JSONResponse{ return util.JSONResponse{
@ -76,7 +75,7 @@ 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 jsonerror.InternalServerError() return 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
@ -107,12 +106,12 @@ func UnpeekRoomByID(
case roomserverAPI.ErrInvalidID: case roomserverAPI.ErrInvalidID:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(e.Error()), JSON: spec.Unknown(e.Error()),
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -21,7 +21,6 @@ import (
"time" "time"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
@ -54,7 +53,7 @@ func SetPresence(
if device.UserID != userID { if device.UserID != userID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Unable to set presence for other user."), JSON: spec.Forbidden("Unable to set presence for other user."),
} }
} }
var presence presenceReq var presence presenceReq
@ -67,7 +66,7 @@ func SetPresence(
if !ok { if !ok {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(fmt.Sprintf("Unknown presence '%s'.", presence.Presence)), JSON: spec.Unknown(fmt.Sprintf("Unknown presence '%s'.", presence.Presence)),
} }
} }
err := producer.SendPresence(req.Context(), userID, presenceStatus, presence.StatusMsg) err := producer.SendPresence(req.Context(), userID, presenceStatus, presence.StatusMsg)
@ -75,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: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
@ -100,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: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
@ -119,7 +118,7 @@ func GetPresence(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }

View file

@ -26,13 +26,11 @@ import (
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -49,12 +47,12 @@ func GetProfile(
if err == appserviceAPI.ErrProfileNotExists { if err == appserviceAPI.ErrProfileNotExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("The user does not exist or does not have a profile"), JSON: spec.NotFound("The user does not exist or does not have a profile"),
} }
} }
util.GetLogger(req.Context()).WithError(err).Error("getProfile failed") util.GetLogger(req.Context()).WithError(err).Error("getProfile failed")
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -95,7 +93,7 @@ func SetAvatarURL(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: spec.Forbidden("userID does not match the current user"),
} }
} }
@ -106,20 +104,20 @@ func SetAvatarURL(
if r.AvatarURL == "" { if r.AvatarURL == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("'avatar_url' must be supplied."), JSON: spec.BadJSON("'avatar_url' must be supplied."),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !cfg.Matrix.IsLocalServerName(domain) { if !cfg.Matrix.IsLocalServerName(domain) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not belong to a locally configured domain"), JSON: spec.Forbidden("userID does not belong to a locally configured domain"),
} }
} }
@ -127,14 +125,14 @@ func SetAvatarURL(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
} }
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 jsonerror.InternalServerError() return 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 {
@ -184,7 +182,7 @@ func SetDisplayName(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not match the current user"), JSON: spec.Forbidden("userID does not match the current user"),
} }
} }
@ -195,20 +193,20 @@ func SetDisplayName(
if r.DisplayName == "" { if r.DisplayName == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("'displayname' must be supplied."), JSON: spec.BadJSON("'displayname' must be supplied."),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !cfg.Matrix.IsLocalServerName(domain) { if !cfg.Matrix.IsLocalServerName(domain) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID does not belong to a locally configured domain"), JSON: spec.Forbidden("userID does not belong to a locally configured domain"),
} }
} }
@ -216,14 +214,14 @@ func SetDisplayName(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
} }
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 jsonerror.InternalServerError() return 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 {
@ -256,13 +254,13 @@ 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 jsonerror.InternalServerError(), err return 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 jsonerror.InternalServerError(), err return spec.InternalServerError(), err
} }
events, err := buildMembershipEvents( events, err := buildMembershipEvents(
@ -273,16 +271,16 @@ func updateProfile(
case gomatrixserverlib.BadJSONError: case gomatrixserverlib.BadJSONError:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
}, e }, e
default: default:
util.GetLogger(ctx).WithError(err).Error("buildMembershipEvents failed") util.GetLogger(ctx).WithError(err).Error("buildMembershipEvents failed")
return jsonerror.InternalServerError(), e return 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 jsonerror.InternalServerError(), err return spec.InternalServerError(), err
} }
return util.JSONResponse{}, nil return util.JSONResponse{}, nil
} }

View file

@ -19,9 +19,9 @@ import (
"net/url" "net/url"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"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"
) )
@ -34,7 +34,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
err = userAPI.QueryPushers(req.Context(), &userapi.QueryPushersRequest{ err = userAPI.QueryPushers(req.Context(), &userapi.QueryPushersRequest{
Localpart: localpart, Localpart: localpart,
@ -42,7 +42,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
for i := range queryRes.Pushers { for i := range queryRes.Pushers {
queryRes.Pushers[i].SessionID = 0 queryRes.Pushers[i].SessionID = 0
@ -63,7 +63,7 @@ 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 jsonerror.InternalServerError() return 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 +99,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -111,6 +111,6 @@ func SetPusher(
func invalidParam(msg string) util.JSONResponse { func invalidParam(msg string) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam(msg), JSON: spec.InvalidParam(msg),
} }
} }

View file

@ -7,17 +7,17 @@ import (
"net/http" "net/http"
"reflect" "reflect"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/pushrules" "github.com/matrix-org/dendrite/internal/pushrules"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
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.(*jsonerror.MatrixError); ok { if eerr, ok := err.(*spec.MatrixError); ok {
var status int var status int
switch eerr.ErrCode { switch eerr.ErrCode {
case "M_INVALID_ARGUMENT_VALUE": case "M_INVALID_PARAM":
status = http.StatusBadRequest status = http.StatusBadRequest
case "M_NOT_FOUND": case "M_NOT_FOUND":
status = http.StatusNotFound status = http.StatusNotFound
@ -27,7 +27,7 @@ func errorResponse(ctx context.Context, err error, msg string, args ...interface
return util.MatrixErrorResponse(status, eerr.ErrCode, eerr.Err) return util.MatrixErrorResponse(status, eerr.ErrCode, eerr.Err)
} }
util.GetLogger(ctx).WithError(err).Errorf(msg, args...) util.GetLogger(ctx).WithError(err).Errorf(msg, args...)
return jsonerror.InternalServerError() return 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 {
@ -48,7 +48,7 @@ func GetPushRulesByScope(ctx context.Context, scope string, device *userapi.Devi
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -63,12 +63,12 @@ func GetPushRulesByKind(ctx context.Context, scope, kind string, device *userapi
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind)) rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind))
// Even if rulesPtr is not nil, there may not be any rules for this kind // Even if rulesPtr is not nil, there may not be any rules for this kind
if rulesPtr == nil || (rulesPtr != nil && len(*rulesPtr) == 0) { if rulesPtr == nil || (rulesPtr != nil && len(*rulesPtr) == 0) {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rules kind"), "pushRuleSetKindPointer failed") return errorResponse(ctx, spec.InvalidParam("invalid push rules kind"), "pushRuleSetKindPointer failed")
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -83,15 +83,15 @@ func GetPushRuleByRuleID(ctx context.Context, scope, kind, ruleID string, device
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind)) rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind))
if rulesPtr == nil { if rulesPtr == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rules kind"), "pushRuleSetKindPointer failed") return errorResponse(ctx, spec.InvalidParam("invalid push rules kind"), "pushRuleSetKindPointer failed")
} }
i := pushRuleIndexByID(*rulesPtr, ruleID) i := pushRuleIndexByID(*rulesPtr, ruleID)
if i < 0 { if i < 0 {
return errorResponse(ctx, jsonerror.NotFound("push rule ID not found"), "pushRuleIndexByID failed") return errorResponse(ctx, spec.NotFound("push rule ID not found"), "pushRuleIndexByID failed")
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -104,14 +104,14 @@ func PutPushRuleByRuleID(ctx context.Context, scope, kind, ruleID, afterRuleID,
if err := json.NewDecoder(body).Decode(&newRule); err != nil { if err := json.NewDecoder(body).Decode(&newRule); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
} }
newRule.RuleID = ruleID newRule.RuleID = ruleID
errs := pushrules.ValidateRule(pushrules.Kind(kind), &newRule) errs := pushrules.ValidateRule(pushrules.Kind(kind), &newRule)
if len(errs) > 0 { if len(errs) > 0 {
return errorResponse(ctx, jsonerror.InvalidArgumentValue(errs[0].Error()), "rule sanity check failed: %v", errs) return errorResponse(ctx, spec.InvalidParam(errs[0].Error()), "rule sanity check failed: %v", errs)
} }
ruleSets, err := userAPI.QueryPushRules(ctx, device.UserID) ruleSets, err := userAPI.QueryPushRules(ctx, device.UserID)
@ -120,12 +120,12 @@ func PutPushRuleByRuleID(ctx context.Context, scope, kind, ruleID, afterRuleID,
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind)) rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind))
if rulesPtr == nil { if rulesPtr == nil {
// while this should be impossible (ValidateRule would already return an error), better keep it around // while this should be impossible (ValidateRule would already return an error), better keep it around
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rules kind"), "pushRuleSetKindPointer failed") return errorResponse(ctx, spec.InvalidParam("invalid push rules kind"), "pushRuleSetKindPointer failed")
} }
i := pushRuleIndexByID(*rulesPtr, ruleID) i := pushRuleIndexByID(*rulesPtr, ruleID)
if i >= 0 && afterRuleID == "" && beforeRuleID == "" { if i >= 0 && afterRuleID == "" && beforeRuleID == "" {
@ -172,15 +172,15 @@ func DeletePushRuleByRuleID(ctx context.Context, scope, kind, ruleID string, dev
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind)) rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind))
if rulesPtr == nil { if rulesPtr == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rules kind"), "pushRuleSetKindPointer failed") return errorResponse(ctx, spec.InvalidParam("invalid push rules kind"), "pushRuleSetKindPointer failed")
} }
i := pushRuleIndexByID(*rulesPtr, ruleID) i := pushRuleIndexByID(*rulesPtr, ruleID)
if i < 0 { if i < 0 {
return errorResponse(ctx, jsonerror.NotFound("push rule ID not found"), "pushRuleIndexByID failed") return errorResponse(ctx, spec.NotFound("push rule ID not found"), "pushRuleIndexByID failed")
} }
*rulesPtr = append((*rulesPtr)[:i], (*rulesPtr)[i+1:]...) *rulesPtr = append((*rulesPtr)[:i], (*rulesPtr)[i+1:]...)
@ -203,15 +203,15 @@ func GetPushRuleAttrByRuleID(ctx context.Context, scope, kind, ruleID, attr stri
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind)) rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind))
if rulesPtr == nil { if rulesPtr == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rules kind"), "pushRuleSetKindPointer failed") return errorResponse(ctx, spec.InvalidParam("invalid push rules kind"), "pushRuleSetKindPointer failed")
} }
i := pushRuleIndexByID(*rulesPtr, ruleID) i := pushRuleIndexByID(*rulesPtr, ruleID)
if i < 0 { if i < 0 {
return errorResponse(ctx, jsonerror.NotFound("push rule ID not found"), "pushRuleIndexByID failed") return errorResponse(ctx, spec.NotFound("push rule ID not found"), "pushRuleIndexByID failed")
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -226,7 +226,7 @@ func PutPushRuleAttrByRuleID(ctx context.Context, scope, kind, ruleID, attr stri
if err := json.NewDecoder(body).Decode(&newPartialRule); err != nil { if err := json.NewDecoder(body).Decode(&newPartialRule); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
} }
if newPartialRule.Actions == nil { if newPartialRule.Actions == nil {
@ -249,15 +249,15 @@ func PutPushRuleAttrByRuleID(ctx context.Context, scope, kind, ruleID, attr stri
} }
ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope)) ruleSet := pushRuleSetByScope(ruleSets, pushrules.Scope(scope))
if ruleSet == nil { if ruleSet == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rule set"), "pushRuleSetByScope failed") return errorResponse(ctx, spec.InvalidParam("invalid push rule set"), "pushRuleSetByScope failed")
} }
rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind)) rulesPtr := pushRuleSetKindPointer(ruleSet, pushrules.Kind(kind))
if rulesPtr == nil { if rulesPtr == nil {
return errorResponse(ctx, jsonerror.InvalidArgumentValue("invalid push rules kind"), "pushRuleSetKindPointer failed") return errorResponse(ctx, spec.InvalidParam("invalid push rules kind"), "pushRuleSetKindPointer failed")
} }
i := pushRuleIndexByID(*rulesPtr, ruleID) i := pushRuleIndexByID(*rulesPtr, ruleID)
if i < 0 { if i < 0 {
return errorResponse(ctx, jsonerror.NotFound("push rule ID not found"), "pushRuleIndexByID failed") return errorResponse(ctx, spec.NotFound("push rule ID not found"), "pushRuleIndexByID failed")
} }
if !reflect.DeepEqual(attrGet((*rulesPtr)[i]), attrGet(&newPartialRule)) { if !reflect.DeepEqual(attrGet((*rulesPtr)[i]), attrGet(&newPartialRule)) {
@ -313,7 +313,7 @@ func pushRuleAttrGetter(attr string) (func(*pushrules.Rule) interface{}, error)
case "enabled": case "enabled":
return func(rule *pushrules.Rule) interface{} { return rule.Enabled }, nil return func(rule *pushrules.Rule) interface{} { return rule.Enabled }, nil
default: default:
return nil, jsonerror.InvalidArgumentValue("invalid push rule attribute") return nil, spec.InvalidParam("invalid push rule attribute")
} }
} }
@ -324,7 +324,7 @@ func pushRuleAttrSetter(attr string) (func(dest, src *pushrules.Rule), error) {
case "enabled": case "enabled":
return func(dest, src *pushrules.Rule) { dest.Enabled = src.Enabled }, nil return func(dest, src *pushrules.Rule) { dest.Enabled = src.Enabled }, nil
default: default:
return nil, jsonerror.InvalidArgumentValue("invalid push rule attribute") return nil, spec.InvalidParam("invalid push rule attribute")
} }
} }
@ -338,10 +338,10 @@ func findPushRuleInsertionIndex(rules []*pushrules.Rule, afterID, beforeID strin
} }
} }
if i == len(rules) { if i == len(rules) {
return 0, jsonerror.NotFound("after: rule ID not found") return 0, spec.NotFound("after: rule ID not found")
} }
if rules[i].Default { if rules[i].Default {
return 0, jsonerror.NotFound("after: rule ID must not be a default rule") return 0, spec.NotFound("after: rule ID must not be a default rule")
} }
// We stopped on the "after" match to differentiate // We stopped on the "after" match to differentiate
// not-found from is-last-entry. Now we move to the earliest // not-found from is-last-entry. Now we move to the earliest
@ -356,10 +356,10 @@ func findPushRuleInsertionIndex(rules []*pushrules.Rule, afterID, beforeID strin
} }
} }
if i == len(rules) { if i == len(rules) {
return 0, jsonerror.NotFound("before: rule ID not found") return 0, spec.NotFound("before: rule ID not found")
} }
if rules[i].Default { if rules[i].Default {
return 0, jsonerror.NotFound("before: rule ID must not be a default rule") return 0, spec.NotFound("before: rule ID must not be a default rule")
} }
} }

View file

@ -20,7 +20,6 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
@ -49,7 +48,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
dataReq := api.InputAccountDataRequest{ dataReq := api.InputAccountDataRequest{

View file

@ -24,7 +24,6 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/internal/transactions" "github.com/matrix-org/dendrite/internal/transactions"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
@ -63,13 +62,13 @@ func SendRedaction(
if ev == nil { if ev == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.NotFound("unknown event ID"), // TODO: is it ok to leak existence? JSON: spec.NotFound("unknown event ID"), // TODO: is it ok to leak existence?
} }
} }
if ev.RoomID() != roomID { if ev.RoomID() != roomID {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.NotFound("cannot redact event in another room"), JSON: spec.NotFound("cannot redact event in another room"),
} }
} }
@ -85,14 +84,14 @@ func SendRedaction(
if plEvent == nil { if plEvent == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden("You don't have permission to redact this event, no power_levels event in this room."), JSON: spec.Forbidden("You don't have permission to redact this event, no power_levels event in this room."),
} }
} }
pl, err := plEvent.PowerLevels() pl, err := plEvent.PowerLevels()
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden( JSON: spec.Forbidden(
"You don't have permission to redact this event, the power_levels event for this room is malformed so auth checks cannot be performed.", "You don't have permission to redact this event, the power_levels event for this room is malformed so auth checks cannot be performed.",
), ),
} }
@ -102,7 +101,7 @@ func SendRedaction(
if !allowedToRedact { if !allowedToRedact {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden("You don't have permission to redact this event, power level too low."), JSON: spec.Forbidden("You don't have permission to redact this event, power level too low."),
} }
} }
@ -122,12 +121,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain()) identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain())
if err != nil { if err != nil {
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
var queryRes roomserverAPI.QueryLatestEventsAndStateResponse var queryRes roomserverAPI.QueryLatestEventsAndStateResponse
@ -135,13 +134,13 @@ func SendRedaction(
if err == eventutil.ErrRoomNoExists { if err == eventutil.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res := util.JSONResponse{ res := util.JSONResponse{

View file

@ -46,7 +46,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/userutil" "github.com/matrix-org/dendrite/clientapi/userutil"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
) )
@ -428,7 +427,7 @@ func validateApplicationService(
if matchedApplicationService == nil { if matchedApplicationService == nil {
return "", &util.JSONResponse{ return "", &util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.UnknownToken("Supplied access_token does not match any known application service"), JSON: spec.UnknownToken("Supplied access_token does not match any known application service"),
} }
} }
@ -439,7 +438,7 @@ func validateApplicationService(
// If we didn't find any matches, return M_EXCLUSIVE // If we didn't find any matches, return M_EXCLUSIVE
return "", &util.JSONResponse{ return "", &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.ASExclusive(fmt.Sprintf( JSON: spec.ASExclusive(fmt.Sprintf(
"Supplied username %s did not match any namespaces for application service ID: %s", username, matchedApplicationService.ID)), "Supplied username %s did not match any namespaces for application service ID: %s", username, matchedApplicationService.ID)),
} }
} }
@ -448,7 +447,7 @@ func validateApplicationService(
if UsernameMatchesMultipleExclusiveNamespaces(cfg, userID) { if UsernameMatchesMultipleExclusiveNamespaces(cfg, userID) {
return "", &util.JSONResponse{ return "", &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.ASExclusive(fmt.Sprintf( JSON: spec.ASExclusive(fmt.Sprintf(
"Supplied username %s matches multiple exclusive application service namespaces. Only 1 match allowed", username)), "Supplied username %s matches multiple exclusive application service namespaces. Only 1 match allowed", username)),
} }
} }
@ -474,7 +473,7 @@ func Register(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("Unable to read request body"), JSON: spec.NotJSON("Unable to read request body"),
} }
} }
@ -518,7 +517,7 @@ func Register(
if _, err = strconv.ParseInt(r.Username, 10, 64); err == nil { if _, err = strconv.ParseInt(r.Username, 10, 64); err == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Numeric user IDs are reserved"), JSON: spec.InvalidUsername("Numeric user IDs are reserved"),
} }
} }
// Auto generate a numeric username if r.Username is empty // Auto generate a numeric username if r.Username is empty
@ -529,7 +528,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
r.Username = strconv.FormatInt(nres.ID, 10) r.Username = strconv.FormatInt(nres.ID, 10)
} }
@ -552,7 +551,7 @@ func Register(
// type is not known or specified) // type is not known or specified)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("A known registration type (e.g. m.login.application_service) must be specified if an access_token is provided"), JSON: spec.MissingParam("A known registration type (e.g. m.login.application_service) must be specified if an access_token is provided"),
} }
default: default:
// Spec-compliant case (neither the access_token nor the login type are // Spec-compliant case (neither the access_token nor the login type are
@ -590,7 +589,7 @@ func handleGuestRegistration(
if !registrationEnabled || !guestsEnabled { if !registrationEnabled || !guestsEnabled {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden( JSON: spec.Forbidden(
fmt.Sprintf("Guest registration is disabled on %q", r.ServerName), fmt.Sprintf("Guest registration is disabled on %q", r.ServerName),
), ),
} }
@ -604,7 +603,7 @@ func handleGuestRegistration(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create account: " + err.Error()), JSON: spec.Unknown("failed to create account: " + err.Error()),
} }
} }
token, err := tokens.GenerateLoginToken(tokens.TokenOptions{ token, err := tokens.GenerateLoginToken(tokens.TokenOptions{
@ -616,7 +615,7 @@ func handleGuestRegistration(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("Failed to generate access token"), JSON: spec.Unknown("Failed to generate access token"),
} }
} }
//we don't allow guests to specify their own device_id //we don't allow guests to specify their own device_id
@ -632,7 +631,7 @@ func handleGuestRegistration(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create device: " + err.Error()), JSON: spec.Unknown("failed to create device: " + err.Error()),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -682,7 +681,7 @@ func handleRegistrationFlow(
if !registrationEnabled && r.Auth.Type != authtypes.LoginTypeSharedSecret { if !registrationEnabled && r.Auth.Type != authtypes.LoginTypeSharedSecret {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden( JSON: spec.Forbidden(
fmt.Sprintf("Registration is disabled on %q", r.ServerName), fmt.Sprintf("Registration is disabled on %q", r.ServerName),
), ),
} }
@ -696,7 +695,7 @@ func handleRegistrationFlow(
UsernameMatchesExclusiveNamespaces(cfg, r.Username) { UsernameMatchesExclusiveNamespaces(cfg, r.Username) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.ASExclusive("This username is reserved by an application service."), JSON: spec.ASExclusive("This username is reserved by an application service."),
} }
} }
@ -706,15 +705,15 @@ func handleRegistrationFlow(
err := validateRecaptcha(cfg, r.Auth.Response, req.RemoteAddr) err := validateRecaptcha(cfg, r.Auth.Response, req.RemoteAddr)
switch err { switch err {
case ErrCaptchaDisabled: case ErrCaptchaDisabled:
return util.JSONResponse{Code: http.StatusForbidden, JSON: jsonerror.Unknown(err.Error())} return util.JSONResponse{Code: http.StatusForbidden, JSON: spec.Unknown(err.Error())}
case ErrMissingResponse: case ErrMissingResponse:
return util.JSONResponse{Code: http.StatusBadRequest, JSON: jsonerror.BadJSON(err.Error())} return util.JSONResponse{Code: http.StatusBadRequest, JSON: spec.BadJSON(err.Error())}
case ErrInvalidCaptcha: case ErrInvalidCaptcha:
return util.JSONResponse{Code: http.StatusUnauthorized, JSON: jsonerror.BadJSON(err.Error())} return util.JSONResponse{Code: http.StatusUnauthorized, JSON: spec.BadJSON(err.Error())}
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: jsonerror.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
@ -732,7 +731,7 @@ func handleRegistrationFlow(
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotImplemented, Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("unknown/unimplemented auth type"), JSON: spec.Unknown("unknown/unimplemented auth type"),
} }
} }
@ -764,7 +763,7 @@ func handleApplicationServiceRegistration(
if tokenErr != nil { if tokenErr != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.MissingToken(tokenErr.Error()), JSON: spec.MissingToken(tokenErr.Error()),
} }
} }
@ -834,14 +833,14 @@ func completeRegistration(
if username == "" { if username == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Missing username"), JSON: spec.MissingParam("Missing username"),
} }
} }
// Blank passwords are only allowed by registered application services // Blank passwords are only allowed by registered application services
if password == "" && appserviceID == "" { if password == "" && appserviceID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Missing password"), JSON: spec.MissingParam("Missing password"),
} }
} }
var accRes userapi.PerformAccountCreationResponse var accRes userapi.PerformAccountCreationResponse
@ -857,12 +856,12 @@ func completeRegistration(
if _, ok := err.(*userapi.ErrorConflict); ok { // user already exists if _, ok := err.(*userapi.ErrorConflict); ok { // user already exists
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UserInUse("Desired user ID is already taken."), JSON: spec.UserInUse("Desired user ID is already taken."),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create account: " + err.Error()), JSON: spec.Unknown("failed to create account: " + err.Error()),
} }
} }
@ -884,7 +883,7 @@ func completeRegistration(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("Failed to generate access token"), JSON: spec.Unknown("Failed to generate access token"),
} }
} }
@ -893,7 +892,7 @@ func completeRegistration(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to set display name: " + err.Error()), JSON: spec.Unknown("failed to set display name: " + err.Error()),
} }
} }
} }
@ -911,7 +910,7 @@ func completeRegistration(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to create device: " + err.Error()), JSON: spec.Unknown("failed to create device: " + err.Error()),
} }
} }
@ -1006,7 +1005,7 @@ func RegisterAvailable(
if v.ServerName == domain && !v.AllowRegistration { if v.ServerName == domain && !v.AllowRegistration {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden( JSON: spec.Forbidden(
fmt.Sprintf("Registration is not allowed on %q", string(v.ServerName)), fmt.Sprintf("Registration is not allowed on %q", string(v.ServerName)),
), ),
} }
@ -1023,7 +1022,7 @@ func RegisterAvailable(
if appservice.OwnsNamespaceCoveringUserId(userID) { if appservice.OwnsNamespaceCoveringUserId(userID) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UserInUse("Desired user ID is reserved by an application service."), JSON: spec.UserInUse("Desired user ID is reserved by an application service."),
} }
} }
} }
@ -1036,14 +1035,14 @@ func RegisterAvailable(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.Unknown("failed to check availability:" + err.Error()), JSON: spec.Unknown("failed to check availability:" + err.Error()),
} }
} }
if !res.Available { if !res.Available {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UserInUse("Desired User ID is already taken."), JSON: spec.UserInUse("Desired User ID is already taken."),
} }
} }
@ -1060,7 +1059,7 @@ func handleSharedSecretRegistration(cfg *config.ClientAPI, userAPI userapi.Clien
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.BadJSON(fmt.Sprintf("malformed json: %s", err)), JSON: spec.BadJSON(fmt.Sprintf("malformed json: %s", err)),
} }
} }
valid, err := sr.IsValidMacLogin(ssrr.Nonce, ssrr.User, ssrr.Password, ssrr.Admin, ssrr.MacBytes) valid, err := sr.IsValidMacLogin(ssrr.Nonce, ssrr.User, ssrr.Password, ssrr.Admin, ssrr.MacBytes)
@ -1070,7 +1069,7 @@ func handleSharedSecretRegistration(cfg *config.ClientAPI, userAPI userapi.Clien
if !valid { if !valid {
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden("bad mac"), JSON: spec.Forbidden("bad mac"),
} }
} }
// downcase capitals // downcase capitals

View file

@ -28,7 +28,6 @@ import (
"time" "time"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
@ -39,6 +38,7 @@ import (
"github.com/matrix-org/dendrite/test/testrig" "github.com/matrix-org/dendrite/test/testrig"
"github.com/matrix-org/dendrite/userapi" "github.com/matrix-org/dendrite/userapi"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/patrickmn/go-cache" "github.com/patrickmn/go-cache"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -306,7 +306,7 @@ func Test_register(t *testing.T) {
guestsDisabled: true, guestsDisabled: true,
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(`Guest registration is disabled on "test"`), JSON: spec.Forbidden(`Guest registration is disabled on "test"`),
}, },
}, },
{ {
@ -318,7 +318,7 @@ func Test_register(t *testing.T) {
loginType: "im.not.known", loginType: "im.not.known",
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusNotImplemented, Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("unknown/unimplemented auth type"), JSON: spec.Unknown("unknown/unimplemented auth type"),
}, },
}, },
{ {
@ -326,7 +326,7 @@ func Test_register(t *testing.T) {
registrationDisabled: true, registrationDisabled: true,
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(`Registration is disabled on "test"`), JSON: spec.Forbidden(`Registration is disabled on "test"`),
}, },
}, },
{ {
@ -344,7 +344,7 @@ func Test_register(t *testing.T) {
username: "success", username: "success",
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UserInUse("Desired user ID is already taken."), JSON: spec.UserInUse("Desired user ID is already taken."),
}, },
}, },
{ {
@ -361,7 +361,7 @@ func Test_register(t *testing.T) {
username: "1337", username: "1337",
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Numeric user IDs are reserved"), JSON: spec.InvalidUsername("Numeric user IDs are reserved"),
}, },
}, },
{ {
@ -369,7 +369,7 @@ func Test_register(t *testing.T) {
loginType: authtypes.LoginTypeRecaptcha, loginType: authtypes.LoginTypeRecaptcha,
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Unknown(ErrCaptchaDisabled.Error()), JSON: spec.Unknown(ErrCaptchaDisabled.Error()),
}, },
}, },
{ {
@ -378,7 +378,7 @@ func Test_register(t *testing.T) {
loginType: authtypes.LoginTypeRecaptcha, loginType: authtypes.LoginTypeRecaptcha,
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(ErrMissingResponse.Error()), JSON: spec.BadJSON(ErrMissingResponse.Error()),
}, },
}, },
{ {
@ -388,7 +388,7 @@ func Test_register(t *testing.T) {
captchaBody: `notvalid`, captchaBody: `notvalid`,
wantResponse: util.JSONResponse{ wantResponse: util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.BadJSON(ErrInvalidCaptcha.Error()), JSON: spec.BadJSON(ErrInvalidCaptcha.Error()),
}, },
}, },
{ {
@ -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: jsonerror.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 *jsonerror.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,7 @@ 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 *jsonerror.MatrixError: 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

@ -19,10 +19,10 @@ import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -39,14 +39,14 @@ func GetTags(
if device.UserID != userID { if device.UserID != userID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot retrieve another user's tags"), JSON: spec.Forbidden("Cannot retrieve another user's tags"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -71,7 +71,7 @@ func PutTag(
if device.UserID != userID { if device.UserID != userID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot modify another user's tags"), JSON: spec.Forbidden("Cannot modify another user's tags"),
} }
} }
@ -83,7 +83,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if tagContent.Tags == nil { if tagContent.Tags == nil {
@ -93,7 +93,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -118,14 +118,14 @@ func DeleteTag(
if device.UserID != userID { if device.UserID != userID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot modify another user's tags"), JSON: spec.Forbidden("Cannot modify another user's tags"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
// Check whether the tag to be deleted exists // Check whether the tag to be deleted exists
@ -141,7 +141,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -33,7 +33,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/api" "github.com/matrix-org/dendrite/clientapi/api"
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
clientutil "github.com/matrix-org/dendrite/clientapi/httputil" clientutil "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
federationAPI "github.com/matrix-org/dendrite/federationapi/api" federationAPI "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/dendrite/internal/httputil" "github.com/matrix-org/dendrite/internal/httputil"
@ -148,7 +147,7 @@ func Setup(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusMethodNotAllowed, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("unknown method"), JSON: spec.NotFound("unknown method"),
} }
}), }),
).Methods(http.MethodGet, http.MethodPost, http.MethodOptions) ).Methods(http.MethodGet, http.MethodPost, http.MethodOptions)
@ -659,7 +658,7 @@ func Setup(
httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("missing trailing slash"), JSON: spec.InvalidParam("missing trailing slash"),
} }
}), }),
).Methods(http.MethodGet, http.MethodOptions) ).Methods(http.MethodGet, http.MethodOptions)
@ -674,7 +673,7 @@ func Setup(
httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("scope, kind and rule ID must be specified"), JSON: spec.InvalidParam("scope, kind and rule ID must be specified"),
} }
}), }),
).Methods(http.MethodPut) ).Methods(http.MethodPut)
@ -693,7 +692,7 @@ func Setup(
httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("missing trailing slash after scope"), JSON: spec.InvalidParam("missing trailing slash after scope"),
} }
}), }),
).Methods(http.MethodGet, http.MethodOptions) ).Methods(http.MethodGet, http.MethodOptions)
@ -702,7 +701,7 @@ func Setup(
httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("kind and rule ID must be specified"), JSON: spec.InvalidParam("kind and rule ID must be specified"),
} }
}), }),
).Methods(http.MethodPut) ).Methods(http.MethodPut)
@ -721,7 +720,7 @@ func Setup(
httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("missing trailing slash after kind"), JSON: spec.InvalidParam("missing trailing slash after kind"),
} }
}), }),
).Methods(http.MethodGet, http.MethodOptions) ).Methods(http.MethodGet, http.MethodOptions)
@ -730,7 +729,7 @@ func Setup(
httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI("push_rules", userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("rule ID must be specified"), JSON: spec.InvalidParam("rule ID must be specified"),
} }
}), }),
).Methods(http.MethodPut) ).Methods(http.MethodPut)
@ -939,7 +938,7 @@ func Setup(
// TODO: Allow people to peek into rooms. // TODO: Allow people to peek into rooms.
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.GuestAccessForbidden("Guest access not implemented"), JSON: spec.GuestAccessForbidden("Guest access not implemented"),
} }
}), }),
).Methods(http.MethodGet, http.MethodOptions) ).Methods(http.MethodGet, http.MethodOptions)
@ -1244,7 +1243,7 @@ func Setup(
if version == "" { if version == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.InvalidArgumentValue("version must be specified"), JSON: spec.InvalidParam("version must be specified"),
} }
} }
var reqBody keyBackupSessionRequest var reqBody keyBackupSessionRequest
@ -1265,7 +1264,7 @@ func Setup(
if version == "" { if version == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.InvalidArgumentValue("version must be specified"), JSON: spec.InvalidParam("version must be specified"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -1297,7 +1296,7 @@ func Setup(
if version == "" { if version == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.InvalidArgumentValue("version must be specified"), JSON: spec.InvalidParam("version must be specified"),
} }
} }
var reqBody userapi.KeyBackupSession var reqBody userapi.KeyBackupSession

View file

@ -30,7 +30,6 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/internal/transactions" "github.com/matrix-org/dendrite/internal/transactions"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
@ -81,7 +80,7 @@ func SendEvent(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion(err.Error()), JSON: spec.UnsupportedRoomVersion(err.Error()),
} }
} }
@ -126,7 +125,7 @@ func SendEvent(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(err.Error()), JSON: spec.InvalidParam(err.Error()),
} }
} }
@ -145,12 +144,12 @@ func SendEvent(
if !aliasReq.Valid() { if !aliasReq.Valid() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam("Request contains invalid aliases."), JSON: spec.InvalidParam("Request contains invalid aliases."),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var found int var found int
requestAliases := append(aliasReq.AltAliases, aliasReq.Alias) requestAliases := append(aliasReq.AltAliases, aliasReq.Alias)
@ -165,7 +164,7 @@ func SendEvent(
if aliasReq.Alias != "" && found < len(requestAliases) { if aliasReq.Alias != "" && found < len(requestAliases) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadAlias("No matching alias found."), JSON: spec.BadAlias("No matching alias found."),
} }
} }
} }
@ -194,7 +193,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
timeToSubmitEvent := time.Since(startedSubmittingEvent) timeToSubmitEvent := time.Since(startedSubmittingEvent)
util.GetLogger(req.Context()).WithFields(logrus.Fields{ util.GetLogger(req.Context()).WithFields(logrus.Fields{
@ -273,13 +272,13 @@ 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 := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return nil, &resErr return nil, &resErr
} }
identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain()) identity, err := cfg.Matrix.SigningIdentityFor(device.UserDomain())
if err != nil { if err != nil {
resErr := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return nil, &resErr return nil, &resErr
} }
@ -288,27 +287,27 @@ func generateSendEvent(
if err == eventutil.ErrRoomNoExists { if err == eventutil.ErrRoomNoExists {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { } else if e, ok := err.(gomatrixserverlib.BadJSONError); ok {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} else if e, ok := err.(gomatrixserverlib.EventValidationError); ok { } else if e, ok := err.(gomatrixserverlib.EventValidationError); ok {
if e.Code == gomatrixserverlib.EventValidationTooLarge { if e.Code == gomatrixserverlib.EventValidationTooLarge {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusRequestEntityTooLarge, Code: http.StatusRequestEntityTooLarge,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} }
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} else if err != nil { } else if err != nil {
util.GetLogger(ctx).WithError(err).Error("eventutil.BuildEvent failed") util.GetLogger(ctx).WithError(err).Error("eventutil.BuildEvent failed")
resErr := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return nil, &resErr return nil, &resErr
} }
@ -321,7 +320,7 @@ func generateSendEvent(
if err = gomatrixserverlib.Allowed(e.PDU, &provider); err != nil { if err = gomatrixserverlib.Allowed(e.PDU, &provider); err != nil {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(err.Error()), // TODO: Is this error string comprehensible to the client? JSON: spec.Forbidden(err.Error()), // TODO: Is this error string comprehensible to the client?
} }
} }
@ -332,13 +331,13 @@ func generateSendEvent(
util.GetLogger(ctx).WithError(err).Error("Cannot unmarshal the event content.") util.GetLogger(ctx).WithError(err).Error("Cannot unmarshal the event content.")
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Cannot unmarshal the event content."), JSON: spec.BadJSON("Cannot unmarshal the event content."),
} }
} }
if content["replacement_room"] == e.RoomID() { if content["replacement_room"] == e.RoomID() {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam("Cannot send tombstone event that points to the same room."), JSON: spec.InvalidParam("Cannot send tombstone event that points to the same room."),
} }
} }
} }

View file

@ -19,10 +19,10 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
"github.com/matrix-org/dendrite/internal/transactions" "github.com/matrix-org/dendrite/internal/transactions"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// SendToDevice handles PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId} // SendToDevice handles PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}
@ -53,7 +53,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
} }

View file

@ -18,10 +18,10 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
type typingContentJSON struct { type typingContentJSON struct {
@ -39,7 +39,7 @@ func SendTyping(
if device.UserID != userID { if device.UserID != userID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot set another user's typing state"), JSON: spec.Forbidden("Cannot set another user's typing state"),
} }
} }
@ -58,7 +58,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -32,12 +32,12 @@ import (
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/internal/transactions" "github.com/matrix-org/dendrite/internal/transactions"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// Unspecced server notice request // Unspecced server notice request
@ -68,7 +68,7 @@ func SendServerNotice(
if device.AccountType != userapi.AccountTypeAdmin { if device.AccountType != userapi.AccountTypeAdmin {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("This API can only be used by admin users."), JSON: spec.Forbidden("This API can only be used by admin users."),
} }
} }
@ -90,7 +90,7 @@ func SendServerNotice(
if !r.valid() { if !r.valid() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid request"), JSON: spec.BadJSON("Invalid request"),
} }
} }
@ -175,7 +175,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
default: default:
@ -189,7 +189,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !membershipRes.IsInRoom { if !membershipRes.IsInRoom {
// re-invite the user // re-invite the user
@ -237,7 +237,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
util.GetLogger(ctx).WithFields(logrus.Fields{ util.GetLogger(ctx).WithFields(logrus.Fields{
"event_id": e.EventID(), "event_id": e.EventID(),

View file

@ -20,7 +20,6 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/syncapi/synctypes" "github.com/matrix-org/dendrite/syncapi/synctypes"
@ -57,12 +56,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !stateRes.RoomExists { if !stateRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("room does not exist"), JSON: spec.Forbidden("room does not exist"),
} }
} }
@ -74,7 +73,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if visibility, ok := content["history_visibility"]; ok { if visibility, ok := content["history_visibility"]; ok {
worldReadable = visibility == "world_readable" worldReadable = visibility == "world_readable"
@ -100,14 +99,14 @@ 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 jsonerror.InternalServerError() return 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.
if !membershipRes.HasBeenInRoom { if !membershipRes.HasBeenInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(fmt.Sprintf("Unknown room %q or user %q has never joined this room", roomID, device.UserID)), JSON: spec.Forbidden(fmt.Sprintf("Unknown room %q or user %q has never joined this room", roomID, device.UserID)),
} }
} }
// Otherwise, if the user has been in the room, whether or not we // Otherwise, if the user has been in the room, whether or not we
@ -148,7 +147,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
for _, ev := range stateAfterRes.StateEvents { for _, ev := range stateAfterRes.StateEvents {
stateEvents = append( stateEvents = append(
@ -203,7 +202,7 @@ 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 jsonerror.InternalServerError() return 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
@ -214,7 +213,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if visibility, ok := content["history_visibility"]; ok { if visibility, ok := content["history_visibility"]; ok {
worldReadable = visibility == "world_readable" worldReadable = visibility == "world_readable"
@ -240,14 +239,14 @@ 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 jsonerror.InternalServerError() return 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.
if !membershipRes.HasBeenInRoom || membershipRes.Membership == spec.Ban { if !membershipRes.HasBeenInRoom || membershipRes.Membership == spec.Ban {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(fmt.Sprintf("Unknown room %q or user %q has never joined this room", roomID, device.UserID)), JSON: spec.Forbidden(fmt.Sprintf("Unknown room %q or user %q has never joined this room", roomID, device.UserID)),
} }
} }
// Otherwise, if the user has been in the room, whether or not we // Otherwise, if the user has been in the room, whether or not we
@ -295,7 +294,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if len(stateAfterRes.StateEvents) > 0 { if len(stateAfterRes.StateEvents) > 0 {
event = stateAfterRes.StateEvents[0] event = stateAfterRes.StateEvents[0]
@ -307,7 +306,7 @@ func OnIncomingStateTypeRequest(
if event == nil { if event == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("Cannot find state event for %q", evType)), JSON: spec.NotFound(fmt.Sprintf("Cannot find state event for %q", evType)),
} }
} }

View file

@ -21,8 +21,8 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// Protocols implements // Protocols implements
@ -33,13 +33,13 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !resp.Exists { if !resp.Exists {
if protocol != "" { if protocol != "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("The protocol is unknown."), JSON: spec.NotFound("The protocol is unknown."),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -71,12 +71,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !resp.Exists { if !resp.Exists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("The Matrix User ID was not found"), JSON: spec.NotFound("The Matrix User ID was not found"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{
@ -97,12 +97,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !resp.Exists { if !resp.Exists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("No portal rooms were found."), JSON: spec.NotFound("No portal rooms were found."),
} }
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -19,12 +19,12 @@ import (
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/threepid" "github.com/matrix-org/dendrite/clientapi/threepid"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
userdb "github.com/matrix-org/dendrite/userapi/storage" userdb "github.com/matrix-org/dendrite/userapi/storage"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util" "github.com/matrix-org/util"
@ -60,13 +60,13 @@ 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 jsonerror.InternalServerError() return 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: jsonerror.MatrixError{ JSON: spec.MatrixError{
ErrCode: "M_THREEPID_IN_USE", ErrCode: "M_THREEPID_IN_USE",
Err: userdb.Err3PIDInUse.Error(), Err: userdb.Err3PIDInUse.Error(),
}, },
@ -77,11 +77,11 @@ func RequestEmailToken(req *http.Request, threePIDAPI api.ClientUserAPI, cfg *co
if err == threepid.ErrNotTrusted { if err == threepid.ErrNotTrusted {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.IDServer), JSON: spec.NotTrusted(body.IDServer),
} }
} else if err != nil { } else if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepid.CreateSession failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.CreateSession failed")
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -105,17 +105,17 @@ func CheckAndSave3PIDAssociation(
if err == threepid.ErrNotTrusted { if err == threepid.ErrNotTrusted {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotTrusted(body.Creds.IDServer), JSON: spec.NotTrusted(body.Creds.IDServer),
} }
} else if err != nil { } else if err != nil {
util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAssociation failed") util.GetLogger(req.Context()).WithError(err).Error("threepid.CheckAssociation failed")
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !verified { if !verified {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MatrixError{ JSON: spec.MatrixError{
ErrCode: "M_THREEPID_AUTH_FAILED", ErrCode: "M_THREEPID_AUTH_FAILED",
Err: "Failed to auth 3pid", Err: "Failed to auth 3pid",
}, },
@ -127,7 +127,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
@ -135,7 +135,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if err = threePIDAPI.PerformSaveThreePIDAssociation(req.Context(), &api.PerformSaveThreePIDAssociationRequest{ if err = threePIDAPI.PerformSaveThreePIDAssociation(req.Context(), &api.PerformSaveThreePIDAssociationRequest{
@ -145,7 +145,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -161,7 +161,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res := &api.QueryThreePIDsForLocalpartResponse{} res := &api.QueryThreePIDsForLocalpartResponse{}
@ -171,7 +171,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -192,7 +192,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -20,13 +20,13 @@ import (
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/version" "github.com/matrix-org/dendrite/roomserver/version"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"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"
) )
@ -55,7 +55,7 @@ func UpgradeRoom(
if _, err := version.SupportedRoomVersion(gomatrixserverlib.RoomVersion(r.NewVersion)); err != nil { if _, err := version.SupportedRoomVersion(gomatrixserverlib.RoomVersion(r.NewVersion)); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion("This server does not support that room version"), JSON: spec.UnsupportedRoomVersion("This server does not support that room version"),
} }
} }
@ -65,16 +65,16 @@ func UpgradeRoom(
case roomserverAPI.ErrNotAllowed: case roomserverAPI.ErrNotAllowed:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.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: jsonerror.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} }
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -25,9 +25,9 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// RequestTurnServer implements: // RequestTurnServer implements:
@ -60,7 +60,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
resp.Password = base64.StdEncoding.EncodeToString(mac.Sum(nil)) resp.Password = base64.StdEncoding.EncodeToString(mac.Sum(nil))

View file

@ -37,12 +37,11 @@ type fedRoomserverAPI struct {
} }
// PerformJoin will call this function // PerformJoin will call this function
func (f *fedRoomserverAPI) InputRoomEvents(ctx context.Context, req *rsapi.InputRoomEventsRequest, res *rsapi.InputRoomEventsResponse) error { func (f *fedRoomserverAPI) InputRoomEvents(ctx context.Context, req *rsapi.InputRoomEventsRequest, res *rsapi.InputRoomEventsResponse) {
if f.inputRoomEvents == nil { if f.inputRoomEvents == nil {
return nil return
} }
f.inputRoomEvents(ctx, req, res) f.inputRoomEvents(ctx, req, res)
return nil
} }
// keychange consumer calls this // keychange consumer calls this

View file

@ -21,7 +21,6 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
@ -50,7 +49,7 @@ func Backfill(
if _, _, err = gomatrixserverlib.SplitID('!', roomID); err != nil { if _, _, err = gomatrixserverlib.SplitID('!', roomID); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Bad room ID: " + err.Error()), JSON: spec.MissingParam("Bad room ID: " + err.Error()),
} }
} }
@ -65,14 +64,14 @@ func Backfill(
if !exists { if !exists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("v is missing"), JSON: spec.MissingParam("v is missing"),
} }
} }
limit = httpReq.URL.Query().Get("limit") limit = httpReq.URL.Query().Get("limit")
if len(limit) == 0 { if len(limit) == 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("limit is missing"), JSON: spec.MissingParam("limit is missing"),
} }
} }
@ -92,14 +91,14 @@ func Backfill(
util.GetLogger(httpReq.Context()).WithError(err).Error("strconv.Atoi failed") util.GetLogger(httpReq.Context()).WithError(err).Error("strconv.Atoi failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(fmt.Sprintf("limit %q is invalid format", limit)), JSON: spec.InvalidParam(fmt.Sprintf("limit %q is invalid format", limit)),
} }
} }
// 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 jsonerror.InternalServerError() return 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

@ -16,7 +16,6 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
@ -39,7 +38,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
sigReq := &api.QuerySignaturesRequest{ sigReq := &api.QuerySignaturesRequest{
@ -51,9 +50,7 @@ func GetUserDevices(
for _, dev := range res.Devices { for _, dev := range res.Devices {
sigReq.TargetIDs[userID] = append(sigReq.TargetIDs[userID], gomatrixserverlib.KeyID(dev.DeviceID)) sigReq.TargetIDs[userID] = append(sigReq.TargetIDs[userID], gomatrixserverlib.KeyID(dev.DeviceID))
} }
if err := keyAPI.QuerySignatures(req.Context(), sigReq, sigRes); err != nil { keyAPI.QuerySignatures(req.Context(), sigReq, sigRes)
return jsonerror.InternalAPIError(req.Context(), err)
}
response := fclient.RespUserDevices{ response := fclient.RespUserDevices{
UserID: userID, UserID: userID,

View file

@ -16,10 +16,10 @@ import (
"context" "context"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -43,7 +43,7 @@ func GetEventAuth(
} }
if event.RoomID() != roomID { if event.RoomID() != roomID {
return util.JSONResponse{Code: http.StatusNotFound, JSON: jsonerror.NotFound("event does not belong to this room")} return util.JSONResponse{Code: http.StatusNotFound, JSON: spec.NotFound("event does not belong to this room")}
} }
resErr = allowedToSeeEvent(ctx, request.Origin(), rsAPI, eventID) resErr = allowedToSeeEvent(ctx, request.Origin(), rsAPI, eventID)
if resErr != nil { if resErr != nil {

View file

@ -20,13 +20,11 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api"
) )
// GetEvent returns the requested event // GetEvent returns the requested event
@ -95,7 +93,7 @@ func fetchEvent(ctx context.Context, rsAPI api.FederationRoomserverAPI, roomID,
if len(eventsResponse.Events) == 0 { if len(eventsResponse.Events) == 0 {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Event not found"), JSON: spec.NotFound("Event not found"),
} }
} }

View file

@ -21,12 +21,12 @@ import (
"net/http" "net/http"
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -46,14 +46,14 @@ func InviteV2(
case gomatrixserverlib.UnsupportedRoomVersionError: case gomatrixserverlib.UnsupportedRoomVersionError:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion( JSON: spec.UnsupportedRoomVersion(
fmt.Sprintf("Room version %q is not supported by this server.", e.Version), fmt.Sprintf("Room version %q is not supported by this server.", e.Version),
), ),
} }
case gomatrixserverlib.BadJSONError: case gomatrixserverlib.BadJSONError:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
case nil: case nil:
return processInvite( return processInvite(
@ -62,7 +62,7 @@ func InviteV2(
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into an invite request. " + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into an invite request. " + err.Error()),
} }
} }
} }
@ -85,13 +85,13 @@ func InviteV1(
case gomatrixserverlib.BadJSONError: case gomatrixserverlib.BadJSONError:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
case nil: case nil:
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into an invite v1 request. " + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into an invite v1 request. " + err.Error()),
} }
} }
var strippedState []fclient.InviteV2StrippedState var strippedState []fclient.InviteV2StrippedState
@ -122,7 +122,7 @@ func processInvite(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion( JSON: spec.UnsupportedRoomVersion(
fmt.Sprintf("Room version %q is not supported by this server.", roomVer), fmt.Sprintf("Room version %q is not supported by this server.", roomVer),
), ),
} }
@ -132,7 +132,7 @@ func processInvite(
if event.RoomID() != roomID { if event.RoomID() != roomID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"), JSON: spec.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"),
} }
} }
@ -140,14 +140,14 @@ func processInvite(
if event.EventID() != eventID { if event.EventID() != eventID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event ID in the request path must match the event ID in the invite event JSON"), JSON: spec.BadJSON("The event ID in the request path must match the event ID in the invite event JSON"),
} }
} }
if event.StateKey() == nil { if event.StateKey() == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The invite event has no state key"), JSON: spec.BadJSON("The invite event has no state key"),
} }
} }
@ -155,7 +155,7 @@ func processInvite(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(fmt.Sprintf("The user ID is invalid or domain %q does not belong to this server", domain)), JSON: spec.InvalidParam(fmt.Sprintf("The user ID is invalid or domain %q does not belong to this server", domain)),
} }
} }
@ -164,14 +164,14 @@ func processInvite(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event JSON could not be redacted"), JSON: spec.BadJSON("The event JSON could not be redacted"),
} }
} }
_, serverName, err := gomatrixserverlib.SplitID('@', event.Sender()) _, serverName, err := gomatrixserverlib.SplitID('@', event.Sender())
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event JSON contains an invalid sender"), JSON: spec.BadJSON("The event JSON contains an invalid sender"),
} }
} }
verifyRequests := []gomatrixserverlib.VerifyJSONRequest{{ verifyRequests := []gomatrixserverlib.VerifyJSONRequest{{
@ -183,12 +183,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if verifyResults[0].Error != nil { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The invite must be signed by the server it originated on"), JSON: spec.Forbidden("The invite must be signed by the server it originated on"),
} }
} }
@ -211,7 +211,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: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
@ -219,12 +219,12 @@ func processInvite(
case api.ErrInvalidID: case api.ErrInvalidID:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown(e.Error()), JSON: spec.Unknown(e.Error()),
} }
case api.ErrNotAllowed: case api.ErrNotAllowed:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(e.Error()), JSON: spec.Forbidden(e.Error()),
} }
case nil: case nil:
default: default:
@ -232,7 +232,7 @@ func processInvite(
sentry.CaptureException(err) sentry.CaptureException(err)
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }

View file

@ -27,7 +27,6 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
@ -47,7 +46,7 @@ func MakeJoin(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
@ -66,7 +65,7 @@ func MakeJoin(
if !remoteSupportsVersion { if !remoteSupportsVersion {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.IncompatibleRoomVersion(roomVersion), JSON: spec.IncompatibleRoomVersion(string(roomVersion)),
} }
} }
@ -74,13 +73,13 @@ func MakeJoin(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid UserID"), JSON: spec.BadJSON("Invalid UserID"),
} }
} }
if domain != request.Origin() { if domain != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The join must be sent by the server of the user"), JSON: spec.Forbidden("The join must be sent by the server of the user"),
} }
} }
@ -92,18 +91,18 @@ func MakeJoin(
inRoomRes := &api.QueryServerJoinedToRoomResponse{} inRoomRes := &api.QueryServerJoinedToRoomResponse{}
if err = rsAPI.QueryServerJoinedToRoom(httpReq.Context(), inRoomReq, inRoomRes); err != nil { if err = rsAPI.QueryServerJoinedToRoom(httpReq.Context(), inRoomReq, inRoomRes); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryServerJoinedToRoom failed") util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryServerJoinedToRoom failed")
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !inRoomRes.RoomExists { if !inRoomRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("Room ID %q was not found on this server", roomID)), JSON: spec.NotFound(fmt.Sprintf("Room ID %q was not found on this server", roomID)),
} }
} }
if !inRoomRes.IsInRoom { if !inRoomRes.IsInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("Room ID %q has no remaining users on this server", roomID)), JSON: spec.NotFound(fmt.Sprintf("Room ID %q has no remaining users on this server", roomID)),
} }
} }
@ -112,7 +111,7 @@ func MakeJoin(
res, authorisedVia, err := checkRestrictedJoin(httpReq, rsAPI, roomVersion, roomID, userID) res, authorisedVia, err := checkRestrictedJoin(httpReq, rsAPI, roomVersion, roomID, userID)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("checkRestrictedJoin failed") util.GetLogger(httpReq.Context()).WithError(err).Error("checkRestrictedJoin failed")
return jsonerror.InternalServerError() return spec.InternalServerError()
} else if res != nil { } else if res != nil {
return *res return *res
} }
@ -130,14 +129,14 @@ func MakeJoin(
} }
if err = proto.SetContent(content); err != nil { if err = proto.SetContent(content); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("builder.SetContent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("builder.SetContent failed")
return jsonerror.InternalServerError() 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{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound( JSON: spec.NotFound(
fmt.Sprintf("Server name %q does not exist", request.Destination()), fmt.Sprintf("Server name %q does not exist", request.Destination()),
), ),
} }
@ -150,16 +149,16 @@ func MakeJoin(
if err == eventutil.ErrRoomNoExists { if err == eventutil.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { } else if e, ok := err.(gomatrixserverlib.BadJSONError); ok {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} else if err != nil { } else if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
// Check that the join is allowed or not // Check that the join is allowed or not
@ -172,7 +171,7 @@ func MakeJoin(
if err = gomatrixserverlib.Allowed(event.PDU, &provider); err != nil { if err = gomatrixserverlib.Allowed(event.PDU, &provider); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(err.Error()), JSON: spec.Forbidden(err.Error()),
} }
} }
@ -202,14 +201,14 @@ 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: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion) verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.UnsupportedRoomVersion( JSON: spec.UnsupportedRoomVersion(
fmt.Sprintf("QueryRoomVersionForRoom returned unknown room version: %s", roomVersion), fmt.Sprintf("QueryRoomVersionForRoom returned unknown room version: %s", roomVersion),
), ),
} }
@ -219,7 +218,7 @@ func SendJoin(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON: " + err.Error()), JSON: spec.BadJSON("The request body could not be decoded into valid JSON: " + err.Error()),
} }
} }
@ -227,13 +226,13 @@ func SendJoin(
if event.StateKey() == nil || event.StateKeyEquals("") { if event.StateKey() == nil || event.StateKeyEquals("") {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("No state key was provided in the join event."), JSON: spec.BadJSON("No state key was provided in the join event."),
} }
} }
if !event.StateKeyEquals(event.Sender()) { if !event.StateKeyEquals(event.Sender()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Event state key must match the event sender."), JSON: spec.BadJSON("Event state key must match the event sender."),
} }
} }
@ -244,12 +243,12 @@ func SendJoin(
if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil { if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The sender of the join is invalid"), JSON: spec.Forbidden("The sender of the join is invalid"),
} }
} else if serverName != request.Origin() { } else if serverName != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The sender does not match the server that originated the request"), JSON: spec.Forbidden("The sender does not match the server that originated the request"),
} }
} }
@ -257,7 +256,7 @@ func SendJoin(
if event.RoomID() != roomID { if event.RoomID() != roomID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON( JSON: spec.BadJSON(
fmt.Sprintf( fmt.Sprintf(
"The room ID in the request path (%q) must match the room ID in the join event JSON (%q)", "The room ID in the request path (%q) must match the room ID in the join event JSON (%q)",
roomID, event.RoomID(), roomID, event.RoomID(),
@ -270,7 +269,7 @@ func SendJoin(
if event.EventID() != eventID { if event.EventID() != eventID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON( JSON: spec.BadJSON(
fmt.Sprintf( fmt.Sprintf(
"The event ID in the request path (%q) must match the event ID in the join event JSON (%q)", "The event ID in the request path (%q) must match the event ID in the join event JSON (%q)",
eventID, event.EventID(), eventID, event.EventID(),
@ -284,13 +283,13 @@ func SendJoin(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing content.membership key"), JSON: spec.BadJSON("missing content.membership key"),
} }
} }
if membership != spec.Join { if membership != spec.Join {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("membership must be 'join'"), JSON: spec.BadJSON("membership must be 'join'"),
} }
} }
@ -300,7 +299,7 @@ func SendJoin(
logrus.WithError(err).Errorf("XXX: join.go") logrus.WithError(err).Errorf("XXX: join.go")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event JSON could not be redacted"), JSON: spec.BadJSON("The event JSON could not be redacted"),
} }
} }
verifyRequests := []gomatrixserverlib.VerifyJSONRequest{{ verifyRequests := []gomatrixserverlib.VerifyJSONRequest{{
@ -312,12 +311,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if verifyResults[0].Error != nil { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Signature check failed: " + verifyResults[0].Error.Error()), JSON: spec.Forbidden("Signature check failed: " + verifyResults[0].Error.Error()),
} }
} }
@ -332,19 +331,19 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !stateAndAuthChainResponse.RoomExists { if !stateAndAuthChainResponse.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} }
if !stateAndAuthChainResponse.StateKnown { if !stateAndAuthChainResponse.StateKnown {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("State not known"), JSON: spec.Forbidden("State not known"),
} }
} }
@ -367,7 +366,7 @@ func SendJoin(
if isBanned { if isBanned {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("user is banned"), JSON: spec.Forbidden("user is banned"),
} }
} }
@ -377,7 +376,7 @@ func SendJoin(
if err := json.Unmarshal(event.Content(), &memberContent); err != nil { if err := json.Unmarshal(event.Content(), &memberContent); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
} }
if memberContent.AuthorisedVia != "" { if memberContent.AuthorisedVia != "" {
@ -385,13 +384,13 @@ func SendJoin(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(fmt.Sprintf("The authorising username %q is invalid.", memberContent.AuthorisedVia)), JSON: spec.BadJSON(fmt.Sprintf("The authorising username %q is invalid.", memberContent.AuthorisedVia)),
} }
} }
if domain != cfg.Matrix.ServerName { if domain != cfg.Matrix.ServerName {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(fmt.Sprintf("The authorising username %q does not belong to this server.", memberContent.AuthorisedVia)), JSON: spec.BadJSON(fmt.Sprintf("The authorising username %q does not belong to this server.", memberContent.AuthorisedVia)),
} }
} }
} }
@ -410,7 +409,7 @@ func SendJoin(
// the room, so set SendAsServer to cfg.Matrix.ServerName // the room, so set SendAsServer to cfg.Matrix.ServerName
if !alreadyJoined { if !alreadyJoined {
var response api.InputRoomEventsResponse var response api.InputRoomEventsResponse
if err := rsAPI.InputRoomEvents(httpReq.Context(), &api.InputRoomEventsRequest{ rsAPI.InputRoomEvents(httpReq.Context(), &api.InputRoomEventsRequest{
InputRoomEvents: []api.InputRoomEvent{ InputRoomEvents: []api.InputRoomEvent{
{ {
Kind: api.KindNew, Kind: api.KindNew,
@ -419,18 +418,16 @@ func SendJoin(
TransactionID: nil, TransactionID: nil,
}, },
}, },
}, &response); err != nil { }, &response)
return jsonerror.InternalAPIError(httpReq.Context(), err)
}
if response.ErrMsg != "" { if response.ErrMsg != "" {
util.GetLogger(httpReq.Context()).WithField(logrus.ErrorKey, response.ErrMsg).Error("SendEvents failed") util.GetLogger(httpReq.Context()).WithField(logrus.ErrorKey, response.ErrMsg).Error("SendEvents failed")
if response.NotAllowed { if response.NotAllowed {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Forbidden(response.ErrMsg), JSON: spec.Forbidden(response.ErrMsg),
} }
} }
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
@ -498,7 +495,7 @@ func checkRestrictedJoin(
// instead. // instead.
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnableToAuthoriseJoin("This server cannot authorise the join."), JSON: spec.UnableToAuthoriseJoin("This server cannot authorise the join."),
}, "", nil }, "", nil
case !res.Allowed: case !res.Allowed:
@ -507,7 +504,7 @@ func checkRestrictedJoin(
// and therefore can't join this room. // and therefore can't join this room.
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You are not joined to any matching rooms."), JSON: spec.Forbidden("You are not joined to any matching rooms."),
}, "", nil }, "", nil
default: default:

View file

@ -20,7 +20,6 @@ import (
"time" "time"
clienthttputil "github.com/matrix-org/dendrite/clientapi/httputil" clienthttputil "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
federationAPI "github.com/matrix-org/dendrite/federationapi/api" federationAPI "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
@ -46,7 +45,7 @@ func QueryDeviceKeys(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
// make sure we only query users on our domain // make sure we only query users on our domain
@ -63,14 +62,12 @@ func QueryDeviceKeys(
} }
var queryRes api.QueryKeysResponse var queryRes api.QueryKeysResponse
if err := keyAPI.QueryKeys(httpReq.Context(), &api.QueryKeysRequest{ keyAPI.QueryKeys(httpReq.Context(), &api.QueryKeysRequest{
UserToDevices: qkr.DeviceKeys, UserToDevices: qkr.DeviceKeys,
}, &queryRes); err != nil { }, &queryRes)
return jsonerror.InternalAPIError(httpReq.Context(), err)
}
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,
@ -100,7 +97,7 @@ func ClaimOneTimeKeys(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
// make sure we only claim users on our domain // make sure we only claim users on our domain
@ -117,14 +114,12 @@ func ClaimOneTimeKeys(
} }
var claimRes api.PerformClaimKeysResponse var claimRes api.PerformClaimKeysResponse
if err := keyAPI.PerformClaimKeys(httpReq.Context(), &api.PerformClaimKeysRequest{ keyAPI.PerformClaimKeys(httpReq.Context(), &api.PerformClaimKeysRequest{
OneTimeKeys: cor.OneTimeKeys, OneTimeKeys: cor.OneTimeKeys,
}, &claimRes); err != nil { }, &claimRes)
return jsonerror.InternalAPIError(httpReq.Context(), err)
}
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: 200, Code: 200,
@ -205,7 +200,7 @@ func NotaryKeys(
if !cfg.Matrix.IsLocalServerName(serverName) { if !cfg.Matrix.IsLocalServerName(serverName) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Server name not known"), JSON: spec.NotFound("Server name not known"),
} }
} }
@ -248,7 +243,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
js, err := gomatrixserverlib.SignJSON( js, err := gomatrixserverlib.SignJSON(
@ -256,7 +251,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
response.ServerKeys = append(response.ServerKeys, js) response.ServerKeys = append(response.ServerKeys, js)

View file

@ -17,7 +17,6 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
@ -41,13 +40,13 @@ func MakeLeave(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid UserID"), JSON: spec.BadJSON("Invalid UserID"),
} }
} }
if domain != request.Origin() { if domain != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The leave must be sent by the server of the user"), JSON: spec.Forbidden("The leave must be sent by the server of the user"),
} }
} }
@ -61,14 +60,14 @@ 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 jsonerror.InternalServerError() 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{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound( JSON: spec.NotFound(
fmt.Sprintf("Server name %q does not exist", request.Destination()), fmt.Sprintf("Server name %q does not exist", request.Destination()),
), ),
} }
@ -79,16 +78,16 @@ func MakeLeave(
if err == eventutil.ErrRoomNoExists { if err == eventutil.ErrRoomNoExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room does not exist"), JSON: spec.NotFound("Room does not exist"),
} }
} else if e, ok := err.(gomatrixserverlib.BadJSONError); ok { } else if e, ok := err.(gomatrixserverlib.BadJSONError); ok {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(e.Error()), JSON: spec.BadJSON(e.Error()),
} }
} else if err != nil { } else if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("eventutil.BuildEvent failed")
return jsonerror.InternalServerError() return 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
@ -118,7 +117,7 @@ func MakeLeave(
if err = gomatrixserverlib.Allowed(event, &provider); err != nil { if err = gomatrixserverlib.Allowed(event, &provider); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(err.Error()), JSON: spec.Forbidden(err.Error()),
} }
} }
@ -145,7 +144,7 @@ func SendLeave(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion(err.Error()), JSON: spec.UnsupportedRoomVersion(err.Error()),
} }
} }
@ -153,7 +152,7 @@ func SendLeave(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.UnsupportedRoomVersion( JSON: spec.UnsupportedRoomVersion(
fmt.Sprintf("QueryRoomVersionForRoom returned unknown version: %s", roomVersion), fmt.Sprintf("QueryRoomVersionForRoom returned unknown version: %s", roomVersion),
), ),
} }
@ -165,13 +164,13 @@ func SendLeave(
case gomatrixserverlib.BadJSONError: case gomatrixserverlib.BadJSONError:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
case nil: case nil:
default: default:
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
@ -179,7 +178,7 @@ func SendLeave(
if event.RoomID() != roomID { if event.RoomID() != roomID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the leave event JSON"), JSON: spec.BadJSON("The room ID in the request path must match the room ID in the leave event JSON"),
} }
} }
@ -187,20 +186,20 @@ func SendLeave(
if event.EventID() != eventID { if event.EventID() != eventID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event ID in the request path must match the event ID in the leave event JSON"), JSON: spec.BadJSON("The event ID in the request path must match the event ID in the leave event JSON"),
} }
} }
if event.StateKey() == nil || event.StateKeyEquals("") { if event.StateKey() == nil || event.StateKeyEquals("") {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("No state key was provided in the leave event."), JSON: spec.BadJSON("No state key was provided in the leave event."),
} }
} }
if !event.StateKeyEquals(event.Sender()) { if !event.StateKeyEquals(event.Sender()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Event state key must match the event sender."), JSON: spec.BadJSON("Event state key must match the event sender."),
} }
} }
@ -211,12 +210,12 @@ func SendLeave(
if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil { if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The sender of the join is invalid"), JSON: spec.Forbidden("The sender of the join is invalid"),
} }
} else if serverName != request.Origin() { } else if serverName != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The sender does not match the server that originated the request"), JSON: spec.Forbidden("The sender does not match the server that originated the request"),
} }
} }
@ -234,7 +233,7 @@ 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 jsonerror.InternalServerError() return 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.
@ -268,7 +267,7 @@ func SendLeave(
logrus.WithError(err).Errorf("XXX: leave.go") logrus.WithError(err).Errorf("XXX: leave.go")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event JSON could not be redacted"), JSON: spec.BadJSON("The event JSON could not be redacted"),
} }
} }
verifyRequests := []gomatrixserverlib.VerifyJSONRequest{{ verifyRequests := []gomatrixserverlib.VerifyJSONRequest{{
@ -280,12 +279,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if verifyResults[0].Error != nil { if verifyResults[0].Error != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("The leave must be signed by the server it originated on"), JSON: spec.Forbidden("The leave must be signed by the server it originated on"),
} }
} }
@ -295,13 +294,13 @@ func SendLeave(
util.GetLogger(httpReq.Context()).WithError(err).Error("event.Membership failed") util.GetLogger(httpReq.Context()).WithError(err).Error("event.Membership failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("missing content.membership key"), JSON: spec.BadJSON("missing content.membership key"),
} }
} }
if mem != spec.Leave { if mem != spec.Leave {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The membership in the event content must be set to leave"), JSON: spec.BadJSON("The membership in the event content must be set to leave"),
} }
} }
@ -309,7 +308,7 @@ func SendLeave(
// We are responsible for notifying other servers that the user has left // We are responsible for notifying other servers that the user has left
// the room, so set SendAsServer to cfg.Matrix.ServerName // the room, so set SendAsServer to cfg.Matrix.ServerName
var response api.InputRoomEventsResponse var response api.InputRoomEventsResponse
if err := rsAPI.InputRoomEvents(httpReq.Context(), &api.InputRoomEventsRequest{ rsAPI.InputRoomEvents(httpReq.Context(), &api.InputRoomEventsRequest{
InputRoomEvents: []api.InputRoomEvent{ InputRoomEvents: []api.InputRoomEvent{
{ {
Kind: api.KindNew, Kind: api.KindNew,
@ -318,19 +317,17 @@ func SendLeave(
TransactionID: nil, TransactionID: nil,
}, },
}, },
}, &response); err != nil { }, &response)
return jsonerror.InternalAPIError(httpReq.Context(), err)
}
if response.ErrMsg != "" { if response.ErrMsg != "" {
util.GetLogger(httpReq.Context()).WithField(logrus.ErrorKey, response.ErrMsg).WithField("not_allowed", response.NotAllowed).Error("producer.SendEvents failed") util.GetLogger(httpReq.Context()).WithField(logrus.ErrorKey, response.ErrMsg).WithField("not_allowed", response.NotAllowed).Error("producer.SendEvents failed")
if response.NotAllowed { if response.NotAllowed {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Forbidden(response.ErrMsg), JSON: spec.Forbidden(response.ErrMsg),
} }
} }
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -16,10 +16,10 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -42,7 +42,7 @@ func GetMissingEvents(
if err := json.Unmarshal(request.Content(), &gme); err != nil { if err := json.Unmarshal(request.Content(), &gme); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
@ -63,7 +63,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
eventsResponse.Events = filterEvents(eventsResponse.Events, roomID) eventsResponse.Events = filterEvents(eventsResponse.Events, roomID)

View file

@ -18,8 +18,8 @@ import (
"net/http" "net/http"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -36,7 +36,7 @@ func GetOpenIDUserInfo(
if len(token) == 0 { if len(token) == 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusUnauthorized, Code: http.StatusUnauthorized,
JSON: jsonerror.MissingArgument("access_token is missing"), JSON: spec.MissingParam("access_token is missing"),
} }
} }
@ -55,7 +55,7 @@ func GetOpenIDUserInfo(
nowMS := time.Now().UnixNano() / int64(time.Millisecond) nowMS := time.Now().UnixNano() / int64(time.Millisecond)
if openIDTokenAttrResponse.Sub == "" || nowMS > openIDTokenAttrResponse.ExpiresAtMS { if openIDTokenAttrResponse.Sub == "" || nowMS > openIDTokenAttrResponse.ExpiresAtMS {
code = http.StatusUnauthorized code = http.StatusUnauthorized
res = jsonerror.UnknownToken("Access Token unknown or expired") res = spec.UnknownToken("Access Token unknown or expired")
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -17,12 +17,12 @@ package routing
import ( import (
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -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: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
@ -58,7 +58,7 @@ func Peek(
if !remoteSupportsVersion { if !remoteSupportsVersion {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.IncompatibleRoomVersion(roomVersion), JSON: spec.IncompatibleRoomVersion(string(roomVersion)),
} }
} }

View file

@ -18,10 +18,10 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -37,7 +37,7 @@ func GetProfile(
if userID == "" { if userID == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("The request body did not contain required argument 'user_id'."), JSON: spec.MissingParam("The request body did not contain required argument 'user_id'."),
} }
} }
@ -46,14 +46,14 @@ func GetProfile(
util.GetLogger(httpReq.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed") util.GetLogger(httpReq.Context()).WithError(err).Error("gomatrixserverlib.SplitID failed")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue(fmt.Sprintf("Domain %q does not match this server", domain)), JSON: spec.InvalidParam(fmt.Sprintf("Domain %q does not match this server", domain)),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var res interface{} var res interface{}
@ -71,7 +71,7 @@ func GetProfile(
} }
default: default:
code = http.StatusBadRequest code = http.StatusBadRequest
res = jsonerror.InvalidArgumentValue("The request body did not contain an allowed value of argument 'field'. Allowed values are either: 'avatar_url', 'displayname'.") res = spec.InvalidParam("The request body did not contain an allowed value of argument 'field'. Allowed values are either: 'avatar_url', 'displayname'.")
} }
} else { } else {
res = eventutil.UserProfile{ res = eventutil.UserProfile{

View file

@ -12,7 +12,6 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
) )
@ -40,7 +39,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
@ -107,7 +106,7 @@ 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 := jsonerror.InternalServerError() reqErr := spec.InternalServerError()
return &reqErr return &reqErr
} }
request.Limit = int16(limit) request.Limit = int16(limit)
@ -119,7 +118,7 @@ func fillPublicRoomsReq(httpReq *http.Request, request *PublicRoomReq) *util.JSO
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusMethodNotAllowed, Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"), JSON: spec.NotFound("Bad method"),
} }
} }

View file

@ -18,13 +18,13 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
federationAPI "github.com/matrix-org/dendrite/federationapi/api" federationAPI "github.com/matrix-org/dendrite/federationapi/api"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"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/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -40,14 +40,14 @@ func RoomAliasToID(
if roomAlias == "" { if roomAlias == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Must supply room alias parameter."), JSON: spec.BadJSON("Must supply room alias parameter."),
} }
} }
_, domain, err := gomatrixserverlib.SplitID('#', roomAlias) _, domain, err := gomatrixserverlib.SplitID('#', roomAlias)
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Room alias must be in the form '#localpart:domain'"), JSON: spec.BadJSON("Room alias must be in the form '#localpart:domain'"),
} }
} }
@ -61,7 +61,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if queryRes.RoomID != "" { if queryRes.RoomID != "" {
@ -69,7 +69,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
resp = fclient.RespDirectory{ resp = fclient.RespDirectory{
@ -80,7 +80,7 @@ func RoomAliasToID(
// If no alias was found, return an error // If no alias was found, return an error
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("Room alias %s not found", roomAlias)), JSON: spec.NotFound(fmt.Sprintf("Room alias %s not found", roomAlias)),
} }
} }
} else { } else {
@ -91,14 +91,14 @@ func RoomAliasToID(
if x.Code == http.StatusNotFound { if x.Code == http.StatusNotFound {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room alias not found"), JSON: spec.NotFound("Room alias not found"),
} }
} }
} }
// 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }

View file

@ -23,7 +23,6 @@ import (
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
fedInternal "github.com/matrix-org/dendrite/federationapi/internal" fedInternal "github.com/matrix-org/dendrite/federationapi/internal"
"github.com/matrix-org/dendrite/federationapi/producers" "github.com/matrix-org/dendrite/federationapi/producers"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
@ -150,7 +149,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return InviteV1( return InviteV1(
@ -166,7 +165,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return InviteV2( return InviteV2(
@ -206,7 +205,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return GetState( return GetState(
@ -221,7 +220,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return GetStateIDs( return GetStateIDs(
@ -236,7 +235,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return GetEventAuth( return GetEventAuth(
@ -279,7 +278,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -310,7 +309,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -341,7 +340,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -354,7 +353,7 @@ func Setup(
body = []interface{}{ body = []interface{}{
res.Code, res.JSON, res.Code, res.JSON,
} }
jerr, ok := res.JSON.(*jsonerror.MatrixError) jerr, ok := res.JSON.(*spec.MatrixError)
if ok { if ok {
body = jerr body = jerr
} }
@ -373,7 +372,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -390,7 +389,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -407,7 +406,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -420,7 +419,7 @@ func Setup(
body = []interface{}{ body = []interface{}{
res.Code, res.JSON, res.Code, res.JSON,
} }
jerr, ok := res.JSON.(*jsonerror.MatrixError) jerr, ok := res.JSON.(*spec.MatrixError)
if ok { if ok {
body = jerr body = jerr
} }
@ -439,7 +438,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
roomID := vars["roomID"] roomID := vars["roomID"]
@ -463,7 +462,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return GetMissingEvents(httpReq, request, rsAPI, vars["roomID"]) return GetMissingEvents(httpReq, request, rsAPI, vars["roomID"])
@ -476,7 +475,7 @@ func Setup(
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Forbidden by server ACLs"), JSON: spec.Forbidden("Forbidden by server ACLs"),
} }
} }
return Backfill(httpReq, request, rsAPI, vars["roomID"], cfg) return Backfill(httpReq, request, rsAPI, vars["roomID"], cfg)
@ -528,7 +527,7 @@ func ErrorIfLocalServerNotInRoom(
if !joinedRes.IsInRoom { if !joinedRes.IsInRoom {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("This server is not joined to room %s", roomID)), JSON: spec.NotFound(fmt.Sprintf("This server is not joined to room %s", roomID)),
} }
} }
return nil return nil

View file

@ -25,12 +25,12 @@ import (
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/federationapi/producers" "github.com/matrix-org/dendrite/federationapi/producers"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userAPI "github.com/matrix-org/dendrite/userapi/api" userAPI "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const ( const (
@ -104,7 +104,7 @@ func Send(
if err := json.Unmarshal(request.Content(), &txnEvents); err != nil { if err := json.Unmarshal(request.Content(), &txnEvents); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
// Transactions are limited in size; they can have at most 50 PDUs and 100 EDUs. // Transactions are limited in size; they can have at most 50 PDUs and 100 EDUs.
@ -112,7 +112,7 @@ func Send(
if len(txnEvents.PDUs) > 50 || len(txnEvents.EDUs) > 100 { if len(txnEvents.PDUs) > 50 || len(txnEvents.EDUs) > 100 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("max 50 pdus / 100 edus"), JSON: spec.BadJSON("max 50 pdus / 100 edus"),
} }
} }

View file

@ -17,10 +17,10 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -88,7 +88,7 @@ func parseEventIDParam(
if eventID == "" { if eventID == "" {
resErr = &util.JSONResponse{ resErr = &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("event_id missing"), JSON: spec.MissingParam("event_id missing"),
} }
} }
@ -114,7 +114,7 @@ func getState(
} }
if event.RoomID() != roomID { if event.RoomID() != roomID {
return nil, nil, &util.JSONResponse{Code: http.StatusNotFound, JSON: jsonerror.NotFound("event does not belong to this room")} return nil, nil, &util.JSONResponse{Code: http.StatusNotFound, JSON: spec.NotFound("event does not belong to this room")}
} }
resErr = allowedToSeeEvent(ctx, request.Origin(), rsAPI, eventID) resErr = allowedToSeeEvent(ctx, request.Origin(), rsAPI, eventID)
if resErr != nil { if resErr != nil {
@ -140,17 +140,17 @@ func getState(
case !response.RoomExists: case !response.RoomExists:
return nil, nil, &util.JSONResponse{ return nil, nil, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Room not found"), JSON: spec.NotFound("Room not found"),
} }
case !response.StateKnown: case !response.StateKnown:
return nil, nil, &util.JSONResponse{ return nil, nil, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("State not known"), JSON: spec.NotFound("State not known"),
} }
case response.IsRejected: case response.IsRejected:
return nil, nil, &util.JSONResponse{ return nil, nil, &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Event not found"), JSON: spec.NotFound("Event not found"),
} }
} }

View file

@ -22,17 +22,14 @@ import (
"time" "time"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types" "github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -74,7 +71,7 @@ func CreateInvitesFrom3PIDInvites(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion(err.Error()), JSON: spec.UnsupportedRoomVersion(err.Error()),
} }
} }
@ -83,7 +80,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if event != nil { if event != nil {
evs = append(evs, &types.HeaderedEvent{PDU: event}) evs = append(evs, &types.HeaderedEvent{PDU: event})
@ -103,7 +100,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{
@ -125,7 +122,7 @@ func ExchangeThirdPartyInvite(
if err := json.Unmarshal(request.Content(), &proto); err != nil { if err := json.Unmarshal(request.Content(), &proto); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
@ -133,7 +130,7 @@ func ExchangeThirdPartyInvite(
if proto.RoomID != roomID { if proto.RoomID != roomID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"), JSON: spec.BadJSON("The room ID in the request path must match the room ID in the invite event JSON"),
} }
} }
@ -141,7 +138,7 @@ func ExchangeThirdPartyInvite(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid sender ID: " + err.Error()), JSON: spec.BadJSON("Invalid sender ID: " + err.Error()),
} }
} }
@ -150,7 +147,7 @@ func ExchangeThirdPartyInvite(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event's state key isn't a Matrix user ID"), JSON: spec.BadJSON("The event's state key isn't a Matrix user ID"),
} }
} }
@ -158,7 +155,7 @@ func ExchangeThirdPartyInvite(
if targetDomain != request.Origin() { if targetDomain != request.Origin() {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The event's state key doesn't have the same domain as the request's origin"), JSON: spec.BadJSON("The event's state key doesn't have the same domain as the request's origin"),
} }
} }
@ -166,7 +163,7 @@ func ExchangeThirdPartyInvite(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion(err.Error()), JSON: spec.UnsupportedRoomVersion(err.Error()),
} }
} }
@ -175,11 +172,11 @@ func ExchangeThirdPartyInvite(
if err == errNotInRoom { if err == errNotInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Unknown room " + roomID), JSON: spec.NotFound("Unknown room " + roomID),
} }
} 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 jsonerror.InternalServerError() return 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
@ -187,22 +184,22 @@ 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
// Send the event to the roomserver // Send the event to the roomserver
@ -219,7 +216,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

10
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-20230504085954-69034410deb1 github.com/matrix-org/gomatrixserverlib v0.0.0-20230509222610-6fd532036ab6
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
@ -42,10 +42,10 @@ require (
github.com/uber/jaeger-lib v2.4.1+incompatible github.com/uber/jaeger-lib v2.4.1+incompatible
github.com/yggdrasil-network/yggdrasil-go v0.4.6 github.com/yggdrasil-network/yggdrasil-go v0.4.6
go.uber.org/atomic v1.10.0 go.uber.org/atomic v1.10.0
golang.org/x/crypto v0.8.0 golang.org/x/crypto v0.9.0
golang.org/x/image v0.5.0 golang.org/x/image v0.5.0
golang.org/x/mobile v0.0.0-20221020085226-b36e6246172e golang.org/x/mobile v0.0.0-20221020085226-b36e6246172e
golang.org/x/term v0.7.0 golang.org/x/term v0.8.0
gopkg.in/h2non/bimg.v1 v1.1.9 gopkg.in/h2non/bimg.v1 v1.1.9
gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v2 v2.4.0
gotest.tools/v3 v3.4.0 gotest.tools/v3 v3.4.0
@ -125,8 +125,8 @@ require (
go.etcd.io/bbolt v1.3.6 // indirect go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/exp v0.0.0-20221205204356-47842c84f3db // indirect golang.org/x/exp v0.0.0-20221205204356-47842c84f3db // indirect
golang.org/x/mod v0.8.0 // indirect golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.9.0 // indirect golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.7.0 // indirect golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect golang.org/x/text v0.9.0 // indirect
golang.org/x/time v0.3.0 // indirect golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.6.0 // indirect golang.org/x/tools v0.6.0 // indirect

30
go.sum
View file

@ -323,18 +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-20230428003202-267b4e79f138 h1:zqMuO/4ye8QnSPLhruxTC4cQcXfrvpPwdtT+4kqEgF4= github.com/matrix-org/gomatrixserverlib v0.0.0-20230509222610-6fd532036ab6 h1:cF6fNfxC73fU9zT3pgzDXI9NDihAdnilqqGcpDWgNP4=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230428003202-267b4e79f138/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU= github.com/matrix-org/gomatrixserverlib v0.0.0-20230509222610-6fd532036ab6/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230428142634-a4fa967eac17 h1:So8d7SZZdKB7+vWFXwmAQ3C+tUkkegMlcGk8n60w2og=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230428142634-a4fa967eac17/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230502101247-782aebf83205 h1:foJFr0V1uZC0oJ3ooenScGtLViq7Hx3rioe1Hf0lnhY=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230502101247-782aebf83205/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230502133856-ad26780a085c h1:5xXMu/08j8tWfiVUvD4yfs6mepz07BgC4kL2i0oGJX4=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230502133856-ad26780a085c/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230503081352-9e29bff996eb h1:qg9iR39ctvB7A4hBcddjxmHQO/t3y4mpQnpmEc3xvNI=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230503081352-9e29bff996eb/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230504085954-69034410deb1 h1:K0wM4rUNdqzWVQ54am8IeQn1q6f03sTNvhUW+ZaK1Zs=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230504085954-69034410deb1/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
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=
@ -521,8 +511,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
@ -602,8 +592,8 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@ -678,12 +668,12 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= golang.org/x/term v0.8.0 h1:n5xxQn2i3PC0yLAbjTpNT85q/Kgzcr2gIoX9OrJUols=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

View file

@ -31,9 +31,9 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// BasicAuth is used for authorization on /metrics handlers // BasicAuth is used for authorization on /metrics handlers
@ -101,7 +101,7 @@ func MakeAuthAPI(
if !opts.GuestAccessAllowed && device.AccountType == userapi.AccountTypeGuest { if !opts.GuestAccessAllowed && device.AccountType == userapi.AccountTypeGuest {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.GuestAccessForbidden("Guest access not allowed"), JSON: spec.GuestAccessForbidden("Guest access not allowed"),
} }
} }
@ -126,7 +126,7 @@ func MakeAdminAPI(
if device.AccountType != userapi.AccountTypeAdmin { if device.AccountType != userapi.AccountTypeAdmin {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("This API can only be used by admin users."), JSON: spec.Forbidden("This API can only be used by admin users."),
} }
} }
return f(req, device) return f(req, device)

View file

@ -5,9 +5,9 @@ import (
"sync" "sync"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -118,7 +118,7 @@ func (l *RateLimits) Limit(req *http.Request, device *userapi.Device) *util.JSON
// We hit the rate limit. Tell the client to back off. // We hit the rate limit. Tell the client to back off.
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusTooManyRequests, Code: http.StatusTooManyRequests,
JSON: jsonerror.LimitExceeded("You are sending too many requests too quickly!", l.cooloffDuration.Milliseconds()), JSON: spec.LimitExceeded("You are sending too many requests too quickly!", l.cooloffDuration.Milliseconds()),
} }
} }

View file

@ -21,7 +21,6 @@ import (
"sync" "sync"
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/federationapi/producers" "github.com/matrix-org/dendrite/federationapi/producers"
"github.com/matrix-org/dendrite/federationapi/types" "github.com/matrix-org/dendrite/federationapi/types"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
@ -153,7 +152,7 @@ func (t *TxnReq) ProcessTransaction(ctx context.Context) (*fclient.RespSend, *ut
// See https://github.com/matrix-org/synapse/issues/7543 // See https://github.com/matrix-org/synapse/issues/7543
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.BadJSON("PDU contains bad JSON"), JSON: spec.BadJSON("PDU contains bad JSON"),
} }
} }
util.GetLogger(ctx).WithError(err).Debugf("Transaction: Failed to parse event JSON of event %s", string(pdu)) util.GetLogger(ctx).WithError(err).Debugf("Transaction: Failed to parse event JSON of event %s", string(pdu))

View file

@ -66,9 +66,8 @@ var (
type FakeRsAPI struct { type FakeRsAPI struct {
rsAPI.RoomserverInternalAPI rsAPI.RoomserverInternalAPI
shouldFailQuery bool shouldFailQuery bool
bannedFromRoom bool bannedFromRoom bool
shouldEventsFail bool
} }
func (r *FakeRsAPI) QueryRoomVersionForRoom( func (r *FakeRsAPI) QueryRoomVersionForRoom(
@ -98,11 +97,7 @@ func (r *FakeRsAPI) InputRoomEvents(
ctx context.Context, ctx context.Context,
req *rsAPI.InputRoomEventsRequest, req *rsAPI.InputRoomEventsRequest,
res *rsAPI.InputRoomEventsResponse, res *rsAPI.InputRoomEventsResponse,
) error { ) {
if r.shouldEventsFail {
return fmt.Errorf("Failure")
}
return nil
} }
func TestEmptyTransactionRequest(t *testing.T) { func TestEmptyTransactionRequest(t *testing.T) {
@ -184,18 +179,6 @@ func TestProcessTransactionRequestPDUInvalidSignature(t *testing.T) {
} }
} }
func TestProcessTransactionRequestPDUSendFail(t *testing.T) {
keyRing := &test.NopJSONVerifier{}
txn := NewTxnReq(&FakeRsAPI{shouldEventsFail: true}, nil, "ourserver", keyRing, nil, nil, false, []json.RawMessage{testEvent}, []gomatrixserverlib.EDU{}, "", "", "")
txnRes, jsonRes := txn.ProcessTransaction(context.Background())
assert.Nil(t, jsonRes)
assert.Equal(t, 1, len(txnRes.PDUs))
for _, result := range txnRes.PDUs {
assert.NotEmpty(t, result.Error)
}
}
func createTransactionWithEDU(ctx *process.ProcessContext, edus []gomatrixserverlib.EDU) (TxnReq, nats.JetStreamContext, *config.Dendrite) { func createTransactionWithEDU(ctx *process.ProcessContext, edus []gomatrixserverlib.EDU) (TxnReq, nats.JetStreamContext, *config.Dendrite) {
cfg := &config.Dendrite{} cfg := &config.Dendrite{}
cfg.Defaults(config.DefaultOpts{ cfg.Defaults(config.DefaultOpts{
@ -659,12 +642,11 @@ func (t *testRoomserverAPI) InputRoomEvents(
ctx context.Context, ctx context.Context,
request *rsAPI.InputRoomEventsRequest, request *rsAPI.InputRoomEventsRequest,
response *rsAPI.InputRoomEventsResponse, response *rsAPI.InputRoomEventsResponse,
) error { ) {
t.inputRoomEvents = append(t.inputRoomEvents, request.InputRoomEvents...) t.inputRoomEvents = append(t.inputRoomEvents, request.InputRoomEvents...)
for _, ire := range request.InputRoomEvents { for _, ire := range request.InputRoomEvents {
fmt.Println("InputRoomEvents: ", ire.Event.EventID()) fmt.Println("InputRoomEvents: ", ire.Event.EventID())
} }
return nil
} }
// Query the latest events and state for a room from the room server. // Query the latest events and state for a room from the room server.

View file

@ -20,7 +20,6 @@ import (
"net/http" "net/http"
"regexp" "regexp"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -58,12 +57,12 @@ func PasswordResponse(err error) *util.JSONResponse {
case ErrPasswordWeak: case ErrPasswordWeak:
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.WeakPassword(ErrPasswordWeak.Error()), JSON: spec.WeakPassword(ErrPasswordWeak.Error()),
} }
case ErrPasswordTooLong: case ErrPasswordTooLong:
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(ErrPasswordTooLong.Error()), JSON: spec.BadJSON(ErrPasswordTooLong.Error()),
} }
} }
return nil return nil
@ -88,12 +87,12 @@ func UsernameResponse(err error) *util.JSONResponse {
case ErrUsernameTooLong: case ErrUsernameTooLong:
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(err.Error()), JSON: spec.BadJSON(err.Error()),
} }
case ErrUsernameInvalid, ErrUsernameUnderscore: case ErrUsernameInvalid, ErrUsernameUnderscore:
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername(err.Error()), JSON: spec.InvalidUsername(err.Error()),
} }
} }
return nil return nil

View file

@ -6,7 +6,6 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -22,13 +21,13 @@ func Test_validatePassword(t *testing.T) {
name: "password too short", name: "password too short",
password: "shortpw", password: "shortpw",
wantError: ErrPasswordWeak, wantError: ErrPasswordWeak,
wantJSON: &util.JSONResponse{Code: http.StatusBadRequest, JSON: jsonerror.WeakPassword(ErrPasswordWeak.Error())}, wantJSON: &util.JSONResponse{Code: http.StatusBadRequest, JSON: spec.WeakPassword(ErrPasswordWeak.Error())},
}, },
{ {
name: "password too long", name: "password too long",
password: strings.Repeat("a", maxPasswordLength+1), password: strings.Repeat("a", maxPasswordLength+1),
wantError: ErrPasswordTooLong, wantError: ErrPasswordTooLong,
wantJSON: &util.JSONResponse{Code: http.StatusBadRequest, JSON: jsonerror.BadJSON(ErrPasswordTooLong.Error())}, wantJSON: &util.JSONResponse{Code: http.StatusBadRequest, JSON: spec.BadJSON(ErrPasswordTooLong.Error())},
}, },
{ {
name: "password OK", name: "password OK",
@ -65,7 +64,7 @@ func Test_validateUsername(t *testing.T) {
wantErr: ErrUsernameInvalid, wantErr: ErrUsernameInvalid,
wantJSON: &util.JSONResponse{ wantJSON: &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername(ErrUsernameInvalid.Error()), JSON: spec.InvalidUsername(ErrUsernameInvalid.Error()),
}, },
}, },
{ {
@ -75,7 +74,7 @@ func Test_validateUsername(t *testing.T) {
wantErr: ErrUsernameInvalid, wantErr: ErrUsernameInvalid,
wantJSON: &util.JSONResponse{ wantJSON: &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername(ErrUsernameInvalid.Error()), JSON: spec.InvalidUsername(ErrUsernameInvalid.Error()),
}, },
}, },
{ {
@ -85,7 +84,7 @@ func Test_validateUsername(t *testing.T) {
wantErr: ErrUsernameTooLong, wantErr: ErrUsernameTooLong,
wantJSON: &util.JSONResponse{ wantJSON: &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON(ErrUsernameTooLong.Error()), JSON: spec.BadJSON(ErrUsernameTooLong.Error()),
}, },
}, },
{ {
@ -95,7 +94,7 @@ func Test_validateUsername(t *testing.T) {
wantErr: ErrUsernameUnderscore, wantErr: ErrUsernameUnderscore,
wantJSON: &util.JSONResponse{ wantJSON: &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername(ErrUsernameUnderscore.Error()), JSON: spec.InvalidUsername(ErrUsernameUnderscore.Error()),
}, },
}, },
{ {
@ -115,7 +114,7 @@ func Test_validateUsername(t *testing.T) {
wantErr: ErrUsernameInvalid, wantErr: ErrUsernameInvalid,
wantJSON: &util.JSONResponse{ wantJSON: &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername(ErrUsernameInvalid.Error()), JSON: spec.InvalidUsername(ErrUsernameInvalid.Error()),
}, },
}, },
{ {
@ -135,7 +134,7 @@ func Test_validateUsername(t *testing.T) {
wantErr: ErrUsernameInvalid, wantErr: ErrUsernameInvalid,
wantJSON: &util.JSONResponse{ wantJSON: &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername(ErrUsernameInvalid.Error()), JSON: spec.InvalidUsername(ErrUsernameInvalid.Error()),
}, },
}, },
{ {

View file

@ -30,7 +30,6 @@ import (
"sync" "sync"
"unicode" "unicode"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/mediaapi/fileutils" "github.com/matrix-org/dendrite/mediaapi/fileutils"
"github.com/matrix-org/dendrite/mediaapi/storage" "github.com/matrix-org/dendrite/mediaapi/storage"
"github.com/matrix-org/dendrite/mediaapi/thumbnailer" "github.com/matrix-org/dendrite/mediaapi/thumbnailer"
@ -130,7 +129,7 @@ func Download(
// TODO: Handle the fact we might have started writing the response // TODO: Handle the fact we might have started writing the response
dReq.jsonErrorResponse(w, util.JSONResponse{ dReq.jsonErrorResponse(w, util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("Failed to download: " + err.Error()), JSON: spec.NotFound("Failed to download: " + err.Error()),
}) })
return return
} }
@ -138,7 +137,7 @@ func Download(
if metadata == nil { if metadata == nil {
dReq.jsonErrorResponse(w, util.JSONResponse{ dReq.jsonErrorResponse(w, util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("File not found"), JSON: spec.NotFound("File not found"),
}) })
return return
} }
@ -168,7 +167,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse {
if !mediaIDRegex.MatchString(string(r.MediaMetadata.MediaID)) { if !mediaIDRegex.MatchString(string(r.MediaMetadata.MediaID)) {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("mediaId must be a non-empty string using only characters in %v", mediaIDCharacters)), JSON: spec.NotFound(fmt.Sprintf("mediaId must be a non-empty string using only characters in %v", mediaIDCharacters)),
} }
} }
// Note: the origin will be validated either by comparison to the configured server name of this homeserver // Note: the origin will be validated either by comparison to the configured server name of this homeserver
@ -176,7 +175,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse {
if r.MediaMetadata.Origin == "" { if r.MediaMetadata.Origin == "" {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("serverName must be a non-empty string"), JSON: spec.NotFound("serverName must be a non-empty string"),
} }
} }
@ -184,7 +183,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse {
if r.ThumbnailSize.Width <= 0 || r.ThumbnailSize.Height <= 0 { if r.ThumbnailSize.Width <= 0 || r.ThumbnailSize.Height <= 0 {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("width and height must be greater than 0"), JSON: spec.Unknown("width and height must be greater than 0"),
} }
} }
// Default method to scale if not set // Default method to scale if not set
@ -194,7 +193,7 @@ func (r *downloadRequest) Validate() *util.JSONResponse {
if r.ThumbnailSize.ResizeMethod != types.Crop && r.ThumbnailSize.ResizeMethod != types.Scale { if r.ThumbnailSize.ResizeMethod != types.Crop && r.ThumbnailSize.ResizeMethod != types.Scale {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("method must be one of crop or scale"), JSON: spec.Unknown("method must be one of crop or scale"),
} }
} }
} }

View file

@ -26,7 +26,6 @@ import (
"path" "path"
"strings" "strings"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/mediaapi/fileutils" "github.com/matrix-org/dendrite/mediaapi/fileutils"
"github.com/matrix-org/dendrite/mediaapi/storage" "github.com/matrix-org/dendrite/mediaapi/storage"
"github.com/matrix-org/dendrite/mediaapi/thumbnailer" "github.com/matrix-org/dendrite/mediaapi/thumbnailer"
@ -34,6 +33,7 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"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"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -165,7 +165,7 @@ func (r *uploadRequest) doUpload(
}).Warn("Error while transferring file") }).Warn("Error while transferring file")
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to upload"), JSON: spec.Unknown("Failed to upload"),
} }
} }
@ -184,7 +184,7 @@ 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 := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return &resErr return &resErr
} }
if existingMetadata != nil { if existingMetadata != nil {
@ -194,7 +194,7 @@ 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 := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return &resErr return &resErr
} }
@ -217,7 +217,7 @@ 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 := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return &resErr return &resErr
} }
} }
@ -239,7 +239,7 @@ func (r *uploadRequest) doUpload(
func requestEntityTooLargeJSONResponse(maxFileSizeBytes config.FileSizeBytes) *util.JSONResponse { func requestEntityTooLargeJSONResponse(maxFileSizeBytes config.FileSizeBytes) *util.JSONResponse {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusRequestEntityTooLarge, Code: http.StatusRequestEntityTooLarge,
JSON: jsonerror.Unknown(fmt.Sprintf("HTTP Content-Length is greater than the maximum allowed upload size (%v).", maxFileSizeBytes)), JSON: spec.Unknown(fmt.Sprintf("HTTP Content-Length is greater than the maximum allowed upload size (%v).", maxFileSizeBytes)),
} }
} }
@ -251,7 +251,7 @@ func (r *uploadRequest) Validate(maxFileSizeBytes config.FileSizeBytes) *util.JS
if strings.HasPrefix(string(r.MediaMetadata.UploadName), "~") { if strings.HasPrefix(string(r.MediaMetadata.UploadName), "~") {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("File name must not begin with '~'."), JSON: spec.Unknown("File name must not begin with '~'."),
} }
} }
// TODO: Validate filename - what are the valid characters? // TODO: Validate filename - what are the valid characters?
@ -264,7 +264,7 @@ func (r *uploadRequest) Validate(maxFileSizeBytes config.FileSizeBytes) *util.JS
if _, _, err := gomatrixserverlib.SplitID('@', string(r.MediaMetadata.UserID)); err != nil { if _, _, err := gomatrixserverlib.SplitID('@', string(r.MediaMetadata.UserID)); err != nil {
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("user id must be in the form @localpart:domain"), JSON: spec.BadJSON("user id must be in the form @localpart:domain"),
} }
} }
} }
@ -290,7 +290,7 @@ func (r *uploadRequest) storeFileAndMetadata(
r.Logger.WithError(err).Error("Failed to move file.") r.Logger.WithError(err).Error("Failed to move file.")
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to upload"), JSON: spec.Unknown("Failed to upload"),
} }
} }
if duplicate { if duplicate {
@ -307,7 +307,7 @@ func (r *uploadRequest) storeFileAndMetadata(
} }
return &util.JSONResponse{ return &util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("Failed to upload"), JSON: spec.Unknown("Failed to upload"),
} }
} }

View file

@ -18,7 +18,6 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/relayapi/api" "github.com/matrix-org/dendrite/relayapi/api"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
@ -40,13 +39,13 @@ func GetTransactionFromRelay(
if err := json.Unmarshal(fedReq.Content(), &previousEntry); err != nil { if err := json.Unmarshal(fedReq.Content(), &previousEntry); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.BadJSON("invalid json provided"), JSON: spec.BadJSON("invalid json provided"),
} }
} }
if previousEntry.EntryID < 0 { if previousEntry.EntryID < 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.BadJSON("Invalid entry id provided. Must be >= 0."), JSON: spec.BadJSON("Invalid entry id provided. Must be >= 0."),
} }
} }
logrus.Infof("Previous entry provided: %v", previousEntry.EntryID) logrus.Infof("Previous entry provided: %v", previousEntry.EntryID)

View file

@ -21,7 +21,6 @@ import (
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/httputil" "github.com/matrix-org/dendrite/internal/httputil"
relayInternal "github.com/matrix-org/dendrite/relayapi/internal" relayInternal "github.com/matrix-org/dendrite/relayapi/internal"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
@ -59,7 +58,7 @@ func Setup(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Username was invalid"), JSON: spec.InvalidUsername("Username was invalid"),
} }
} }
return SendTransactionToRelay( return SendTransactionToRelay(
@ -84,7 +83,7 @@ func Setup(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Username was invalid"), JSON: spec.InvalidUsername("Username was invalid"),
} }
} }
return GetTransactionFromRelay(httpReq, request, relayAPI, *userID) return GetTransactionFromRelay(httpReq, request, relayAPI, *userID)

View file

@ -18,7 +18,6 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/relayapi/api" "github.com/matrix-org/dendrite/relayapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
@ -43,7 +42,7 @@ func SendTransactionToRelay(
logrus.Info("The request body could not be decoded into valid JSON." + err.Error()) logrus.Info("The request body could not be decoded into valid JSON." + err.Error())
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotJSON("The request body could not be decoded into valid JSON." + err.Error()), JSON: spec.NotJSON("The request body could not be decoded into valid JSON." + err.Error()),
} }
} }
@ -52,7 +51,7 @@ func SendTransactionToRelay(
if len(txnEvents.PDUs) > 50 || len(txnEvents.EDUs) > 100 { if len(txnEvents.PDUs) > 50 || len(txnEvents.EDUs) > 100 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("max 50 pdus / 100 edus"), JSON: spec.BadJSON("max 50 pdus / 100 edus"),
} }
} }
@ -69,7 +68,7 @@ func SendTransactionToRelay(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
JSON: jsonerror.BadJSON("could not store the transaction for forwarding"), JSON: spec.BadJSON("could not store the transaction for forwarding"),
} }
} }

View file

@ -60,7 +60,7 @@ type InputRoomEventsAPI interface {
ctx context.Context, ctx context.Context,
req *InputRoomEventsRequest, req *InputRoomEventsRequest,
res *InputRoomEventsResponse, res *InputRoomEventsResponse,
) error )
} }
// Query the latest events and state for a room from the room server. // Query the latest events and state for a room from the room server.

View file

@ -104,9 +104,7 @@ func SendInputRoomEvents(
VirtualHost: virtualHost, VirtualHost: virtualHost,
} }
var response InputRoomEventsResponse var response InputRoomEventsResponse
if err := rsAPI.InputRoomEvents(ctx, &request, &response); err != nil { rsAPI.InputRoomEvents(ctx, &request, &response)
return err
}
return response.Err() return response.Err()
} }

View file

@ -389,18 +389,18 @@ func (r *Inputer) InputRoomEvents(
ctx context.Context, ctx context.Context,
request *api.InputRoomEventsRequest, request *api.InputRoomEventsRequest,
response *api.InputRoomEventsResponse, response *api.InputRoomEventsResponse,
) error { ) {
// Queue up the event into the roomserver. // Queue up the event into the roomserver.
replySub, err := r.queueInputRoomEvents(ctx, request) replySub, err := r.queueInputRoomEvents(ctx, request)
if err != nil { if err != nil {
response.ErrMsg = err.Error() response.ErrMsg = err.Error()
return nil return
} }
// If we aren't waiting for synchronous responses then we can // If we aren't waiting for synchronous responses then we can
// give up here, there is nothing further to do. // give up here, there is nothing further to do.
if replySub == nil { if replySub == nil {
return nil return
} }
// Otherwise, we'll want to sit and wait for the responses // Otherwise, we'll want to sit and wait for the responses
@ -412,14 +412,12 @@ func (r *Inputer) InputRoomEvents(
msg, err := replySub.NextMsgWithContext(ctx) msg, err := replySub.NextMsgWithContext(ctx)
if err != nil { if err != nil {
response.ErrMsg = err.Error() response.ErrMsg = err.Error()
return nil return
} }
if len(msg.Data) > 0 { if len(msg.Data) > 0 {
response.ErrMsg = string(msg.Data) response.ErrMsg = string(msg.Data)
} }
} }
return nil
} }
var roomserverInputBackpressure = prometheus.NewGaugeVec( var roomserverInputBackpressure = prometheus.NewGaugeVec(

View file

@ -893,5 +893,6 @@ func (r *Inputer) kickGuests(ctx context.Context, event gomatrixserverlib.PDU, r
Asynchronous: true, // Needs to be async, as we otherwise create a deadlock Asynchronous: true, // Needs to be async, as we otherwise create a deadlock
} }
inputRes := &api.InputRoomEventsResponse{} inputRes := &api.InputRoomEventsResponse{}
return r.InputRoomEvents(ctx, inputReq, inputRes) r.InputRoomEvents(ctx, inputReq, inputRes)
return nil
} }

View file

@ -141,8 +141,8 @@ func (r *Admin) PerformAdminEvacuateRoom(
Asynchronous: true, Asynchronous: true,
} }
inputRes := &api.InputRoomEventsResponse{} inputRes := &api.InputRoomEventsResponse{}
err = r.Inputer.InputRoomEvents(ctx, inputReq, inputRes) r.Inputer.InputRoomEvents(ctx, inputReq, inputRes)
return affected, err return affected, nil
} }
// PerformAdminEvacuateUser will remove the given user from all rooms. // PerformAdminEvacuateUser will remove the given user from all rooms.
@ -334,9 +334,7 @@ func (r *Admin) PerformAdminDownloadState(
SendAsServer: string(r.Cfg.Matrix.ServerName), SendAsServer: string(r.Cfg.Matrix.ServerName),
}) })
if err = r.Inputer.InputRoomEvents(ctx, inputReq, inputRes); err != nil { r.Inputer.InputRoomEvents(ctx, inputReq, inputRes)
return fmt.Errorf("r.Inputer.InputRoomEvents: %w", err)
}
if inputRes.ErrMsg != "" { if inputRes.ErrMsg != "" {
return inputRes.Err() return inputRes.Err()

View file

@ -226,9 +226,7 @@ func (r *Inviter) PerformInvite(
}, },
} }
inputRes := &api.InputRoomEventsResponse{} inputRes := &api.InputRoomEventsResponse{}
if err = r.Inputer.InputRoomEvents(context.Background(), inputReq, inputRes); err != nil { r.Inputer.InputRoomEvents(context.Background(), inputReq, inputRes)
return nil, fmt.Errorf("r.Inputer.InputRoomEvents: %w", err)
}
if err = inputRes.Err(); err != nil { if err = inputRes.Err(); err != nil {
logger.WithError(err).WithField("event_id", event.EventID()).Error("r.InputRoomEvents failed") logger.WithError(err).WithField("event_id", event.EventID()).Error("r.InputRoomEvents failed")
return nil, api.ErrNotAllowed{Err: err} return nil, api.ErrNotAllowed{Err: err}

View file

@ -313,9 +313,7 @@ func (r *Joiner) performJoinRoomByID(
}, },
} }
inputRes := rsAPI.InputRoomEventsResponse{} inputRes := rsAPI.InputRoomEventsResponse{}
if err = r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes); err != nil { r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes)
return "", "", rsAPI.ErrNotAllowed{Err: err}
}
if err = inputRes.Err(); err != nil { if err = inputRes.Err(); err != nil {
return "", "", rsAPI.ErrNotAllowed{Err: err} return "", "", rsAPI.ErrNotAllowed{Err: err}
} }

View file

@ -21,7 +21,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/eventutil" "github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
@ -115,7 +114,7 @@ func (r *Leaver) performLeaveRoomByID(
// mimic the returned values from Synapse // mimic the returned values from Synapse
res.Message = "You cannot reject this invite" res.Message = "You cannot reject this invite"
res.Code = 403 res.Code = 403
return nil, jsonerror.LeaveServerNoticeError() return nil, spec.LeaveServerNoticeError()
} }
} }
} }
@ -203,9 +202,7 @@ func (r *Leaver) performLeaveRoomByID(
}, },
} }
inputRes := api.InputRoomEventsResponse{} inputRes := api.InputRoomEventsResponse{}
if err = r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes); err != nil { r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes)
return nil, fmt.Errorf("r.Inputer.InputRoomEvents: %w", err)
}
if err = inputRes.Err(); err != nil { if err = inputRes.Err(); err != nil {
return nil, fmt.Errorf("r.InputRoomEvents: %w", err) return nil, fmt.Errorf("r.InputRoomEvents: %w", err)
} }

View file

@ -27,7 +27,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
fs "github.com/matrix-org/dendrite/federationapi/api" fs "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/dendrite/internal/hooks" "github.com/matrix-org/dendrite/internal/hooks"
"github.com/matrix-org/dendrite/internal/httputil" "github.com/matrix-org/dendrite/internal/httputil"
@ -169,7 +168,7 @@ func eventRelationshipHandler(db Database, rsAPI roomserver.RoomserverInternalAP
util.GetLogger(req.Context()).WithError(err).Error("failed to decode HTTP request as JSON") util.GetLogger(req.Context()).WithError(err).Error("failed to decode HTTP request as JSON")
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.BadJSON(fmt.Sprintf("invalid json: %s", err)), JSON: spec.BadJSON(fmt.Sprintf("invalid json: %s", err)),
} }
} }
rc := reqCtx{ rc := reqCtx{
@ -201,7 +200,7 @@ func federatedEventRelationship(
util.GetLogger(ctx).WithError(err).Error("failed to decode HTTP request as JSON") util.GetLogger(ctx).WithError(err).Error("failed to decode HTTP request as JSON")
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.BadJSON(fmt.Sprintf("invalid json: %s", err)), JSON: spec.BadJSON(fmt.Sprintf("invalid json: %s", err)),
} }
} }
rc := reqCtx{ rc := reqCtx{
@ -268,7 +267,7 @@ func (rc *reqCtx) process() (*MSC2836EventRelationshipsResponse, *util.JSONRespo
if event == nil || !rc.authorisedToSeeEvent(event) { if event == nil || !rc.authorisedToSeeEvent(event) {
return nil, &util.JSONResponse{ return nil, &util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden("Event does not exist or you are not authorised to see it"), JSON: spec.Forbidden("Event does not exist or you are not authorised to see it"),
} }
} }
rc.roomVersion = event.Version() rc.roomVersion = event.Version()
@ -428,7 +427,7 @@ 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 := jsonerror.InternalServerError() resErr := spec.InternalServerError()
return nil, &resErr return nil, &resErr
} }
var childEvents []*types.HeaderedEvent var childEvents []*types.HeaderedEvent

View file

@ -28,7 +28,6 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
fs "github.com/matrix-org/dendrite/federationapi/api" fs "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/httputil" "github.com/matrix-org/dendrite/internal/httputil"
@ -96,7 +95,7 @@ func federatedSpacesHandler(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.InvalidParam("bad request uri"), JSON: spec.InvalidParam("bad request uri"),
} }
} }
@ -214,13 +213,13 @@ func (w *walker) walk() util.JSONResponse {
// CS API format // CS API format
return util.JSONResponse{ return util.JSONResponse{
Code: 403, Code: 403,
JSON: jsonerror.Forbidden("room is unknown/forbidden"), JSON: spec.Forbidden("room is unknown/forbidden"),
} }
} else { } else {
// SS API format // SS API format
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("room is unknown/forbidden"), JSON: spec.NotFound("room is unknown/forbidden"),
} }
} }
} }
@ -233,7 +232,7 @@ func (w *walker) walk() util.JSONResponse {
if cache == nil { if cache == nil {
return util.JSONResponse{ return util.JSONResponse{
Code: 400, Code: 400,
JSON: jsonerror.InvalidArgumentValue("invalid from"), JSON: spec.InvalidParam("invalid from"),
} }
} }
} else { } else {
@ -377,7 +376,7 @@ func (w *walker) walk() util.JSONResponse {
if len(discoveredRooms) == 0 { if len(discoveredRooms) == 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: 404, Code: 404,
JSON: jsonerror.NotFound("room is unknown/forbidden"), JSON: spec.NotFound("room is unknown/forbidden"),
} }
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -34,20 +34,16 @@ func (k *mockKeyAPI) PerformUploadKeys(ctx context.Context, req *userapi.Perform
func (k *mockKeyAPI) SetUserAPI(i userapi.UserInternalAPI) {} func (k *mockKeyAPI) SetUserAPI(i userapi.UserInternalAPI) {}
// PerformClaimKeys claims one-time keys for use in pre-key messages // PerformClaimKeys claims one-time keys for use in pre-key messages
func (k *mockKeyAPI) PerformClaimKeys(ctx context.Context, req *userapi.PerformClaimKeysRequest, res *userapi.PerformClaimKeysResponse) error { func (k *mockKeyAPI) PerformClaimKeys(ctx context.Context, req *userapi.PerformClaimKeysRequest, res *userapi.PerformClaimKeysResponse) {
return nil
} }
func (k *mockKeyAPI) PerformDeleteKeys(ctx context.Context, req *userapi.PerformDeleteKeysRequest, res *userapi.PerformDeleteKeysResponse) error { func (k *mockKeyAPI) PerformDeleteKeys(ctx context.Context, req *userapi.PerformDeleteKeysRequest, res *userapi.PerformDeleteKeysResponse) error {
return nil return nil
} }
func (k *mockKeyAPI) PerformUploadDeviceKeys(ctx context.Context, req *userapi.PerformUploadDeviceKeysRequest, res *userapi.PerformUploadDeviceKeysResponse) error { func (k *mockKeyAPI) PerformUploadDeviceKeys(ctx context.Context, req *userapi.PerformUploadDeviceKeysRequest, res *userapi.PerformUploadDeviceKeysResponse) {
return nil
} }
func (k *mockKeyAPI) PerformUploadDeviceSignatures(ctx context.Context, req *userapi.PerformUploadDeviceSignaturesRequest, res *userapi.PerformUploadDeviceSignaturesResponse) error { func (k *mockKeyAPI) PerformUploadDeviceSignatures(ctx context.Context, req *userapi.PerformUploadDeviceSignaturesRequest, res *userapi.PerformUploadDeviceSignaturesResponse) {
return nil
} }
func (k *mockKeyAPI) QueryKeys(ctx context.Context, req *userapi.QueryKeysRequest, res *userapi.QueryKeysResponse) error { func (k *mockKeyAPI) QueryKeys(ctx context.Context, req *userapi.QueryKeysRequest, res *userapi.QueryKeysResponse) {
return nil
} }
func (k *mockKeyAPI) QueryKeyChanges(ctx context.Context, req *userapi.QueryKeyChangesRequest, res *userapi.QueryKeyChangesResponse) error { func (k *mockKeyAPI) QueryKeyChanges(ctx context.Context, req *userapi.QueryKeyChangesRequest, res *userapi.QueryKeyChangesResponse) error {
return nil return nil
@ -60,8 +56,7 @@ func (k *mockKeyAPI) QueryDeviceMessages(ctx context.Context, req *userapi.Query
return nil return nil
} }
func (k *mockKeyAPI) QuerySignatures(ctx context.Context, req *userapi.QuerySignaturesRequest, res *userapi.QuerySignaturesResponse) error { func (k *mockKeyAPI) QuerySignatures(ctx context.Context, req *userapi.QuerySignaturesRequest, res *userapi.QuerySignaturesResponse) {
return nil
} }
type mockRoomserverAPI struct { type mockRoomserverAPI struct {

View file

@ -23,7 +23,6 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
roomserver "github.com/matrix-org/dendrite/roomserver/api" roomserver "github.com/matrix-org/dendrite/roomserver/api"
@ -57,7 +56,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)
@ -75,7 +74,7 @@ func Context(
} }
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidParam(errMsg), JSON: spec.InvalidParam(errMsg),
Headers: nil, Headers: nil,
} }
} }
@ -88,12 +87,12 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !membershipRes.RoomExists { if !membershipRes.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("room does not exist"), JSON: spec.Forbidden("room does not exist"),
} }
} }
@ -114,11 +113,11 @@ func Context(
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound(fmt.Sprintf("Event %s not found", eventID)), JSON: spec.NotFound(fmt.Sprintf("Event %s not found", eventID)),
} }
} }
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 jsonerror.InternalServerError() return 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
@ -126,7 +125,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
"duration": time.Since(startTime), "duration": time.Since(startTime),
@ -135,27 +134,27 @@ func Context(
if len(filteredEvents) == 0 { if len(filteredEvents) == 0 {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("User is not allowed to query context"), JSON: spec.Forbidden("User is not allowed to query 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
@ -167,7 +166,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
eventsBeforeClient := synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(eventsBeforeFiltered), synctypes.FormatAll) eventsBeforeClient := synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(eventsBeforeFiltered), synctypes.FormatAll)
@ -181,7 +180,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }

View file

@ -23,11 +23,11 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/syncapi/storage" "github.com/matrix-org/dendrite/syncapi/storage"
"github.com/matrix-org/dendrite/syncapi/sync" "github.com/matrix-org/dendrite/syncapi/sync"
"github.com/matrix-org/dendrite/syncapi/synctypes" "github.com/matrix-org/dendrite/syncapi/synctypes"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// GetFilter implements GET /_matrix/client/r0/user/{userId}/filter/{filterId} // GetFilter implements GET /_matrix/client/r0/user/{userId}/filter/{filterId}
@ -37,13 +37,13 @@ func GetFilter(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot get filters for other users"), JSON: spec.Forbidden("Cannot get filters for other users"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
filter := synctypes.DefaultFilter() filter := synctypes.DefaultFilter()
@ -53,7 +53,7 @@ func GetFilter(
// even though it is not correct. // even though it is not correct.
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.NotFound("No such filter"), JSON: spec.NotFound("No such filter"),
} }
} }
@ -76,14 +76,14 @@ func PutFilter(
if userID != device.UserID { if userID != device.UserID {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("Cannot create filters for other users"), JSON: spec.Forbidden("Cannot create filters for other users"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var filter synctypes.Filter var filter synctypes.Filter
@ -93,14 +93,14 @@ func PutFilter(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be read. " + err.Error()), JSON: spec.BadJSON("The request body could not be read. " + err.Error()),
} }
} }
if err = json.Unmarshal(body, &filter); err != nil { if err = json.Unmarshal(body, &filter); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()), JSON: spec.BadJSON("The request body could not be decoded into valid JSON. " + err.Error()),
} }
} }
// the filter `limit` is `int` which defaults to 0 if not set which is not what we want. We want to use the default // the filter `limit` is `int` which defaults to 0 if not set which is not what we want. We want to use the default
@ -115,14 +115,14 @@ func PutFilter(
if err = filter.Validate(); err != nil { if err = filter.Validate(); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("Invalid filter: " + err.Error()), JSON: spec.BadJSON("Invalid filter: " + err.Error()),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
return util.JSONResponse{ return util.JSONResponse{

View file

@ -20,13 +20,13 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/syncapi/internal" "github.com/matrix-org/dendrite/syncapi/internal"
"github.com/matrix-org/dendrite/syncapi/storage" "github.com/matrix-org/dendrite/syncapi/storage"
"github.com/matrix-org/dendrite/syncapi/synctypes" "github.com/matrix-org/dendrite/syncapi/synctypes"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// GetEvent implements // GetEvent implements
@ -51,13 +51,13 @@ 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
// The requested event does not exist in our database // The requested event does not exist in our database
@ -65,7 +65,7 @@ func GetEvent(
logger.Debugf("GetEvent: requested event doesn't exist locally") logger.Debugf("GetEvent: requested event doesn't exist locally")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("The event was not found or you do not have permission to read this event"), JSON: spec.NotFound("The event was not found or you do not have permission to read this event"),
} }
} }
@ -81,7 +81,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: jsonerror.InternalServerError(), JSON: spec.InternalServerError(),
} }
} }
@ -91,7 +91,7 @@ func GetEvent(
logger.WithField("event_count", len(events)).Debug("GetEvent: can't return the requested event") logger.WithField("event_count", len(events)).Debug("GetEvent: can't return the requested event")
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,
JSON: jsonerror.NotFound("The event was not found or you do not have permission to read this event"), JSON: spec.NotFound("The event was not found or you do not have permission to read this event"),
} }
} }

View file

@ -19,13 +19,13 @@ import (
"math" "math"
"net/http" "net/http"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/syncapi/storage" "github.com/matrix-org/dendrite/syncapi/storage"
"github.com/matrix-org/dendrite/syncapi/synctypes" "github.com/matrix-org/dendrite/syncapi/synctypes"
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"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"
) )
@ -67,26 +67,26 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !queryRes.HasBeenInRoom { if !queryRes.HasBeenInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You aren't a member of the room and weren't previously a member of the room."), JSON: spec.Forbidden("You aren't a member of the room and weren't previously a member of the room."),
} }
} }
if joinedOnly && !queryRes.IsInRoom { if joinedOnly && !queryRes.IsInRoom {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("You aren't a member of the room and weren't previously a member of the room."), JSON: spec.Forbidden("You aren't a member of the room and weren't previously a member of the room."),
} }
} }
db, err := syncDB.NewDatabaseSnapshot(req.Context()) db, err := syncDB.NewDatabaseSnapshot(req.Context())
if err != nil { if err != nil {
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
defer db.Rollback() // nolint: errcheck defer db.Rollback() // nolint: errcheck
@ -98,7 +98,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
} }
@ -106,13 +106,13 @@ 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 jsonerror.InternalServerError() return 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
result := qryRes.Events result := qryRes.Events
@ -124,7 +124,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
res.Joined[ev.Sender()] = joinedMember(content) res.Joined[ev.Sender()] = joinedMember(content)
} }

View file

@ -27,7 +27,6 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
@ -82,7 +81,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)
@ -90,19 +89,19 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
if !membershipResp.RoomExists { if !membershipResp.RoomExists {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("room does not exist"), JSON: spec.Forbidden("room does not exist"),
} }
} }
if membershipResp.IsRoomForgotten { if membershipResp.IsRoomForgotten {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("user already forgot about this room"), JSON: spec.Forbidden("user already forgot about this room"),
} }
} }
@ -110,7 +109,7 @@ func OnIncomingMessagesRequest(
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("unable to parse filter"), JSON: spec.InvalidParam("unable to parse filter"),
} }
} }
@ -132,7 +131,7 @@ func OnIncomingMessagesRequest(
if dir != "b" && dir != "f" { if dir != "b" && dir != "f" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Bad or missing dir query parameter (should be either 'b' or 'f')"), JSON: spec.MissingParam("Bad or missing dir query parameter (should be either 'b' or 'f')"),
} }
} }
// A boolean is easier to handle in this case, especially since dir is sure // A boolean is easier to handle in this case, especially since dir is sure
@ -145,14 +144,14 @@ func OnIncomingMessagesRequest(
if streamToken, err = types.NewStreamTokenFromString(fromQuery); err != nil { if streamToken, err = types.NewStreamTokenFromString(fromQuery); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("Invalid from parameter: " + err.Error()), JSON: spec.InvalidParam("Invalid from parameter: " + err.Error()),
} }
} else { } else {
fromStream = &streamToken fromStream = &streamToken
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
} }
@ -168,13 +167,13 @@ func OnIncomingMessagesRequest(
if streamToken, err = types.NewStreamTokenFromString(toQuery); err != nil { if streamToken, err = types.NewStreamTokenFromString(toQuery); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.InvalidArgumentValue("Invalid to parameter: " + err.Error()), JSON: spec.InvalidParam("Invalid to parameter: " + err.Error()),
} }
} else { } else {
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
} }
} }
@ -197,7 +196,7 @@ func OnIncomingMessagesRequest(
if _, _, err = gomatrixserverlib.SplitID('!', roomID); err != nil { if _, _, err = gomatrixserverlib.SplitID('!', roomID); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Bad room ID: " + err.Error()), JSON: spec.MissingParam("Bad room ID: " + err.Error()),
} }
} }
@ -233,7 +232,7 @@ 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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
util.GetLogger(req.Context()).WithFields(logrus.Fields{ util.GetLogger(req.Context()).WithFields(logrus.Fields{
@ -254,7 +253,7 @@ 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 jsonerror.InternalServerError() return 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

@ -21,7 +21,6 @@ import (
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
rstypes "github.com/matrix-org/dendrite/roomserver/types" rstypes "github.com/matrix-org/dendrite/roomserver/types"
@ -30,6 +29,7 @@ import (
"github.com/matrix-org/dendrite/syncapi/synctypes" "github.com/matrix-org/dendrite/syncapi/synctypes"
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
type RelationsResponse struct { type RelationsResponse struct {
@ -73,14 +73,14 @@ func Relations(
if dir != "b" && dir != "f" { if dir != "b" && dir != "f" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.MissingArgument("Bad or missing dir query parameter (should be either 'b' or 'f')"), JSON: spec.MissingParam("Bad or missing dir query parameter (should be either 'b' or 'f')"),
} }
} }
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 jsonerror.InternalServerError() return spec.InternalServerError()
} }
var succeeded bool var succeeded bool
defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err) defer sqlutil.EndTransactionWithCheck(snapshot, &succeeded, &err)

View file

@ -21,7 +21,6 @@ import (
"github.com/matrix-org/gomatrixserverlib/spec" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/fulltext" "github.com/matrix-org/dendrite/internal/fulltext"
"github.com/matrix-org/dendrite/internal/httputil" "github.com/matrix-org/dendrite/internal/httputil"
@ -158,12 +157,12 @@ func Setup(
if !cfg.Fulltext.Enabled { if !cfg.Fulltext.Enabled {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotImplemented, Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("Search has been disabled by the server administrator."), JSON: spec.Unknown("Search has been disabled by the server administrator."),
} }
} }
var nextBatch *string var nextBatch *string
if err := req.ParseForm(); err != nil { if err := req.ParseForm(); err != nil {
return jsonerror.InternalServerError() return spec.InternalServerError()
} }
if req.Form.Has("next_batch") { if req.Form.Has("next_batch") {
nb := req.FormValue("next_batch") nb := req.FormValue("next_batch")

Some files were not shown because too many files have changed in this diff Show more