diff --git a/api/application.go b/api/application.go index 0ef87ed18..7289b63f9 100644 --- a/api/application.go +++ b/api/application.go @@ -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 @@ -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) @@ -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 } diff --git a/api/application_test.go b/api/application_test.go index 197b9cb0c..b98973ca6 100644 --- a/api/application_test.go +++ b/api/application_test.go @@ -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() { @@ -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) + } +} diff --git a/api/message.go b/api/message.go index 849de197e..2f4561bb4 100644 --- a/api/message.go +++ b/api/message.go @@ -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 @@ -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 @@ -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 diff --git a/api/message_test.go b/api/message_test.go index 0f6e9ee26..766383ff1 100644 --- a/api/message_test.go +++ b/api/message_test.go @@ -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) diff --git a/docs/spec.json b/docs/spec.json index 1aa938fe4..bbe462a0e 100644 --- a/docs/spec.json +++ b/docs/spec.json @@ -1640,6 +1640,15 @@ "/message/{id}": { "delete": { "security": [ + { + "appTokenAuthorizationHeader": [] + }, + { + "appTokenHeader": [] + }, + { + "appTokenQuery": [] + }, { "clientTokenAuthorizationHeader": [] }, @@ -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" ], @@ -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", @@ -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", diff --git a/model/application.go b/model/application.go index ed8e7489f..94f5d4d82 100644 --- a/model/application.go +++ b/model/application.go @@ -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 diff --git a/router/router.go b/router/router.go index 7f71ffaeb..eee6a5b23 100644 --- a/router/router.go +++ b/router/router.go @@ -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) @@ -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) diff --git a/router/router_test.go b/router/router_test.go index d4dbb8a89..ee3a23eb9 100644 --- a/router/router_test.go +++ b/router/router_test.go @@ -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") diff --git a/ui/src/application/AppStore.ts b/ui/src/application/AppStore.ts index a6fa32ba6..3e752665e 100644 --- a/ui/src/application/AppStore.ts +++ b/ui/src/application/AppStore.ts @@ -86,7 +86,7 @@ export class AppStore extends BaseStore { ...app }: Pick< IApplication, - 'id' | 'name' | 'description' | 'defaultPriority' | 'sortKey' + 'id' | 'name' | 'description' | 'defaultPriority' | 'sortKey' | 'allowMessageDelete' >): Promise => { await axios.put(`${config.get('url')}application/${id}`, app); await this.refresh(); diff --git a/ui/src/application/Applications.tsx b/ui/src/application/Applications.tsx index 048edc394..8aa94d7c3 100644 --- a/ui/src/application/Applications.tsx +++ b/ui/src/application/Applications.tsx @@ -178,12 +178,19 @@ const Applications = observer(() => { {toUpdateApp != null && ( setToUpdateApp(undefined)} - fOnSubmit={(name, description, defaultPriority) => - appStore.update({...toUpdateApp, name, description, defaultPriority}) + fOnSubmit={(name, description, defaultPriority, allowMessageDelete) => + appStore.update({ + ...toUpdateApp, + name, + description, + defaultPriority, + allowMessageDelete, + }) } initialDescription={toUpdateApp?.description} initialName={toUpdateApp?.name} initialDefaultPriority={toUpdateApp?.defaultPriority} + initialAllowMessageDelete={toUpdateApp?.allowMessageDelete} /> )} {toRegenerateTokenApp != null && ( diff --git a/ui/src/application/UpdateApplicationDialog.tsx b/ui/src/application/UpdateApplicationDialog.tsx index a4d13fad8..359184964 100644 --- a/ui/src/application/UpdateApplicationDialog.tsx +++ b/ui/src/application/UpdateApplicationDialog.tsx @@ -4,6 +4,8 @@ import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogContentText from '@mui/material/DialogContentText'; import DialogTitle from '@mui/material/DialogTitle'; +import FormControlLabel from '@mui/material/FormControlLabel'; +import Switch from '@mui/material/Switch'; import TextField from '@mui/material/TextField'; import Tooltip from '@mui/material/Tooltip'; import {NumberField} from '../common/NumberField'; @@ -11,26 +13,34 @@ import React, {useState} from 'react'; interface IProps { fClose: VoidFunction; - fOnSubmit: (name: string, description: string, defaultPriority: number) => Promise; + fOnSubmit: ( + name: string, + description: string, + defaultPriority: number, + allowMessageDelete: boolean + ) => Promise; initialName: string; initialDescription: string; initialDefaultPriority: number; + initialAllowMessageDelete: boolean; } export const UpdateApplicationDialog = ({ initialName, initialDescription, initialDefaultPriority, + initialAllowMessageDelete, fClose, fOnSubmit, }: IProps) => { const [name, setName] = useState(initialName); const [description, setDescription] = useState(initialDescription); const [defaultPriority, setDefaultPriority] = useState(initialDefaultPriority); + const [allowMessageDelete, setAllowMessageDelete] = useState(initialAllowMessageDelete); const submitEnabled = name.length !== 0; const submitAndClose = async () => { - await fOnSubmit(name, description, defaultPriority); + await fOnSubmit(name, description, defaultPriority, allowMessageDelete); fClose(); }; @@ -66,6 +76,16 @@ export const UpdateApplicationDialog = ({ onChange={(e) => setDefaultPriority(e)} fullWidth /> + setAllowMessageDelete(e.target.checked)} + /> + } + label="Allow the application to delete its own messages" + /> diff --git a/ui/src/tests/application.test.ts b/ui/src/tests/application.test.ts index 71ff65ac4..142d21fb4 100644 --- a/ui/src/tests/application.test.ts +++ b/ui/src/tests/application.test.ts @@ -107,6 +107,29 @@ describe('Application', () => { await waitforApp('desktop', 'kitchen_computer', 2)(); await waitforApp('raspberry_pi', 'home_pi', 3)(); }); + describe('message deletes', () => { + const $switch = '#app-dialog .allow-message-delete input'; + const isAllowed = async (row: number) => { + await page.click($table.cell(row, Col.EditUpdate, '.edit')); + await page.waitForSelector($switch); + const checked = await page.$eval($switch, (el) => (el as HTMLInputElement).checked); + await page.keyboard.press('Escape'); + await waitToDisappear(page, $dialog.selector()); + return checked; + }; + it('are not allowed by default', async () => { + expect(await isAllowed(1)).toBe(false); + }); + it('can be allowed per application', async () => { + await page.click($table.cell(1, Col.EditUpdate, '.edit')); + await page.waitForSelector($switch); + await page.click($switch); + await page.click($dialog.button('.update')); + await waitToDisappear(page, $dialog.selector()); + expect(await isAllowed(1)).toBe(true); + expect(await isAllowed(3)).toBe(false); + }); + }); describe('security updates', () => { it('regenerates application token', async () => { await page.click($table.cell(1, Col.EditRegenerateToken, '.regenerate-token')); diff --git a/ui/src/types.ts b/ui/src/types.ts index c9f0324c4..583c17679 100644 --- a/ui/src/types.ts +++ b/ui/src/types.ts @@ -7,6 +7,7 @@ export interface IApplication { image: string; internal: boolean; defaultPriority: number; + allowMessageDelete: boolean; lastUsed: string | null; createdAt: string; }