Files
mostlymatter/api4/license_test.go
Harshil Sharma e4aa729a0c MM-34437 Preventing infinite trial requests (#17472)
* MM-34434: Added 'is_trial' boolean to all trial license requests and to the License struct.

* MM-34434: Generalized the concept of a license request.

* MM-34434: Verifies JSON field of license instance is set.

* MM-34434: Added missing client param.

* MM-34434: Added some tests of the request trial API endpoint.

* MM-34434: Removed comment.

* fix broken test (#17348)

* Add missing wrapped errors (#17339)

* Improve document extraction and including a document extraction command (#17183)

* Add extract documents content command

* Adding the extraction command and making the pure go pdf library as secondary option

* Improving the memory usage and docextractor interface

* Enable content extraction by default in all the instances

* Tiny improvement on archive indexing

* Adding App interface generation and the opentracing layer

* Fixing linter errors

* Addressing PR review comments

* Addressing PR review comments

* Update en.json (#17356)

Automatic Merge

* adding new feature flag (#17308)

Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.local>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>

* Bump no_output_timeout to 2 hours (#17358)

* log invalid username (#17345)

Automatic Merge

* MM-34434: Added missing client param.

MM-34434: Added some tests of the request trial API endpoint.

MM-34434: Removed comment.

* MM-34434: Switched to a hard-coded true value.

* MM-34434: Reverts test change.

* MM-34434: Removes unnecessary field.

* MM-34434: Tests that is_trial is hard-coded by TrialLicenseRequest.

* MM-34434: Removed accidental commit.

* MM-34434: Removes unnecessary is_trial key from JSON payload.

* MM-34434: Reverts to old pointer receiver variable name.

* MM-34434: Removes test.

* #MM-34437 Initialized license service

* ##MM-34437 Verified at all points if server is trial elligible

* WIp

* #MM-34437 removed unused commented code

* MM-34437 make a log less severe

* #MM-34437 generated einterface mocks

* #MM-34437 added license on new file

* #MM-34437 removed unused translation

* #MM-34437 some refactoring

* Update api4/license.go

* Update api4/license.go

* #MM-34437 made a variable name consistent

* #MM-34437 Added mocks for lince validator

* #M--34437 Added license validator test framework

* #MM-34437 Renamed isTrial method to isTrialLicense to avoid conflict with newlya dded field

* #M--34437 Allowed sales-sanctioned trials

* #MM-34437 fixed trial license API tests

* Added tests for add license API

* #MM-34437 fixed ValidateLicense test

* #MM-34437 Added util tests

* #MM-34437 using NoError for checking no error

* #MM-34437 using NoError for checking no error

* Added dummy piblic key for testing

* Fixed tests

* #MM-34437 udpaetd trial license URL for testing

* #MM-34437 adjusted times for licences generated through admin portal

* Reverted test-only changes

Co-authored-by: Martin Kraft <martin@upspin.org>
Co-authored-by: Hossein <hahmadia@users.noreply.github.com>
Co-authored-by: Ben Schumacher <ben.schumacher@mattermost.com>
Co-authored-by: Jesús Espino <jespinog@gmail.com>
Co-authored-by: Amy Blais <amy_blais@hotmail.com>
Co-authored-by: Ben Cooke <benkcooke@gmail.com>
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.local>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Co-authored-by: Agniva De Sarker <agnivade@yahoo.co.in>
Co-authored-by: Max Erenberg <max.erenberg@mattermost.com>
2021-06-17 17:37:34 +05:30

233 строки
7.4 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package api4
import (
"encoding/json"
"net/http"
"testing"
"time"
"github.com/mattermost/mattermost-server/v5/einterfaces/mocks"
"github.com/mattermost/mattermost-server/v5/utils"
mocks2 "github.com/mattermost/mattermost-server/v5/utils/mocks"
"github.com/mattermost/mattermost-server/v5/utils/testutils"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v5/model"
)
func TestGetOldClientLicense(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
license, resp := Client.GetOldClientLicense("")
CheckNoError(t, resp)
require.NotEqual(t, license["IsLicensed"], "", "license not returned correctly")
Client.Logout()
_, resp = Client.GetOldClientLicense("")
CheckNoError(t, resp)
_, err := Client.DoApiGet("/license/client", "")
require.NotNil(t, err, "get /license/client did not return an error")
require.Equal(t, err.StatusCode, http.StatusNotImplemented,
"expected 501 Not Implemented")
_, err = Client.DoApiGet("/license/client?format=junk", "")
require.NotNil(t, err, "get /license/client?format=junk did not return an error")
require.Equal(t, err.StatusCode, http.StatusBadRequest,
"expected 400 Bad Request")
license, resp = th.SystemAdminClient.GetOldClientLicense("")
CheckNoError(t, resp)
require.NotEmpty(t, license["IsLicensed"], "license not returned correctly")
}
func TestUploadLicenseFile(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
LocalClient := th.LocalClient
t.Run("as system user", func(t *testing.T) {
ok, resp := Client.UploadLicenseFile([]byte{})
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
ok, resp := c.UploadLicenseFile([]byte{})
CheckBadRequestStatus(t, resp)
require.False(t, ok)
}, "as system admin user")
t.Run("as restricted system admin user", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := th.SystemAdminClient.UploadLicenseFile([]byte{})
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
t.Run("restricted admin setting not honoured through local client", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := LocalClient.UploadLicenseFile([]byte{})
CheckBadRequestStatus(t, resp)
require.False(t, ok)
})
t.Run("server has already gone through trial", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = false })
mockLicenseValidator := mocks2.LicenseValidatorIface{}
defer testutils.ResetLicenseValidator()
//startTimestamp, err := time.Parse("2 Jan 2006 3:04 pm", "1 Jan 2021 12:00 am")
//require.Nil(t, err)
userCount := 100
mills := model.GetMillis()
license := model.License{
Id: "AAAAAAAAAAAAAAAAAAAAAAAAAA",
Features: &model.Features{
Users: &userCount,
},
Customer: &model.Customer{
Name: "Test",
},
StartsAt: mills + 100,
ExpiresAt: mills + 100 + (30*(time.Hour*24) + (time.Hour * 8)).Milliseconds(),
}
mockLicenseValidator.On("LicenseFromBytes", mock.Anything).Return(&license, nil).Once()
licenseBytes, _ := json.Marshal(license)
licenseStr := string(licenseBytes)
mockLicenseValidator.On("ValidateLicense", mock.Anything).Return(true, licenseStr)
utils.LicenseValidator = &mockLicenseValidator
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(false, nil).Once()
th.App.Srv().LicenseManager = licenseManagerMock
ok, resp := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa"))
require.False(t, ok)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
require.Equal(t, "api.license.request-trial.can-start-trial.not-allowed", resp.Error.Id)
})
t.Run("allow uploading sanctioned trials even if server already gone through trial", func(t *testing.T) {
mockLicenseValidator := mocks2.LicenseValidatorIface{}
defer testutils.ResetLicenseValidator()
userCount := 100
mills := model.GetMillis()
license := model.License{
Id: "PPPPPPPPPPPPPPPPPPPPPPPPPP",
Features: &model.Features{
Users: &userCount,
},
Customer: &model.Customer{
Name: "Test",
},
IsTrial: true,
StartsAt: mills + 100,
ExpiresAt: mills + 100 + (29*(time.Hour*24) + (time.Hour * 8)).Milliseconds(),
}
mockLicenseValidator.On("LicenseFromBytes", mock.Anything).Return(&license, nil).Once()
licenseBytes, _ := json.Marshal(license)
licenseStr := string(licenseBytes)
mockLicenseValidator.On("ValidateLicense", mock.Anything).Return(true, licenseStr)
utils.LicenseValidator = &mockLicenseValidator
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(false, nil).Once()
th.App.Srv().LicenseManager = licenseManagerMock
ok, resp := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa"))
require.False(t, ok)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Nil(t, resp.Error)
})
}
func TestRemoveLicenseFile(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
LocalClient := th.LocalClient
t.Run("as system user", func(t *testing.T) {
ok, resp := Client.RemoveLicenseFile()
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
ok, resp := c.RemoveLicenseFile()
CheckNoError(t, resp)
require.True(t, ok)
}, "as system admin user")
t.Run("as restricted system admin user", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := th.SystemAdminClient.RemoveLicenseFile()
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
t.Run("restricted admin setting not honoured through local client", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := LocalClient.RemoveLicenseFile()
CheckNoError(t, resp)
require.True(t, ok)
})
}
func TestRequestTrialLicense(t *testing.T) {
th := Setup(t)
defer th.TearDown()
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(true, nil)
th.App.Srv().LicenseManager = licenseManagerMock
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "http://localhost:8065/" })
t.Run("permission denied", func(t *testing.T) {
ok, resp := th.Client.RequestTrialLicense(1000)
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
t.Run("blank site url", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "" })
defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "http://localhost:8065/" })
ok, resp := th.SystemAdminClient.RequestTrialLicense(1000)
CheckBadRequestStatus(t, resp)
require.Equal(t, "api.license.request_trial_license.no-site-url.app_error", resp.Error.Id)
require.False(t, ok)
})
t.Run("trial license user count less than current users", func(t *testing.T) {
ok, resp := th.SystemAdminClient.RequestTrialLicense(1)
CheckBadRequestStatus(t, resp)
require.Equal(t, "api.license.add_license.unique_users.app_error", resp.Error.Id)
require.False(t, ok)
})
}