Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions api/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ type ApplicationParams struct {
//
// example: 5
DefaultPriority int `form:"defaultPriority" query:"defaultPriority" json:"defaultPriority"`
// Whether the application may delete its own messages with its application token.
// Defaults to false on create. When omitted on update, the current value is kept.
//
// example: false
AllowMessageDelete *bool `form:"allowMessageDelete" query:"allowMessageDelete" json:"allowMessageDelete"`
// The sortKey for the application. Uses fractional indexing.
//
// example: a1
Expand Down Expand Up @@ -108,6 +113,9 @@ func (a *ApplicationAPI) CreateApplication(ctx *gin.Context) {
UserID: auth.GetUserID(ctx),
Internal: false,
}
if applicationParams.AllowMessageDelete != nil {
app.AllowMessageDelete = *applicationParams.AllowMessageDelete
}

if err := a.DB.CreateApplication(&app); err != nil {
handleApplicationError(ctx, err)
Expand Down Expand Up @@ -273,6 +281,9 @@ func (a *ApplicationAPI) UpdateApplication(ctx *gin.Context) {
app.Description = applicationParams.Description
app.Name = applicationParams.Name
app.DefaultPriority = applicationParams.DefaultPriority
if applicationParams.AllowMessageDelete != nil {
app.AllowMessageDelete = *applicationParams.AllowMessageDelete
}
if applicationParams.SortKey != "" {
app.SortKey = applicationParams.SortKey
}
Expand Down
53 changes: 52 additions & 1 deletion api/application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (s *ApplicationSuite) Test_ensureApplicationHasCorrectJsonRepresentation()
SortKey: "a1",
CreatedAt: testdb.Now,
}
test.JSONEquals(s.T(), actual, `{"id":1,"token":"Aasdasfgeeg","name":"myapp","description":"mydesc", "image": "asd", "internal":true, "defaultPriority":0, "createdAt":"2020-01-01T00:00:00Z", "lastUsed":null, "sortKey":"a1"}`)
test.JSONEquals(s.T(), actual, `{"id":1,"token":"Aasdasfgeeg","name":"myapp","description":"mydesc", "image": "asd", "internal":true, "defaultPriority":0, "createdAt":"2020-01-01T00:00:00Z", "lastUsed":null, "sortKey":"a1", "allowMessageDelete":false}`)
}

func (s *ApplicationSuite) Test_CreateApplication_expectBadRequestOnEmptyName() {
Expand Down Expand Up @@ -879,3 +879,54 @@ func (d *failingUpdateAppDB) UpdateApplication(*model.Application) error {
type errReader struct{ err error }

func (r errReader) Read([]byte) (int, error) { return 0, r.err }

func (s *ApplicationSuite) Test_CreateApplication_messageDeletesDisabledByDefault() {
s.db.User(5)

test.WithUser(s.ctx, 5)
s.withFormData("name=app")
s.a.CreateApplication(s.ctx)

assert.Equal(s.T(), 200, s.recorder.Code)
if apps, err := s.db.GetApplicationsByUser(5); assert.NoError(s.T(), err) && assert.Len(s.T(), apps, 1) {
assert.False(s.T(), apps[0].AllowMessageDelete)
}
}

func (s *ApplicationSuite) Test_CreateApplication_allowMessageDelete() {
s.db.User(5)

test.WithUser(s.ctx, 5)
s.withFormData("name=app&allowMessageDelete=true")
s.a.CreateApplication(s.ctx)

assert.Equal(s.T(), 200, s.recorder.Code)
if apps, err := s.db.GetApplicationsByUser(5); assert.NoError(s.T(), err) && assert.Len(s.T(), apps, 1) {
assert.True(s.T(), apps[0].AllowMessageDelete)
}
}

func (s *ApplicationSuite) Test_UpdateApplication_allowMessageDelete() {
s.db.User(5).NewAppWithToken(2, "app-2")
test.WithUser(s.ctx, 5)
s.ctx.Params = gin.Params{{Key: "id", Value: "2"}}

s.withFormData("name=name&allowMessageDelete=true")
s.a.UpdateApplication(s.ctx)
assert.Equal(s.T(), 200, s.recorder.Code)
if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) {
assert.True(s.T(), app.AllowMessageDelete)
}

s.withFormData("name=other")
s.a.UpdateApplication(s.ctx)
if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) {
assert.True(s.T(), app.AllowMessageDelete, "omitting the field keeps the value")
}

s.withFormData("name=other&allowMessageDelete=false")
s.a.UpdateApplication(s.ctx)
if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) {
assert.False(s.T(), app.AllowMessageDelete)
}
}
18 changes: 17 additions & 1 deletion api/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,13 @@ func (a *MessageAPI) DeleteMessageWithApplication(ctx *gin.Context) {
//
// Deletes a message with an id.
//
// __NOTE__: When authenticating with an application token, only messages
// of this application can be deleted. This has to be enabled per application
// (`allowMessageDelete`), it is disabled by default. Otherwise 403 is returned.
//
// ---
// produces: [application/json]
// security: [clientTokenAuthorizationHeader: [], clientTokenHeader: [], clientTokenQuery: [], basicAuth: []]
// security: [appTokenAuthorizationHeader: [], appTokenHeader: [], appTokenQuery: [], clientTokenAuthorizationHeader: [], clientTokenHeader: [], clientTokenQuery: [], basicAuth: []]
// parameters:
// - name: id
// in: path
Expand Down Expand Up @@ -302,6 +306,10 @@ func (a *MessageAPI) DeleteMessageWithApplication(ctx *gin.Context) {
// $ref: "#/definitions/Error"
func (a *MessageAPI) DeleteMessage(ctx *gin.Context) {
withID(ctx, "id", func(id uint) {
if tokenApp := auth.GetApplication(ctx); tokenApp != nil && !tokenApp.AllowMessageDelete {
ctx.AbortWithError(403, errors.New("deleting messages is not enabled for this application"))
return
}
msg, err := a.DB.GetMessageByID(id)
if success := successOrAbort(ctx, 500, err); !success {
return
Expand All @@ -310,6 +318,14 @@ func (a *MessageAPI) DeleteMessage(ctx *gin.Context) {
ctx.AbortWithError(404, errors.New("message does not exist"))
return
}
if tokenApp := auth.GetApplication(ctx); tokenApp != nil {
if msg.ApplicationID == tokenApp.ID {
successOrAbort(ctx, 500, a.DB.DeleteMessageByID(id))
} else {
ctx.AbortWithError(404, errors.New("message does not exist"))
}
return
}
app, err := a.DB.GetApplicationByID(msg.ApplicationID)
if success := successOrAbort(ctx, 500, err); !success {
return
Expand Down
73 changes: 73 additions & 0 deletions api/message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,79 @@ func (s *MessageSuite) Test_DeleteMessage() {
s.db.AssertMessageNotExist(50)
}

func (s *MessageSuite) Test_DeleteMessage_appToken() {
s.db.User(6).AppWithToken(1, "Aapp").Message(50)
app, err := s.db.GetApplicationByID(1)
assert.NoError(s.T(), err)

auth.RegisterApplication(s.ctx, allowDeletes(app))
s.ctx.Params = gin.Params{{Key: "id", Value: "50"}}
s.a.DeleteMessage(s.ctx)

assert.Equal(s.T(), 200, s.recorder.Code)
s.db.AssertMessageNotExist(50)
}

func (s *MessageSuite) Test_DeleteMessage_appToken_messageOfOtherApp() {
user := s.db.User(6)
user.AppWithToken(1, "Aapp")
user.AppWithToken(2, "Aother").Message(50)
app, err := s.db.GetApplicationByID(1)
assert.NoError(s.T(), err)

auth.RegisterApplication(s.ctx, allowDeletes(app))
s.ctx.Params = gin.Params{{Key: "id", Value: "50"}}
s.a.DeleteMessage(s.ctx)

assert.Equal(s.T(), 404, s.recorder.Code)
s.db.AssertMessageExist(50)
}

func (s *MessageSuite) Test_DeleteMessage_appToken_messageOfOtherUser() {
s.db.User(6).AppWithToken(1, "Aapp")
s.db.User(7).AppWithToken(2, "Aother").Message(50)
app, err := s.db.GetApplicationByID(1)
assert.NoError(s.T(), err)

auth.RegisterApplication(s.ctx, allowDeletes(app))
s.ctx.Params = gin.Params{{Key: "id", Value: "50"}}
s.a.DeleteMessage(s.ctx)

assert.Equal(s.T(), 404, s.recorder.Code)
s.db.AssertMessageExist(50)
}

func (s *MessageSuite) Test_DeleteMessage_appToken_notExistingID() {
s.db.User(6).AppWithToken(1, "Aapp").Message(50)
app, err := s.db.GetApplicationByID(1)
assert.NoError(s.T(), err)

auth.RegisterApplication(s.ctx, allowDeletes(app))
s.ctx.Params = gin.Params{{Key: "id", Value: "51"}}
s.a.DeleteMessage(s.ctx)

assert.Equal(s.T(), 404, s.recorder.Code)
s.db.AssertMessageExist(50)
}

func (s *MessageSuite) Test_DeleteMessage_appToken_notAllowedForApplication() {
s.db.User(6).AppWithToken(1, "Aapp").Message(50)
app, err := s.db.GetApplicationByID(1)
assert.NoError(s.T(), err)

auth.RegisterApplication(s.ctx, app)
s.ctx.Params = gin.Params{{Key: "id", Value: "50"}}
s.a.DeleteMessage(s.ctx)

assert.Equal(s.T(), 403, s.recorder.Code)
s.db.AssertMessageExist(50)
}

func allowDeletes(app *model.Application) *model.Application {
app.AllowMessageDelete = true
return app
}

func (s *MessageSuite) Test_DeleteMessageWithID() {
s.db.User(2).AppWithToken(5, "mytoken").Message(55)

Expand Down
23 changes: 23 additions & 0 deletions docs/spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -1640,6 +1640,15 @@
"/message/{id}": {
"delete": {
"security": [
{
"appTokenAuthorizationHeader": []
},
{
"appTokenHeader": []
},
{
"appTokenQuery": []
},
{
"clientTokenAuthorizationHeader": []
},
Expand All @@ -1653,6 +1662,7 @@
"basicAuth": []
}
],
"description": "__NOTE__: When authenticating with an application token, only messages\nof this application can be deleted. This has to be enabled per application\n(`allowMessageDelete`), it is disabled by default. Otherwise 403 is returned.",
"produces": [
"application/json"
],
Expand Down Expand Up @@ -2543,10 +2553,17 @@
"description",
"internal",
"image",
"allowMessageDelete",
"createdAt",
"sortKey"
],
"properties": {
"allowMessageDelete": {
"description": "Whether the application may delete its own messages with its application token.\nDisabled by default, it has to be enabled per application.",
"type": "boolean",
"x-go-name": "AllowMessageDelete",
"example": false
},
"createdAt": {
"description": "The date the application was created.",
"type": "string",
Expand Down Expand Up @@ -2628,6 +2645,12 @@
"name"
],
"properties": {
"allowMessageDelete": {
"description": "Whether the application may delete its own messages with its application token.\nDefaults to false on create. When omitted on update, the current value is kept.",
"type": "boolean",
"x-go-name": "AllowMessageDelete",
"example": false
},
"defaultPriority": {
"description": "The default priority of messages sent by this application. Defaults to 0.",
"type": "integer",
Expand Down
6 changes: 6 additions & 0 deletions model/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ type Application struct {
// required: false
// example: 4
DefaultPriority int `form:"defaultPriority" query:"defaultPriority" json:"defaultPriority"`
// Whether the application may delete its own messages with its application token.
// Disabled by default, it has to be enabled per application.
//
// required: true
// example: false
AllowMessageDelete bool `gorm:"not null;default:false" form:"allowMessageDelete" query:"allowMessageDelete" json:"allowMessageDelete"`
// The date the application was created.
//
// read only: true
Expand Down
2 changes: 1 addition & 1 deletion router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Co
})

g.Group("/").Use(authentication.RequireApplicationOrClient).POST("/message", messageHandler.CreateMessage)
g.Group("/").Use(authentication.RequireApplicationOrClient).DELETE("/message/:id", messageHandler.DeleteMessage)

if conf.MCP.Enabled {
mcpHandler := api.NewMCP(&messageHandler, vInfo.Version)
Expand Down Expand Up @@ -243,7 +244,6 @@ func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Co
{
message.GET("", messageHandler.GetMessages)
message.DELETE("", messageHandler.DeleteMessages)
message.DELETE("/:id", messageHandler.DeleteMessage)
}

clientAuth.GET("/stream", streamHandler.Handle)
Expand Down
74 changes: 74 additions & 0 deletions router/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,80 @@ func (s *IntegrationSuite) TestSendMessage() {
assert.Equal(s.T(), token.ID, msg.ApplicationID)
}

func (s *IntegrationSuite) TestDeleteMessage() {
user := s.db.User(2)
user.AppWithToken(1, "Aapp").Message(10).Message(11).Message(12)
user.AppWithToken(2, "Aother").Message(20)
user.ClientWithToken(1, "Cclient")
s.db.User(3).AppWithToken(3, "Aforeign").Message(30)

forbidden := `{"error":"Forbidden", "errorCode":403, "errorDescription":"deleting messages is not enabled for this application"}`

// deleting is disabled by default
req := s.newRequest("DELETE", "message/12", "")
req.Header.Set("X-Gotify-Key", "Aapp")
doRequestAndExpect(s.T(), req, 403, forbidden)
s.db.AssertMessageExist(12)

app, err := s.db.GetApplicationByID(1)
assert.Nil(s.T(), err)
app.AllowMessageDelete = true
assert.Nil(s.T(), s.db.UpdateApplication(app))

notFound := `{"error":"Not Found", "errorCode":404, "errorDescription":"message does not exist"}`
unauthorized := `{"error":"Unauthorized", "errorCode":401, "errorDescription":"you need to provide a valid access token or user credentials to access this api"}`

// own message with application token
req = s.newRequest("DELETE", "message/10", "")
req.Header.Set("X-Gotify-Key", "Aapp")
res, err := client.Do(req)
assert.Nil(s.T(), err)
assert.Equal(s.T(), 200, res.StatusCode)
s.db.AssertMessageNotExist(10)

// message of another application of the same user
req = s.newRequest("DELETE", "message/20", "")
req.Header.Set("X-Gotify-Key", "Aapp")
doRequestAndExpect(s.T(), req, 404, notFound)
s.db.AssertMessageExist(20)

// message of another user
req = s.newRequest("DELETE", "message/30", "")
req.Header.Set("X-Gotify-Key", "Aapp")
doRequestAndExpect(s.T(), req, 404, notFound)
s.db.AssertMessageExist(30)

// unknown id
req = s.newRequest("DELETE", "message/99", "")
req.Header.Set("X-Gotify-Key", "Aapp")
doRequestAndExpect(s.T(), req, 404, notFound)

// invalid token
req = s.newRequest("DELETE", "message/11", "")
req.Header.Set("X-Gotify-Key", "Ainvalid")
doRequestAndExpect(s.T(), req, 401, unauthorized)
s.db.AssertMessageExist(11)

// no token
req = s.newRequest("DELETE", "message/11", "")
doRequestAndExpect(s.T(), req, 401, unauthorized)
s.db.AssertMessageExist(11)

// client token can still delete messages of all applications of its user
req = s.newRequest("DELETE", "message/20", "")
req.Header.Set("X-Gotify-Key", "Cclient")
res, err = client.Do(req)
assert.Nil(s.T(), err)
assert.Equal(s.T(), 200, res.StatusCode)
s.db.AssertMessageNotExist(20)

// application token cannot delete all messages
req = s.newRequest("DELETE", "message", "")
req.Header.Set("X-Gotify-Key", "Aapp")
doRequestAndExpect(s.T(), req, 401, unauthorized)
s.db.AssertMessageExist(11)
}

func (s *IntegrationSuite) TestMaxBodyBytes() {
s.db.User(2).AppWithToken(1, "Aapp")

Expand Down
2 changes: 1 addition & 1 deletion ui/src/application/AppStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export class AppStore extends BaseStore<IApplication> {
...app
}: Pick<
IApplication,
'id' | 'name' | 'description' | 'defaultPriority' | 'sortKey'
'id' | 'name' | 'description' | 'defaultPriority' | 'sortKey' | 'allowMessageDelete'
>): Promise<void> => {
await axios.put(`${config.get('url')}application/${id}`, app);
await this.refresh();
Expand Down
Loading