Files
lincodex/backend/integration_test/company_context_test.go
T

266 lines
12 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/domain"
)
func TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
defer cancel()
harness := newOrganizationHTTPHarness(ctx, t, env)
resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"})
truncateTables(ctx, t, harness.pool, resetTables...)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
owner := createOrganizationHTTPUser(ctx, t, harness, "company-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreignOwner := createOrganizationHTTPUser(ctx, t, harness, "company-foreign-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
recruiter := createOrganizationHTTPUser(ctx, t, harness, "company-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
candidate := createOrganizationHTTPUser(ctx, t, harness, "company-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
foreignSession := loginOrganizationHTTP(t, harness, foreignOwner.Email.Address())
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address())
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
organizationA := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a")
organizationA2 := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a2")
organizationB := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, foreignSession, "company-context-b")
insertOrganizationHTTPMembership(ctx, t, harness, organizationA, recruiter.ID, "recruiter", "active", now)
insertOrganizationHTTPMembership(ctx, t, harness, organizationA, candidate.ID, "owner", "active", now)
ownerRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "")
if ownerRead.Code != http.StatusOK {
t.Fatalf("owner read = %d %s, want 200", ownerRead.Code, ownerRead.Body.String())
}
for _, test := range []struct {
name string
session organizationHTTPSession
want int
}{
{name: "foreign company", session: foreignSession, want: http.StatusNotFound},
{name: "recruiter membership", session: recruiterSession, want: http.StatusForbidden},
{name: "candidate with manually inserted owner membership", session: candidateSession, want: http.StatusForbidden},
} {
t.Run(test.name, func(t *testing.T) {
response := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", test.session, "")
if response.Code != test.want {
t.Fatalf("company read = %d %s, want %d", response.Code, response.Body.String(), test.want)
}
assertNoCompanyDetails(t, response)
})
}
childForeign := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", foreignSession, "")
if childForeign.Code != http.StatusNotFound {
t.Fatalf("foreign owner on tenant needs route = %d %s, want 404 before fallback", childForeign.Code, childForeign.Body.String())
}
assertNoCompanyDetails(t, childForeign)
childOwner := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "")
if childOwner.Code != http.StatusNotImplemented {
t.Fatalf("owner on currently unimplemented needs route = %d %s, want guarded 501 fallback", childOwner.Code, childOwner.Body.String())
}
candidateHide := organizationHTTPRequest(t, harness, http.MethodPut,
"/api/v1/me/privacy/hidden-organizations/"+organizationA.String(), "", env.Config.AppPublicURL, candidateSession, "")
if candidateHide.Code != http.StatusNotImplemented {
t.Fatalf("candidate-owned hiding route = %d %s, want its own 501 fallback", candidateHide.Code, candidateHide.Body.String())
}
assertNoCompanyDetails(t, candidateHide)
firstPage := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations?limit=1", http.StatusOK)
if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
t.Fatalf("first organization page = %+v, want one item and a next cursor", firstPage)
}
if firstPage.Items[0].Membership.Role != "owner" || firstPage.Items[0].Membership.State != "active" {
t.Fatalf("owner directory membership = %+v, want active owner", firstPage.Items[0].Membership)
}
secondPage := readOrganizationDirectory(t, harness, ownerSession,
"/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), http.StatusOK)
if len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil {
t.Fatalf("second organization page = %+v, want one last item", secondPage)
}
if firstPage.Items[0].Organization.ID == secondPage.Items[0].Organization.ID {
t.Fatal("organization directory repeated an item across pages")
}
for _, item := range []organizationDirectoryItem{firstPage.Items[0], secondPage.Items[0]} {
if item.Organization.ID != organizationA.String() && item.Organization.ID != organizationA2.String() {
t.Fatalf("owner directory exposed another account's organization %s", item.Organization.ID)
}
}
foreignCursor := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", "", foreignSession, "")
requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed")
foreignDirectory := readOrganizationDirectory(t, harness, foreignSession, "/api/v1/me/organizations", http.StatusOK)
if len(foreignDirectory.Items) != 1 || foreignDirectory.Items[0].Organization.ID != organizationB.String() {
t.Fatalf("foreign owner's directory = %+v, want only %s", foreignDirectory.Items, organizationB)
}
recruiterDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK)
if len(recruiterDirectory.Items) != 1 || recruiterDirectory.Items[0].Membership.Role != "recruiter" {
t.Fatalf("recruiter's directory = %+v, want its active recruiter membership", recruiterDirectory.Items)
}
candidateDirectory := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/organizations", "", "", candidateSession, "")
requireSessionProblem(t, candidateDirectory, http.StatusForbidden, "forbidden")
assertNoCompanyDetails(t, candidateDirectory)
if _, err := harness.pool.Exec(ctx,
"UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3",
now.Add(time.Second), organizationA, recruiter.ID,
); err != nil {
t.Fatalf("revoke recruiter membership: %v", err)
}
revokedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", recruiterSession, "")
requireSessionProblem(t, revokedRead, http.StatusNotFound, "not_found")
revokedDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK)
if len(revokedDirectory.Items) != 0 {
t.Fatalf("directory with the same cookie after revocation = %+v, want empty", revokedDirectory.Items)
}
if _, err := harness.pool.Exec(ctx,
"UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3",
now.Add(2*time.Second), organizationA, owner.ID,
); err != nil {
t.Fatalf("revoke owner membership: %v", err)
}
revokedOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "")
requireSessionProblem(t, revokedOwnerRead, http.StatusNotFound, "not_found")
assertNoCompanyDetails(t, revokedOwnerRead)
revokedOwnerChild := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "")
if revokedOwnerChild.Code != http.StatusNotFound {
t.Fatalf("same owner cookie after revocation on tenant route = %d %s, want 404", revokedOwnerChild.Code, revokedOwnerChild.Body.String())
}
assertNoCompanyDetails(t, revokedOwnerChild)
remainingOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA2.String(), "", "", ownerSession, "")
if remainingOwnerRead.Code != http.StatusOK {
t.Fatalf("same owner cookie for its remaining organization = %d %s, want 200", remainingOwnerRead.Code, remainingOwnerRead.Body.String())
}
remainingOwnerDirectory := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations", http.StatusOK)
if len(remainingOwnerDirectory.Items) != 1 || remainingOwnerDirectory.Items[0].Organization.ID != organizationA2.String() {
t.Fatalf("owner directory after membership revocation = %+v, want only %s", remainingOwnerDirectory.Items, organizationA2)
}
for _, marker := range []string{
owner.Email.Address(), foreignOwner.Email.Address(), recruiter.Email.Address(), candidate.Email.Address(),
"ООО Тестовая компания",
} {
if strings.Contains(harness.logs.String(), marker) {
t.Fatalf("company context logs contain account or profile data %q", marker)
}
}
}
func createCompanyForContextTest(
t *testing.T,
harness *sessionHTTPHarness,
origin string,
session organizationHTTPSession,
idempotencyKey string,
) uuid.UUID {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations",
"{\"name\":\"ООО Тестовая компания\",\"contacts\":{\"website\":\"https://company-context.example.test\",\"email\":\"careers@company-context.example.test\",\"phone\":\"+12025550123\",\"telegram\":\"@companycontext\"}}",
origin, session, idempotencyKey)
if response.Code != http.StatusCreated {
t.Fatalf("create test company = %d %s, want 201", response.Code, response.Body.String())
}
var company struct {
ID uuid.UUID `json:"id"`
}
if err := json.Unmarshal(response.Body.Bytes(), &company); err != nil {
t.Fatalf("decode test company: %v", err)
}
return company.ID
}
func assertNoCompanyDetails(t *testing.T, response *httptest.ResponseRecorder) {
t.Helper()
body := response.Body.String()
for _, marker := range []string{
"ООО Тестовая компания",
"company-context.example.test",
"careers@company-context.example.test",
"+12025550123",
"@companycontext",
} {
if strings.Contains(body, marker) {
t.Fatalf("denied company response contains company profile data %q", marker)
}
}
}
func insertOrganizationHTTPMembership(
ctx context.Context,
t *testing.T,
harness *sessionHTTPHarness,
organizationID uuid.UUID,
userID uuid.UUID,
role, state string,
at time.Time,
) {
t.Helper()
membershipID, err := uuid.NewV7()
if err != nil {
t.Fatalf("NewV7 membership ID: %v", err)
}
if _, err := harness.pool.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $6)
`, membershipID, organizationID, userID, role, state, at); err != nil {
t.Fatalf("insert test company membership: %v", err)
}
}
type organizationDirectoryResponse struct {
Items []organizationDirectoryItem `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
type organizationDirectoryItem struct {
Organization struct {
ID string `json:"id"`
} `json:"organization"`
Membership struct {
Role string `json:"role"`
State string `json:"state"`
} `json:"membership"`
}
func readOrganizationDirectory(
t *testing.T,
harness *sessionHTTPHarness,
session organizationHTTPSession,
path string,
wantStatus int,
) organizationDirectoryResponse {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "")
if response.Code != wantStatus {
t.Fatalf("organization directory = %d %s, want %d", response.Code, response.Body.String(), wantStatus)
}
var directory organizationDirectoryResponse
if err := json.Unmarshal(response.Body.Bytes(), &directory); err != nil {
t.Fatalf("decode organization directory: %v", err)
}
return directory
}