feat(profile): persist candidate edits and enforce company access

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 14:15:16 +03:00
1 parent 3ab6bd91a3
commit 73c7caa225
67 files changed
+5286 -229

No files matched your search

@@ -0,0 +1,205 @@
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 TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(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{
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("candidate/self-scoped operation: 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")
}
}
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) != 14 {
t.Fatalf("owner operation inventory has %d entries, want 14", 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))
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
}
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)
}
}
}
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},
}
}