package invitation import ( "context" "encoding/json" "errors" "fmt" "slices" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/consent" ) const ( acceptOperation = "candidate_invitation.accept" acceptLocation = "invitation.Service.AcceptMine" // consentTextPointer and consentFieldsPointer name the consent rules of // the body in the problem response. consentTextPointer = "/consent_c4/text_version" consentFieldsPointer = "/consent_c4/fields" ) // AcceptCommand binds the session candidate and the path to one acceptance: // the invitation version and the terms version that the candidate read, the // consent text version that the candidate saw, and the contact kinds that the // candidate selected, in the order sent. type AcceptCommand struct { ActorID uuid.UUID InvitationID uuid.UUID IdempotencyKey string ExpectedVersion int64 TermsVersion int64 TextVersion string Fields []domain.ContactField } type acceptRequest struct { fingerprint [outbound.IdempotencyDigestSize]byte scope [outbound.IdempotencyDigestSize]byte record outbound.IdempotencyRecord now time.Time textVersion domain.ConsentTextVersion fields domain.ContactFieldSet } // acceptFingerprint is the canonical request of an acceptance. The fields keep // their order, so a reordered choice is a different request under one key. type acceptFingerprint struct { InvitationID uuid.UUID `json:"invitation_id"` ExpectedVersion int64 `json:"expected_version"` TermsVersion int64 `json:"terms_version"` TextVersion string `json:"text_version"` Fields []domain.ContactField `json:"fields"` } // acceptOutcome is what a committed acceptance transaction decided: the // invitation, or a refusal that the contract stores under the key and that the // caller returns after the commit. type acceptOutcome struct { view domain.CandidateInvitationView refusal error } // AcceptMine accepts the current terms of an invitation of the session // candidate with the consent C4. In one transaction it checks the candidate, // the key, the invitation, a repeat of the acceptance, a terminal state or a // passed deadline, the versions, the state, and the consent rules; then it // moves the invitation to accepted, records the consent C4 in the consent // ledger, stores the contact grant of exactly the selected fields, and appends // the audit event. The acceptance never publishes the profile and never lifts // a hiding: the grant is readable only while the organization may read the // profile. // // Locks: the idempotency record of the candidate's own key and then only the // invitation row, never the organization, as for the other candidate commands. func (service *Service) AcceptMine(ctx context.Context, command AcceptCommand) (domain.CandidateInvitationView, error) { request, err := service.prepareAccept(command) if err != nil { return domain.CandidateInvitationView{}, err } var outcome acceptOutcome err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error outcome, err = service.acceptInTransaction(ctx, unit, command, request) return err }) if err != nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", acceptLocation, err) } if outcome.refusal != nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", acceptLocation, outcome.refusal) } return outcome.view, nil } // prepareAccept validates the request before any storage is read, in the order // of the contract: the request is validated before the account. func (service *Service) prepareAccept(command AcceptCommand) (acceptRequest, error) { const location = "invitation.Service.prepareAccept" switch { case command.ActorID == uuid.Nil: return acceptRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden) case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: return acceptRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) case command.ExpectedVersion < 1: return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"}) case command.TermsVersion < 1: return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/terms_version", Reason: "must be positive"}) } textVersion, err := domain.ParseConsentTextVersion(command.TextVersion) if err != nil { return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be a consent text version"}) } fields, err := domain.NewContactFieldSet(command.Fields...) if err != nil { return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentFieldsPointer, Reason: "must name one to four distinct kinds"}) } now, err := service.now(location) if err != nil { return acceptRequest{}, err } canonical, err := json.Marshal(acceptFingerprint{ InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion, TermsVersion: command.TermsVersion, TextVersion: command.TextVersion, Fields: command.Fields, }) if err != nil { return acceptRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err) } fingerprint := service.keyring.Fingerprint(canonical) scope := service.keyring.IdempotencyScope(acceptOperation, command.IdempotencyKey, command.ActorID.String()) return acceptRequest{ fingerprint: fingerprint, scope: scope, now: now, textVersion: textVersion, fields: fields, record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)}, }, nil } // acceptInTransaction follows the order of checks of the contract after the // HTTP boundary: the account (403), the key (422 or a replay), the invitation // (404, stored), the repeat of an accepted invitation (200), a terminal state // or a passed deadline (409, stored), the versions (412, not stored), any other // state that does not allow an acceptance (409, stored), and the consent rules // (400, not stored). func (service *Service) acceptInTransaction( ctx context.Context, unit outbound.UnitOfWork, command AcceptCommand, request acceptRequest, ) (acceptOutcome, error) { if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil { return acceptOutcome{}, err } stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) if err != nil { return acceptOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", acceptLocation, err) } if !created { return service.replayAccept(ctx, unit, request, command, stored) } entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true) if errors.Is(err, outbound.ErrInvitationNotFound) { return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptNotFound) } if err != nil { return acceptOutcome{}, err } return service.acceptFound(ctx, unit, command, request, entry) } // acceptFound applies the checks that follow a found invitation and, when they // pass, stores the acceptance with its consent and grant. The deadline is judged // at the time the row is held, and a due expiry is applied first, so an // acceptance at the deadline or later is refused with the expired state. func (service *Service) acceptFound( ctx context.Context, unit outbound.UnitOfWork, command AcceptCommand, request acceptRequest, entry outbound.CandidateInvitationEntry, ) (acceptOutcome, error) { now, err := service.now(acceptLocation) if err != nil { return acceptOutcome{}, err } entry, err = settleCandidateEntry(ctx, unit, entry, now) if err != nil { return acceptOutcome{}, fmt.Errorf("%s - expire due invitation: %w", acceptLocation, err) } current := entry.Invitation at := notBefore(now, current.UpdatedAt()) switch { case current.State() == domain.InvitationAccepted: return service.repeatAccept(ctx, unit, command, request, entry) case current.IsTerminal() || current.ResponseDeadlinePassed(at): return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict) } if command.ExpectedVersion != current.Version() || command.TermsVersion != current.TermsVersion() { return acceptOutcome{}, fmt.Errorf("%s - compare versions: %w", acceptLocation, domain.ErrInvitationVersionConflict) } accepted, err := current.Accept(command.TermsVersion, at) if errors.Is(err, domain.ErrInvitationNotAnswerable) { return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict) } if err != nil { return acceptOutcome{}, fmt.Errorf("%s - accept invitation: %w", acceptLocation, err) } if err := service.checkAcceptConsent(ctx, unit, command, request); err != nil { return acceptOutcome{}, err } if err := service.storeAcceptance(ctx, unit, command, request, entry, accepted); err != nil { return acceptOutcome{}, err } entry.Invitation = accepted return service.completeAccept(ctx, unit, request, entry) } // checkAcceptConsent refuses a consent text that is not the published one and a // kind that the profile does not hold. It stores nothing: the caller returns the // error, and the transaction rolls back. func (service *Service) checkAcceptConsent( ctx context.Context, unit outbound.UnitOfWork, command AcceptCommand, request acceptRequest, ) error { if _, err := service.consents.CheckTextVersion(ctx, unit, domain.ConsentPurposeContactDisclosure, request.textVersion); err != nil { if errors.Is(err, consent.ErrStaleConsentText) { return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be the published consent text"}) } return fmt.Errorf("%s - check consent text: %w", acceptLocation, err) } profile, err := unit.CandidateProfiles().Get(ctx, command.ActorID) if err != nil { return fmt.Errorf("%s - read candidate profile: %w", acceptLocation, err) } held := heldContactFields(profile) for index, field := range command.Fields { if !slices.Contains(held, field) { return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{ Pointer: fmt.Sprintf("%s/%d", consentFieldsPointer, index), Reason: "the profile holds no such contact", }) } } return nil } // storeAcceptance writes the acceptance in the transaction: the invitation moves // to accepted with its audit event, the consent C4 is recorded in the ledger, and // the grant of the selected fields is stored next to them. func (service *Service) storeAcceptance( ctx context.Context, unit outbound.UnitOfWork, command AcceptCommand, request acceptRequest, entry outbound.CandidateInvitationEntry, accepted domain.Invitation, ) error { current := entry.Invitation event, err := accepted.AnswerEvent(command.ActorID) if err != nil { return fmt.Errorf("%s - build audit event: %w", acceptLocation, err) } if err := unit.Invitations().Accept(ctx, current.Version(), accepted, event); err != nil { if errors.Is(err, outbound.ErrInvitationVersionConflict) { return fmt.Errorf("%s - store acceptance: %w", acceptLocation, domain.ErrInvitationVersionConflict) } return fmt.Errorf("%s - store acceptance: %w", acceptLocation, err) } granted, err := service.consents.GrantContact(ctx, unit, consent.ContactGrantInput{ SubjectID: command.ActorID, OrganizationID: current.OrganizationID(), OrganizationName: entry.OrganizationName, Fields: request.fields, InvitationID: current.ID(), InvitationTermsVersion: command.TermsVersion, TextVersion: request.textVersion, }) if err != nil { return fmt.Errorf("%s - grant consent C4: %w", acceptLocation, err) } if !granted.Created { return fmt.Errorf("%s - the invitation already has a consent C4 record: %w", acceptLocation, domain.ErrInvalidContactGrant) } grant, err := domain.NewContactGrant(granted.Record, accepted) if err != nil { return fmt.Errorf("%s - build contact grant: %w", acceptLocation, err) } if err := unit.ContactGrants().Create(ctx, grant); err != nil { return fmt.Errorf("%s - store contact grant: %w", acceptLocation, err) } return nil } // repeatAccept answers an acceptance of an invitation that is already accepted. // The same terms version and the same fields answer 200 with the invitation, // even under a new key or an older expected version, and record nothing. Any // other terms version or field set is a conflict with the accepted answer. func (service *Service) repeatAccept( ctx context.Context, unit outbound.UnitOfWork, command AcceptCommand, request acceptRequest, entry outbound.CandidateInvitationEntry, ) (acceptOutcome, error) { grant, err := unit.ContactGrants().GetByInvitation(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID()) if err != nil { return acceptOutcome{}, fmt.Errorf("%s - read contact grant: %w", acceptLocation, err) } if grant.TermsVersion() == command.TermsVersion && grant.Fields().Equal(request.fields) { return service.completeAccept(ctx, unit, request, entry) } return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict) } // completeAccept stores the successful outcome under the key and builds the // response with the contact grant. func (service *Service) completeAccept( ctx context.Context, unit outbound.UnitOfWork, request acceptRequest, entry outbound.CandidateInvitationEntry, ) (acceptOutcome, error) { view, err := service.candidateView(ctx, unit, entry, request.now) if err != nil { return acceptOutcome{}, err } result := outbound.InvitationAcceptResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationAcceptAccepted} if err := finishAccept(ctx, unit, request, result); err != nil { return acceptOutcome{}, err } return acceptOutcome{view: view}, nil } // refuseAccept stores a refusal that the contract keeps under the key and lets // the transaction commit, since nothing else was written. func (service *Service) refuseAccept( ctx context.Context, unit outbound.UnitOfWork, command AcceptCommand, request acceptRequest, outcome outbound.InvitationAcceptOutcome, ) (acceptOutcome, error) { result := outbound.InvitationAcceptResult{InvitationID: command.InvitationID, Outcome: outcome} if err := finishAccept(ctx, unit, request, result); err != nil { return acceptOutcome{}, err } return acceptOutcome{refusal: acceptRefusal(outcome)}, nil } func finishAccept(ctx context.Context, unit outbound.UnitOfWork, request acceptRequest, result outbound.InvitationAcceptResult) error { if err := unit.InvitationAcceptResults().SaveAcceptResult(ctx, request.scope, result); err != nil { return fmt.Errorf("%s - store outcome: %w", acceptLocation, err) } if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { return fmt.Errorf("%s - purge expired idempotency records: %w", acceptLocation, err) } return nil } func acceptRefusal(outcome outbound.InvitationAcceptOutcome) error { if outcome == outbound.InvitationAcceptNotFound { return outbound.ErrInvitationNotFound } return ErrAnswerBlocked } // replayAccept returns the stored outcome of the same request, or refuses a key // used with another request. A stored acceptance is rebuilt from the invitation // and its grant, which the acceptance keeps. func (service *Service) replayAccept( ctx context.Context, unit outbound.UnitOfWork, request acceptRequest, command AcceptCommand, stored outbound.IdempotencyRecord, ) (acceptOutcome, error) { if stored.Fingerprint != request.fingerprint { return acceptOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", acceptLocation, ErrIdempotencyKeyReused) } original, err := unit.InvitationAcceptResults().GetAcceptResult(ctx, request.scope) if err != nil { return acceptOutcome{}, fmt.Errorf("%s - read original outcome: %w", acceptLocation, err) } if original.InvitationID != command.InvitationID { return acceptOutcome{}, fmt.Errorf("%s - validate original outcome: %w", acceptLocation, domain.ErrInvalidInvitation) } if original.Outcome != outbound.InvitationAcceptAccepted { return acceptOutcome{refusal: acceptRefusal(original.Outcome)}, nil } entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false) if err != nil { return acceptOutcome{}, err } view, err := service.candidateView(ctx, unit, entry, request.now) if err != nil { return acceptOutcome{}, err } return acceptOutcome{view: view}, nil } // heldContactFields lists the kinds that the profile holds as confirmed claims, // in the order of ContactFieldKind. A suggestion that nobody confirmed is not // held, so it can never be disclosed. func heldContactFields(profile domain.CandidateProfile) []domain.ContactField { content := profile.Content() held := make([]domain.ContactField, 0, 4) if claim, ok := content.FullName(); confirmedClaim(claim.Status(), ok) { held = append(held, domain.ContactFieldFullName) } if claim, ok := content.Email(); confirmedClaim(claim.Status(), ok) { held = append(held, domain.ContactFieldEmail) } if claim, ok := content.Phone(); confirmedClaim(claim.Status(), ok) { held = append(held, domain.ContactFieldPhone) } if claim, ok := content.Telegram(); confirmedClaim(claim.Status(), ok) { held = append(held, domain.ContactFieldTelegram) } return held } func confirmedClaim(status domain.ProfileClaimStatus, present bool) bool { return present && status == domain.ProfileClaimConfirmed }