feat(accounts): add consent settings and organization management
This commit is contained in:
1 parent
24638d46d2
commit
391af7a1ef
83 files changed
+10198
-613
No files matched your search
@@ -0,0 +1,90 @@
|
||||
package consent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// QueryService reads published consent texts and the current account's ledger.
|
||||
// The repository is a PostgreSQL adapter outside a transaction; history reads
|
||||
// always receive the subject ID selected by the authenticated HTTP boundary.
|
||||
type QueryService struct {
|
||||
repositories outbound.ConsentRepositories
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewQueryService(repositories outbound.ConsentRepositories, clock func() time.Time) *QueryService {
|
||||
if repositories == nil {
|
||||
panic("consent.NewQueryService - repositories must not be nil")
|
||||
}
|
||||
if clock == nil {
|
||||
panic("consent.NewQueryService - clock must not be nil")
|
||||
}
|
||||
return &QueryService{repositories: repositories, clock: clock}
|
||||
}
|
||||
|
||||
func (service *QueryService) CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error) {
|
||||
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
|
||||
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - validate purpose: %w", err)
|
||||
}
|
||||
if purpose.OrganizationScoped() {
|
||||
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - c4 text requires an organization snapshot: %w", ErrScopedConsentRequired)
|
||||
}
|
||||
text, err := service.repositories.ConsentTexts().Current(ctx, purpose, service.clock())
|
||||
if err != nil {
|
||||
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - read current text: %w", err)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
func (service *QueryService) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
|
||||
if query.SubjectID == uuid.Nil {
|
||||
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - subject is required: %w", domain.ErrInvalidConsent)
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize {
|
||||
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - limit is out of range: %w", domain.ErrInvalidConsent)
|
||||
}
|
||||
if query.State != "" {
|
||||
if _, err := domain.ParseConsentState(string(query.State)); err != nil {
|
||||
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - validate state: %w", err)
|
||||
}
|
||||
}
|
||||
if query.After != nil && (query.After.ID == uuid.Nil || query.After.GrantedAt.IsZero()) {
|
||||
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - cursor position is invalid: %w", domain.ErrInvalidConsent)
|
||||
}
|
||||
page, err := service.repositories.ConsentLedger().List(ctx, query)
|
||||
if err != nil {
|
||||
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - read ledger: %w", err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// HasCurrentConsent is the fail-closed check used by consumers that must not
|
||||
// proceed without a current grant. A missing record is a denial; a storage
|
||||
// failure is returned so the caller must also deny instead of assuming consent.
|
||||
func (service *QueryService) HasCurrentConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (bool, error) {
|
||||
if subjectID == uuid.Nil {
|
||||
return false, fmt.Errorf("QueryService.HasCurrentConsent - subject is required: %w", domain.ErrInvalidConsent)
|
||||
}
|
||||
if purpose.OrganizationScoped() {
|
||||
return false, fmt.Errorf("QueryService.HasCurrentConsent - c4 needs an organization scope: %w", domain.ErrInvalidConsent)
|
||||
}
|
||||
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
|
||||
return false, fmt.Errorf("QueryService.HasCurrentConsent - validate purpose: %w", err)
|
||||
}
|
||||
_, err := service.repositories.ConsentLedger().Current(ctx, subjectID, purpose)
|
||||
if errors.Is(err, outbound.ErrConsentNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("QueryService.HasCurrentConsent - read current consent: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package consent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestQueryServiceReadsCurrentTextAndOwnLedgerPosition(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
body := "Current c2 text."
|
||||
hash := domain.HashConsentText(body)
|
||||
text, err := domain.RestoreConsentText(domain.StoredConsentText{
|
||||
Purpose: string(domain.ConsentPurposePublication), Version: "c2-current", Body: body,
|
||||
Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: now.Add(-time.Hour),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountID := uuid.New()
|
||||
position := outbound.ConsentListPosition{GrantedAt: now.Add(-time.Minute), ID: uuid.New()}
|
||||
ledger := &queryTestLedger{current: domain.ConsentRecord{}, page: outbound.ConsentPage{HasMore: true}}
|
||||
reader := NewQueryService(&queryTestRepositories{
|
||||
texts: queryTestTexts{text: text},
|
||||
ledger: ledger,
|
||||
}, func() time.Time { return now })
|
||||
|
||||
gotText, err := reader.CurrentText(context.Background(), domain.ConsentPurposePublication)
|
||||
if err != nil || gotText.Version() != text.Version() || gotText.Body() != body {
|
||||
t.Fatalf("CurrentText() = %#v, %v", gotText, err)
|
||||
}
|
||||
query := outbound.ConsentListQuery{
|
||||
SubjectID: accountID, State: domain.ConsentStateActive,
|
||||
After: &position, Limit: 25,
|
||||
}
|
||||
page, err := reader.List(context.Background(), query)
|
||||
if err != nil || !page.HasMore {
|
||||
t.Fatalf("List() = %#v, %v", page, err)
|
||||
}
|
||||
if ledger.listQuery.SubjectID != accountID || ledger.listQuery.State != query.State ||
|
||||
ledger.listQuery.After == nil || *ledger.listQuery.After != position || ledger.listQuery.Limit != 25 {
|
||||
t.Fatalf("List query = %#v", ledger.listQuery)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryServiceHasCurrentConsentFailsClosed(t *testing.T) {
|
||||
accountID := uuid.New()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
current error
|
||||
want bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "missing grant denies", current: outbound.ErrConsentNotFound},
|
||||
{name: "current grant allows", want: true},
|
||||
{name: "storage failure denies", current: errors.New("storage unavailable"), wantErr: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ledger := &queryTestLedger{currentErr: test.current}
|
||||
reader := NewQueryService(&queryTestRepositories{ledger: ledger}, time.Now)
|
||||
allowed, err := reader.HasCurrentConsent(context.Background(), accountID, domain.ConsentPurposeFSPImport)
|
||||
if allowed != test.want || (err != nil) != test.wantErr {
|
||||
t.Fatalf("HasCurrentConsent() = %v, %v", allowed, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryServiceRejectsC4TextWithoutOrganizationSnapshot(t *testing.T) {
|
||||
reader := NewQueryService(&queryTestRepositories{}, time.Now)
|
||||
if _, err := reader.CurrentText(context.Background(), domain.ConsentPurposeContactDisclosure); !errors.Is(err, ErrScopedConsentRequired) {
|
||||
t.Fatalf("CurrentText(c4) error = %v, want ErrScopedConsentRequired", err)
|
||||
}
|
||||
}
|
||||
|
||||
type queryTestRepositories struct {
|
||||
outbound.ConsentRepositories
|
||||
|
||||
texts outbound.ConsentTextRepository
|
||||
ledger outbound.ConsentLedger
|
||||
}
|
||||
|
||||
func (repositories *queryTestRepositories) ConsentTexts() outbound.ConsentTextRepository {
|
||||
return repositories.texts
|
||||
}
|
||||
|
||||
func (repositories *queryTestRepositories) ConsentLedger() outbound.ConsentLedger {
|
||||
return repositories.ledger
|
||||
}
|
||||
|
||||
type queryTestTexts struct {
|
||||
outbound.ConsentTextRepository
|
||||
|
||||
text domain.ConsentText
|
||||
}
|
||||
|
||||
func (texts queryTestTexts) Current(context.Context, domain.ConsentPurpose, time.Time) (domain.ConsentText, error) {
|
||||
return texts.text, nil
|
||||
}
|
||||
|
||||
type queryTestLedger struct {
|
||||
outbound.ConsentLedger
|
||||
|
||||
currentErr error
|
||||
current domain.ConsentRecord
|
||||
listQuery outbound.ConsentListQuery
|
||||
page outbound.ConsentPage
|
||||
}
|
||||
|
||||
func (ledger *queryTestLedger) Current(context.Context, uuid.UUID, domain.ConsentPurpose) (domain.ConsentRecord, error) {
|
||||
if ledger.currentErr != nil {
|
||||
return domain.ConsentRecord{}, ledger.currentErr
|
||||
}
|
||||
return ledger.current, nil
|
||||
}
|
||||
|
||||
func (ledger *queryTestLedger) List(_ context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
|
||||
ledger.listQuery = query
|
||||
return ledger.page, nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package consent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type SettingsRevocationInput struct {
|
||||
SubjectID uuid.UUID
|
||||
Purpose domain.ConsentPurpose
|
||||
OrganizationID uuid.UUID
|
||||
}
|
||||
|
||||
type RevocationResult struct {
|
||||
Records []domain.ConsentRecord
|
||||
}
|
||||
|
||||
func (service *Service) RevokeInSettingsInNewTransaction(ctx context.Context, input SettingsRevocationInput) (RevocationResult, error) {
|
||||
const location = "Service.RevokeInSettingsInNewTransaction"
|
||||
if input.Purpose == domain.ConsentPurposePersonalData {
|
||||
return RevocationResult{}, fmt.Errorf("%s - c1 uses the account deletion request: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
if input.Purpose == domain.ConsentPurposeContactDisclosure && input.OrganizationID == uuid.Nil {
|
||||
return RevocationResult{}, fmt.Errorf("%s - c4 organization is required: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
if input.Purpose != domain.ConsentPurposeContactDisclosure && input.OrganizationID != uuid.Nil {
|
||||
return RevocationResult{}, fmt.Errorf("%s - organization scope is only valid for c4: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
if _, err := domain.ParseConsentPurpose(string(input.Purpose)); err != nil {
|
||||
return RevocationResult{}, fmt.Errorf("%s - validate purpose: %w", location, err)
|
||||
}
|
||||
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
|
||||
SubjectID: input.SubjectID, Purpose: input.Purpose, OrganizationID: input.OrganizationID,
|
||||
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: service.clock(),
|
||||
})
|
||||
if err != nil {
|
||||
return RevocationResult{}, fmt.Errorf("%s - create revocation: %w", location, err)
|
||||
}
|
||||
var result RevocationResult
|
||||
err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
records, err := unit.ConsentLedger().Revoke(ctx, revocation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - revoke consent ledger: %w", location, err)
|
||||
}
|
||||
if len(records) == 0 {
|
||||
result = RevocationResult{}
|
||||
return nil
|
||||
}
|
||||
if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil {
|
||||
return fmt.Errorf("%s - apply revocation effects: %w", location, err)
|
||||
}
|
||||
result = RevocationResult{Records: records}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return RevocationResult{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error) {
|
||||
const location = "Service.RequestAccountDeletionInNewTransaction"
|
||||
request, err := domain.NewAccountDeletionRequest(subjectID, service.clock())
|
||||
if err != nil {
|
||||
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create request: %w", location, err)
|
||||
}
|
||||
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
|
||||
SubjectID: subjectID, Purpose: domain.ConsentPurposePersonalData,
|
||||
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: request.RequestedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create c1 revocation: %w", location, err)
|
||||
}
|
||||
var result domain.AccountDeletionRequest
|
||||
err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
storedRequest, created, err := unit.AccountDeletionRequests().CreateOrGet(ctx, request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - store account deletion request: %w", location, err)
|
||||
}
|
||||
records, err := unit.ConsentLedger().Revoke(ctx, revocation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - revoke c1 consent: %w", location, err)
|
||||
}
|
||||
if len(records) > 0 {
|
||||
if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil {
|
||||
return fmt.Errorf("%s - apply c1 revocation effects: %w", location, err)
|
||||
}
|
||||
}
|
||||
if created {
|
||||
if err := appendDeletionRequestedEvent(ctx, unit, storedRequest); err != nil {
|
||||
return fmt.Errorf("%s - append deletion request event: %w", location, err)
|
||||
}
|
||||
}
|
||||
result = storedRequest
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type accountDeletionRequestedPayload struct {
|
||||
RequestID uuid.UUID `json:"request_id"`
|
||||
SubjectID uuid.UUID `json:"subject_id"`
|
||||
RequestedAt time.Time `json:"requested_at"`
|
||||
}
|
||||
|
||||
func appendDeletionRequestedEvent(ctx context.Context, unit outbound.UnitOfWork, request domain.AccountDeletionRequest) error {
|
||||
const location = "appendDeletionRequestedEvent"
|
||||
body, err := json.Marshal(accountDeletionRequestedPayload{
|
||||
RequestID: request.ID(), SubjectID: request.SubjectID(), RequestedAt: request.RequestedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - marshal payload: %w", location, err)
|
||||
}
|
||||
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
||||
EventType: "privacy.account_deletion_requested", SchemaVersion: 1,
|
||||
AggregateType: "account_deletion_request", AggregateID: request.ID(), AggregateVersion: 1, Payload: body,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build event: %w", location, err)
|
||||
}
|
||||
if err := unit.Outbox().Append(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - append event: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
package consent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestSettingsRevocationAppliesEffectsOnce(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
subject := uuid.New()
|
||||
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
|
||||
revocationTestRecord(t, subject, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)),
|
||||
}}
|
||||
harness := newRevocationTestService(now, ledger)
|
||||
input := SettingsRevocationInput{SubjectID: subject, Purpose: domain.ConsentPurposePublication}
|
||||
|
||||
first, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input)
|
||||
if err != nil || len(first.Records) != 1 || first.Records[0].State() != domain.ConsentStateRevoked {
|
||||
t.Fatalf("first revoke = %#v, %v; want one revoked record", first, err)
|
||||
}
|
||||
if len(harness.effects.calls) != 1 || harness.effects.calls[0].SubjectID() != subject {
|
||||
t.Fatalf("revocation effects = %v; want one effect for the caller", harness.effects.calls)
|
||||
}
|
||||
|
||||
second, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input)
|
||||
if err != nil || len(second.Records) != 0 {
|
||||
t.Fatalf("repeat revoke = %#v, %v; want no changed records", second, err)
|
||||
}
|
||||
if len(harness.effects.calls) != 1 {
|
||||
t.Fatalf("repeat revoke applied effects again: %d calls", len(harness.effects.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownstreamGrantClosureIsRecordBoundAcrossRegrant(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
for _, purpose := range []domain.ConsentPurpose{domain.ConsentPurposePublication, domain.ConsentPurposeContactDisclosure} {
|
||||
t.Run(string(purpose), func(t *testing.T) {
|
||||
subject := uuid.New()
|
||||
organization := uuid.Nil
|
||||
if purpose.OrganizationScoped() {
|
||||
organization = uuid.New()
|
||||
}
|
||||
oldRecord := revocationTestRecord(t, subject, purpose, organization, now.Add(-time.Hour))
|
||||
ledger := &revocationTestLedger{records: []domain.ConsentRecord{oldRecord}}
|
||||
harness := newRevocationTestService(now, ledger)
|
||||
text := revocationTestConsentText(t, purpose, now.Add(-time.Minute))
|
||||
harness.transactor.unit.texts = revocationTestTexts{text: text}
|
||||
harness.effects.activeDownstreamGrants = map[uuid.UUID]bool{oldRecord.ID(): true}
|
||||
|
||||
_, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
|
||||
SubjectID: subject, Purpose: purpose, OrganizationID: organization,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("revoke %s: %v", purpose, err)
|
||||
}
|
||||
if harness.effects.activeDownstreamGrants[oldRecord.ID()] || !harness.effects.closedConsentRecords[oldRecord.ID()] {
|
||||
t.Fatalf("revocation did not synchronously close downstream grant for consent record %s", oldRecord.ID())
|
||||
}
|
||||
|
||||
var newRecord domain.ConsentRecord
|
||||
if purpose == domain.ConsentPurposeContactDisclosure {
|
||||
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grant, err := harness.service.GrantContact(context.Background(), harness.transactor.unit, ContactGrantInput{
|
||||
SubjectID: subject, OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", Fields: fields,
|
||||
InvitationID: uuid.New(), InvitationTermsVersion: 1, TextVersion: text.Version(),
|
||||
})
|
||||
if err != nil || !grant.Created {
|
||||
t.Fatalf("grant new C4 invitation = %#v, %v", grant, err)
|
||||
}
|
||||
newRecord = grant.Record
|
||||
} else {
|
||||
grant, err := harness.service.GrantInSettingsInNewTransaction(context.Background(), SettingsGrantInput{
|
||||
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(),
|
||||
})
|
||||
if err != nil || !grant.Created {
|
||||
t.Fatalf("grant new C2 version = %#v, %v", grant, err)
|
||||
}
|
||||
newRecord = grant.Record
|
||||
}
|
||||
if newRecord.ID() == oldRecord.ID() || newRecord.State() != domain.ConsentStateActive {
|
||||
t.Fatalf("new consent record = %s/%s, want a distinct active record", newRecord.ID(), newRecord.State())
|
||||
}
|
||||
if harness.effects.closedConsentRecords[newRecord.ID()] || harness.effects.activeDownstreamGrants[oldRecord.ID()] {
|
||||
t.Fatalf("new consent reopened the old downstream grant: old=%s new=%s", oldRecord.ID(), newRecord.ID())
|
||||
}
|
||||
if !harness.effects.tryOpenForCurrentConsent(context.Background(), newRecord, ledger) ||
|
||||
!harness.effects.activeDownstreamGrants[newRecord.ID()] {
|
||||
t.Fatal("test adapter did not open a downstream grant for the new current consent record")
|
||||
}
|
||||
if harness.effects.tryOpenForCurrentConsent(context.Background(), oldRecord, ledger) {
|
||||
t.Fatal("test adapter reopened a grant bound to the revoked consent record")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContactRevocationStaysWithinStoredOrganizationScope(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
subject := uuid.New()
|
||||
organization := uuid.New()
|
||||
otherOrganization := uuid.New()
|
||||
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
|
||||
revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, organization, now.Add(-time.Hour)),
|
||||
revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, otherOrganization, now.Add(-30*time.Minute)),
|
||||
}}
|
||||
harness := newRevocationTestService(now, ledger)
|
||||
|
||||
result, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
|
||||
SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization,
|
||||
})
|
||||
if err != nil || len(result.Records) != 1 || result.Records[0].OrganizationID() != organization {
|
||||
t.Fatalf("scoped revoke = %#v, %v; want only organization %s", result, err, organization)
|
||||
}
|
||||
if len(harness.effects.records) != 1 || harness.effects.records[0].OrganizationID() != organization ||
|
||||
harness.effects.records[0].Fields().Fields()[0] != domain.ContactFieldPhone {
|
||||
t.Fatalf("revocation effect records = %v; want stored organization and field scope", harness.effects.records)
|
||||
}
|
||||
if ledger.records[1].State() != domain.ConsentStateActive {
|
||||
t.Fatalf("record for another organization changed to %s", ledger.records[1].State())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountDeletionRequestIsDurableAndIdempotent(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
subject := uuid.New()
|
||||
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
|
||||
revocationTestRecord(t, subject, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(-time.Hour)),
|
||||
}}
|
||||
harness := newRevocationTestService(now, ledger)
|
||||
|
||||
first, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject)
|
||||
if err != nil || first.IsZero() || first.SubjectID() != subject {
|
||||
t.Fatalf("first deletion request = %#v, %v", first, err)
|
||||
}
|
||||
if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 ||
|
||||
harness.outbox.events[0].EventType() != "privacy.account_deletion_requested" {
|
||||
t.Fatalf("request/outbox counts = %d/%d; want one durable request and one event", len(harness.deletions.requests), len(harness.outbox.events))
|
||||
}
|
||||
if ledger.records[0].State() != domain.ConsentStateRevoked || len(harness.effects.calls) != 1 {
|
||||
t.Fatalf("C1 revocation = %s, effects=%d; want revoked with one intent", ledger.records[0].State(), len(harness.effects.calls))
|
||||
}
|
||||
|
||||
second, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject)
|
||||
if err != nil || second.ID() != first.ID() {
|
||||
t.Fatalf("repeat deletion request = %#v, %v; want same durable request", second, err)
|
||||
}
|
||||
if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 || len(harness.effects.calls) != 1 {
|
||||
t.Fatalf("repeat request duplicated effects: requests=%d events=%d revocations=%d",
|
||||
len(harness.deletions.requests), len(harness.outbox.events), len(harness.effects.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevocationFailureReturnsToTheTransactionBoundary(t *testing.T) {
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
subject := uuid.New()
|
||||
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
|
||||
revocationTestRecord(t, subject, domain.ConsentPurposeFSPImport, uuid.Nil, now.Add(-time.Hour)),
|
||||
}}
|
||||
harness := newRevocationTestService(now, ledger)
|
||||
harness.effects.err = errors.New("outbox unavailable")
|
||||
|
||||
_, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
|
||||
SubjectID: subject, Purpose: domain.ConsentPurposeFSPImport,
|
||||
})
|
||||
if err == nil || !errors.Is(harness.transactor.lastErr, harness.effects.err) {
|
||||
t.Fatalf("revoke error = %v, transaction error = %v; want the effect failure", err, harness.transactor.lastErr)
|
||||
}
|
||||
}
|
||||
|
||||
type revocationTestHarness struct {
|
||||
service *Service
|
||||
transactor *revocationTestTransactor
|
||||
deletions *revocationTestDeletions
|
||||
effects *revocationTestEffects
|
||||
outbox *revocationTestOutbox
|
||||
}
|
||||
|
||||
func newRevocationTestService(now time.Time, ledger *revocationTestLedger) *revocationTestHarness {
|
||||
harness := &revocationTestHarness{
|
||||
deletions: &revocationTestDeletions{}, effects: &revocationTestEffects{}, outbox: &revocationTestOutbox{},
|
||||
}
|
||||
unit := &revocationTestUnit{
|
||||
ledger: ledger, deletions: harness.deletions, effects: harness.effects, outbox: harness.outbox,
|
||||
}
|
||||
harness.transactor = &revocationTestTransactor{unit: unit}
|
||||
harness.service = NewService(harness.transactor, func() time.Time { return now })
|
||||
return harness
|
||||
}
|
||||
|
||||
func revocationTestConsentText(t *testing.T, purpose domain.ConsentPurpose, publishedAt time.Time) domain.ConsentText {
|
||||
t.Helper()
|
||||
body := "I consent to this test purpose."
|
||||
if purpose == domain.ConsentPurposeContactDisclosure {
|
||||
body = "I consent to share selected contacts with {organization}."
|
||||
}
|
||||
hash := domain.HashConsentText(body)
|
||||
text, err := domain.RestoreConsentText(domain.StoredConsentText{
|
||||
Purpose: string(purpose), Version: string(purpose) + "-2026-10-01", Body: body,
|
||||
Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: publishedAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreConsentText() error = %v", err)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func revocationTestRecord(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, organization uuid.UUID, grantedAt time.Time) domain.ConsentRecord {
|
||||
t.Helper()
|
||||
version := domain.ConsentTextVersion(string(purpose) + "-2026-10-01")
|
||||
hash := domain.HashConsentText("consent text")
|
||||
source := domain.ConsentSourceConsentSettings
|
||||
if purpose == domain.ConsentPurposeContactDisclosure {
|
||||
source = domain.ConsentSourceInvitationAcceptance
|
||||
}
|
||||
stored := domain.StoredConsentRecord{
|
||||
ID: uuid.New(), SubjectID: subject, Purpose: string(purpose), TextVersion: string(version), TextHash: hash[:],
|
||||
Source: string(source), State: string(domain.ConsentStateActive), GrantedAt: grantedAt,
|
||||
}
|
||||
if purpose == domain.ConsentPurposeContactDisclosure {
|
||||
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.OrganizationID = organization
|
||||
stored.OrganizationName = "Acme Synthetic LLC"
|
||||
stored.FieldSet = contactFieldCodes(fields.Fields())
|
||||
stored.InvitationID = uuid.New()
|
||||
stored.InvitationTermsVersion = 1
|
||||
}
|
||||
record, err := domain.RestoreConsentRecord(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreConsentRecord() error = %v", err)
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
type revocationTestLedger struct {
|
||||
outbound.ConsentLedger
|
||||
|
||||
records []domain.ConsentRecord
|
||||
}
|
||||
|
||||
type revocationTestTexts struct {
|
||||
outbound.ConsentTextRepository
|
||||
|
||||
text domain.ConsentText
|
||||
}
|
||||
|
||||
func (texts revocationTestTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) {
|
||||
if texts.text.IsZero() || texts.text.Purpose() != purpose {
|
||||
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
|
||||
}
|
||||
return texts.text, nil
|
||||
}
|
||||
|
||||
func (ledger *revocationTestLedger) Grant(_ context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) {
|
||||
for _, existing := range ledger.records {
|
||||
if existing.SubjectID() == grant.SubjectID() && existing.Purpose() == grant.Purpose() &&
|
||||
existing.TextVersion() == grant.TextVersion() && existing.State() != domain.ConsentStateRevoked {
|
||||
return existing, false, nil
|
||||
}
|
||||
}
|
||||
hash := grant.TextHash()
|
||||
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
|
||||
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()),
|
||||
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(grant.Source()),
|
||||
RegistrationVersion: grant.RegistrationVersion(), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, false, err
|
||||
}
|
||||
ledger.records = append(ledger.records, record)
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func (ledger *revocationTestLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
|
||||
for _, existing := range ledger.records {
|
||||
if existing.InvitationID() == grant.InvitationID() {
|
||||
if existing.SubjectID() != grant.SubjectID() {
|
||||
return domain.ConsentRecord{}, false, outbound.ErrConsentInvitationTaken
|
||||
}
|
||||
return existing, false, nil
|
||||
}
|
||||
}
|
||||
hash := grant.TextHash()
|
||||
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
|
||||
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure),
|
||||
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
|
||||
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(),
|
||||
OrganizationName: grant.OrganizationName(), FieldSet: contactFieldCodes(grant.Fields().Fields()),
|
||||
InvitationID: grant.InvitationID(), InvitationTermsVersion: grant.InvitationTermsVersion(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, false, err
|
||||
}
|
||||
ledger.records = append(ledger.records, record)
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func (ledger *revocationTestLedger) Current(_ context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) {
|
||||
var current domain.ConsentRecord
|
||||
for _, record := range ledger.records {
|
||||
if record.SubjectID() != subjectID || record.Purpose() != purpose || record.State() == domain.ConsentStateRevoked {
|
||||
continue
|
||||
}
|
||||
if current.IsZero() || record.GrantedAt().After(current.GrantedAt()) ||
|
||||
(record.GrantedAt().Equal(current.GrantedAt()) && record.ID().String() > current.ID().String()) {
|
||||
current = record
|
||||
}
|
||||
}
|
||||
if current.IsZero() {
|
||||
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (ledger *revocationTestLedger) CurrentContact(_ context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
|
||||
var current []domain.ConsentRecord
|
||||
for _, record := range ledger.records {
|
||||
if record.SubjectID() == subjectID && record.Purpose() == domain.ConsentPurposeContactDisclosure &&
|
||||
record.OrganizationID() == organizationID && record.State() != domain.ConsentStateRevoked {
|
||||
current = append(current, record)
|
||||
}
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (ledger *revocationTestLedger) Revoke(_ context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) {
|
||||
var revoked []domain.ConsentRecord
|
||||
for index, record := range ledger.records {
|
||||
if record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
|
||||
record.State() == domain.ConsentStateRevoked ||
|
||||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
|
||||
continue
|
||||
}
|
||||
revokedAt := revocation.RevokedAt()
|
||||
if revokedAt.Before(record.GrantedAt()) {
|
||||
revokedAt = record.GrantedAt()
|
||||
}
|
||||
hash := record.TextHash()
|
||||
var contactFields []string
|
||||
if revocation.Purpose().OrganizationScoped() {
|
||||
contactFields = contactFieldCodes(record.Fields().Fields())
|
||||
}
|
||||
stored := domain.StoredConsentRecord{
|
||||
ID: record.ID(), SubjectID: record.SubjectID(), Purpose: string(record.Purpose()),
|
||||
TextVersion: string(record.TextVersion()), TextHash: hash[:], Source: string(record.Source()),
|
||||
RegistrationVersion: record.RegistrationVersion(), State: string(domain.ConsentStateRevoked), GrantedAt: record.GrantedAt(),
|
||||
RevokedAt: &revokedAt, RevocationSource: string(revocation.Source()), OrganizationID: record.OrganizationID(),
|
||||
OrganizationName: record.OrganizationName(), FieldSet: contactFields, InvitationID: record.InvitationID(),
|
||||
InvitationTermsVersion: record.InvitationTermsVersion(),
|
||||
}
|
||||
updated, err := domain.RestoreConsentRecord(stored)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ledger.records[index] = updated
|
||||
revoked = append(revoked, updated)
|
||||
}
|
||||
return revoked, nil
|
||||
}
|
||||
|
||||
func contactFieldCodes(fields []domain.ContactField) []string {
|
||||
codes := make([]string, 0, len(fields))
|
||||
for _, field := range fields {
|
||||
codes = append(codes, string(field))
|
||||
}
|
||||
return codes
|
||||
}
|
||||
|
||||
type revocationTestDeletions struct {
|
||||
outbound.AccountDeletionRequests
|
||||
|
||||
requests []domain.AccountDeletionRequest
|
||||
}
|
||||
|
||||
func (repository *revocationTestDeletions) CreateOrGet(_ context.Context, request domain.AccountDeletionRequest) (domain.AccountDeletionRequest, bool, error) {
|
||||
for _, existing := range repository.requests {
|
||||
if existing.SubjectID() == request.SubjectID() {
|
||||
return existing, false, nil
|
||||
}
|
||||
}
|
||||
repository.requests = append(repository.requests, request)
|
||||
return request, true, nil
|
||||
}
|
||||
|
||||
type revocationTestEffects struct {
|
||||
outbound.ConsentRevocationEffects
|
||||
|
||||
calls []domain.ConsentRevocation
|
||||
records []domain.ConsentRecord
|
||||
activeDownstreamGrants map[uuid.UUID]bool
|
||||
closedConsentRecords map[uuid.UUID]bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (effects *revocationTestEffects) Apply(_ context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error {
|
||||
if effects.err != nil {
|
||||
return effects.err
|
||||
}
|
||||
effects.calls = append(effects.calls, revocation)
|
||||
effects.records = append(effects.records, records...)
|
||||
if effects.activeDownstreamGrants == nil {
|
||||
effects.activeDownstreamGrants = make(map[uuid.UUID]bool)
|
||||
}
|
||||
if effects.closedConsentRecords == nil {
|
||||
effects.closedConsentRecords = make(map[uuid.UUID]bool)
|
||||
}
|
||||
for _, record := range records {
|
||||
effects.activeDownstreamGrants[record.ID()] = false
|
||||
effects.closedConsentRecords[record.ID()] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (effects *revocationTestEffects) tryOpenForCurrentConsent(
|
||||
ctx context.Context,
|
||||
record domain.ConsentRecord,
|
||||
ledger outbound.ConsentLedger,
|
||||
) bool {
|
||||
if record.IsZero() || effects.closedConsentRecords[record.ID()] {
|
||||
return false
|
||||
}
|
||||
if record.Purpose().OrganizationScoped() {
|
||||
current, err := ledger.CurrentContact(ctx, record.SubjectID(), record.OrganizationID())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, candidate := range current {
|
||||
if candidate.ID() == record.ID() {
|
||||
effects.activeDownstreamGrants[record.ID()] = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
current, err := ledger.Current(ctx, record.SubjectID(), record.Purpose())
|
||||
if err != nil || current.ID() != record.ID() {
|
||||
return false
|
||||
}
|
||||
if effects.activeDownstreamGrants == nil {
|
||||
effects.activeDownstreamGrants = make(map[uuid.UUID]bool)
|
||||
}
|
||||
effects.activeDownstreamGrants[record.ID()] = true
|
||||
return true
|
||||
}
|
||||
|
||||
type revocationTestOutbox struct {
|
||||
outbound.OutboxWriter
|
||||
|
||||
events []domain.DomainEvent
|
||||
}
|
||||
|
||||
func (outbox *revocationTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
|
||||
outbox.events = append(outbox.events, events...)
|
||||
return nil
|
||||
}
|
||||
|
||||
type revocationTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
ledger *revocationTestLedger
|
||||
texts outbound.ConsentTextRepository
|
||||
deletions *revocationTestDeletions
|
||||
effects *revocationTestEffects
|
||||
outbox *revocationTestOutbox
|
||||
}
|
||||
|
||||
func (unit *revocationTestUnit) ConsentLedger() outbound.ConsentLedger { return unit.ledger }
|
||||
|
||||
func (unit *revocationTestUnit) ConsentTexts() outbound.ConsentTextRepository { return unit.texts }
|
||||
|
||||
func (unit *revocationTestUnit) AccountDeletionRequests() outbound.AccountDeletionRequests {
|
||||
return unit.deletions
|
||||
}
|
||||
|
||||
func (unit *revocationTestUnit) ConsentRevocationEffects() outbound.ConsentRevocationEffects {
|
||||
return unit.effects
|
||||
}
|
||||
|
||||
func (unit *revocationTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
|
||||
|
||||
type revocationTestTransactor struct {
|
||||
unit *revocationTestUnit
|
||||
lastErr error
|
||||
}
|
||||
|
||||
func (transactor *revocationTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.lastErr = work(ctx, transactor.unit)
|
||||
return transactor.lastErr
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package consent grants the consents C1-C5 of the consent ledger.
|
||||
// Package consent manages consent grants, revocations, and the C1 deletion request.
|
||||
//
|
||||
// A grant is checked against the current published text of its purpose and
|
||||
// is recorded with the application clock; the client names the text version
|
||||
@@ -9,9 +9,13 @@
|
||||
// product function; a subject without C3 simply has no C3 record, and
|
||||
// Current reports ErrConsentNotFound for it.
|
||||
//
|
||||
// Revocation is not part of this package. Its downstream effects (closing
|
||||
// publication and grants, the deletion request, the manual path, stopping
|
||||
// the import) belong to consent revocation, which calls ConsentLedger().Revoke.
|
||||
// C1 revocation creates a durable account-deletion request and never deletes
|
||||
// the account synchronously. Other revocations update the ledger and apply
|
||||
// transaction-bound effects. C2 closes local publication, C3 leaves the
|
||||
// manual assessment path available, and C5 denies future import through the
|
||||
// current-consent gate. Outbox events are notifications rather than access
|
||||
// checks; external FSP deletion and downstream contact-grant adapters are not
|
||||
// implemented here.
|
||||
package consent
|
||||
|
||||
import (
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package organization
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// ErrForbidden reports an account that cannot create or manage an
|
||||
// organization.
|
||||
ErrForbidden = errors.New("organization operation forbidden")
|
||||
|
||||
// ErrEmailNotVerified reports an account whose current email is not
|
||||
// confirmed.
|
||||
ErrEmailNotVerified = errors.New("organization requires a confirmed email")
|
||||
|
||||
// ErrIdempotencyKeyReused reports a live key first used with another body.
|
||||
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
|
||||
|
||||
// ErrInvalidIdempotencyKey reports a key outside the public contract bound.
|
||||
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
|
||||
|
||||
// ErrInvalidCreateRequest reports an oversized canonical request body.
|
||||
ErrInvalidCreateRequest = errors.New("invalid organization create request")
|
||||
)
|
||||
@@ -0,0 +1,376 @@
|
||||
// Package organization creates organizations and lets their owners edit the
|
||||
// company profile.
|
||||
package organization
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
createOperation = "organization.create"
|
||||
createLocation = "organization.Service.Create"
|
||||
maxIdempotencyKeySize = 255
|
||||
maxCanonicalBodySize = 1 << 20
|
||||
purgeExpiredBatch = 100
|
||||
)
|
||||
|
||||
// Keyring computes scoped idempotency digests. identity.Keyring implements
|
||||
// this interface so the feature uses the existing server secret and storage.
|
||||
type Keyring interface {
|
||||
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
|
||||
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
|
||||
}
|
||||
|
||||
// Dependencies are the collaborators of Service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Keyring Keyring
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
// Service applies organization commands. It stores no request state.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewService fails at startup when a required dependency is missing.
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
|
||||
return nil, errors.New("organization.NewService - every dependency must be set")
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
|
||||
}
|
||||
|
||||
// CreateCommand is the caller and profile content of one create request.
|
||||
type CreateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
IdempotencyKey string
|
||||
CanonicalBody []byte
|
||||
Profile domain.OrganizationProfileInput
|
||||
}
|
||||
|
||||
// CreateResult is the organization and owner membership created by a request.
|
||||
// Replayed marks an identical request answered from the immutable result
|
||||
// snapshot; it does not change the public status or body.
|
||||
type CreateResult struct {
|
||||
Organization domain.Organization
|
||||
Owner domain.Membership
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
type createRequest struct {
|
||||
command CreateCommand
|
||||
fingerprint [outbound.IdempotencyDigestSize]byte
|
||||
scope [outbound.IdempotencyDigestSize]byte
|
||||
record outbound.IdempotencyRecord
|
||||
now time.Time
|
||||
}
|
||||
|
||||
// Create creates a company and its active owner membership in one
|
||||
// transaction. An identical key and body returns the original creation
|
||||
// snapshot, even if the live profile has since changed.
|
||||
func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) {
|
||||
request, err := service.prepareCreateRequest(command)
|
||||
if err != nil {
|
||||
return CreateResult{}, err
|
||||
}
|
||||
var result CreateResult
|
||||
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
created, err := service.createInTransaction(ctx, unit, request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result = created
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) {
|
||||
switch {
|
||||
case command.ActorID == uuid.Nil:
|
||||
return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", createLocation, ErrForbidden)
|
||||
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
|
||||
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", createLocation, ErrInvalidIdempotencyKey)
|
||||
}
|
||||
canonical := command.CanonicalBody
|
||||
if len(canonical) == 0 {
|
||||
var err error
|
||||
canonical, err = canonicalCreateBody(command.Profile)
|
||||
if err != nil {
|
||||
return createRequest{}, fmt.Errorf("%s - encode canonical profile", createLocation)
|
||||
}
|
||||
}
|
||||
if len(canonical) > maxCanonicalBodySize {
|
||||
return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", createLocation, ErrInvalidCreateRequest)
|
||||
}
|
||||
fingerprint := service.keyring.Fingerprint(canonical)
|
||||
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String())
|
||||
now := service.clock()
|
||||
if now.IsZero() {
|
||||
return createRequest{}, fmt.Errorf("%s - application time must be set", createLocation)
|
||||
}
|
||||
record := outbound.IdempotencyRecord{
|
||||
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention),
|
||||
}
|
||||
return createRequest{command: command, fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
|
||||
}
|
||||
|
||||
func (service *Service) createInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request createRequest,
|
||||
) (CreateResult, error) {
|
||||
if err := requireEmployer(ctx, unit, request.command.ActorID, createLocation); err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - authorize creator: %w", createLocation, err)
|
||||
}
|
||||
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
|
||||
}
|
||||
if !created {
|
||||
return replayCreation(ctx, unit, request, stored)
|
||||
}
|
||||
return service.createOrganization(ctx, unit, request)
|
||||
}
|
||||
|
||||
func replayCreation(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request createRequest,
|
||||
stored outbound.IdempotencyRecord,
|
||||
) (CreateResult, error) {
|
||||
if stored.Fingerprint != request.fingerprint {
|
||||
return CreateResult{}, ErrIdempotencyKeyReused
|
||||
}
|
||||
snapshot, err := unit.Organizations().GetCreationResult(ctx, request.scope)
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - read creation snapshot: %w", createLocation, err)
|
||||
}
|
||||
if !validCreationSnapshot(snapshot, request.command.ActorID) {
|
||||
return CreateResult{}, fmt.Errorf("%s - stored creation snapshot does not match the actor: %w", createLocation, domain.ErrInvalidMembership)
|
||||
}
|
||||
return CreateResult{Organization: snapshot.Organization, Owner: snapshot.Owner, Replayed: true}, nil
|
||||
}
|
||||
|
||||
func validCreationSnapshot(snapshot outbound.OrganizationCreationResult, actorID uuid.UUID) bool {
|
||||
if snapshot.Organization.IsZero() || snapshot.Owner.IsZero() {
|
||||
return false
|
||||
}
|
||||
return snapshot.Owner.UserID() == actorID &&
|
||||
snapshot.Owner.OrganizationID() == snapshot.Organization.ID() &&
|
||||
snapshot.Owner.Role() == domain.OrganizationRoleOwner && snapshot.Owner.GrantsAccess()
|
||||
}
|
||||
|
||||
func (service *Service) createOrganization(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
request createRequest,
|
||||
) (CreateResult, error) {
|
||||
profile, err := domain.NewOrganizationProfile(request.command.Profile)
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - validate profile: %w", createLocation, err)
|
||||
}
|
||||
company, err := domain.NewOrganization(profile, request.now)
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - build organization: %w", createLocation, err)
|
||||
}
|
||||
owner, err := domain.NewOwnerMembership(company.ID(), request.command.ActorID, request.now)
|
||||
if err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - build owner membership: %w", createLocation, err)
|
||||
}
|
||||
if err := unit.Organizations().CreateWithOwner(ctx, company, owner); err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - store organization and owner: %w", createLocation, err)
|
||||
}
|
||||
creation := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
|
||||
if err := unit.Organizations().SaveCreationResult(ctx, request.scope, creation); err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - store creation snapshot: %w", createLocation, err)
|
||||
}
|
||||
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
|
||||
return CreateResult{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
|
||||
}
|
||||
return CreateResult{Organization: company, Owner: owner}, nil
|
||||
}
|
||||
|
||||
func canonicalCreateBody(profile domain.OrganizationProfileInput) ([]byte, error) {
|
||||
// An ordered array makes the fingerprint stable for non-HTTP callers.
|
||||
return json.Marshal([]any{
|
||||
profile.Name,
|
||||
profile.Description,
|
||||
profile.Sphere,
|
||||
profile.Contacts.Website,
|
||||
profile.Contacts.Email,
|
||||
profile.Contacts.Phone,
|
||||
profile.Contacts.Telegram,
|
||||
profile.Representatives,
|
||||
})
|
||||
}
|
||||
|
||||
// OptionalString distinguishes an absent field from a present value. An empty
|
||||
// value clears nullable description and sphere fields.
|
||||
type OptionalString struct {
|
||||
Set bool
|
||||
Value string
|
||||
}
|
||||
|
||||
// ProfilePatch is the set of editable fields present in an update request.
|
||||
// Contacts and representatives replace their complete value when set.
|
||||
type ProfilePatch struct {
|
||||
Name OptionalString
|
||||
Description OptionalString
|
||||
Sphere OptionalString
|
||||
Contacts *domain.OrganizationContactsInput
|
||||
Representatives *[]domain.OrganizationRepresentativeInput
|
||||
}
|
||||
|
||||
// UpdateCommand describes a versioned profile edit.
|
||||
type UpdateCommand struct {
|
||||
ActorID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
ExpectedVersion int64
|
||||
Patch ProfilePatch
|
||||
}
|
||||
|
||||
// Update merges the patch over the current profile, preserves verification,
|
||||
// and checks that the acting account is the active owner.
|
||||
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Organization, error) {
|
||||
const location = "organization.Service.Update"
|
||||
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
if command.ExpectedVersion < 1 {
|
||||
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
|
||||
}
|
||||
var result domain.Organization
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
|
||||
return fmt.Errorf("%s - authorize editor: %w", location, err)
|
||||
}
|
||||
current, membership, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read organization for member: %w", location, err)
|
||||
}
|
||||
if !membership.CanManageOrganization() {
|
||||
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
|
||||
}
|
||||
profile, err := applyPatch(current.Profile(), command.Patch)
|
||||
if err != nil {
|
||||
if command.ExpectedVersion != current.Version() {
|
||||
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
|
||||
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
|
||||
}
|
||||
return fmt.Errorf("%s - validate profile: %w", location, err)
|
||||
}
|
||||
if current.Profile().Equal(profile) {
|
||||
result = current
|
||||
return nil
|
||||
}
|
||||
if command.ExpectedVersion != current.Version() {
|
||||
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
|
||||
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
|
||||
}
|
||||
updated, err := current.ApplyProfile(profile, service.clock())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - apply profile: %w", location, err)
|
||||
}
|
||||
result, err = unit.Organizations().UpdateProfile(ctx, command.ActorID, updated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - store profile: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Get reads an organization only for an active member of the employer
|
||||
// account. The membership is checked in the same transaction as the account.
|
||||
func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) {
|
||||
const location = "organization.Service.Get"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
|
||||
}
|
||||
var result domain.Organization
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
|
||||
return fmt.Errorf("%s - authorize reader: %w", location, err)
|
||||
}
|
||||
organization, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read organization for member: %w", location, err)
|
||||
}
|
||||
if !membership.GrantsAccess() {
|
||||
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
result = organization
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
|
||||
contacts := current.Contacts()
|
||||
input := domain.OrganizationProfileInput{
|
||||
Name: current.Name(), Description: current.Description(), Sphere: current.Sphere(),
|
||||
Contacts: domain.OrganizationContactsInput{
|
||||
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
|
||||
},
|
||||
}
|
||||
for _, representative := range current.Representatives() {
|
||||
input.Representatives = append(input.Representatives, domain.OrganizationRepresentativeInput{
|
||||
Name: representative.Name(), JobTitle: representative.JobTitle(),
|
||||
})
|
||||
}
|
||||
if patch.Name.Set {
|
||||
input.Name = patch.Name.Value
|
||||
}
|
||||
if patch.Description.Set {
|
||||
input.Description = patch.Description.Value
|
||||
}
|
||||
if patch.Sphere.Set {
|
||||
input.Sphere = patch.Sphere.Value
|
||||
}
|
||||
if patch.Contacts != nil {
|
||||
input.Contacts = *patch.Contacts
|
||||
}
|
||||
if patch.Representatives != nil {
|
||||
input.Representatives = append([]domain.OrganizationRepresentativeInput(nil), (*patch.Representatives)...)
|
||||
}
|
||||
return domain.NewOrganizationProfile(input)
|
||||
}
|
||||
|
||||
func requireEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) error {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return ErrEmailNotVerified
|
||||
}
|
||||
if user.Scenario != domain.ScenarioEmployer {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
package organization
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
type organizationTestState struct {
|
||||
users map[uuid.UUID]domain.User
|
||||
organizations map[uuid.UUID]domain.Organization
|
||||
memberships map[organizationTestMembershipKey]domain.Membership
|
||||
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
||||
results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult
|
||||
}
|
||||
|
||||
type organizationTestMembershipKey struct {
|
||||
organizationID uuid.UUID
|
||||
userID uuid.UUID
|
||||
}
|
||||
|
||||
func newOrganizationTestState() organizationTestState {
|
||||
return organizationTestState{
|
||||
users: map[uuid.UUID]domain.User{},
|
||||
organizations: map[uuid.UUID]domain.Organization{},
|
||||
memberships: map[organizationTestMembershipKey]domain.Membership{},
|
||||
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
|
||||
results: map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult{},
|
||||
}
|
||||
}
|
||||
|
||||
func (state organizationTestState) clone() organizationTestState {
|
||||
cloned := newOrganizationTestState()
|
||||
for id, user := range state.users {
|
||||
cloned.users[id] = user
|
||||
}
|
||||
for id, company := range state.organizations {
|
||||
cloned.organizations[id] = company
|
||||
}
|
||||
for key, membership := range state.memberships {
|
||||
cloned.memberships[key] = membership
|
||||
}
|
||||
for scope, record := range state.idempotency {
|
||||
cloned.idempotency[scope] = record
|
||||
}
|
||||
for scope, result := range state.results {
|
||||
cloned.results[scope] = result
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
type organizationTestTransactor struct {
|
||||
mu sync.Mutex
|
||||
state organizationTestState
|
||||
failOwnerInsert bool
|
||||
}
|
||||
|
||||
func newOrganizationTestTransactor() *organizationTestTransactor {
|
||||
return &organizationTestTransactor{state: newOrganizationTestState()}
|
||||
}
|
||||
|
||||
func (transactor *organizationTestTransactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
work func(context.Context, outbound.UnitOfWork) error,
|
||||
) error {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
working := transactor.state.clone()
|
||||
unit := &organizationTestUnit{state: &working, failOwnerInsert: transactor.failOwnerInsert}
|
||||
if err := work(ctx, unit); err != nil {
|
||||
return err
|
||||
}
|
||||
transactor.state = working
|
||||
return nil
|
||||
}
|
||||
|
||||
func (transactor *organizationTestTransactor) snapshot() organizationTestState {
|
||||
transactor.mu.Lock()
|
||||
defer transactor.mu.Unlock()
|
||||
return transactor.state.clone()
|
||||
}
|
||||
|
||||
type organizationTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
state *organizationTestState
|
||||
failOwnerInsert bool
|
||||
}
|
||||
|
||||
func (unit *organizationTestUnit) Users() outbound.UserRepository {
|
||||
return organizationTestUsers{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *organizationTestUnit) IdempotencyRecords() outbound.IdempotencyRepository {
|
||||
return organizationTestIdempotency{state: unit.state}
|
||||
}
|
||||
|
||||
func (unit *organizationTestUnit) Organizations() outbound.OrganizationRepository {
|
||||
return organizationTestOrganizations{state: unit.state, failOwnerInsert: unit.failOwnerInsert}
|
||||
}
|
||||
|
||||
type organizationTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
state *organizationTestState
|
||||
}
|
||||
|
||||
func (repository organizationTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.state.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type organizationTestIdempotency struct {
|
||||
outbound.IdempotencyRepository
|
||||
|
||||
state *organizationTestState
|
||||
}
|
||||
|
||||
func (repository organizationTestIdempotency) Reserve(
|
||||
_ context.Context,
|
||||
record outbound.IdempotencyRecord,
|
||||
) (outbound.IdempotencyRecord, bool, error) {
|
||||
if stored, ok := repository.state.idempotency[record.Scope]; ok && stored.ExpiresAt.After(record.CreatedAt) {
|
||||
return stored, false, nil
|
||||
}
|
||||
repository.state.idempotency[record.Scope] = record
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func (repository organizationTestIdempotency) Find(
|
||||
_ context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
at time.Time,
|
||||
) (outbound.IdempotencyRecord, error) {
|
||||
record, ok := repository.state.idempotency[scope]
|
||||
if !ok || !record.ExpiresAt.After(at) {
|
||||
return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (repository organizationTestIdempotency) PurgeExpired(
|
||||
_ context.Context,
|
||||
at time.Time,
|
||||
limit int32,
|
||||
) (int64, error) {
|
||||
var deleted int64
|
||||
for scope, record := range repository.state.idempotency {
|
||||
if deleted >= int64(limit) {
|
||||
break
|
||||
}
|
||||
if !record.ExpiresAt.After(at) {
|
||||
delete(repository.state.idempotency, scope)
|
||||
delete(repository.state.results, scope)
|
||||
deleted++
|
||||
}
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
type organizationTestOrganizations struct {
|
||||
outbound.OrganizationRepository
|
||||
|
||||
state *organizationTestState
|
||||
failOwnerInsert bool
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) CreateWithOwner(
|
||||
_ context.Context,
|
||||
company domain.Organization,
|
||||
owner domain.Membership,
|
||||
) error {
|
||||
repository.state.organizations[company.ID()] = company
|
||||
if repository.failOwnerInsert {
|
||||
return errors.New("simulated owner membership insert failure")
|
||||
}
|
||||
repository.state.memberships[organizationTestMembershipKey{company.ID(), owner.UserID()}] = owner
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) SaveCreationResult(
|
||||
_ context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
result outbound.OrganizationCreationResult,
|
||||
) error {
|
||||
if _, ok := repository.state.idempotency[scope]; !ok {
|
||||
return outbound.ErrIdempotencyRecordNotFound
|
||||
}
|
||||
repository.state.results[scope] = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) GetCreationResult(
|
||||
_ context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (outbound.OrganizationCreationResult, error) {
|
||||
result, ok := repository.state.results[scope]
|
||||
if !ok {
|
||||
return outbound.OrganizationCreationResult{}, outbound.ErrOrganizationCreationResultNotFound
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) GetForMember(
|
||||
_ context.Context,
|
||||
organizationID, userID uuid.UUID,
|
||||
) (domain.Organization, domain.Membership, error) {
|
||||
company, companyOK := repository.state.organizations[organizationID]
|
||||
membership, memberOK := repository.state.memberships[organizationTestMembershipKey{organizationID, userID}]
|
||||
if !companyOK || !memberOK || !membership.GrantsAccess() {
|
||||
return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return company, membership, nil
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) ListForUser(
|
||||
context.Context,
|
||||
outbound.OrganizationListQuery,
|
||||
) (outbound.OrganizationPage, error) {
|
||||
return outbound.OrganizationPage{}, nil
|
||||
}
|
||||
|
||||
func (repository organizationTestOrganizations) UpdateProfile(
|
||||
_ context.Context,
|
||||
actorID uuid.UUID,
|
||||
updated domain.Organization,
|
||||
) (domain.Organization, error) {
|
||||
current, ok := repository.state.organizations[updated.ID()]
|
||||
if !ok {
|
||||
return domain.Organization{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
membership, ok := repository.state.memberships[organizationTestMembershipKey{updated.ID(), actorID}]
|
||||
if !ok || !membership.GrantsAccess() {
|
||||
return domain.Organization{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
if !membership.CanManageOrganization() {
|
||||
return domain.Organization{}, outbound.ErrOrganizationManagerRequired
|
||||
}
|
||||
if current.Version() != updated.Version() {
|
||||
return domain.Organization{}, outbound.ErrOrganizationVersionConflict
|
||||
}
|
||||
company, err := restoreOrganizationVersion(updated, current.Version()+1)
|
||||
if err != nil {
|
||||
return domain.Organization{}, err
|
||||
}
|
||||
repository.state.organizations[updated.ID()] = company
|
||||
return company, nil
|
||||
}
|
||||
|
||||
func restoreOrganizationVersion(company domain.Organization, version int64) (domain.Organization, error) {
|
||||
profile := company.Profile()
|
||||
contacts := profile.Contacts()
|
||||
representatives := profile.Representatives()
|
||||
storedRepresentatives := make([]domain.StoredRepresentative, 0, len(representatives))
|
||||
for _, representative := range representatives {
|
||||
storedRepresentatives = append(storedRepresentatives, domain.StoredRepresentative{
|
||||
Name: representative.Name(), JobTitle: representative.JobTitle(),
|
||||
})
|
||||
}
|
||||
verification := company.Verification()
|
||||
return domain.RestoreOrganization(domain.StoredOrganization{
|
||||
ID: company.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(),
|
||||
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
|
||||
Representatives: storedRepresentatives, VerificationLevel: string(verification.Level()),
|
||||
VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(),
|
||||
Version: version, CreatedAt: company.CreatedAt(), UpdatedAt: company.UpdatedAt(),
|
||||
})
|
||||
}
|
||||
|
||||
func newOrganizationTestService(t *testing.T, tx *organizationTestTransactor, clock func() time.Time) *Service {
|
||||
t.Helper()
|
||||
keyring, err := identity.NewKeyring([]byte(strings.Repeat("k", identity.MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
service, err := NewService(Dependencies{Transactor: tx, Keyring: keyring, Clock: clock})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
func verifiedEmployer(id uuid.UUID, at time.Time) domain.User {
|
||||
verifiedAt := at
|
||||
return domain.User{ID: id, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
|
||||
}
|
||||
|
||||
func organizationProfile(name, description string) domain.OrganizationProfileInput {
|
||||
return domain.OrganizationProfileInput{
|
||||
Name: name, Description: description, Sphere: "Payments",
|
||||
Contacts: domain.OrganizationContactsInput{
|
||||
Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example",
|
||||
},
|
||||
Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}},
|
||||
}
|
||||
}
|
||||
|
||||
func canonicalBodyForTest(t *testing.T, profile domain.OrganizationProfileInput) []byte {
|
||||
t.Helper()
|
||||
body, err := canonicalCreateBody(profile)
|
||||
if err != nil {
|
||||
t.Fatalf("canonicalCreateBody() error = %v", err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func TestCreateStoresOwnerAtE0AndReplaysOriginalSnapshotAfterEdit(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 123456000, time.UTC)
|
||||
currentTime := now
|
||||
tx := newOrganizationTestTransactor()
|
||||
ownerID := uuid.New()
|
||||
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return currentTime })
|
||||
profile := organizationProfile("ООО Пример", "Первоначальные данные")
|
||||
command := CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: "company-create-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
|
||||
}
|
||||
|
||||
created, err := service.Create(ctx, command)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
if created.Replayed || created.Organization.Version() != 1 || created.Owner.UserID() != ownerID ||
|
||||
created.Owner.Role() != domain.OrganizationRoleOwner || !created.Owner.GrantsAccess() {
|
||||
t.Fatalf("Create() = %+v, want a new version 1 organization and its active owner", created)
|
||||
}
|
||||
verification := created.Organization.Verification()
|
||||
if verification.Level() != domain.OrganizationVerificationE0 || verification.Basis() != domain.OrganizationBasisConfirmedEmail {
|
||||
t.Fatalf("verification = %s %s, want e0 from confirmed email", verification.Level(), verification.Basis())
|
||||
}
|
||||
if card := created.Organization.CandidateCard(); card.ID() != created.Organization.ID() || card.VerificationLevel() != domain.OrganizationVerificationE0 {
|
||||
t.Fatalf("CandidateCard() = %+v, want the safe organization card", card)
|
||||
}
|
||||
|
||||
currentTime = now.Add(time.Minute)
|
||||
updated, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Измененные данные"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Update() error = %v", err)
|
||||
}
|
||||
if updated.Profile().Description() != "Измененные данные" || updated.Version() != 2 ||
|
||||
updated.Verification().Level() != domain.OrganizationVerificationE0 {
|
||||
t.Fatalf("Update() = %+v, want version 2 with the edited profile and e0", updated)
|
||||
}
|
||||
|
||||
replayed, err := service.Create(ctx, command)
|
||||
if err != nil {
|
||||
t.Fatalf("Create(retry) error = %v", err)
|
||||
}
|
||||
if !replayed.Replayed || replayed.Organization.ID() != created.Organization.ID() ||
|
||||
!replayed.Organization.Profile().Equal(created.Organization.Profile()) ||
|
||||
replayed.Organization.Version() != 1 || replayed.Owner.ID() != created.Owner.ID() {
|
||||
t.Fatalf("Create(retry) = %+v, want the original immutable result", replayed)
|
||||
}
|
||||
state := tx.snapshot()
|
||||
if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 {
|
||||
t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRejectsChangedBodyAndAllowsReuseAfterExpiration(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
currentTime := now
|
||||
tx := newOrganizationTestTransactor()
|
||||
ownerID := uuid.New()
|
||||
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return currentTime })
|
||||
firstProfile := organizationProfile("ООО Пример", "Первоначальные данные")
|
||||
first := CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: "company-create-02", CanonicalBody: canonicalBodyForTest(t, firstProfile), Profile: firstProfile,
|
||||
}
|
||||
created, err := service.Create(ctx, first)
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
changedProfile := organizationProfile("ООО Другое", "Первоначальные данные")
|
||||
changed := CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: first.IdempotencyKey,
|
||||
CanonicalBody: canonicalBodyForTest(t, changedProfile), Profile: changedProfile,
|
||||
}
|
||||
if _, err := service.Create(ctx, changed); !errors.Is(err, ErrIdempotencyKeyReused) {
|
||||
t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err)
|
||||
}
|
||||
if count := len(tx.snapshot().organizations); count != 1 {
|
||||
t.Fatalf("organization count after changed-body retry = %d, want 1", count)
|
||||
}
|
||||
|
||||
currentTime = now.Add(outbound.IdempotencyRetention + time.Second)
|
||||
reused, err := service.Create(ctx, first)
|
||||
if err != nil {
|
||||
t.Fatalf("Create(expired key) error = %v", err)
|
||||
}
|
||||
if reused.Replayed || reused.Organization.ID() == created.Organization.ID() {
|
||||
t.Fatalf("Create(expired key) = %+v, want a new organization", reused)
|
||||
}
|
||||
state := tx.snapshot()
|
||||
if len(state.organizations) != 2 || len(state.memberships) != 2 || len(state.results) != 1 {
|
||||
t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 2/2/1", len(state.organizations), len(state.memberships), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRollsBackOrganizationOwnerIdempotencyAndSnapshot(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
tx := newOrganizationTestTransactor()
|
||||
tx.failOwnerInsert = true
|
||||
ownerID := uuid.New()
|
||||
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return now })
|
||||
profile := organizationProfile("ООО Пример", "Данные")
|
||||
_, err := service.Create(ctx, CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: "company-create-03", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "run transaction") {
|
||||
t.Fatalf("Create(owner insert failure) error = %v, want transaction failure", err)
|
||||
}
|
||||
state := tx.snapshot()
|
||||
if len(state.organizations) != 0 || len(state.memberships) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
||||
t.Fatalf("state after failed transaction = companies:%d memberships:%d idempotency:%d results:%d, want all zero",
|
||||
len(state.organizations), len(state.memberships), len(state.idempotency), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRequiresVerifiedEmployer(t *testing.T) {
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
user domain.User
|
||||
want error
|
||||
}{
|
||||
{name: "candidate", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}, want: ErrForbidden},
|
||||
{name: "unverified employer", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioEmployer}, want: ErrEmailNotVerified},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
tx := newOrganizationTestTransactor()
|
||||
tx.state.users[test.user.ID] = test.user
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return now })
|
||||
profile := organizationProfile("ООО Пример", "Данные")
|
||||
_, err := service.Create(t.Context(), CreateCommand{
|
||||
ActorID: test.user.ID, IdempotencyKey: "company-create-04", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
|
||||
})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("Create() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if state := tx.snapshot(); len(state.organizations) != 0 || len(state.idempotency) != 0 {
|
||||
t.Fatalf("state after denied create = companies:%d idempotency:%d, want both zero", len(state.organizations), len(state.idempotency))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
currentTime := now
|
||||
tx := newOrganizationTestTransactor()
|
||||
ownerID := uuid.New()
|
||||
foreignID := uuid.New()
|
||||
memberID := uuid.New()
|
||||
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
|
||||
tx.state.users[foreignID] = verifiedEmployer(foreignID, now)
|
||||
tx.state.users[memberID] = verifiedEmployer(memberID, now)
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return currentTime })
|
||||
profile := organizationProfile("ООО Пример", "Данные")
|
||||
created, err := service.Create(ctx, CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: "company-create-05", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
|
||||
if _, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: foreignID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}},
|
||||
}); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("Update(foreign user) error = %v, want ErrOrganizationNotFound", err)
|
||||
}
|
||||
member, err := domain.NewMembership(domain.MembershipInput{
|
||||
OrganizationID: created.Organization.ID(), UserID: memberID,
|
||||
Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewMembership() error = %v", err)
|
||||
}
|
||||
tx.mu.Lock()
|
||||
tx.state.memberships[organizationTestMembershipKey{created.Organization.ID(), memberID}] = member
|
||||
tx.mu.Unlock()
|
||||
if _, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: memberID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}},
|
||||
}); !errors.Is(err, outbound.ErrOrganizationManagerRequired) {
|
||||
t.Fatalf("Update(non-owner member) error = %v, want ErrOrganizationManagerRequired", err)
|
||||
}
|
||||
|
||||
currentTime = now.Add(time.Minute)
|
||||
updated, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Update(owner) error = %v", err)
|
||||
}
|
||||
if updated.Version() != 2 || updated.Profile().Description() != "Новый текст" ||
|
||||
updated.Verification().Level() != domain.OrganizationVerificationE0 ||
|
||||
updated.Verification().Basis() != domain.OrganizationBasisConfirmedEmail {
|
||||
t.Fatalf("Update(owner) = %+v, want profile version 2 with unchanged e0 verification", updated)
|
||||
}
|
||||
if _, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Другая версия"}},
|
||||
}); !errors.Is(err, outbound.ErrOrganizationVersionConflict) {
|
||||
t.Fatalf("Update(stale version) error = %v, want ErrOrganizationVersionConflict", err)
|
||||
}
|
||||
noOp, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}},
|
||||
})
|
||||
if err != nil || noOp.Version() != 2 {
|
||||
t.Fatalf("Update(stale no-op) = %v, %v, want current version 2", noOp, err)
|
||||
}
|
||||
invalidContacts := domain.OrganizationContactsInput{Website: "http://invalid.example"}
|
||||
if _, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
|
||||
Patch: ProfilePatch{Contacts: &invalidContacts},
|
||||
}); !errors.Is(err, outbound.ErrOrganizationVersionConflict) {
|
||||
t.Fatalf("Update(stale invalid website) error = %v, want version conflict", err)
|
||||
}
|
||||
if _, err := service.Update(ctx, UpdateCommand{
|
||||
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 2,
|
||||
Patch: ProfilePatch{Contacts: &invalidContacts},
|
||||
}); !errors.Is(err, domain.ErrInvalidOrganization) {
|
||||
t.Fatalf("Update(current invalid website) error = %v, want domain validation error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
|
||||
tx := newOrganizationTestTransactor()
|
||||
ownerID := uuid.New()
|
||||
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
|
||||
service := newOrganizationTestService(t, tx, func() time.Time { return now })
|
||||
profile := organizationProfile("ООО Пример", "Данные")
|
||||
command := CreateCommand{
|
||||
ActorID: ownerID, IdempotencyKey: "company-create-06", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
|
||||
}
|
||||
const requests = 12
|
||||
results := make(chan CreateResult, requests)
|
||||
errorsFound := make(chan error, requests)
|
||||
var wait sync.WaitGroup
|
||||
for range requests {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
result, err := service.Create(ctx, command)
|
||||
if err != nil {
|
||||
errorsFound <- err
|
||||
return
|
||||
}
|
||||
results <- result
|
||||
}()
|
||||
}
|
||||
wait.Wait()
|
||||
close(results)
|
||||
close(errorsFound)
|
||||
for err := range errorsFound {
|
||||
t.Fatalf("Create(concurrent) error = %v", err)
|
||||
}
|
||||
var organizationID uuid.UUID
|
||||
createdCount := 0
|
||||
for result := range results {
|
||||
if organizationID == uuid.Nil {
|
||||
organizationID = result.Organization.ID()
|
||||
}
|
||||
if result.Organization.ID() != organizationID || result.Owner.UserID() != ownerID {
|
||||
t.Fatalf("concurrent result = %+v, want the same company and owner", result)
|
||||
}
|
||||
if !result.Replayed {
|
||||
createdCount++
|
||||
}
|
||||
}
|
||||
if createdCount != 1 {
|
||||
t.Fatalf("non-replayed results = %d, want one", createdCount)
|
||||
}
|
||||
state := tx.snapshot()
|
||||
if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 {
|
||||
t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateInputCanonicalizationIsStable(t *testing.T) {
|
||||
profile := organizationProfile("ООО Пример", "Данные")
|
||||
one := canonicalBodyForTest(t, profile)
|
||||
two := canonicalBodyForTest(t, profile)
|
||||
if string(one) != string(two) {
|
||||
t.Fatalf("canonical bodies differ: %q and %q", one, two)
|
||||
}
|
||||
changed := profile
|
||||
changed.Representatives = append([]domain.OrganizationRepresentativeInput(nil), profile.Representatives...)
|
||||
changed.Representatives[0].Name = "Другой человек"
|
||||
three := canonicalBodyForTest(t, changed)
|
||||
if string(one) == string(three) {
|
||||
t.Fatalf("canonical body did not change with representative name: %q", one)
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleOptionalString() {
|
||||
patch := ProfilePatch{Description: OptionalString{Set: true, Value: ""}}
|
||||
fmt.Println(patch.Description.Set, patch.Description.Value == "")
|
||||
// Output: true true
|
||||
}
|
||||
Reference in new issue
Block a user