) => {
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;
}