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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion server/channels/api4/apitestlib.go
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ func SetupConfigWithStoreMock(tb testing.TB, updateConfig func(cfg *model.Config
}

func SetupWithStoreMock(tb testing.TB) *TestHelper {
th := setupTestHelper(tb, testlib.GetMockStoreForSetupFunctions(), nil, nil, false, false, nil, nil)
th := setupTestHelper(tb, testlib.GetMockStoreForSetupFunctions(), nil, nil, false, false, useCustomPushNotificationServer, nil)
statusMock := mocks.StatusStore{}
statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil)
Expand All @@ -383,10 +383,15 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper {
return th
}

func useCustomPushNotificationServer(config *model.Config) {
*config.EmailSettings.PushNotificationServer = "https://push.example.com"
}

func SetupEnterpriseWithStoreMock(tb testing.TB, options ...app.Option) *TestHelper {
removeSpuriousErrors := func(config *model.Config) {
// If not set, you will receive an unactionable error in the console
*config.ServiceSettings.SiteURL = "http://localhost:8065"
useCustomPushNotificationServer(config)
}

th := setupTestHelper(tb, testlib.GetMockStoreForSetupFunctions(), nil, nil, true, false, removeSpuriousErrors, options)
Expand Down
10 changes: 10 additions & 0 deletions server/channels/api4/channel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6878,6 +6878,11 @@ func TestGetChannelModerations(t *testing.T) {
scheme := th.SetupTeamScheme(t)
scheme.DefaultChannelGuestRole = ""

// Restore the real store so helper cleanup (cache invalidation, license reload)
// doesn't run against the partial mock.
originalStore := th.App.Srv().Store()
t.Cleanup(func() { th.App.Srv().SetStore(originalStore) })

mockStore := mocks.Store{}

// Playbooks DB job requires a plugin mock
Expand Down Expand Up @@ -7034,6 +7039,11 @@ func TestPatchChannelModerations(t *testing.T) {
scheme := th.SetupTeamScheme(t)
scheme.DefaultChannelGuestRole = ""

// Restore the real store so helper cleanup (cache invalidation, license reload)
// doesn't run against the partial mock.
originalStore := th.App.Srv().Store()
t.Cleanup(func() { th.App.Srv().SetStore(originalStore) })

mockStore := mocks.Store{}

// Playbooks DB job requires a plugin mock
Expand Down
8 changes: 6 additions & 2 deletions server/channels/app/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,9 +261,13 @@ func SetupWithoutPreloadMigrations(tb testing.TB) *TestHelper {
return setupTestHelper(dbStore, mainHelper.GetSQLStore(), mainHelper.GetSQLSettings(), mainHelper.GetSearchEngine(), false, true, nil, nil, tb)
}

func useCustomPushNotificationServer(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = "https://push.example.com"
}

func SetupWithStoreMock(tb testing.TB) *TestHelper {
mockStore := testlib.GetMockStoreForSetupFunctions()
th := setupTestHelper(mockStore, mainHelper.GetSQLStore(), mainHelper.GetSQLSettings(), mainHelper.GetSearchEngine(), false, false, nil, nil, tb)
th := setupTestHelper(mockStore, mainHelper.GetSQLStore(), mainHelper.GetSQLSettings(), mainHelper.GetSearchEngine(), false, false, useCustomPushNotificationServer, nil, tb)
statusMock := mocks.StatusStore{}
statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil)
Expand All @@ -284,7 +288,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper {

func SetupEnterpriseWithStoreMock(tb testing.TB) *TestHelper {
mockStore := testlib.GetMockStoreForSetupFunctions()
th := setupTestHelper(mockStore, mainHelper.GetSQLStore(), mainHelper.GetSQLSettings(), mainHelper.GetSearchEngine(), true, false, nil, nil, tb)
th := setupTestHelper(mockStore, mainHelper.GetSQLStore(), mainHelper.GetSQLSettings(), mainHelper.GetSearchEngine(), true, false, useCustomPushNotificationServer, nil, tb)
statusMock := mocks.StatusStore{}
statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil)
Expand Down
10 changes: 1 addition & 9 deletions server/channels/app/notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,7 @@ func (a *App) canSendPushNotifications() bool {
}

pushServer := *a.Config().EmailSettings.PushNotificationServer
// Check for MHPNS servers (both current and legacy DNS aliases)
isMHPNSServer := pushServer == model.MHPNS ||
pushServer == model.MHPNSLegacyUS ||
pushServer == model.MHPNSLegacyDE ||
pushServer == model.MHPNSGlobal ||
pushServer == model.MHPNSUS ||
pushServer == model.MHPNSEU ||
pushServer == model.MHPNSAP
if license := a.Srv().License(); isMHPNSServer && (license == nil || !*license.Features.MHPNS) {
if model.IsMHPNSEndpoint(pushServer) && !a.Srv().License().HasMHPNS() {
a.Log().LogM(mlog.MlvlNotificationWarn, "Push notifications are disabled - license missing",
mlog.String("status", model.NotificationStatusNotSent),
mlog.String("reason", "push_disabled_license"),
Expand Down
79 changes: 79 additions & 0 deletions server/channels/app/push_notification_server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package app

import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
)

// syncPushNotificationServerWithLicense switches EmailSettings.PushNotificationServer to the
// hosted push notification service (MHPNS) endpoint when the license grants MHPNS access, and
// back to the test (TPNS) endpoint when it no longer does. It runs on license changes, on
// server start, and when this node becomes the cluster leader.
//
// The contract: promote only from exact TPNS to the Global endpoint; on entitlement loss,
// revert any Mattermost-hosted production endpoint (global, regional, or legacy) to TPNS, so
// a lapsed license never leaves push pointing at an endpoint that refuses to send. Custom
// endpoints and env-managed values are never touched. The sync stays stateless because both
// directions derive entirely from the current config value and the license.
func (s *Server) syncPushNotificationServerWithLicense() {
if !s.IsLeader() {
return
}

license := s.License()
// Cloud config is centrally managed; never rewrite it here.
if license.IsCloud() {
return
}

if s.platform.IsConfigReadOnly() {
return
}

// Respect an environment-variable override on the setting. The config store re-applies env
// overrides on save anyway, so without this guard a save would be futile and only produce
// spurious audit records, logs, and cluster config traffic on every license event.
if emailOverrides, ok := s.platform.GetEnvironmentOverrides()["EmailSettings"].(map[string]any); ok {
if _, overridden := emailOverrides["PushNotificationServer"]; overridden {
return
}
}

entitled := license.HasMHPNS()

// Decide and mutate on the same snapshot so a concurrent config write between the
// decision and the save can't be stomped with a stale value. The residual race between
// Clone and Set is inherent to every SaveConfig caller.
cfg := s.platform.Config().Clone()
current := *cfg.EmailSettings.PushNotificationServer

var target string
switch {
case entitled && current == model.GenericNotificationServer:
target = model.MHPNSGlobal
case !entitled && model.IsMHPNSEndpoint(current):
target = model.GenericNotificationServer
default:
return
}

cfg.EmailSettings.PushNotificationServer = model.NewPointer(target)
if _, _, appErr := s.platform.SaveConfig(cfg, true); appErr != nil {
mlog.Warn("Failed to switch push notification server for license entitlement",
mlog.String("old", current), mlog.String("new", target), mlog.Err(appErr))
return
}
mlog.Info("Automatically switched push notification server based on license entitlement",
mlog.String("old", current), mlog.String("new", target))

rctx := request.EmptyContext(s.Log())
appInstance := New(ServerConnector(s.Channels()))
rec := appInstance.MakeAuditRecord(rctx, model.AuditEventAutoSelectPushNotificationServer, model.AuditStatusSuccess)
model.AddEventParameterToAuditRec(rec, "old_push_notification_server", current)
model.AddEventParameterToAuditRec(rec, "new_push_notification_server", target)
appInstance.LogAuditRec(rctx, rec, nil)
}
192 changes: 192 additions & 0 deletions server/channels/app/push_notification_server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package app

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"

"github.com/mattermost/mattermost/server/public/model"
emailmocks "github.com/mattermost/mattermost/server/v8/channels/app/email/mocks"
clustermocks "github.com/mattermost/mattermost/server/v8/einterfaces/mocks"
)

func TestSyncPushNotificationServerWithLicense(t *testing.T) {
// Not parallel: subtests mutate the license, shared config, and environment.
th := Setup(t)

licenseWithMHPNS := model.NewTestLicense("mhpns")
licenseWithoutMHPNS := model.NewTestLicense()
licenseWithoutMHPNS.Features.MHPNS = model.NewPointer(false)

tests := []struct {
name string
license *model.License
initialServer string
expectedServer string
}{
{
name: "entitled license switches TPNS to Global",
license: licenseWithMHPNS,
initialServer: model.GenericNotificationServer,
expectedServer: model.MHPNSGlobal,
},
{
name: "entitlement removed reverts Global to TPNS",
license: licenseWithoutMHPNS,
initialServer: model.MHPNSGlobal,
expectedServer: model.GenericNotificationServer,
},
{
name: "license removed reverts Global to TPNS",
license: nil,
initialServer: model.MHPNSGlobal,
expectedServer: model.GenericNotificationServer,
},
{
name: "entitled license leaves custom endpoint untouched",
license: licenseWithMHPNS,
initialServer: "https://push.example.com",
expectedServer: "https://push.example.com",
},
{
name: "entitled license leaves regional endpoint untouched",
license: licenseWithMHPNS,
initialServer: model.MHPNSEU,
expectedServer: model.MHPNSEU,
},
{
name: "entitled license leaves Global untouched",
license: licenseWithMHPNS,
initialServer: model.MHPNSGlobal,
expectedServer: model.MHPNSGlobal,
},
{
name: "unentitled license reverts regional endpoint (MHPNSUS) to TPNS",
license: licenseWithoutMHPNS,
initialServer: model.MHPNSUS,
expectedServer: model.GenericNotificationServer,
},
{
name: "unentitled license reverts legacy endpoint (MHPNSLegacyDE) to TPNS",
license: licenseWithoutMHPNS,
initialServer: model.MHPNSLegacyDE,
expectedServer: model.GenericNotificationServer,
},
{
name: "unentitled license leaves TPNS untouched",
license: licenseWithoutMHPNS,
initialServer: model.GenericNotificationServer,
expectedServer: model.GenericNotificationServer,
},
{
name: "unentitled license leaves custom endpoint untouched",
license: licenseWithoutMHPNS,
initialServer: "https://push.example.com",
expectedServer: "https://push.example.com",
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
th.App.Srv().SetLicense(nil)
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = tc.initialServer
*cfg.EmailSettings.SendPushNotifications = true
})

// Setting the license fires the listener registered in NewServer,
// which runs syncPushNotificationServerWithLicense.
th.App.Srv().SetLicense(tc.license)

cfg := th.App.Config()
assert.Equal(t, tc.expectedServer, *cfg.EmailSettings.PushNotificationServer)
assert.True(t, *cfg.EmailSettings.SendPushNotifications, "SendPushNotifications must never be modified")
})
}

t.Run("direct call switches TPNS to Global on the startup path", func(t *testing.T) {
th.App.Srv().SetLicense(licenseWithMHPNS)
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = model.GenericNotificationServer
})

th.Server.syncPushNotificationServerWithLicense()

assert.Equal(t, model.MHPNSGlobal, *th.App.Config().EmailSettings.PushNotificationServer)
})

t.Run("license with nil MHPNS feature is unentitled and reverts Global to TPNS", func(t *testing.T) {
license := model.NewTestLicense()
th.App.Srv().SetLicense(license)
// SetLicense normalizes feature defaults, back-filling any nil pointer, so a license
// with a nil MHPNS can only reach the sync through the direct path. Clear the field
// on the stored license to prove the entitlement check is nil-safe and treats the
// license as unentitled. Restore it afterwards: license logging during teardown
// dereferences every feature pointer via Features.ToMap.
license.Features.MHPNS = nil
t.Cleanup(func() { license.Features.MHPNS = model.NewPointer(false) })
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = model.MHPNSGlobal
})

th.Server.syncPushNotificationServerWithLicense()

assert.Equal(t, model.GenericNotificationServer, *th.App.Config().EmailSettings.PushNotificationServer)
})

t.Run("environment override leaves setting untouched", func(t *testing.T) {
t.Setenv("MM_EMAILSETTINGS_PUSHNOTIFICATIONSERVER", model.GenericNotificationServer)

// The config value alone can't prove the env-override guard fired: a save of this
// config would be a no-op anyway, because the store re-applies env overrides and
// skips config listeners when the effective config is unchanged. The one side
// effect a futile save cannot avoid is cluster propagation — SaveConfig calls
// ConfigChanged on the cluster interface unconditionally — so probe that to prove
// the guard returned before saving.
clusterMock := &clustermocks.ClusterInterface{}
clusterMock.On("IsLeader").Return(true).Maybe()
clusterMock.On("GetClusterId").Return("").Maybe()
clusterMock.On("SendClusterMessage", mock.Anything).Return().Maybe()
clusterMock.On("RegisterClusterMessageHandler", mock.Anything, mock.Anything).Return().Maybe()
clusterMock.On("StopInterNodeCommunication").Return().Maybe()
clusterMock.On("Shutdown").Return().Maybe()
clusterMock.On("ConfigChanged", mock.Anything, mock.Anything, mock.Anything).Return(nil).Maybe()

// The subtest needs its own harness so the mock is installed before the platform
// starts; swapping the cluster interface mid-test races with platform goroutines
// that read it. Setup also isolates the env var set above.
envTh := SetupWithClusterMock(t, clusterMock)

envTh.App.Srv().SetLicense(licenseWithMHPNS)
envTh.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = model.GenericNotificationServer
})

envTh.Server.syncPushNotificationServerWithLicense()

clusterMock.AssertNotCalled(t, "ConfigChanged", mock.Anything, mock.Anything, mock.Anything)
assert.Equal(t, model.GenericNotificationServer, *envTh.App.Config().EmailSettings.PushNotificationServer)
})

t.Run("reverting hosted endpoint does not re-init email batching", func(t *testing.T) {
originalEmailService := th.App.Srv().EmailService
t.Cleanup(func() {
th.App.Srv().EmailService = originalEmailService
})

emailServiceMock := emailmocks.ServiceInterface{}
th.App.Srv().EmailService = &emailServiceMock

th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.EmailSettings.PushNotificationServer = model.MHPNSGlobal
})
th.App.Srv().SetLicense(nil)

emailServiceMock.AssertNotCalled(t, "InitEmailBatching")
assert.Equal(t, model.GenericNotificationServer, *th.App.Config().EmailSettings.PushNotificationServer)
})
}
Loading
Loading