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
1 change: 1 addition & 0 deletions cla-backend-go/cla_manager/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func isValidUser(claUser *user.CLAUser) bool {

// Configure is the API handler routine for the CLA manager routes
func Configure(api *operations.ClaAPI, service IService, companyService company.IService, projectService service2.Service, usersService users.Service, sigService signatures.SignatureService, eventsService events.Service, emailSvc emails.EmailTemplateService) { // nolint
configureOrgLens(api, companyService, projectService, utils.GetOrgLensURLContext)
api.ClaManagerCreateCLAManagerRequestHandler = cla_manager.CreateCLAManagerRequestHandlerFunc(func(params cla_manager.CreateCLAManagerRequestParams, claUser *user.CLAUser) middleware.Responder {
reqID := utils.GetRequestID(params.XREQUESTID)
ctx := context.WithValue(context.Background(), utils.XREQUESTID, reqID) // nolint
Expand Down
66 changes: 66 additions & 0 deletions cla-backend-go/cla_manager/org_lens.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright The Linux Foundation and each contributor to CommunityBridge.
// SPDX-License-Identifier: MIT

package cla_manager

import (
"context"
"errors"

"github.com/go-openapi/runtime/middleware"
"github.com/linuxfoundation/easycla/cla-backend-go/company"
"github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/models"
"github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/restapi/operations"
"github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/restapi/operations/cla_manager"
log "github.com/linuxfoundation/easycla/cla-backend-go/logging"
service2 "github.com/linuxfoundation/easycla/cla-backend-go/project/service"
"github.com/linuxfoundation/easycla/cla-backend-go/utils"
"github.com/sirupsen/logrus"
)

func companyCLAGroupOrgLens(ctx context.Context, companyService company.IService, projectService service2.Service, lensURL func(ctx context.Context, companySFID, claGroupID string) string, companyID, claGroupID string) (*models.CompanyClaGroupOrgLens, error) {
companyModel, err := companyService.GetCompany(ctx, companyID)
if err != nil {
return nil, err
}
if companyModel == nil {
return nil, &utils.CompanyNotFound{CompanyID: companyID}
}
claGroupModel, err := projectService.GetCLAGroupByID(ctx, claGroupID)
Comment thread
lukaszgryglicki marked this conversation as resolved.
Resolved
if err != nil {
return nil, err
}
if claGroupModel == nil {
return nil, &utils.CLAGroupNotFound{CLAGroupID: claGroupID}
}
return &models.CompanyClaGroupOrgLens{
CompanyID: companyModel.CompanyID,
CompanySFID: companyModel.CompanyExternalID,
ClaGroupID: claGroupModel.ProjectID,
FoundationSFID: claGroupModel.FoundationSFID,
OrgLensURL: lensURL(ctx, companyModel.CompanyExternalID, claGroupModel.ProjectID),
}, nil
}

func configureOrgLens(api *operations.ClaAPI, companyService company.IService, projectService service2.Service, lensURL func(ctx context.Context, companySFID, claGroupID string) string) {
api.ClaManagerGetCompanyCLAGroupOrgLensHandler = cla_manager.GetCompanyCLAGroupOrgLensHandlerFunc(func(params cla_manager.GetCompanyCLAGroupOrgLensParams) middleware.Responder {
reqID := utils.GetRequestID(params.XREQUESTID)
ctx := context.WithValue(params.HTTPRequest.Context(), utils.XREQUESTID, reqID) // nolint
lens, err := companyCLAGroupOrgLens(ctx, companyService, projectService, lensURL, params.CompanyID, params.ClaGroupID)
if err != nil {
var companyNotFound *utils.CompanyNotFound
var claGroupNotFound *utils.CLAGroupNotFound
if errors.As(err, &companyNotFound) || errors.As(err, &claGroupNotFound) {
return cla_manager.NewGetCompanyCLAGroupOrgLensNotFound().WithXRequestID(reqID).WithPayload(&models.ErrorResponse{Code: "404", Message: err.Error()})
}
log.WithFields(logrus.Fields{
"functionName": "cla_manager.handlers.GetCompanyCLAGroupOrgLens",
utils.XREQUESTID: reqID,
"companyID": params.CompanyID,
"claGroupID": params.ClaGroupID,
}).WithError(err).Warn("unable to load the company or the CLA Group")
return cla_manager.NewGetCompanyCLAGroupOrgLensInternalServerError().WithXRequestID(reqID).WithPayload(&models.ErrorResponse{Code: "500", Message: "unable to load the company or the CLA Group"})
}
return cla_manager.NewGetCompanyCLAGroupOrgLensOK().WithXRequestID(reqID).WithPayload(lens)
})
}
131 changes: 131 additions & 0 deletions cla-backend-go/cla_manager/org_lens_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright The Linux Foundation and each contributor to CommunityBridge.
// SPDX-License-Identifier: MIT

package cla_manager

import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"

"github.com/go-openapi/runtime"
"github.com/golang/mock/gomock"
mock_company "github.com/linuxfoundation/easycla/cla-backend-go/company/mocks"
"github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/models"
"github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/restapi/operations"
claManagerOps "github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/restapi/operations/cla_manager"
mock_project "github.com/linuxfoundation/easycla/cla-backend-go/project/mocks"
"github.com/linuxfoundation/easycla/cla-backend-go/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const (
orgLensTestBase = "https://app.example.org"
orgLensTestCompanyID = "00000000-0000-4000-8000-00000000000c"
orgLensTestSFID = "001000000000000AAA"
orgLensTestCLAGroupID = "00000000-0000-4000-8000-000000000001"
orgLensTestFoundation = "a0P000000000001AAA"
)

func orgLensTestURL(ctx context.Context, companySFID, claGroupID string) string {
return utils.OrgLensURLContext(ctx, orgLensTestBase, companySFID, claGroupID)
}

func TestGetCompanyCLAGroupOrgLens(t *testing.T) {
company := &models.Company{CompanyID: orgLensTestCompanyID, CompanyExternalID: orgLensTestSFID, CompanyName: "Example Org"}
claGroup := &models.ClaGroup{ProjectID: orgLensTestCLAGroupID, FoundationSFID: orgLensTestFoundation, ProjectName: "Example Group"}
page := orgLensTestBase + "/org/" + orgLensTestSFID + "/easycla/" + orgLensTestCLAGroupID

tests := []struct {
name string
company *models.Company
companyErr error
claGroup *models.ClaGroup
groupErr error
live bool
wantStatus int
wantBody string
}{
{
name: "live Account gets the lens page", company: company, claGroup: claGroup, live: true, wantStatus: http.StatusOK,
wantBody: `{"claGroupID":"` + orgLensTestCLAGroupID + `","companyID":"` + orgLensTestCompanyID + `","companySFID":"` + orgLensTestSFID + `","foundationSFID":"` + orgLensTestFoundation + `","orgLensURL":"` + page + `"}`,
},
{
name: "Account that is not live keeps the Corporate Console", company: company, claGroup: claGroup, wantStatus: http.StatusOK,
wantBody: `{"claGroupID":"` + orgLensTestCLAGroupID + `","companyID":"` + orgLensTestCompanyID + `","companySFID":"` + orgLensTestSFID + `","foundationSFID":"` + orgLensTestFoundation + `","orgLensURL":""}`,
},
{
name: "company without a Salesforce Account keeps the Corporate Console",
company: &models.Company{CompanyID: orgLensTestCompanyID, CompanyExternalID: "lf0000000000000AAA"}, claGroup: claGroup, live: true, wantStatus: http.StatusOK,
wantBody: `{"claGroupID":"` + orgLensTestCLAGroupID + `","companyID":"` + orgLensTestCompanyID + `","companySFID":"lf0000000000000AAA","foundationSFID":"` + orgLensTestFoundation + `","orgLensURL":""}`,
},
{
name: "unknown company", companyErr: &utils.CompanyNotFound{CompanyID: orgLensTestCompanyID}, live: true, wantStatus: http.StatusNotFound,
wantBody: `{"Code":"404","Message":"company does not exist - company ID: ` + orgLensTestCompanyID + `"}`,
},
{
name: "unknown CLA Group", company: company, groupErr: &utils.CLAGroupNotFound{CLAGroupID: orgLensTestCLAGroupID}, live: true, wantStatus: http.StatusNotFound,
wantBody: `{"Code":"404","Message":"cla group ` + orgLensTestCLAGroupID + ` not found"}`,
},
{
name: "company lookup fails", companyErr: errors.New("dynamodb is down"), live: true, wantStatus: http.StatusInternalServerError,
wantBody: `{"Code":"500","Message":"unable to load the company or the CLA Group"}`,
},
{
name: "CLA Group lookup fails", company: company, groupErr: errors.New("dynamodb is down"), live: true, wantStatus: http.StatusInternalServerError,
wantBody: `{"Code":"500","Message":"unable to load the company or the CLA Group"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
utils.SetOrgLensLiveCheck(func(context.Context, string) bool { return tt.live })
t.Cleanup(func() { utils.SetOrgLensLiveCheck(nil) })
ctrl := gomock.NewController(t)
defer ctrl.Finish()
companyService := mock_company.NewMockIService(ctrl)
projectService := mock_project.NewMockService(ctrl)
companyService.EXPECT().GetCompany(gomock.Any(), orgLensTestCompanyID).Return(tt.company, tt.companyErr)
if tt.companyErr == nil {
projectService.EXPECT().GetCLAGroupByID(gomock.Any(), orgLensTestCLAGroupID).Return(tt.claGroup, tt.groupErr)
}

api := operations.NewClaAPI(nil)
configureOrgLens(api, companyService, projectService, orgLensTestURL)
reqID := "req-lens"
recorder := httptest.NewRecorder()
api.ClaManagerGetCompanyCLAGroupOrgLensHandler.Handle(claManagerOps.GetCompanyCLAGroupOrgLensParams{
HTTPRequest: httptest.NewRequest(http.MethodGet, "/v3/company/"+orgLensTestCompanyID+"/cla-group/"+orgLensTestCLAGroupID+"/org-lens", nil),
XREQUESTID: &reqID,
CompanyID: orgLensTestCompanyID,
ClaGroupID: orgLensTestCLAGroupID,
}).WriteResponse(recorder, runtime.JSONProducer())

assert.Equal(t, tt.wantStatus, recorder.Code, recorder.Body.String())
assert.Equal(t, reqID, recorder.Header().Get("X-Request-Id"))
assert.JSONEq(t, tt.wantBody, recorder.Body.String())
})
}
}

func TestCompanyCLAGroupOrgLensWithoutARecord(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
companyService := mock_company.NewMockIService(ctrl)
projectService := mock_project.NewMockService(ctrl)

companyService.EXPECT().GetCompany(gomock.Any(), orgLensTestCompanyID).Return(nil, nil)
_, err := companyCLAGroupOrgLens(context.Background(), companyService, projectService, orgLensTestURL, orgLensTestCompanyID, orgLensTestCLAGroupID)
var companyNotFound *utils.CompanyNotFound
require.ErrorAs(t, err, &companyNotFound)
assert.Equal(t, orgLensTestCompanyID, companyNotFound.CompanyID)

companyService.EXPECT().GetCompany(gomock.Any(), orgLensTestCompanyID).Return(&models.Company{CompanyID: orgLensTestCompanyID}, nil)
projectService.EXPECT().GetCLAGroupByID(gomock.Any(), orgLensTestCLAGroupID).Return(nil, nil)
_, err = companyCLAGroupOrgLens(context.Background(), companyService, projectService, orgLensTestURL, orgLensTestCompanyID, orgLensTestCLAGroupID)
var claGroupNotFound *utils.CLAGroupNotFound
require.ErrorAs(t, err, &claGroupNotFound)
assert.Equal(t, orgLensTestCLAGroupID, claGroupNotFound.CLAGroupID)
}
6 changes: 4 additions & 2 deletions cla-backend-go/cmd/org_import/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,10 @@ lfbd1c2b3a4d5e6f7a8,0014100000NewNewNe,matched,true
lf000000000000000001,,ambiguous,false
```

- `action`: `matched` (existing account found by domain/name — **requires `approved=true`**, a human checked it), `created` (new account created for this org, accepted as is), `ambiguous` (several candidates — stays manual).
- `new_id` must be a 15/18-char alphanumeric Salesforce id (`ambiguous` rows may leave it empty); `new_id == old_id` is refused (`mapping_same_id`).
- `action`: `matched` (existing account found by domain/name — **requires `approved=true`**, a human checked it), `created` (new account created for this org, accepted as is), `ambiguous` (several candidates — stays manual),
`create` (**requires `approved=true`** and an empty `new_id`: the apply creates the Account through the member-service find-or-create of the
company create flow, with the organization's name and website; an Account that already matches the website stops the group for review).
- `new_id` must be a 15/18-char alphanumeric Salesforce id (`ambiguous` and `create` rows leave it empty); `new_id == old_id` is refused (`mapping_same_id`).
- Ids are compared **per Account**: the 15-char id and its 18-char form (first 15 chars + checksum) name the same target, so co-targeting
mappings and rows already carrying the other form collide the same way; a source group whose Account appears in the inventory in both
forms is `sfid_alias_forms` (manual) until the rows are normalized to one form, and a destination that would end up carrying both forms
Expand Down
1 change: 1 addition & 0 deletions cla-backend-go/cmd/org_import/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,7 @@ func wire(ctx context.Context, stage string, useApex bool) (env, error) {
case err == nil:
e.deps.Members = members
e.members = members
e.deps.Creator = orgimport.MemberApex{Members: members}
case errors.Is(err, member_service.ErrNotConfigured):
log.Warnf("member-service not configured (cla-member-service-base-url-%s / cla-member-service-auth0-audience-%s): liveness is unverified, SFID groups stay pending (crm_unverified) and nothing is registered or rewritten for them", stage, stage)
default:
Expand Down
62 changes: 62 additions & 0 deletions cla-backend-go/cmd/org_lens_live_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright The Linux Foundation and each contributor to CommunityBridge.
// SPDX-License-Identifier: MIT

package cmd

import (
"context"
"net/http"
"net/http/httptest"
"testing"

"github.com/linuxfoundation/easycla/cla-backend-go/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestOrgLensLiveCheckNeedsOnlyTheLensBase(t *testing.T) {
const sfid = "0014100000Te0G7AAJ"
lookups := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body := ""
switch r.URL.Path {
case "/oauth/token":
body = `{"access_token":"member-token","token_type":"Bearer","expires_in":3600}`
case "/b2b_orgs/" + sfid:
lookups++
body = `{"uid":"` + sfid + `","name":"Example Org"}`
default:
http.NotFound(w, r)
return
}
if _, err := w.Write([]byte(body)); err != nil {
t.Error(err)
}
}))
defer server.Close()
cfg := config.Config{
OrgLensURL: "https://app.example.org",
MemberService: config.MemberService{BaseURL: server.URL, Audience: "member-audience"},
Auth0Platform: config.Auth0Platform{URL: server.URL + "/oauth/token", ClientID: "test-client", ClientSecret: "test-secret"},
}
members, err := newMemberServiceClient(cfg)
require.NoError(t, err)
require.Nil(t, members, "both member-service flags are off")

assert.True(t, newOrgLensLiveCheck(cfg, members)(context.Background(), sfid), "the lens base alone is enough for the live check")
assert.Equal(t, 1, lookups)

cfg.OrgLensURL = ""
assert.False(t, newOrgLensLiveCheck(cfg, members)(context.Background(), sfid), "without a lens base nothing asks member-service")
assert.Equal(t, 1, lookups)

cfg.OrgLensURL, cfg.MemberService.BaseURL = "https://app.example.org", ""
assert.False(t, newOrgLensLiveCheck(cfg, members)(context.Background(), sfid), "member-service not configured: the Corporate Console link stays")

cfg.MemberService.BaseURL = server.URL
cfg.MemberService.CreateCompanyEnabled = true
members, err = newMemberServiceClient(cfg)
require.NoError(t, err)
require.NotNil(t, members)
assert.True(t, newOrgLensLiveCheck(cfg, members)(context.Background(), sfid), "the client of the rollout flags is reused")
}
17 changes: 17 additions & 0 deletions cla-backend-go/cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,22 @@ func newMemberServiceClient(cfg config.Config) (*member_service.Client, error) {
if !cfg.MemberService.CreateCompanyEnabled && !cfg.ACSDirectCLARolesEnabled {
return nil, nil
}
return memberServiceClient(cfg)
}

// newOrgLensLiveCheck returns the "live Account" check of the Organization lens links; it has its own client when the
// member-service flags are off, so that the lens base alone is enough for it
func newOrgLensLiveCheck(cfg config.Config, members *member_service.Client) func(ctx context.Context, companySFID string) bool {
if members == nil && strings.TrimSpace(cfg.OrgLensURL) != "" {
var err error
if members, err = memberServiceClient(cfg); err != nil {
log.WithError(err).Warn("unable to configure member-service client for the Organization lens links: every e-mail keeps the Corporate Console link")
}
}
return member_service.NewLiveAccounts(members).IsLive
}

func memberServiceClient(cfg config.Config) (*member_service.Client, error) {
return member_service.NewClient(member_service.Config{
BaseURL: cfg.MemberService.BaseURL,
Audience: cfg.MemberService.Audience,
Expand Down Expand Up @@ -454,6 +470,7 @@ func server(localMode bool) http.Handler {
if memberErr != nil {
log.WithError(memberErr).Warn("unable to configure member-service client for company creation or pending-Account screening")
}
utils.SetOrgLensLiveCheck(newOrgLensLiveCheck(configFile, members))
if configFile.MemberService.CreateCompanyEnabled {
v2CompanyService.EnableMemberServiceCreate(members)
v2CompanyService.EnableCreateLock(v2Company.DynamoCreateLocks{DB: dynamodb.New(awsSession), Table: fmt.Sprintf("cla-%s-store", stage)})
Expand Down
14 changes: 14 additions & 0 deletions cla-backend-go/emails/org_lens_links_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package emails

import (
"context"
"testing"

"github.com/linuxfoundation/easycla/cla-backend-go/utils"
Expand All @@ -18,6 +19,11 @@ const (
lensTestPage = lensTestBase + "/org/" + lensTestCompany + "/easycla/" + lensTestCLAGroupID
)

func lensTestLive(t *testing.T, live bool) {
utils.SetOrgLensLiveCheck(func(context.Context, string) bool { return live })
t.Cleanup(func() { utils.SetOrgLensLiveCheck(nil) })
}

func lensTestCommon() CommonEmailParams {
return CommonEmailParams{RecipientName: "Example Manager", CompanyName: "Example Org", CompanySFID: lensTestCompany}
}
Expand Down Expand Up @@ -84,6 +90,7 @@ func TestCLAManagerEmailsLinkToOrgLens(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
lensTestLive(t, true)
lens, err := RenderTemplate(utils.V2, tt.name, tt.template, tt.params(lensTestBase))
assert.NoError(t, err)
assert.Contains(t, lens, `<a href="`+lensTestPage+`" target="_blank">Example Group in the Organization lens</a>`)
Expand All @@ -93,13 +100,19 @@ func TestCLAManagerEmailsLinkToOrgLens(t *testing.T) {
assert.NoError(t, err)
assert.Contains(t, console, lensTestConsole)
assert.NotContains(t, console, "Organization lens")

lensTestLive(t, false)
notLive, err := RenderTemplate(utils.V2, tt.name, tt.template, tt.params(lensTestBase))
assert.NoError(t, err)
assert.Equal(t, console, notLive, "a company whose Account is not live keeps the Corporate Console copy")
})
}
}

func TestOrgLensLinkWithoutValidCompanySFIDKeepsCorporateConsole(t *testing.T) {
for _, sfid := range []string{"", "lf0000000000000AAA", "001000000000000"} {
t.Run(sfid, func(t *testing.T) {
lensTestLive(t, true)
params := ClaManagerAddedEToUserTemplateParams{CommonEmailParams: lensTestCommon(), CLAGroupTemplateParams: lensTestCLAGroup(lensTestBase)}
params.CompanySFID = sfid

Expand Down Expand Up @@ -134,6 +147,7 @@ func TestContactClaManagerEmailLinksToOrgLens(t *testing.T) {
}

func TestCLAManagerEmailsKeepTheCLAGroupOfTheSender(t *testing.T) {
lensTestLive(t, true)
const own = "00000000-0000-4000-8000-00000000000a"
svc := &documentSignedTemplateServiceStub{projectParams: lensTestCLAGroup(lensTestBase)}
ownPage := lensTestBase + "/org/" + lensTestCompany + "/easycla/" + own
Expand Down
3 changes: 3 additions & 0 deletions cla-backend-go/emails/prefill_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package emails

import (
"context"
"errors"
"testing"

Expand All @@ -14,6 +15,8 @@ import (
)

func TestGetCLAGroupTemplateParamsFromCLAGroupUsesAuthoritativeCLAGroup(t *testing.T) {
utils.SetOrgLensLiveCheck(func(context.Context, string) bool { return true })
t.Cleanup(func() { utils.SetOrgLensLiveCheck(nil) })
const (
claGroupID = "b941159a-7bb9-4a07-bc03-6fcce4431434"
claGroupName = "ACES"
Expand Down
Loading
Loading