Merge branch 'master' of github.com:mattermost/mattermost-server into MM-50966-in-product-expansion-backend

Этот коммит содержится в:
Conor Macpherson
2023-04-12 14:26:59 -04:00
родитель 4bd3701363 c3e69e97e4
Коммит dcdc9c5f4b
1198 изменённых файлов: 25928 добавлений и 23781 удалений

Просмотреть файл

@@ -177,7 +177,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent
*cfg.PasswordSettings.Symbol = false
*cfg.PasswordSettings.Number = false
*cfg.ServiceSettings.ListenAddress = ":0"
*cfg.ServiceSettings.ListenAddress = "localhost:0"
})
if err := th.Server.Start(); err != nil {
panic(err)

Просмотреть файл

@@ -60,7 +60,21 @@ func (api *API) InitCloud() {
api.BaseRoutes.Cloud.Handle("/delete-workspace", api.APISessionRequired(selfServeDeleteWorkspace)).Methods(http.MethodDelete)
}
func ensureCloudInterface(c *Context, where string) bool {
cloud := c.App.Cloud()
if cloud == nil {
c.Err = model.NewAppError(where, "api.server.cws.needs_enterprise_edition", nil, "", http.StatusBadRequest)
return false
}
return true
}
func getSubscription(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getSubscription")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.getSubscription", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -102,6 +116,10 @@ func getSubscription(c *Context, w http.ResponseWriter, r *http.Request) {
}
func changeSubscription(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.changeSubscription")
if !ensured {
return
}
userId := c.AppContext.Session().UserId
if !c.App.Channels().License().IsCloud() {
@@ -176,6 +194,11 @@ func changeSubscription(c *Context, w http.ResponseWriter, r *http.Request) {
}
func requestCloudTrial(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.requestCloudTrial")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -218,13 +241,8 @@ func requestCloudTrial(c *Context, w http.ResponseWriter, r *http.Request) {
}
func validateBusinessEmail(c *Context, w http.ResponseWriter, r *http.Request) {
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.validateBusinessEmail", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
}
if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteBilling) {
c.SetPermissionError(model.PermissionSysconsoleWriteBilling)
ensured := ensureCloudInterface(c, "Api4.validateBusinessEmail")
if !ensured {
return
}
@@ -263,6 +281,11 @@ func validateBusinessEmail(c *Context, w http.ResponseWriter, r *http.Request) {
}
func validateWorkspaceBusinessEmail(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.validateWorkspaceBusinessEmail")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.validateWorkspaceBusinessEmail", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -309,6 +332,11 @@ func validateWorkspaceBusinessEmail(c *Context, w http.ResponseWriter, r *http.R
}
func getSelfHostedProducts(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getSelfHostedProducts")
if !ensured {
return
}
products, err := c.App.Cloud().GetSelfHostedProducts(c.AppContext.Session().UserId)
if err != nil {
c.Err = model.NewAppError("Api4.getSelfHostedProducts", "api.cloud.request_error", nil, "", http.StatusInternalServerError).Wrap(err)
@@ -343,6 +371,11 @@ func getSelfHostedProducts(c *Context, w http.ResponseWriter, r *http.Request) {
}
func getCloudProducts(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getCloudProducts")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.getCloudProducts", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -384,6 +417,11 @@ func getCloudProducts(c *Context, w http.ResponseWriter, r *http.Request) {
}
func getCloudLimits(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getCloudLimits")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.getCloudLimits", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -405,6 +443,11 @@ func getCloudLimits(c *Context, w http.ResponseWriter, r *http.Request) {
}
func getCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getCloudCustomer")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.getCloudCustomer", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -432,6 +475,11 @@ func getCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) {
// getLicenseSelfServeStatus makes check for the license in the CWS self-serve portal and establishes if the license is renewable, expandable etc.
func getLicenseSelfServeStatus(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getLicenseSelfServeStatus")
if !ensured {
return
}
if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageLicenseInformation) {
c.SetPermissionError(model.PermissionManageLicenseInformation)
return
@@ -460,6 +508,11 @@ func getLicenseSelfServeStatus(c *Context, w http.ResponseWriter, r *http.Reques
}
func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.updateCloudCustomer")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.updateCloudCustomer", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -498,6 +551,11 @@ func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) {
}
func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.updateCloudCustomerAddress")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.updateCloudCustomerAddress", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -536,6 +594,11 @@ func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Reque
}
func createCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.createCustomerPayment")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.createCustomerPayment", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -567,6 +630,11 @@ func createCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) {
}
func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.confirmCustomerPayment")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.confirmCustomerPayment", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -604,6 +672,11 @@ func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request)
}
func getInvoicesForSubscription(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getInvoicesForSubscription")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.getInvoicesForSubscription", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -630,6 +703,11 @@ func getInvoicesForSubscription(c *Context, w http.ResponseWriter, r *http.Reque
}
func getSubscriptionInvoicePDF(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.getSubscriptionInvoicePDF")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.getSubscriptionInvoicePDF", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -665,6 +743,11 @@ func getSubscriptionInvoicePDF(c *Context, w http.ResponseWriter, r *http.Reques
}
func handleCWSWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.handleCWSWebhook")
if !ensured {
return
}
if !c.App.Channels().License().IsCloud() {
c.Err = model.NewAppError("Api4.handleCWSWebhook", "api.cloud.license_error", nil, "", http.StatusForbidden)
return
@@ -765,12 +848,12 @@ func handleCWSWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
}
func handleCheckCWSConnection(c *Context, w http.ResponseWriter, r *http.Request) {
cloud := c.App.Cloud()
if cloud == nil {
c.Err = model.NewAppError("Api4.handleCWSHealthCheck", "api.server.cws.needs_enterprise_edition", nil, "", http.StatusBadRequest)
ensured := ensureCloudInterface(c, "Api4.handleCheckCWSConnection")
if !ensured {
return
}
if err := cloud.CheckCWSConnection(c.AppContext.Session().UserId); err != nil {
if err := c.App.Cloud().CheckCWSConnection(c.AppContext.Session().UserId); err != nil {
c.Err = model.NewAppError("Api4.handleCWSHealthCheck", "api.server.cws.health_check.app_error", nil, "CWS Server is not available.", http.StatusInternalServerError)
return
}
@@ -779,6 +862,11 @@ func handleCheckCWSConnection(c *Context, w http.ResponseWriter, r *http.Request
}
func selfServeDeleteWorkspace(c *Context, w http.ResponseWriter, r *http.Request) {
ensured := ensureCloudInterface(c, "Api4.selfServeDeleteWorkspace")
if !ensured {
return
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
c.Err = model.NewAppError("Api4.selfServeDeleteWorkspace", "api.cloud.app_error", nil, err.Error(), http.StatusBadRequest)

Просмотреть файл

@@ -20,6 +20,15 @@ func Test_getCloudLimits(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
cloud := &mocks.CloudInterface{}
cloud.Mock.On("GetCloudLimits", mock.Anything).Return(nil, errors.New("Unable to get limits"))
cloudImpl := th.App.Srv().Cloud
defer func() {
th.App.Srv().Cloud = cloudImpl
}()
th.App.Srv().Cloud = cloud
th.App.Srv().RemoveLicense()
th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
@@ -34,6 +43,15 @@ func Test_getCloudLimits(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
cloud := &mocks.CloudInterface{}
cloud.Mock.On("GetCloudLimits", mock.Anything).Return(nil, errors.New("Unable to get limits"))
cloudImpl := th.App.Srv().Cloud
defer func() {
th.App.Srv().Cloud = cloudImpl
}()
th.App.Srv().Cloud = cloud
th.App.Srv().SetLicense(model.NewTestLicense())
th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
@@ -310,30 +328,6 @@ func Test_requestTrial(t *testing.T) {
}
func Test_validateBusinessEmail(t *testing.T) {
t.Run("Returns forbidden for non admin executors", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
invalidEmail := model.ValidateBusinessEmailRequest{Email: "invalid@gmail.com"}
th.App.Srv().SetLicense(model.NewTestLicense("cloud"))
cloud := mocks.CloudInterface{}
cloud.Mock.On("ValidateBusinessEmail", th.SystemAdminUser.Id, invalidEmail.Email).Return(errors.New("invalid email"))
cloudImpl := th.App.Srv().Cloud
defer func() {
th.App.Srv().Cloud = cloudImpl
}()
th.App.Srv().Cloud = &cloud
res, err := th.Client.ValidateBusinessEmail(&invalidEmail)
require.Error(t, err)
require.Equal(t, http.StatusForbidden, res.StatusCode, "403")
})
t.Run("Returns forbidden for invalid business email", func(t *testing.T) {
th := Setup(t).InitBasic()

Просмотреть файл

@@ -353,7 +353,6 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) {
commandArgs.UserId = c.AppContext.Session().UserId
commandArgs.T = c.AppContext.T
commandArgs.SiteURL = c.GetSiteURLHeader()
commandArgs.Session = *c.AppContext.Session()
response, err := c.App.ExecuteCommand(c.AppContext, &commandArgs)
if err != nil {
@@ -424,7 +423,6 @@ func listCommandAutocompleteSuggestions(c *Context, w http.ResponseWriter, r *ht
RootId: query.Get("root_id"),
UserId: c.AppContext.Session().UserId,
T: c.AppContext.T,
Session: *c.AppContext.Session(),
SiteURL: c.GetSiteURLHeader(),
Command: userInput,
}

Просмотреть файл

@@ -62,7 +62,7 @@ func upsertDraft(c *Context, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(dt); err != nil {
mlog.Warn("Error while writing response", mlog.Err(err))
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
@@ -94,7 +94,7 @@ func getDrafts(c *Context, w http.ResponseWriter, r *http.Request) {
}
if err := json.NewEncoder(w).Encode(drafts); err != nil {
mlog.Warn("Error while writing response", mlog.Err(err))
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}

Просмотреть файл

@@ -36,12 +36,13 @@ func (api *API) InitHostedCustomer() {
api.BaseRoutes.HostedCustomer.Handle("/invoices", api.APISessionRequired(selfHostedInvoices)).Methods("GET")
// GET /api/v4/hosted_customer/invoices/{invoice_id:in_[A-Za-z0-9]+}/pdf
api.BaseRoutes.HostedCustomer.Handle("/invoices/{invoice_id:in_[A-Za-z0-9]+}/pdf", api.APISessionRequired(selfHostedInvoicePDF)).Methods("GET")
api.BaseRoutes.HostedCustomer.Handle("/subscribe-newsletter", api.APIHandler(handleSubscribeToNewsletter)).Methods(http.MethodPost)
}
func ensureSelfHostedAdmin(c *Context, where string) {
cloud := c.App.Cloud()
if cloud == nil {
c.Err = model.NewAppError(where, "api.server.cws.needs_enterprise_edition", nil, "", http.StatusBadRequest)
ensured := ensureCloudInterface(c, where)
if !ensured {
return
}
@@ -317,3 +318,33 @@ func selfHostedInvoicePDF(c *Context, w http.ResponseWriter, r *http.Request) {
r,
)
}
func handleSubscribeToNewsletter(c *Context, w http.ResponseWriter, r *http.Request) {
const where = "Api4.handleSubscribeToNewsletter"
ensured := ensureCloudInterface(c, where)
if !ensured {
return
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
c.Err = model.NewAppError(where, "api.cloud.app_error", nil, "", http.StatusBadRequest).Wrap(err)
return
}
req := new(model.SubscribeNewsletterRequest)
err = json.Unmarshal(bodyBytes, req)
if err != nil {
c.Err = model.NewAppError(where, "api.cloud.request_error", nil, "", http.StatusBadRequest).Wrap(err)
return
}
req.ServerID = c.App.Srv().TelemetryId()
if err := c.App.Cloud().SubscribeToNewsletter("", req); err != nil {
c.Err = model.NewAppError(where, "api.server.cws.subscribe_to_newsletter.app_error", nil, "CWS Server failed to subscribe to newsletter.", http.StatusInternalServerError).Wrap(err)
return
}
ReturnStatusOK(w)
}

Просмотреть файл

@@ -210,11 +210,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
var trialRequest struct {
Users int `json:"users"`
TermsAccepted bool `json:"terms_accepted"`
ReceiveEmailsAccepted bool `json:"receive_emails_accepted"`
}
var trialRequest *model.TrialLicenseRequest
b, readErr := io.ReadAll(r.Body)
if readErr != nil {
@@ -223,8 +219,16 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) {
}
json.Unmarshal(b, &trialRequest)
if err := c.App.Channels().RequestTrialLicense(c.AppContext.Session().UserId, trialRequest.Users, trialRequest.TermsAccepted, trialRequest.ReceiveEmailsAccepted); err != nil {
c.Err = err
var appErr *model.AppError
// If any of the newly supported trial request fields are set (ie, not a legacy request), process this as a new trial request (requiring the new fields) otherwise fall back on the old method.
if !trialRequest.IsLegacy() {
appErr = c.App.Channels().RequestTrialLicenseWithExtraFields(c.AppContext.Session().UserId, trialRequest)
} else {
appErr = c.App.Channels().RequestTrialLicense(c.AppContext.Session().UserId, trialRequest.Users, trialRequest.TermsAccepted, trialRequest.ReceiveEmailsAccepted)
}
if appErr != nil {
c.Err = appErr
return
}

Просмотреть файл

@@ -120,7 +120,7 @@ func TestUploadLicenseFile(t *testing.T) {
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
t.Run("try to get gone through trial, with TE build", func(t *testing.T) {
t.Run("try to get one through trial, with TE build", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = false })
th.App.Srv().Platform().SetLicenseManager(nil)
@@ -223,6 +223,154 @@ func TestRemoveLicenseFile(t *testing.T) {
})
}
func TestRequestTrialLicenseWithExtraFields(t *testing.T) {
th := Setup(t)
defer th.TearDown()
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(true, nil)
th.App.Srv().Platform().SetLicenseManager(licenseManagerMock)
cloud := mocks.CloudInterface{}
cloudImpl := th.App.Srv().Cloud
defer func() {
th.App.Srv().Cloud = cloudImpl
}()
th.App.Srv().Cloud = &cloud
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "http://localhost:8065/" })
nUsers := 1
validTrialRequest := &model.TrialLicenseRequest{
Email: "test@mattermost.com",
Users: nUsers,
TermsAccepted: true,
CompanyCountry: "US",
CompanyName: "mattermost",
CompanySize: "1-10",
ContactName: "Matter Most",
}
t.Run("permission denied", func(t *testing.T) {
resp, err := th.Client.RequestTrialLicenseWithExtraFields(&model.TrialLicenseRequest{})
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("trial license user count less than current users", func(t *testing.T) {
license := model.NewTestLicense()
license.Features.Users = model.NewInt(nUsers)
licenseJSON, jsonErr := json.Marshal(license)
require.NoError(t, jsonErr)
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
response := map[string]string{
"license": string(licenseJSON),
}
err := json.NewEncoder(res).Encode(response)
require.NoError(t, err)
}))
defer testServer.Close()
mockLicenseValidator := mocks2.LicenseValidatorIface{}
defer testutils.ResetLicenseValidator()
mockLicenseValidator.On("ValidateLicense", mock.Anything).Return(true, string(licenseJSON))
utils.LicenseValidator = &mockLicenseValidator
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(true, nil).Once()
th.App.Srv().Platform().SetLicenseManager(licenseManagerMock)
originalCwsUrl := *th.App.Srv().Config().CloudSettings.CWSURL
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.CloudSettings.CWSURL = testServer.URL })
defer func(requestTrialURL string) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.CloudSettings.CWSURL = requestTrialURL })
}(originalCwsUrl)
cloud.On("ValidateBusinessEmail", mock.Anything, mock.Anything).Return(nil)
resp, err := th.SystemAdminClient.RequestTrialLicenseWithExtraFields(validTrialRequest)
CheckErrorID(t, err, "api.license.add_license.unique_users.app_error")
CheckBadRequestStatus(t, resp)
})
t.Run("returns status 451 when it receives status 451", func(t *testing.T) {
license := model.NewTestLicense()
license.Features.Users = model.NewInt(nUsers)
licenseJSON, jsonErr := json.Marshal(license)
require.NoError(t, jsonErr)
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusUnavailableForLegalReasons)
}))
defer testServer.Close()
mockLicenseValidator := mocks2.LicenseValidatorIface{}
defer testutils.ResetLicenseValidator()
mockLicenseValidator.On("ValidateLicense", mock.Anything).Return(true, string(licenseJSON))
utils.LicenseValidator = &mockLicenseValidator
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(true, nil).Once()
th.App.Srv().Platform().SetLicenseManager(licenseManagerMock)
originalCwsUrl := *th.App.Srv().Config().CloudSettings.CWSURL
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.CloudSettings.CWSURL = testServer.URL })
defer func(requestTrialURL string) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.CloudSettings.CWSURL = requestTrialURL })
}(originalCwsUrl)
resp, err := th.SystemAdminClient.RequestTrialLicenseWithExtraFields(validTrialRequest)
require.Error(t, err)
require.Equal(t, resp.StatusCode, 451)
})
t.Run("returns status 400 if request is a mix of legacy and new fields", func(t *testing.T) {
validTrialRequest.CompanyCountry = ""
validTrialRequest.Users = 100
defer func() { validTrialRequest.CompanyCountry = "US" }()
license := model.NewTestLicense()
license.Features.Users = model.NewInt(nUsers)
licenseJSON, jsonErr := json.Marshal(license)
require.NoError(t, jsonErr)
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
response := map[string]string{
"license": string(licenseJSON),
}
err := json.NewEncoder(res).Encode(response)
require.NoError(t, err)
}))
defer testServer.Close()
mockLicenseValidator := mocks2.LicenseValidatorIface{}
defer testutils.ResetLicenseValidator()
mockLicenseValidator.On("ValidateLicense", mock.Anything).Return(true, string(licenseJSON))
utils.LicenseValidator = &mockLicenseValidator
licenseManagerMock := &mocks.LicenseInterface{}
licenseManagerMock.On("CanStartTrial").Return(true, nil).Once()
th.App.Srv().Platform().SetLicenseManager(licenseManagerMock)
originalCwsUrl := *th.App.Srv().Config().CloudSettings.CWSURL
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.CloudSettings.CWSURL = testServer.URL })
defer func(requestTrialURL string) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.CloudSettings.CWSURL = requestTrialURL })
}(originalCwsUrl)
cloud.On("ValidateBusinessEmail", mock.Anything, mock.Anything).Return(nil)
resp, err := th.SystemAdminClient.RequestTrialLicenseWithExtraFields(validTrialRequest)
CheckErrorID(t, err, "api.license.request-trial.bad-request")
CheckBadRequestStatus(t, resp)
})
th.App.Srv().Platform().SetLicenseManager(nil)
t.Run("trial license should fail if LicenseManager is nil", func(t *testing.T) {
resp, err := th.SystemAdminClient.RequestTrialLicenseWithExtraFields(validTrialRequest)
CheckErrorID(t, err, "api.license.upgrade_needed.app_error")
CheckForbiddenStatus(t, resp)
})
}
func TestRequestTrialLicense(t *testing.T) {
th := Setup(t)
defer th.TearDown()

Просмотреть файл

@@ -2372,10 +2372,14 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
audit.AddEventParameter(auditRec, "user_id", c.Params.UserId)
defer c.LogAuditRec(auditRec)
if user, err := c.App.GetUser(c.Params.UserId); err == nil {
audit.AddEventParameterAuditable(auditRec, "user", user)
user, err := c.App.GetUser(c.Params.UserId)
if err != nil {
c.Err = err
return
}
audit.AddEventParameterAuditable(auditRec, "user", user)
if c.AppContext.Session().IsOAuth {
c.SetPermissionError(model.PermissionCreateUserAccessToken)
c.Err.DetailedError += ", attempted access by oauth app"
@@ -2405,6 +2409,11 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) {
return
}
if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) {
c.SetPermissionError(model.PermissionManageSystem)
return
}
accessToken.UserId = c.Params.UserId
accessToken.Token = ""

Просмотреть файл

@@ -4339,7 +4339,38 @@ func TestCreateUserAccessToken(t *testing.T) {
CheckForbiddenStatus(t, resp)
})
t.Run("create user access token for basic user as as system admin", func(t *testing.T) {
t.Run("create user access token for another user, with permission", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
th.AddPermissionToRole(model.PermissionEditOtherUsers.Id, model.SystemUserManagerRoleId)
th.App.UpdateUserRoles(th.Context, th.BasicUser.Id, model.SystemUserManagerRoleId+" "+model.SystemUserAccessTokenRoleId, false)
rtoken, _, err := th.Client.CreateUserAccessToken(th.BasicUser2.Id, "test token")
require.NoError(t, err)
assert.Equal(t, th.BasicUser2.Id, rtoken.UserId)
oldSessionToken := th.Client.AuthToken
defer func() { th.Client.AuthToken = oldSessionToken }()
assertToken(t, th, rtoken, th.BasicUser2.Id)
})
t.Run("create user access token for system admin, as system user manager", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
th.AddPermissionToRole(model.PermissionEditOtherUsers.Id, model.SystemUserManagerRoleId)
th.App.UpdateUserRoles(th.Context, th.BasicUser.Id, model.SystemUserManagerRoleId+" "+model.SystemUserAccessTokenRoleId, false)
_, resp, err := th.Client.CreateUserAccessToken(th.SystemAdminUser.Id, "test token")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("create user access token for basic user as a system admin", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()

Просмотреть файл

@@ -22,23 +22,6 @@ func areWorkTemplatesEnabled(c *Context) *model.AppError {
return model.NewAppError("areWorkTemplatesEnabled", "api.work_templates.disabled", nil, "feature flag is off", http.StatusNotFound)
}
// we have to make sure that playbooks plugin is enabled and board is a product
pbActive, err := c.App.IsPluginActive(model.PluginIdPlaybooks)
if err != nil {
return model.NewAppError("areWorkTemplatesEnabled", "api.work_templates.disabled", nil, "", http.StatusInternalServerError).Wrap(err)
}
if !pbActive {
return model.NewAppError("areWorkTemplatesEnabled", "api.work_templates.disabled", nil, "playbook plugin not active", http.StatusNotFound)
}
hasBoard, err := c.App.HasBoardProduct()
if err != nil {
return model.NewAppError("areWorkTemplatesEnabled", "api.work_templates.disabled", nil, "", http.StatusInternalServerError).Wrap(err)
}
if !hasBoard {
return model.NewAppError("areWorkTemplatesEnabled", "api.work_templates.disabled", nil, "board product not found", http.StatusNotFound)
}
return nil
}