From 2f7b9e01a230de4a2c5b0d4520c55fad4c8b8149 Mon Sep 17 00:00:00 2001 From: EinfacheSache <69739334+EinfacheSache@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:02:08 +0000 Subject: [PATCH 1/2] feat: allow applications to update their messages Adds PUT /message/{id} for the application that sent a message. The message keeps its id and date and gets an updated timestamp. Clients that connect to the stream with updates=true receive updated messages, other clients are unaffected. The web UI updates messages in place and marks them as edited. --- api/message.go | 114 ++++++++++++++++++-- api/message_test.go | 180 +++++++++++++++++++++++++++++++ api/stream/client.go | 4 +- api/stream/stream.go | 27 ++++- api/stream/stream_test.go | 31 ++++++ database/message.go | 5 + docs/spec.json | 94 ++++++++++++++++ model/message.go | 6 ++ router/router.go | 1 + router/router_test.go | 61 +++++++++++ ui/src/message/Message.tsx | 20 +++- ui/src/message/Messages.tsx | 1 + ui/src/message/MessagesStore.ts | 13 +++ ui/src/message/WebSocketStore.ts | 2 +- ui/src/reactions.ts | 4 + ui/src/tests/message.test.ts | 60 +++++++++++ ui/src/types.ts | 1 + 17 files changed, 611 insertions(+), 13 deletions(-) diff --git a/api/message.go b/api/message.go index 849de197e..23d44caa7 100644 --- a/api/message.go +++ b/api/message.go @@ -24,6 +24,7 @@ type MessageDatabase interface { DeleteMessagesByUser(userID uint) error DeleteMessagesByApplication(applicationID uint) error CreateMessage(message *model.Message) error + UpdateMessage(message *model.Message) error } var timeNow = time.Now @@ -33,10 +34,16 @@ type Notifier interface { Notify(userID uint, message *model.MessageExternal) } +// MessageNotifier notifies when a message was created or updated. +type MessageNotifier interface { + Notifier + NotifyUpdated(userID uint, message *model.MessageExternal) +} + // The MessageAPI provides handlers for managing messages. type MessageAPI struct { DB MessageDatabase - Notifier Notifier + Notifier MessageNotifier } type pagingParams struct { @@ -390,8 +397,105 @@ func (a *MessageAPI) CreateMessage(ctx *gin.Context) { ctx.JSON(200, created) } +// UpdateMessage updates a message, authentication via application token is required. +// swagger:operation PUT /message/{id} message updateMessage +// +// Update a message. +// +// Only the application that created the message can update it. The message keeps +// its id and creation date. Title, message, priority and extras are replaced with +// the values from the request body, the same defaults as for creating a message apply: +// an omitted title or priority falls back to the application defaults and omitted +// extras are removed. Any "appid" in the body is ignored. +// +// Clients connected to the stream with `updates=true` receive the updated message. +// +// --- +// consumes: [application/json] +// produces: [application/json] +// security: [appTokenAuthorizationHeader: [], appTokenHeader: [], appTokenQuery: []] +// parameters: +// - name: id +// in: path +// description: the message id +// required: true +// type: integer +// format: int64 +// - name: body +// in: body +// description: the new content of the message +// required: true +// schema: +// $ref: "#/definitions/CreateMessage" +// responses: +// 200: +// description: Ok +// schema: +// $ref: "#/definitions/Message" +// 400: +// description: Bad Request +// schema: +// $ref: "#/definitions/Error" +// 401: +// description: Unauthorized +// schema: +// $ref: "#/definitions/Error" +// 403: +// description: Forbidden +// schema: +// $ref: "#/definitions/Error" +// 404: +// description: Not Found +// schema: +// $ref: "#/definitions/Error" +func (a *MessageAPI) UpdateMessage(ctx *gin.Context) { + withID(ctx, "id", func(id uint) { + update := model.CreateMessage{} + if err := ctx.Bind(&update); err != nil { + return + } + + app := auth.GetApplication(ctx) + msg, err := a.DB.GetMessageByID(id) + if success := successOrAbort(ctx, 500, err); !success { + return + } + if app == nil || msg == nil || msg.ApplicationID != app.ID { + ctx.AbortWithError(404, errors.New("message does not exist")) + return + } + + applyApplicationDefaults(app, &update) + updated := toInternalMessage(&update) + now := timeNow() + msg.Title = updated.Title + msg.Message = updated.Message + msg.Priority = updated.Priority + msg.Extras = updated.Extras + msg.Updated = &now + if success := successOrAbort(ctx, 500, a.DB.UpdateMessage(msg)); !success { + return + } + + external := toExternalMessage(msg) + a.Notifier.NotifyUpdated(app.UserID, external) + ctx.JSON(200, external) + }) +} + // createMessage fills in defaults from the application, stores the message and notifies the user. func (a *MessageAPI) createMessage(app *model.Application, message *model.CreateMessage) (*model.MessageExternal, error) { + applyApplicationDefaults(app, message) + msgInternal := toInternalMessage(message) + if err := a.DB.CreateMessage(msgInternal); err != nil { + return nil, err + } + a.Notifier.Notify(app.UserID, toExternalMessage(msgInternal)) + return toExternalMessage(msgInternal), nil +} + +// applyApplicationDefaults sets the application id and fills in the title and priority from the application if unset. +func applyApplicationDefaults(app *model.Application, message *model.CreateMessage) { message.ApplicationID = app.ID if strings.TrimSpace(message.Title) == "" { message.Title = app.Name @@ -400,13 +504,6 @@ func (a *MessageAPI) createMessage(app *model.Application, message *model.Create if message.Priority == nil { message.Priority = &app.DefaultPriority } - - msgInternal := toInternalMessage(message) - if err := a.DB.CreateMessage(msgInternal); err != nil { - return nil, err - } - a.Notifier.Notify(app.UserID, toExternalMessage(msgInternal)) - return toExternalMessage(msgInternal), nil } func toInternalMessage(msg *model.CreateMessage) *model.Message { @@ -434,6 +531,7 @@ func toExternalMessage(msg *model.Message) *model.MessageExternal { Title: msg.Title, Priority: &msg.Priority, Date: msg.Date, + Updated: msg.Updated, } if len(msg.Extras) != 0 { res.Extras = make(map[string]any) diff --git a/api/message_test.go b/api/message_test.go index 0f6e9ee26..e3def59da 100644 --- a/api/message_test.go +++ b/api/message_test.go @@ -28,6 +28,7 @@ type MessageSuite struct { ctx *gin.Context recorder *httptest.ResponseRecorder notifiedMessage *model.MessageExternal + updatedMessage *model.MessageExternal } func (s *MessageSuite) BeforeTest(suiteName, testName string) { @@ -37,6 +38,7 @@ func (s *MessageSuite) BeforeTest(suiteName, testName string) { s.ctx.Request = httptest.NewRequest("GET", "/irrelevant", nil) s.db = testdb.NewDB(s.T()) s.notifiedMessage = nil + s.updatedMessage = nil s.a = &MessageAPI{DB: s.db, Notifier: s} } @@ -48,6 +50,10 @@ func (s *MessageSuite) Notify(userID uint, msg *model.MessageExternal) { s.notifiedMessage = msg } +func (s *MessageSuite) NotifyUpdated(userID uint, msg *model.MessageExternal) { + s.updatedMessage = msg +} + func (s *MessageSuite) Test_ensureCorrectJsonRepresentation() { t, _ := time.Parse("2006/01/02", "2017/01/02") @@ -649,6 +655,180 @@ func (s *MessageSuite) Test_CreateMessage_appToken_ignoresBodyAppId() { assert.Equal(s.T(), 200, s.recorder.Code) } +func (s *MessageSuite) Test_UpdateMessage() { + created, _ := time.Parse("2006/01/02", "2017/01/02") + updated, _ := time.Parse("2006/01/02", "2017/01/03") + timeNow = func() time.Time { return updated } + defer func() { timeNow = time.Now }() + + app := s.db.User(4).NewAppWithTokenAndDefaultPriority(7, "app-token", 3) + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Title: "old", Message: "Backup 40%", Priority: 1, Date: created, Extras: []byte(`{"gotify::test":1}`)}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"title": "Backup", "message": "Backup 100%", "priority": 2}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + expected := &model.MessageExternal{ID: 9, ApplicationID: 7, Title: "Backup", Message: "Backup 100%", Priority: intPtr(2), Date: created, Updated: &updated} + assert.Equal(s.T(), 200, s.recorder.Code) + test.BodyEquals(s.T(), expected, s.recorder) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Equal(s.T(), expected, toExternalMessage(msg)) + assert.Equal(s.T(), expected, s.updatedMessage) + assert.Nil(s.T(), s.notifiedMessage) +} + +func (s *MessageSuite) Test_UpdateMessage_usesApplicationDefaults() { + s.db.User(4) + app := &model.Application{ID: 7, UserID: 4, Token: "app-token", Name: "backup-server", DefaultPriority: 3} + s.db.CreateApplication(app) + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Title: "old", Message: "old", Priority: 1}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 200, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Equal(s.T(), "new", msg.Message) + assert.Equal(s.T(), "backup-server", msg.Title) + assert.Equal(s.T(), 3, msg.Priority) +} + +func (s *MessageSuite) Test_UpdateMessage_replacesExtras() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "approve?", Extras: []byte(`{"gotify::old":{"a":1}}`)}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "approved", "extras": {"gotify::new":{"b":2}}}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 200, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Equal(s.T(), map[string]any{"gotify::new": map[string]any{"b": float64(2)}}, toExternalMessage(msg).Extras) +} + +func (s *MessageSuite) Test_UpdateMessage_removesExtrasWhenOmitted() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "approve?", Extras: []byte(`{"gotify::old":{"a":1}}`)}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "approved"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 200, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Nil(s.T(), toExternalMessage(msg).Extras) +} + +func (s *MessageSuite) Test_UpdateMessage_ignoresAppID() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.User(4).App(8) + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "old"}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new", "appid": 8}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 200, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Equal(s.T(), uint(7), msg.ApplicationID) +} + +func (s *MessageSuite) Test_UpdateMessage_messageOfOtherApplication() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.User(4).App(8).Message(9) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 404, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.NotEqual(s.T(), "new", msg.Message) + assert.Nil(s.T(), msg.Updated) + assert.Nil(s.T(), s.updatedMessage) +} + +func (s *MessageSuite) Test_UpdateMessage_messageOfOtherUser() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.User(5).App(8).Message(9) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 404, s.recorder.Code) + assert.Nil(s.T(), s.updatedMessage) +} + +func (s *MessageSuite) Test_UpdateMessage_notExistingID() { + auth.RegisterApplication(s.ctx, s.db.User(4).NewAppWithToken(7, "app-token")) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 404, s.recorder.Code) + assert.Nil(s.T(), s.updatedMessage) +} + +func (s *MessageSuite) Test_UpdateMessage_invalidID() { + auth.RegisterApplication(s.ctx, s.db.User(4).NewAppWithToken(7, "app-token")) + s.ctx.Params = gin.Params{{Key: "id", Value: "string"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/string", strings.NewReader(`{"message": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 400, s.recorder.Code) +} + +func (s *MessageSuite) Test_UpdateMessage_failWhenNoMessage() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "old"}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"title": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 400, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Equal(s.T(), "old", msg.Message) + assert.Nil(s.T(), s.updatedMessage) +} + func (s *MessageSuite) withURL(scheme, host, path, query string) { s.ctx.Request.URL = &url.URL{Path: path, RawQuery: query} s.ctx.Set("location", &url.URL{Scheme: scheme, Host: host}) diff --git a/api/stream/client.go b/api/stream/client.go index dcd6d6b7d..ef8a7d377 100644 --- a/api/stream/client.go +++ b/api/stream/client.go @@ -27,16 +27,18 @@ type client struct { closed chan struct{} userID uint token string + updates bool once once } -func newClient(conn *websocket.Conn, userID uint, token string, onClose func(*client)) *client { +func newClient(conn *websocket.Conn, userID uint, token string, updates bool, onClose func(*client)) *client { return &client{ conn: conn, write: make(chan *model.MessageExternal, 1), closed: make(chan struct{}), userID: userID, token: token, + updates: updates, onClose: onClose, } } diff --git a/api/stream/stream.go b/api/stream/stream.go index 4cf26b485..9e60c2efd 100644 --- a/api/stream/stream.go +++ b/api/stream/stream.go @@ -4,6 +4,7 @@ import ( "net/http" "net/url" "regexp" + "strconv" "strings" "sync" "time" @@ -81,10 +82,22 @@ func (a *API) NotifyDeletedClient(userID uint, token string) { // Notify notifies the clients with the given userID that a new messages was created. func (a *API) Notify(userID uint, msg *model.MessageExternal) { + a.notify(userID, msg, func(*client) bool { return true }) +} + +// NotifyUpdated notifies the clients with the given userID, that subscribed to updates, that a message was updated. +func (a *API) NotifyUpdated(userID uint, msg *model.MessageExternal) { + a.notify(userID, msg, func(c *client) bool { return c.updates }) +} + +func (a *API) notify(userID uint, msg *model.MessageExternal, include func(*client) bool) { a.lock.RLock() defer a.lock.RUnlock() if clients, ok := a.clients[userID]; ok { for _, c := range clients { + if !include(c) { + continue + } select { case c.write <- msg: case <-c.closed: @@ -118,10 +131,21 @@ func (a *API) register(client *client) { // // Websocket, return newly created messages. // +// With `updates=true`, the stream additionally returns messages that were updated. +// An updated message has the id of a message that was sent before and the `updated` field set. +// Clients should replace the existing message with the same id instead of adding a new one. +// // --- // schema: ws, wss // produces: [application/json] // security: [clientTokenAuthorizationHeader: [], clientTokenHeader: [], clientTokenQuery: [], basicAuth: []] +// parameters: +// - name: updates +// in: query +// description: also return updated messages +// required: false +// type: boolean +// default: false // responses: // 200: // description: Ok @@ -154,7 +178,8 @@ func (a *API) Handle(ctx *gin.Context) { if c := auth.GetClient(ctx); c != nil { token = c.Token } - client := newClient(conn, auth.GetUserID(ctx), token, a.remove) + updates, _ := strconv.ParseBool(ctx.Query("updates")) + client := newClient(conn, auth.GetUserID(ctx), token, updates, a.remove) a.register(client) go client.startReading(a.pongTimeout) go client.startWriteHandler(a.pingPeriod) diff --git a/api/stream/stream_test.go b/api/stream/stream_test.go index 8ed0697b5..5d7761604 100644 --- a/api/stream/stream_test.go +++ b/api/stream/stream_test.go @@ -638,3 +638,34 @@ func waitForConnectedClients(api *API, count int) { time.Sleep(10 * time.Millisecond) } } + +func TestNotifyUpdatedOnlyToClientsWithUpdates(t *testing.T) { + mode.Set(mode.TestDev) + + defer leaktest.Check(t)() + server, api := bootTestServer(staticUserID()) + defer server.Close() + defer api.Close() + + wsURL := wsURL(server.URL) + + legacy := testClient(t, wsURL) + defer legacy.conn.Close() + disabled := testClient(t, wsURL+"?updates=false") + defer disabled.conn.Close() + withUpdates := testClient(t, wsURL+"?updates=true") + defer withUpdates.conn.Close() + + waitForConnectedClients(api, 3) + + api.Notify(1, &model.MessageExternal{ID: 1, Message: "Backup 40%"}) + expectMessage(&model.MessageExternal{ID: 1, Message: "Backup 40%"}, legacy, disabled, withUpdates) + + updated := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + api.NotifyUpdated(1, &model.MessageExternal{ID: 1, Message: "Backup 100%", Updated: &updated}) + expectMessage(&model.MessageExternal{ID: 1, Message: "Backup 100%", Updated: &updated}, withUpdates) + expectNoMessage(legacy, disabled) + + api.NotifyUpdated(2, &model.MessageExternal{ID: 2, Message: "other user", Updated: &updated}) + expectNoMessage(legacy, disabled, withUpdates) +} diff --git a/database/message.go b/database/message.go index 405f517ad..d8d5e563f 100644 --- a/database/message.go +++ b/database/message.go @@ -23,6 +23,11 @@ func (d *GormDatabase) CreateMessage(message *model.Message) error { return d.DB.Create(message).Error } +// UpdateMessage updates a message. +func (d *GormDatabase) UpdateMessage(message *model.Message) error { + return d.DB.Save(message).Error +} + // GetMessagesByUser returns all messages from a user. func (d *GormDatabase) GetMessagesByUser(userID uint) ([]*model.Message, error) { var messages []*model.Message diff --git a/docs/spec.json b/docs/spec.json index 1aa938fe4..d3f297db4 100644 --- a/docs/spec.json +++ b/docs/spec.json @@ -1638,6 +1638,82 @@ } }, "/message/{id}": { + "put": { + "security": [ + { + "appTokenAuthorizationHeader": [] + }, + { + "appTokenHeader": [] + }, + { + "appTokenQuery": [] + } + ], + "description": "Only the application that created the message can update it. The message keeps\nits id and creation date. Title, message, priority and extras are replaced with\nthe values from the request body, the same defaults as for creating a message apply:\nan omitted title or priority falls back to the application defaults and omitted\nextras are removed. Any \"appid\" in the body is ignored.\n\nClients connected to the stream with `updates=true` receive the updated message.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "message" + ], + "summary": "Update a message.", + "operationId": "updateMessage", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "the message id", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "the new content of the message", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/CreateMessage" + } + } + ], + "responses": { + "200": { + "description": "Ok", + "schema": { + "$ref": "#/definitions/Message" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/Error" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/Error" + } + }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/Error" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, "delete": { "security": [ { @@ -2139,6 +2215,7 @@ "basicAuth": [] } ], + "description": "With `updates=true`, the stream additionally returns messages that were updated.\nAn updated message has the id of a message that was sent before and the `updated` field set.\nClients should replace the existing message with the same id instead of adding a new one.", "produces": [ "application/json" ], @@ -2147,6 +2224,15 @@ ], "summary": "Websocket, return newly created messages.", "operationId": "streamMessages", + "parameters": [ + { + "type": "boolean", + "default": false, + "description": "also return updated messages", + "name": "updates", + "in": "query" + } + ], "responses": { "200": { "description": "Ok", @@ -3082,6 +3168,14 @@ "type": "string", "x-go-name": "Title", "example": "Backup" + }, + "updated": { + "description": "The date the message was last updated. Not set if the message was never updated.", + "type": "string", + "format": "date-time", + "x-go-name": "Updated", + "readOnly": true, + "example": "2018-02-27T19:40:12.1234567+01:00" } }, "x-go-name": "MessageExternal", diff --git a/model/message.go b/model/message.go index b18273954..54ac888a8 100644 --- a/model/message.go +++ b/model/message.go @@ -13,6 +13,7 @@ type Message struct { Priority int Extras []byte Date time.Time + Updated *time.Time } // MessageExternal Model @@ -63,6 +64,11 @@ type MessageExternal struct { // required: true // example: 2018-02-27T19:36:10.5045044+01:00 Date time.Time `json:"date"` + // The date the message was last updated. Not set if the message was never updated. + // + // read only: true + // example: 2018-02-27T19:40:12.1234567+01:00 + Updated *time.Time `json:"updated,omitempty"` } // CreateMessage Model diff --git a/router/router.go b/router/router.go index 7f71ffaeb..ec261cd38 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.RequireApplicationToken).PUT("/message/:id", messageHandler.UpdateMessage) if conf.MCP.Enabled { mcpHandler := api.NewMCP(&messageHandler, vInfo.Version) diff --git a/router/router_test.go b/router/router_test.go index d4dbb8a89..b29bb2091 100644 --- a/router/router_test.go +++ b/router/router_test.go @@ -362,6 +362,67 @@ func (s *IntegrationSuite) TestSendMessage() { assert.Equal(s.T(), token.ID, msg.ApplicationID) } +func (s *IntegrationSuite) TestUpdateMessage() { + s.db.User(1).ClientWithToken(1, "Cclient") + s.db.User(1).AppWithToken(1, "Abackup") + s.db.User(1).AppWithToken(2, "Aother") + s.db.User(2).AppWithToken(3, "Aforeign") + + req := s.newRequest("POST", "message", `{"message": "Backup 40%", "title": "Backup"}`) + req.Header.Add("X-Gotify-Key", "Abackup") + res, err := client.Do(req) + assert.Nil(s.T(), err) + assert.Equal(s.T(), 200, res.StatusCode) + created := &model.MessageExternal{} + json.NewDecoder(res.Body).Decode(created) + assert.Nil(s.T(), created.Updated) + + path := fmt.Sprintf("message/%d", created.ID) + 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"}` + + for _, token := range []string{"Aother", "Aforeign"} { + req = s.newRequest("PUT", path, `{"message": "Backup 100%"}`) + req.Header.Add("X-Gotify-Key", token) + doRequestAndExpect(s.T(), req, 404, notFound) + } + + req = s.newRequest("PUT", "message/1000", `{"message": "Backup 100%"}`) + req.Header.Add("X-Gotify-Key", "Abackup") + doRequestAndExpect(s.T(), req, 404, notFound) + + for _, token := range []string{"Cclient", "Ainvalid"} { + req = s.newRequest("PUT", path, `{"message": "Backup 100%"}`) + req.Header.Add("X-Gotify-Key", token) + doRequestAndExpect(s.T(), req, 401, unauthorized) + } + + req = s.newRequest("PUT", path, `{"message": "Backup 100%"}`) + req.SetBasicAuth("admin", "pw") + doRequestAndExpect(s.T(), req, 403, forbiddenJSON) + + req = s.newRequest("PUT", path, `{"message": "Backup 100%", "title": "Backup"}`) + req.Header.Add("X-Gotify-Key", "Abackup") + res, err = client.Do(req) + assert.Nil(s.T(), err) + assert.Equal(s.T(), 200, res.StatusCode) + + req = s.newRequest("GET", "message", "") + req.SetBasicAuth("admin", "pw") + res, err = client.Do(req) + assert.Nil(s.T(), err) + assert.Equal(s.T(), 200, res.StatusCode) + msgs := &model.PagedMessages{} + json.NewDecoder(res.Body).Decode(&msgs) + if assert.Len(s.T(), msgs.Messages, 1) { + msg := msgs.Messages[0] + assert.Equal(s.T(), created.ID, msg.ID) + assert.Equal(s.T(), "Backup 100%", msg.Message) + assert.True(s.T(), created.Date.Equal(msg.Date)) + assert.NotNil(s.T(), msg.Updated) + } +} + func (s *IntegrationSuite) TestMaxBodyBytes() { s.db.User(2).AppWithToken(1, "Aapp") diff --git a/ui/src/message/Message.tsx b/ui/src/message/Message.tsx index 9ea99f5a3..dd533fa66 100644 --- a/ui/src/message/Message.tsx +++ b/ui/src/message/Message.tsx @@ -95,6 +95,7 @@ interface IProps { title: string; image?: string; date: string; + updated?: string; content: string; priority: number; appName: string; @@ -118,6 +119,7 @@ const Message = ({ fDelete, title, date, + updated, image, priority, content, @@ -179,6 +181,7 @@ const Message = ({ appName={appName} image={image} date={date} + updated={updated} /> ) : ( )} @@ -221,9 +225,10 @@ const HeaderWide = ({ appName, image, date, + updated, fDelete, title, -}: Pick) => { +}: Pick) => { const {classes} = useStyles(); return ( @@ -249,6 +254,7 @@ const HeaderWide = ({ + ) => { +}: Pick) => { const {classes} = useStyles(); return ( @@ -280,6 +287,7 @@ const HeaderSmall = ({ +
@@ -304,4 +312,12 @@ const HeaderSmall = ({ ); }; +const Edited = ({updated}: Pick) => + updated ? ( + + {' '} + (edited) + + ) : null; + export default Message; diff --git a/ui/src/message/Messages.tsx b/ui/src/message/Messages.tsx index 02c582ff3..34fe1c732 100644 --- a/ui/src/message/Messages.tsx +++ b/ui/src/message/Messages.tsx @@ -64,6 +64,7 @@ const Messages = observer(() => { onExpand={(expanded) => (expandedState.current[message.id] = expanded)} title={message.title} date={message.date} + updated={message.updated} appName={appStore.getName(message.appid)} expanded={expandedState.current[message.id] ?? false} content={message.message} diff --git a/ui/src/message/MessagesStore.ts b/ui/src/message/MessagesStore.ts index e72ac558d..bd8197852 100644 --- a/ui/src/message/MessagesStore.ts +++ b/ui/src/message/MessagesStore.ts @@ -80,6 +80,19 @@ export class MessagesStore { } }; + @action + public updateSingleMessage = (message: IMessage) => { + [AllMessages, message.appid] + .filter((appId) => this.exists(appId)) + .forEach((appId) => { + const messages = this.stateOf(appId).messages; + const index = messages.findIndex((existing) => existing.id === message.id); + if (index !== -1) { + messages[index] = message; + } + }); + }; + @action public removeByApp = async (appId: number) => { if (appId === AllMessages) { diff --git a/ui/src/message/WebSocketStore.ts b/ui/src/message/WebSocketStore.ts index 377403860..93eb73276 100644 --- a/ui/src/message/WebSocketStore.ts +++ b/ui/src/message/WebSocketStore.ts @@ -20,7 +20,7 @@ export class WebSocketStore { this.wsActive = true; const wsUrl = config.get('url').replace('http', 'ws').replace('https', 'wss'); - const ws = new WebSocket(wsUrl + 'stream'); + const ws = new WebSocket(wsUrl + 'stream?updates=true'); ws.onerror = (e) => { this.wsActive = false; diff --git a/ui/src/reactions.ts b/ui/src/reactions.ts index 1a5015c91..24678cfda 100644 --- a/ui/src/reactions.ts +++ b/ui/src/reactions.ts @@ -20,6 +20,10 @@ export const registerReactions = (stores: StoreMapping) => { const loadAll = () => { stores.wsStore.listen((message) => { + if (message.updated) { + stores.messagesStore.updateSingleMessage(message); + return; + } stores.messagesStore.publishSingleMessage(message); Notifications.notifyNewMessage(message); if (message.priority >= 4 && Date.now() > lastAudio + AUDIO_REPEAT_DELAY) { diff --git a/ui/src/tests/message.test.ts b/ui/src/tests/message.test.ts index d9b417277..addc09442 100644 --- a/ui/src/tests/message.test.ts +++ b/ui/src/tests/message.test.ts @@ -276,6 +276,66 @@ describe('Messages', () => { }); }); }); + describe('update a message', () => { + const progress = m('Backup running', 'Gotify Backup 40%'); + const done = m('Backup finished', 'Gotify Backup 100%'); + let id: number; + + const updateMessage = (msg: Partial, token: string) => + axios.put(`${gotify.url}/message/${id}`, msg, { + headers: {'X-Gotify-Key': token}, + }); + + it('creates a message', async () => { + id = (await createMessage(progress, backupServerToken)).data.id; + await expectMessages({ + all: [progress, backup2, linux3, windows3, backup1, windows1], + windows: [windows3, windows1], + linux: [linux3], + backup: [progress, backup2, backup1], + }); + expect(await count(page, '#messages .message .edited')).toBe(0); + }); + it('updates the message without reload', async () => { + await updateMessage(done, backupServerToken); + await waitForExists(page, '#messages .message .title', done.title); + expect(await extractMessages(6)).toEqual([ + done, + backup2, + linux3, + windows3, + backup1, + windows1, + ]); + expect(await count(page, '#messages .message .edited')).toBe(1); + }); + it('updates the message in the application view', async () => { + await navigate('Backup'); + await updateMessage(progress, backupServerToken); + await waitForExists(page, '#messages .message .title', progress.title); + expect(await extractMessages(3)).toEqual([progress, backup2, backup1]); + await updateMessage(done, backupServerToken); + await waitForExists(page, '#messages .message .title', done.title); + expect(await extractMessages(3)).toEqual([done, backup2, backup1]); + await navigate('All Messages'); + }); + it('keeps the update after reload', async () => { + await page.reload(); + await waitForExists(page, selector.heading(), 'All Messages'); + await expectMessages({ + all: [done, backup2, linux3, windows3, backup1, windows1], + windows: [windows3, windows1], + linux: [linux3], + backup: [done, backup2, backup1], + }); + expect(await count(page, '#messages .message .edited')).toBe(1); + }); + it('does not update a message of another application', async () => { + await expect(updateMessage(linux1, linuxServerToken)).rejects.toMatchObject({ + response: {status: 404}, + }); + }); + }); it('deletes all messages', async () => { await navigate('All Messages'); await page.click('#delete-all'); diff --git a/ui/src/types.ts b/ui/src/types.ts index c9f0324c4..fff4b6e1e 100644 --- a/ui/src/types.ts +++ b/ui/src/types.ts @@ -42,6 +42,7 @@ export interface IMessage { title: string; priority: number; date: string; + updated?: string; image?: string; extras?: IMessageExtras; } From 587b409eaefe746aed138b2c8bbdd5df3832ada8 Mon Sep 17 00:00:00 2001 From: EinfacheSache <69739334+EinfacheSache@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:53:36 +0100 Subject: [PATCH 2/2] feat: require updates to be allowed per application Updating messages is disabled by default. It has to be enabled per application with the new `allowMessageUpdate` setting, e.g. in the application's edit dialog in the web UI. Otherwise `PUT /message/{id}` returns 403. This keeps applications push-only unless the user explicitly allows more. An application whose token could be misused (e.g. an ssh login notifier) can't change its messages afterwards. On `PUT /application/{id}` an omitted `allowMessageUpdate` keeps the current value, so existing clients don't reset it. --- api/application.go | 11 ++++ api/application_test.go | 53 ++++++++++++++++++- api/message.go | 9 +++- api/message_test.go | 44 +++++++++++---- docs/spec.json | 15 +++++- model/application.go | 6 +++ router/router_test.go | 16 ++++-- ui/src/application/AppStore.ts | 2 +- ui/src/application/Applications.tsx | 11 +++- .../application/UpdateApplicationDialog.tsx | 24 ++++++++- ui/src/tests/application.test.ts | 23 ++++++++ ui/src/tests/message.test.ts | 19 +++++++ ui/src/types.ts | 1 + 13 files changed, 213 insertions(+), 21 deletions(-) diff --git a/api/application.go b/api/application.go index 0ef87ed18..1df3f642e 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 update its own messages with its application token. + // Defaults to false on create. When omitted on update, the current value is kept. + // + // example: false + AllowMessageUpdate *bool `form:"allowMessageUpdate" query:"allowMessageUpdate" json:"allowMessageUpdate"` // 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.AllowMessageUpdate != nil { + app.AllowMessageUpdate = *applicationParams.AllowMessageUpdate + } 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.AllowMessageUpdate != nil { + app.AllowMessageUpdate = *applicationParams.AllowMessageUpdate + } if applicationParams.SortKey != "" { app.SortKey = applicationParams.SortKey } diff --git a/api/application_test.go b/api/application_test.go index 197b9cb0c..fd549a2e2 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", "allowMessageUpdate":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_messageUpdatesDisabledByDefault() { + 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].AllowMessageUpdate) + } +} + +func (s *ApplicationSuite) Test_CreateApplication_allowMessageUpdate() { + s.db.User(5) + + test.WithUser(s.ctx, 5) + s.withFormData("name=app&allowMessageUpdate=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].AllowMessageUpdate) + } +} + +func (s *ApplicationSuite) Test_UpdateApplication_allowMessageUpdate() { + 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&allowMessageUpdate=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.AllowMessageUpdate) + } + + 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.AllowMessageUpdate, "omitting the field keeps the value") + } + + s.withFormData("name=other&allowMessageUpdate=false") + s.a.UpdateApplication(s.ctx) + if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) { + assert.False(s.T(), app.AllowMessageUpdate) + } +} diff --git a/api/message.go b/api/message.go index 23d44caa7..514d62291 100644 --- a/api/message.go +++ b/api/message.go @@ -402,6 +402,9 @@ func (a *MessageAPI) CreateMessage(ctx *gin.Context) { // // Update a message. // +// Updating has to be enabled per application (`allowMessageUpdate`), it is disabled +// by default. Otherwise 403 is returned. +// // Only the application that created the message can update it. The message keeps // its id and creation date. Title, message, priority and extras are replaced with // the values from the request body, the same defaults as for creating a message apply: @@ -456,11 +459,15 @@ func (a *MessageAPI) UpdateMessage(ctx *gin.Context) { } app := auth.GetApplication(ctx) + if app == nil || !app.AllowMessageUpdate { + ctx.AbortWithError(403, errors.New("updating messages is not enabled for this application")) + return + } msg, err := a.DB.GetMessageByID(id) if success := successOrAbort(ctx, 500, err); !success { return } - if app == nil || msg == nil || msg.ApplicationID != app.ID { + if msg == nil || msg.ApplicationID != app.ID { ctx.AbortWithError(404, errors.New("message does not exist")) return } diff --git a/api/message_test.go b/api/message_test.go index e3def59da..e2a6027c9 100644 --- a/api/message_test.go +++ b/api/message_test.go @@ -664,7 +664,7 @@ func (s *MessageSuite) Test_UpdateMessage() { app := s.db.User(4).NewAppWithTokenAndDefaultPriority(7, "app-token", 3) s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Title: "old", Message: "Backup 40%", Priority: 1, Date: created, Extras: []byte(`{"gotify::test":1}`)}) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"title": "Backup", "message": "Backup 100%", "priority": 2}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -687,7 +687,7 @@ func (s *MessageSuite) Test_UpdateMessage_usesApplicationDefaults() { s.db.CreateApplication(app) s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Title: "old", Message: "old", Priority: 1}) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -706,7 +706,7 @@ func (s *MessageSuite) Test_UpdateMessage_replacesExtras() { app := s.db.User(4).NewAppWithToken(7, "app-token") s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "approve?", Extras: []byte(`{"gotify::old":{"a":1}}`)}) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "approved", "extras": {"gotify::new":{"b":2}}}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -723,7 +723,7 @@ func (s *MessageSuite) Test_UpdateMessage_removesExtrasWhenOmitted() { app := s.db.User(4).NewAppWithToken(7, "app-token") s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "approve?", Extras: []byte(`{"gotify::old":{"a":1}}`)}) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "approved"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -741,7 +741,7 @@ func (s *MessageSuite) Test_UpdateMessage_ignoresAppID() { s.db.User(4).App(8) s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "old"}) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new", "appid": 8}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -758,7 +758,7 @@ func (s *MessageSuite) Test_UpdateMessage_messageOfOtherApplication() { app := s.db.User(4).NewAppWithToken(7, "app-token") s.db.User(4).App(8).Message(9) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -777,7 +777,7 @@ func (s *MessageSuite) Test_UpdateMessage_messageOfOtherUser() { app := s.db.User(4).NewAppWithToken(7, "app-token") s.db.User(5).App(8).Message(9) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -789,7 +789,7 @@ func (s *MessageSuite) Test_UpdateMessage_messageOfOtherUser() { } func (s *MessageSuite) Test_UpdateMessage_notExistingID() { - auth.RegisterApplication(s.ctx, s.db.User(4).NewAppWithToken(7, "app-token")) + auth.RegisterApplication(s.ctx, allowUpdates(s.db.User(4).NewAppWithToken(7, "app-token"))) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -801,7 +801,7 @@ func (s *MessageSuite) Test_UpdateMessage_notExistingID() { } func (s *MessageSuite) Test_UpdateMessage_invalidID() { - auth.RegisterApplication(s.ctx, s.db.User(4).NewAppWithToken(7, "app-token")) + auth.RegisterApplication(s.ctx, allowUpdates(s.db.User(4).NewAppWithToken(7, "app-token"))) s.ctx.Params = gin.Params{{Key: "id", Value: "string"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/string", strings.NewReader(`{"message": "new"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -815,7 +815,7 @@ func (s *MessageSuite) Test_UpdateMessage_failWhenNoMessage() { app := s.db.User(4).NewAppWithToken(7, "app-token") s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "old"}) - auth.RegisterApplication(s.ctx, app) + auth.RegisterApplication(s.ctx, allowUpdates(app)) s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"title": "new"}`)) s.ctx.Request.Header.Set("Content-Type", "application/json") @@ -829,6 +829,30 @@ func (s *MessageSuite) Test_UpdateMessage_failWhenNoMessage() { assert.Nil(s.T(), s.updatedMessage) } +func (s *MessageSuite) Test_UpdateMessage_notAllowedForApplication() { + app := s.db.User(4).NewAppWithToken(7, "app-token") + s.db.CreateMessage(&model.Message{ID: 9, ApplicationID: 7, Message: "old"}) + + auth.RegisterApplication(s.ctx, app) + s.ctx.Params = gin.Params{{Key: "id", Value: "9"}} + s.ctx.Request = httptest.NewRequest("PUT", "/message/9", strings.NewReader(`{"message": "new"}`)) + s.ctx.Request.Header.Set("Content-Type", "application/json") + + s.a.UpdateMessage(s.ctx) + + assert.Equal(s.T(), 403, s.recorder.Code) + msg, err := s.db.GetMessageByID(9) + assert.NoError(s.T(), err) + assert.Equal(s.T(), "old", msg.Message) + assert.Nil(s.T(), msg.Updated) + assert.Nil(s.T(), s.updatedMessage) +} + +func allowUpdates(app *model.Application) *model.Application { + app.AllowMessageUpdate = true + return app +} + func (s *MessageSuite) withURL(scheme, host, path, query string) { s.ctx.Request.URL = &url.URL{Path: path, RawQuery: query} s.ctx.Set("location", &url.URL{Scheme: scheme, Host: host}) diff --git a/docs/spec.json b/docs/spec.json index d3f297db4..b6d48c273 100644 --- a/docs/spec.json +++ b/docs/spec.json @@ -1650,7 +1650,7 @@ "appTokenQuery": [] } ], - "description": "Only the application that created the message can update it. The message keeps\nits id and creation date. Title, message, priority and extras are replaced with\nthe values from the request body, the same defaults as for creating a message apply:\nan omitted title or priority falls back to the application defaults and omitted\nextras are removed. Any \"appid\" in the body is ignored.\n\nClients connected to the stream with `updates=true` receive the updated message.", + "description": "Updating has to be enabled per application (`allowMessageUpdate`), it is disabled\nby default. Otherwise 403 is returned.\n\nOnly the application that created the message can update it. The message keeps\nits id and creation date. Title, message, priority and extras are replaced with\nthe values from the request body, the same defaults as for creating a message apply:\nan omitted title or priority falls back to the application defaults and omitted\nextras are removed. Any \"appid\" in the body is ignored.\n\nClients connected to the stream with `updates=true` receive the updated message.", "consumes": [ "application/json" ], @@ -2629,10 +2629,17 @@ "description", "internal", "image", + "allowMessageUpdate", "createdAt", "sortKey" ], "properties": { + "allowMessageUpdate": { + "description": "Whether the application may update its own messages with its application token.\nDisabled by default, it has to be enabled per application.", + "type": "boolean", + "x-go-name": "AllowMessageUpdate", + "example": false + }, "createdAt": { "description": "The date the application was created.", "type": "string", @@ -2714,6 +2721,12 @@ "name" ], "properties": { + "allowMessageUpdate": { + "description": "Whether the application may update 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": "AllowMessageUpdate", + "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..95eba1948 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 update its own messages with its application token. + // Disabled by default, it has to be enabled per application. + // + // required: true + // example: false + AllowMessageUpdate bool `gorm:"not null;default:false" form:"allowMessageUpdate" query:"allowMessageUpdate" json:"allowMessageUpdate"` // The date the application was created. // // read only: true diff --git a/router/router_test.go b/router/router_test.go index b29bb2091..2ad694f09 100644 --- a/router/router_test.go +++ b/router/router_test.go @@ -364,9 +364,15 @@ func (s *IntegrationSuite) TestSendMessage() { func (s *IntegrationSuite) TestUpdateMessage() { s.db.User(1).ClientWithToken(1, "Cclient") - s.db.User(1).AppWithToken(1, "Abackup") - s.db.User(1).AppWithToken(2, "Aother") - s.db.User(2).AppWithToken(3, "Aforeign") + for _, app := range []*model.Application{ + s.db.User(1).NewAppWithToken(1, "Abackup"), + s.db.User(1).NewAppWithToken(2, "Aother"), + s.db.User(2).NewAppWithToken(3, "Aforeign"), + } { + app.AllowMessageUpdate = true + assert.Nil(s.T(), s.db.UpdateApplication(app)) + } + s.db.User(1).AppWithToken(4, "Anotallowed") req := s.newRequest("POST", "message", `{"message": "Backup 40%", "title": "Backup"}`) req.Header.Add("X-Gotify-Key", "Abackup") @@ -391,6 +397,10 @@ func (s *IntegrationSuite) TestUpdateMessage() { req.Header.Add("X-Gotify-Key", "Abackup") doRequestAndExpect(s.T(), req, 404, notFound) + req = s.newRequest("PUT", path, `{"message": "Backup 100%"}`) + req.Header.Add("X-Gotify-Key", "Anotallowed") + doRequestAndExpect(s.T(), req, 403, `{"error":"Forbidden", "errorCode":403, "errorDescription":"updating messages is not enabled for this application"}`) + for _, token := range []string{"Cclient", "Ainvalid"} { req = s.newRequest("PUT", path, `{"message": "Backup 100%"}`) req.Header.Add("X-Gotify-Key", token) diff --git a/ui/src/application/AppStore.ts b/ui/src/application/AppStore.ts index a6fa32ba6..bff343e1c 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' | 'allowMessageUpdate' >): 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..6bce2ef65 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, allowMessageUpdate) => + appStore.update({ + ...toUpdateApp, + name, + description, + defaultPriority, + allowMessageUpdate, + }) } initialDescription={toUpdateApp?.description} initialName={toUpdateApp?.name} initialDefaultPriority={toUpdateApp?.defaultPriority} + initialAllowMessageUpdate={toUpdateApp?.allowMessageUpdate} /> )} {toRegenerateTokenApp != null && ( diff --git a/ui/src/application/UpdateApplicationDialog.tsx b/ui/src/application/UpdateApplicationDialog.tsx index a4d13fad8..eb433d5b9 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, + allowMessageUpdate: boolean + ) => Promise; initialName: string; initialDescription: string; initialDefaultPriority: number; + initialAllowMessageUpdate: boolean; } export const UpdateApplicationDialog = ({ initialName, initialDescription, initialDefaultPriority, + initialAllowMessageUpdate, fClose, fOnSubmit, }: IProps) => { const [name, setName] = useState(initialName); const [description, setDescription] = useState(initialDescription); const [defaultPriority, setDefaultPriority] = useState(initialDefaultPriority); + const [allowMessageUpdate, setAllowMessageUpdate] = useState(initialAllowMessageUpdate); const submitEnabled = name.length !== 0; const submitAndClose = async () => { - await fOnSubmit(name, description, defaultPriority); + await fOnSubmit(name, description, defaultPriority, allowMessageUpdate); fClose(); }; @@ -66,6 +76,16 @@ export const UpdateApplicationDialog = ({ onChange={(e) => setDefaultPriority(e)} fullWidth /> + setAllowMessageUpdate(e.target.checked)} + /> + } + label="Allow the application to update its own messages" + /> diff --git a/ui/src/tests/application.test.ts b/ui/src/tests/application.test.ts index 71ff65ac4..578cbe55d 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 updates', () => { + const $switch = '#app-dialog .allow-message-update 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/tests/message.test.ts b/ui/src/tests/message.test.ts index addc09442..214ea163a 100644 --- a/ui/src/tests/message.test.ts +++ b/ui/src/tests/message.test.ts @@ -286,6 +286,16 @@ describe('Messages', () => { headers: {'X-Gotify-Key': token}, }); + const allowMessageUpdate = async (name: string) => { + const apps = await axios.get(`${gotify.url}/application`, axiosAuth); + const app = apps.data.find((a) => a.name === name)!; + await axios.put( + `${gotify.url}/application/${app.id}`, + {...app, allowMessageUpdate: true}, + axiosAuth + ); + }; + it('creates a message', async () => { id = (await createMessage(progress, backupServerToken)).data.id; await expectMessages({ @@ -296,6 +306,15 @@ describe('Messages', () => { }); expect(await count(page, '#messages .message .edited')).toBe(0); }); + it('does not update when updates are not allowed for the application', async () => { + await expect(updateMessage(done, backupServerToken)).rejects.toMatchObject({ + response: {status: 403}, + }); + }); + it('allows updates for the applications', async () => { + await allowMessageUpdate('Backup'); + await allowMessageUpdate('Linux'); + }); it('updates the message without reload', async () => { await updateMessage(done, backupServerToken); await waitForExists(page, '#messages .message .title', done.title); diff --git a/ui/src/types.ts b/ui/src/types.ts index fff4b6e1e..46e254962 100644 --- a/ui/src/types.ts +++ b/ui/src/types.ts @@ -7,6 +7,7 @@ export interface IApplication { image: string; internal: boolean; defaultPriority: number; + allowMessageUpdate: boolean; lastUsed: string | null; createdAt: string; }