package httpadapter import ( "context" "errors" "net/http" "net/http/httptest" "os" "strings" "testing" "time" "github.com/google/uuid" ogenmiddleware "github.com/ogen-go/ogen/middleware" "github.com/ogen-go/ogen/openapi" "go.yaml.in/yaml/v3" apiadapter "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/organization" ) type companyAuthorizerFunc func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) type requestContextRecorder struct { context context.Context } func (recorder *requestContextRecorder) ServeHTTP(_ http.ResponseWriter, request *http.Request) { recorder.context = request.Context() } func (authorizer companyAuthorizerFunc) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error) { return authorizer(ctx, actorID, organizationID) } func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T) { organizationID := uuid.New() request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, organizationID) if _, err := NewCompanyContextMiddleware(nil)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) { t.Fatal("owner operation reached next without an authorizer") return ogenmiddleware.Response{}, nil }); err == nil { t.Fatal("owner operation passed without an authorizer") } for _, operation := range []apiadapter.OperationName{ // Card reads lock any active membership inside their read transaction; // the owner-only capability does not apply to that operation. apiadapter.GetOrganizationCandidateCardOperation, apiadapter.GetOrganizationCandidateEvidenceOperation, // The inbox runs the membership check in the read transaction for any role. apiadapter.ListOrganizationNotificationsOperation, apiadapter.MarkOrganizationNotificationReadOperation, apiadapter.HideOrganizationOperation, apiadapter.UnhideOrganizationOperation, apiadapter.RevokeMyOrganizationContactConsentOperation, apiadapter.ListMyOrganizationsOperation, } { t.Run(operation, func(t *testing.T) { called := false _, err := NewCompanyContextMiddleware(nil)(ownerCompanyMiddlewareRequest(t, uuid.New(), operation, organizationID), func(ogenmiddleware.Request) (ogenmiddleware.Response, error) { called = true return ogenmiddleware.Response{}, nil }) if err != nil || !called { t.Fatalf("operation outside owner scope: called=%v err=%v; want pass-through", called, err) } }) } } func TestCompanyContextMiddlewareMapsMembershipFailuresToPublicProblems(t *testing.T) { for _, test := range []struct { name string err error code apiadapter.ProblemCode }{ {name: "candidate", err: organization.ErrForbidden, code: apiadapter.ProblemCodeForbidden}, {name: "unverified employer", err: organization.ErrEmailNotVerified, code: apiadapter.ProblemCodeEmailNotVerified}, {name: "other role", err: outbound.ErrOrganizationManagerRequired, code: apiadapter.ProblemCodeForbidden}, {name: "missing or inactive membership", err: outbound.ErrOrganizationNotFound, code: apiadapter.ProblemCodeNotFound}, } { t.Run(test.name, func(t *testing.T) { request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, uuid.New()) authorizer := companyAuthorizerFunc(func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) { return organization.CompanyAccess{}, test.err }) called := false _, err := NewCompanyContextMiddleware(authorizer)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) { called = true return ogenmiddleware.Response{}, nil }) var response *apiadapter.ProblemStatusCode if !errors.As(err, &response) || response.Response.Code != test.code || called { t.Fatalf("middleware error=%v response=%+v called=%v; want %s and no next call", err, response, called, test.code) } }) } request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, uuid.New()) if _, err := NewCompanyContextMiddleware(companyAuthorizerFunc(func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) { return organization.CompanyAccess{}, nil }))(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) { t.Fatal("mismatched capability reached next") return ogenmiddleware.Response{}, nil }); err == nil { t.Fatal("mismatched capability was accepted") } } // organizationNotificationPaths are the inbox operations of one organization, // which check the membership inside their own transaction. var organizationNotificationPaths = map[string]string{ "ListOrganizationNotifications": "/api/v1/organizations/{org_id}/notifications", "MarkOrganizationNotificationRead": "/api/v1/organizations/{org_id}/notifications/{notification_id}/read", } func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) { const bundlePath = "../../../../../api/core/openapi.bundle.yml" data, err := os.ReadFile(bundlePath) if err != nil { t.Fatalf("read OpenAPI bundle: %v", err) } var document struct { Paths map[string]map[string]struct { OperationID string `yaml:"operationId"` } `yaml:"paths"` } if err := yaml.Unmarshal(data, &document); err != nil { t.Fatalf("decode OpenAPI bundle: %v", err) } if len(ownerCompanyOperations) != 15 { t.Fatalf("owner operation inventory has %d entries, want 15", len(ownerCompanyOperations)) } candidateExceptions := map[string]string{ "HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}", "UnhideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}", "RevokeMyOrganizationContactConsent": "/api/v1/me/consents/c4/organizations/{org_id}", } seen := make(map[string]string, len(ownerCompanyOperations)) seenExceptions := make(map[string]bool, len(candidateExceptions)) seenCardRead := false seenEvidenceRead := false seenNotifications := map[string]bool{} for path, methods := range document.Paths { for _, operation := range methods { if operation.OperationID == "" { continue } _, ownerScoped := ownerCompanyOperations[operation.OperationID] if ownerScoped { if !strings.HasPrefix(path, "/api/v1/organizations/") || !strings.Contains(path, "{org_id}") { t.Errorf("owner operation %s is at unexpected path %s", operation.OperationID, path) } if previous, exists := seen[operation.OperationID]; exists { t.Errorf("owner operation %s appears at both %s and %s", operation.OperationID, previous, path) } seen[operation.OperationID] = path continue } if !strings.Contains(path, "{org_id}") { continue } // The card usecase checks and locks active membership together with // current visibility and quota. It does not require the owner role. if operation.OperationID == "GetOrganizationCandidateCard" && path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" { seenCardRead = true continue } // The evidence of a card is a section of that card: it runs the same // transaction-bound membership, visibility, and quota checks. if operation.OperationID == "GetOrganizationCandidateEvidence" && path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence" { seenEvidenceRead = true continue } // The inbox of one organization authorizes any active membership and // the recipient together with the read, inside the read transaction; // the owner-only capability does not apply. if notificationPath, ok := organizationNotificationPaths[operation.OperationID]; ok && notificationPath == path { seenNotifications[operation.OperationID] = true continue } expectedPath, candidateOperation := candidateExceptions[operation.OperationID] if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") { seenExceptions[operation.OperationID] = true continue } t.Errorf("unclassified organization-scoped operation %s at %s", operation.OperationID, path) } } for operation := range ownerCompanyOperations { if _, ok := seen[operation]; !ok { t.Errorf("owner operation %s is absent from the organization-scoped API contract", operation) } } for operation := range candidateExceptions { if !seenExceptions[operation] { t.Errorf("candidate exception %s is absent or moved without updating the explicit exception", operation) } } if !seenCardRead { t.Error("transaction-authorized candidate card read is absent or moved") } if !seenEvidenceRead { t.Error("transaction-authorized candidate evidence read is absent or moved") } for operation := range organizationNotificationPaths { if !seenNotifications[operation] { t.Errorf("transaction-authorized inbox operation %s is absent or moved", operation) } } } type companyContextAuthenticator struct { session identity.AuthenticatedSession } func (authenticator companyContextAuthenticator) Authenticate(context.Context, string) (identity.AuthenticatedSession, error) { return authenticator.session, nil } func ownerCompanyMiddlewareRequest(t *testing.T, actorID uuid.UUID, operation apiadapter.OperationName, organizationID uuid.UUID) ogenmiddleware.Request { t.Helper() token, err := domain.NewSecretToken() if err != nil { t.Fatalf("NewSecretToken() error = %v", err) } verifiedAt := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC) request := httptest.NewRequest(http.MethodGet, "https://api.example.test/api/v1/organizations/"+organizationID.String(), nil) request.AddCookie(&http.Cookie{Name: httpmiddleware.SessionCookieName, Value: token.Reveal()}) metadata := &requestContextRecorder{} httpmiddleware.SessionRequestMetadata()(metadata).ServeHTTP(httptest.NewRecorder(), request) metadataContext := metadata.context security := v1.NewSessionSecurity(companyContextAuthenticator{session: identity.AuthenticatedSession{ User: domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}, SessionID: uuid.New(), CSRFToken: "company-context-test-csrf", }}, "https://api.example.test") ctx, err := security.HandleSessionCookie(metadataContext, operation, apiadapter.SessionCookie{APIKey: token.Reveal()}) if err != nil { t.Fatalf("HandleSessionCookie() error = %v", err) } return ogenmiddleware.Request{ Context: ctx, OperationName: operation, Params: ogenmiddleware.Parameters{{Name: "org_id", In: openapi.LocationPath}: organizationID}, } }