feat(visibility): add the candidate publication, hiding and search status contract

This commit is contained in:
shira committed 2026-10-07 00:15:52 +03:00
1 parent 4436f626a3
commit 0529601021
87 files changed
+21456 -83

No files matched your search

+837
View File
@@ -0,0 +1,837 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"regexp"
"slices"
"strings"
"time"
"unicode"
"github.com/google/uuid"
"golang.org/x/text/unicode/norm"
)
// This file holds the visibility settings of a candidate (PRD FR02 and FR12,
// TASK-088): the publication of the anonymous card, the search status, and the
// organizations the candidate hides the profile from.
//
// The rules that shape every type here:
// - A candidate is closed by default. A new account has version 0 of every
// setting, and no value in this file opens anything by itself.
// - The consent C2 stays in the consent ledger. A publication refers to the
// C2 record that backs it and is effective only while that record is
// unrevoked; the search status is a statement and never a consent, so no
// function of one setting reads or changes another.
// - Nothing becomes more public automatically: a lapse of the search status
// only narrows it, a revoked C2 closes the card, and a new C2 publishes
// nothing.
var (
// ErrInvalidVisibility reports a visibility setting, request, or stored
// row that breaks a rule.
ErrInvalidVisibility = errors.New("invalid visibility setting")
// ErrVisibilityVersionConflict reports that the expected version of a
// setting is not the current one: another change advanced it, or the
// client named a version that does not exist. Nothing was changed; the
// client reads the settings again.
ErrVisibilityVersionConflict = errors.New("visibility setting changed concurrently")
// ErrPublicationConsentRequired reports a publication without an active
// C2 consent of the account. The candidate gives C2 first.
ErrPublicationConsentRequired = errors.New("publication needs an active C2 consent")
)
// VisibilityFieldError reports the request field that broke a visibility
// rule. It matches ErrInvalidVisibility with errors.Is, and an HTTP adapter
// reads Pointer with errors.As to answer 400 with the pointer of the field.
// Neither field quotes the submitted value.
type VisibilityFieldError struct {
// Pointer is the JSON Pointer of the field in the request body, such as
// "/fields".
Pointer string
// Reason says which rule the field broke.
Reason string
}
func (err *VisibilityFieldError) Error() string {
return "visibility field " + err.Pointer + " " + err.Reason
}
func (err *VisibilityFieldError) Unwrap() error { return ErrInvalidVisibility }
func invalidVisibilityField(location, pointer, reason string) error {
return fmt.Errorf("%s - %w", location, &VisibilityFieldError{Pointer: pointer, Reason: reason})
}
// MaxHiddenOrganizations is the number of organizations one candidate can
// hide the profile from. The database trigger
// candidate_hidden_organizations_enforce_limit enforces the same bound, and
// the contract's hidden_organizations_total maximum equals it.
const MaxHiddenOrganizations = 1000
// CardField is a group of values of the anonymous candidate card that a
// candidate chooses to publish. The set is closed and has no member for the
// full name, a contact, or the lowest salary: the card never carries them, so
// no choice can publish them.
type CardField string
const (
CardFieldCategories CardField = "categories"
CardFieldStack CardField = "stack"
CardFieldExperience CardField = "experience"
CardFieldSoftSkills CardField = "soft_skills"
CardFieldLocation CardField = "location"
CardFieldRelocation CardField = "relocation"
)
const (
// cardFieldsPointer is the request pointer of the field set.
cardFieldsPointer = "/fields"
// firstStoredVersion is the version of the first saved row of a setting;
// the contract's version 0 is the absence of a row.
firstStoredVersion int64 = 1
)
var cardFields = []CardField{
CardFieldCategories, CardFieldStack, CardFieldExperience,
CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation,
}
// CardFields returns every card field the contract defines.
func CardFields() []CardField { return slices.Clone(cardFields) }
// Valid reports whether the field is one of the contract's codes.
func (field CardField) Valid() bool { return slices.Contains(cardFields, field) }
// CardFieldSet is a set of distinct card fields in the canonical order that
// the database stores: ascending order of the codes. The zero value is the
// empty set. Equal sets are equal arrays.
type CardFieldSet struct {
fields []CardField
}
// NewCardFieldSet validates the fields and returns them in canonical order. A
// repeated or unknown field is invalid, because the contract requires unique
// items from the closed enum.
func NewCardFieldSet(fields []CardField) (CardFieldSet, error) {
const location = "domain.NewCardFieldSet"
if len(fields) > len(cardFields) {
return CardFieldSet{}, invalidVisibilityField(location, cardFieldsPointer, "has more items than card fields exist")
}
// Unknown values are reported at their position in the request.
for index, field := range fields {
if !field.Valid() {
return CardFieldSet{}, invalidVisibilityField(location, fmt.Sprintf("%s/%d", cardFieldsPointer, index), "is not a card field")
}
}
ordered := slices.Clone(fields)
slices.Sort(ordered)
if len(slices.Compact(slices.Clone(ordered))) != len(ordered) {
return CardFieldSet{}, invalidVisibilityField(location, cardFieldsPointer, "repeats a card field")
}
return CardFieldSet{fields: ordered}, nil
}
// Fields returns a copy of the fields in canonical order.
func (set CardFieldSet) Fields() []CardField { return slices.Clone(set.fields) }
// Codes returns the field codes in canonical order, the form that the storage
// column holds. It is never nil, so an empty set is stored as an empty array.
func (set CardFieldSet) Codes() []string {
codes := make([]string, 0, len(set.fields))
for _, field := range set.fields {
codes = append(codes, string(field))
}
return codes
}
func (set CardFieldSet) IsEmpty() bool { return len(set.fields) == 0 }
func (set CardFieldSet) Contains(field CardField) bool { return slices.Contains(set.fields, field) }
func (set CardFieldSet) Equal(other CardFieldSet) bool { return slices.Equal(set.fields, other.fields) }
// PublicationState says whether organizations can read the card at all.
type PublicationState string
const (
PublicationClosed PublicationState = "closed"
PublicationPublished PublicationState = "published"
)
// PublicationClosedReason explains a closed profile to its candidate.
type PublicationClosedReason string
const (
ClosedNeverPublished PublicationClosedReason = "never_published"
ClosedByCandidate PublicationClosedReason = "closed_by_candidate"
ClosedConsentRevoked PublicationClosedReason = "consent_revoked"
)
// StoredPublication is a candidate_publications row joined with the
// revocation state of its C2 record, as one read returns them.
type StoredPublication struct {
UserID uuid.UUID
State string
Fields []string
ConsentRecordID uuid.UUID
PublishedAt time.Time
ClosedAt time.Time
Version int64
// ConsentRevoked is true when the referenced C2 record has been revoked.
ConsentRevoked bool
}
// Publication is the publication setting of one candidate. The zero state of
// a candidate who never published is built by NewPublication: closed, version
// 0, no consent record. The stored state is not the effective state: the card
// is readable only while the stored setting is published and its C2 record is
// unrevoked.
type Publication struct {
userID uuid.UUID
state PublicationState
fields CardFieldSet
consentRecordID uuid.UUID
publishedAt time.Time
closedAt time.Time
version int64
consentRevoked bool
}
// NewPublication returns the setting of a candidate who never published: the
// profile is closed. A new account starts here, and nothing in the account,
// profile, or questionnaire flows leaves it.
func NewPublication(userID uuid.UUID) (Publication, error) {
if userID == uuid.Nil {
return Publication{}, fmt.Errorf("domain.NewPublication - %w: user ID is empty", ErrInvalidVisibility)
}
return Publication{userID: userID, state: PublicationClosed}, nil
}
// RestorePublication rebuilds a setting from a stored row and rejects a row
// that breaks the invariants the database also enforces.
func RestorePublication(stored StoredPublication) (Publication, error) {
const location = "domain.RestorePublication"
if stored.UserID == uuid.Nil || stored.ConsentRecordID == uuid.Nil || stored.Version < firstStoredVersion || stored.PublishedAt.IsZero() {
return Publication{}, fmt.Errorf("%s - %w: identifiers, version, or time are missing", location, ErrInvalidVisibility)
}
state := PublicationState(stored.State)
fields, err := restoreCardFieldSet(location, stored.Fields)
if err != nil {
return Publication{}, err
}
switch {
case state == PublicationPublished && !fields.IsEmpty() && stored.ClosedAt.IsZero():
case state == PublicationClosed && fields.IsEmpty() && !stored.ClosedAt.IsZero() && !stored.ClosedAt.Before(stored.PublishedAt):
default:
return Publication{}, fmt.Errorf("%s - %w: state, fields, and closing time disagree", location, ErrInvalidVisibility)
}
return Publication{
userID: stored.UserID, state: state, fields: fields, consentRecordID: stored.ConsentRecordID,
publishedAt: stored.PublishedAt, closedAt: stored.ClosedAt, version: stored.Version, consentRevoked: stored.ConsentRevoked,
}, nil
}
// restoreCardFieldSet decodes the stored codes and requires the canonical
// form, so a row changed outside the application is rejected.
func restoreCardFieldSet(location string, codes []string) (CardFieldSet, error) {
fields := make([]CardField, 0, len(codes))
for _, code := range codes {
fields = append(fields, CardField(code))
}
set, err := NewCardFieldSet(fields)
if err != nil {
return CardFieldSet{}, fmt.Errorf("%s - stored card fields: %w", location, err)
}
if !slices.Equal(set.Codes(), codes) && len(codes) > 0 {
return CardFieldSet{}, fmt.Errorf("%s - %w: stored card fields are not in canonical order", location, ErrInvalidVisibility)
}
return set, nil
}
func (publication Publication) UserID() uuid.UUID { return publication.userID }
// Version is 0 for a candidate who never published.
func (publication Publication) Version() int64 { return publication.version }
// ConsentRecordID is the C2 record behind the latest publication, or the zero
// UUID when the candidate never published.
func (publication Publication) ConsentRecordID() uuid.UUID { return publication.consentRecordID }
// PublishedAt is the time of the latest change that published the card, and
// the zero time when the candidate never published.
func (publication Publication) PublishedAt() time.Time { return publication.publishedAt }
// State is the effective state: published only while the stored setting is
// published and the C2 record behind it is unrevoked.
func (publication Publication) State() PublicationState {
if publication.state == PublicationPublished && !publication.consentRevoked {
return PublicationPublished
}
return PublicationClosed
}
// Fields are the fields organizations may read now; empty while closed.
func (publication Publication) Fields() CardFieldSet {
if publication.State() == PublicationClosed {
return CardFieldSet{}
}
return publication.fields
}
// ClosedReason says why a closed profile is closed. It is empty while the
// profile is published.
func (publication Publication) ClosedReason() PublicationClosedReason {
switch {
case publication.State() == PublicationPublished:
return ""
case publication.version == 0:
return ClosedNeverPublished
case publication.state == PublicationPublished:
return ClosedConsentRevoked
default:
return ClosedByCandidate
}
}
// PublicationRequest is the complete new publication setting a candidate
// sends. Build it with NewPublicationRequest.
type PublicationRequest struct {
state PublicationState
fields CardFieldSet
}
// NewPublicationRequest validates the rules that depend on the body alone: a
// published state needs at least one field and a closed state none.
func NewPublicationRequest(state PublicationState, fields []CardField) (PublicationRequest, error) {
const location = "domain.NewPublicationRequest"
set, err := NewCardFieldSet(fields)
if err != nil {
return PublicationRequest{}, err
}
switch state {
case PublicationPublished:
if set.IsEmpty() {
return PublicationRequest{}, invalidVisibilityField(location, cardFieldsPointer, "needs at least one card field to publish")
}
case PublicationClosed:
if !set.IsEmpty() {
return PublicationRequest{}, invalidVisibilityField(location, cardFieldsPointer, "must be empty when the profile is closed")
}
default:
return PublicationRequest{}, invalidVisibilityField(location, "/state", "is not a publication state")
}
return PublicationRequest{state: state, fields: set}, nil
}
// PublicationChange is the outcome of applying a request.
type PublicationChange struct {
// Publication is the setting after the request. It equals the current one
// when Changed is false.
Publication Publication
// Changed is false when the request left the effective setting as it was:
// nothing is stored, the version stays, and no event is recorded.
Changed bool
// Event is the kind of history record the change needs; empty when
// Changed is false.
Event PrivacyEventKind
}
// Apply applies a request over the version the client read. activeConsent is
// the identifier of the account's current unrevoked C2 record, or the zero
// UUID when it has none. The order follows the contract: a version above the
// current one is a conflict, an unchanged effective setting is not a change,
// any other change over a stale version is a conflict, and a publication needs
// an active C2.
func (publication Publication) Apply(request PublicationRequest, expectedVersion int64, activeConsent uuid.UUID, at time.Time) (PublicationChange, error) {
const location = "domain.Publication.Apply"
if publication.userID == uuid.Nil || request.state == "" {
return PublicationChange{}, fmt.Errorf("%s - %w: setting or request is not initialized", location, ErrInvalidVisibility)
}
if expectedVersion > publication.version {
return PublicationChange{}, fmt.Errorf("%s - version %d does not exist: %w", location, expectedVersion, ErrVisibilityVersionConflict)
}
effective := publication.State()
if publication.repeats(request, effective) {
return PublicationChange{Publication: publication}, nil
}
if expectedVersion < publication.version {
return PublicationChange{}, fmt.Errorf("%s - expected version is not current: %w", location, ErrVisibilityVersionConflict)
}
next := publication
next.version = publication.version + 1
next.consentRevoked = false
if request.state == PublicationClosed {
next.close(at)
return PublicationChange{Publication: next, Changed: true, Event: PrivacyEventPublicationClosed}, nil
}
if activeConsent == uuid.Nil {
return PublicationChange{}, fmt.Errorf("%s - no active C2 record: %w", location, ErrPublicationConsentRequired)
}
next.state = PublicationPublished
next.fields = request.fields
next.consentRecordID = activeConsent
next.publishedAt = at
next.closedAt = time.Time{}
event := PrivacyEventPublicationChanged
if effective == PublicationClosed {
event = PrivacyEventPublicationOpened
}
return PublicationChange{Publication: next, Changed: true, Event: event}, nil
}
// repeats reports a request that leaves the setting as it is. A closing over
// a stored publication whose C2 was revoked is a real change: the card is
// already closed in effect, but the stored setting still says published, so
// the request normalizes the row to closed and records the closing (and the
// usecase revokes the contact grants it closes). Only a stored closed setting,
// or a profile that never published, makes a closing a repeat.
func (publication Publication) repeats(request PublicationRequest, effective PublicationState) bool {
if request.state == PublicationClosed {
return publication.state == PublicationClosed
}
return effective == PublicationPublished && request.fields.Equal(publication.Fields())
}
// close stores the closing. The last published time stays as evidence, and a
// closing never moves back before it, whatever the instance clock says.
func (publication *Publication) close(at time.Time) {
publication.state = PublicationClosed
publication.fields = CardFieldSet{}
publication.closedAt = at
if publication.closedAt.Before(publication.publishedAt) {
publication.closedAt = publication.publishedAt
}
}
// StoredFields returns the canonical codes of the stored set for the database
// column, whatever the effective state.
func (publication Publication) StoredFields() []string { return publication.fields.Codes() }
// StoredState returns the stored state for the database column.
func (publication Publication) StoredState() PublicationState { return publication.state }
// ClosedAt is the time the candidate closed the publication, and the zero
// time while it is published or was never published.
func (publication Publication) ClosedAt() time.Time { return publication.closedAt }
// LogValue logs only the account identifier, the version, and the effective
// state.
func (publication Publication) LogValue() slog.Value {
return slog.GroupValue(
slog.String("user_id", publication.userID.String()),
slog.Int64("version", publication.version),
slog.String("state", string(publication.State())),
)
}
// SearchStatusValue is what a candidate says about searching for work. It is
// a statement, never a consent: it publishes nothing and hides nothing.
type SearchStatusValue string
const (
SearchStatusLooking SearchStatusValue = "looking"
SearchStatusNotLooking SearchStatusValue = "not_looking"
)
// SearchStatusConfirmation is the policy a confirmation of looking is made
// under: the version of the product policy and its confirmation interval.
type SearchStatusConfirmation struct {
policyVersionID PolicyVersionID
interval CalendarDays
}
// NewSearchStatusConfirmation takes the interval from the search_status
// section of one stored policy version. The interval comes from the versioned
// policy, never from a constant in the code, so the owner changes it by
// publishing a new policy version.
func NewSearchStatusConfirmation(policyVersionID PolicyVersionID, policy SearchStatusPolicy) (SearchStatusConfirmation, error) {
const location = "domain.NewSearchStatusConfirmation"
if policyVersionID.IsZero() {
return SearchStatusConfirmation{}, fmt.Errorf("%s - %w: policy version is empty", location, ErrInvalidVisibility)
}
if err := policy.Validate(); err != nil {
return SearchStatusConfirmation{}, fmt.Errorf("%s - %w: %w", location, ErrInvalidVisibility, err)
}
return SearchStatusConfirmation{policyVersionID: policyVersionID, interval: policy.SearchingConfirmationInterval}, nil
}
// StoredSearchStatus is a candidate_search_statuses row.
type StoredSearchStatus struct {
UserID uuid.UUID
Status string
ConfirmedAt time.Time
LapsesAt time.Time
PolicyVersionID PolicyVersionID
Version int64
}
// SearchStatus is the search status of one candidate. A candidate who never
// set it is not looking at version 0. The stored status is what the candidate
// last said; the status that holds now is computed against the clock, so a
// lapse is never written and cannot make anyone more visible.
type SearchStatus struct {
userID uuid.UUID
stored SearchStatusValue
confirmedAt time.Time
lapsesAt time.Time
policyVersionID PolicyVersionID
version int64
}
// NewSearchStatus returns the status of a candidate who never set it.
func NewSearchStatus(userID uuid.UUID) (SearchStatus, error) {
if userID == uuid.Nil {
return SearchStatus{}, fmt.Errorf("domain.NewSearchStatus - %w: user ID is empty", ErrInvalidVisibility)
}
return SearchStatus{userID: userID, stored: SearchStatusNotLooking}, nil
}
// RestoreSearchStatus rebuilds a status from a stored row and rejects a row
// that breaks the invariants the database also enforces.
func RestoreSearchStatus(stored StoredSearchStatus) (SearchStatus, error) {
const location = "domain.RestoreSearchStatus"
if stored.UserID == uuid.Nil || stored.Version < firstStoredVersion {
return SearchStatus{}, fmt.Errorf("%s - %w: identifier or version is invalid", location, ErrInvalidVisibility)
}
status := SearchStatusValue(stored.Status)
switch {
case status == SearchStatusLooking && !stored.ConfirmedAt.IsZero() && stored.LapsesAt.After(stored.ConfirmedAt) && !stored.PolicyVersionID.IsZero():
case status == SearchStatusNotLooking && stored.ConfirmedAt.IsZero() && stored.LapsesAt.IsZero() && stored.PolicyVersionID.IsZero():
default:
return SearchStatus{}, fmt.Errorf("%s - %w: status, confirmation, and policy version disagree", location, ErrInvalidVisibility)
}
return SearchStatus{
userID: stored.UserID, stored: status, confirmedAt: stored.ConfirmedAt, lapsesAt: stored.LapsesAt,
policyVersionID: stored.PolicyVersionID, version: stored.Version,
}, nil
}
func (status SearchStatus) UserID() uuid.UUID { return status.userID }
// Version is 0 for a candidate who never set the status.
func (status SearchStatus) Version() int64 { return status.version }
// StoredValue is the status the candidate last set.
func (status SearchStatus) StoredValue() SearchStatusValue { return status.stored }
// ConfirmedAt is the latest confirmation of looking, or the zero time.
func (status SearchStatus) ConfirmedAt() time.Time { return status.confirmedAt }
// LapsesAt is when the confirmed status lapses, or the zero time. It was fixed
// at the confirmation and no later policy change moves it.
func (status SearchStatus) LapsesAt() time.Time { return status.lapsesAt }
// PolicyVersionID is the policy version the lapse time was computed under, or
// the zero value when the candidate is not looking.
func (status SearchStatus) PolicyVersionID() PolicyVersionID { return status.policyVersionID }
// Effective is the status that holds at now: looking only while the
// confirmation has not lapsed. A lapse falls to the non-public status.
func (status SearchStatus) Effective(now time.Time) SearchStatusValue {
if status.stored == SearchStatusLooking && now.Before(status.lapsesAt) {
return SearchStatusLooking
}
return SearchStatusNotLooking
}
// Lapsed reports a status the candidate set to looking and did not confirm in
// time.
func (status SearchStatus) Lapsed(now time.Time) bool {
return status.stored == SearchStatusLooking && !now.Before(status.lapsesAt)
}
// SearchStatusChange is the outcome of applying a status request.
type SearchStatusChange struct {
Status SearchStatus
// Changed is false when the request left the stored status as it was.
Changed bool
// Event is the history record the change needs; empty when unchanged.
Event PrivacyEventKind
}
// Apply sets or confirms the status over the version the client read. The
// confirmation is only used for looking and fixes the lapse time from the
// policy at the moment of the confirmation. The request never touches the
// publication or the hidden organizations: this type knows neither.
//
// Looking always changes the stored confirmation, so a stale version is a
// conflict even for a repeat. Not looking over a stored not looking is not a
// change.
func (status SearchStatus) Apply(value SearchStatusValue, expectedVersion int64, confirmation SearchStatusConfirmation, at time.Time) (SearchStatusChange, error) {
const location = "domain.SearchStatus.Apply"
if status.userID == uuid.Nil {
return SearchStatusChange{}, fmt.Errorf("%s - %w: status is not initialized", location, ErrInvalidVisibility)
}
if value != SearchStatusLooking && value != SearchStatusNotLooking {
return SearchStatusChange{}, invalidVisibilityField(location, "/value", "is not a search status")
}
if expectedVersion > status.version {
return SearchStatusChange{}, fmt.Errorf("%s - version %d does not exist: %w", location, expectedVersion, ErrVisibilityVersionConflict)
}
if value == SearchStatusNotLooking && status.stored == SearchStatusNotLooking {
return SearchStatusChange{Status: status}, nil
}
if expectedVersion < status.version {
return SearchStatusChange{}, fmt.Errorf("%s - expected version is not current: %w", location, ErrVisibilityVersionConflict)
}
next := SearchStatus{userID: status.userID, stored: value, version: status.version + 1}
event := PrivacyEventSearchStatusCleared
if value == SearchStatusLooking {
if confirmation.policyVersionID.IsZero() || confirmation.interval <= 0 {
return SearchStatusChange{}, fmt.Errorf("%s - %w: confirmation policy is missing", location, ErrInvalidVisibility)
}
next.confirmedAt = at
next.lapsesAt = at.Add(confirmation.interval.Duration())
next.policyVersionID = confirmation.policyVersionID
event = PrivacyEventSearchStatusConfirmed
}
return SearchStatusChange{Status: next, Changed: true, Event: event}, nil
}
// LogValue logs only the account identifier, the version, and the stored
// value.
func (status SearchStatus) LogValue() slog.Value {
return slog.GroupValue(
slog.String("user_id", status.userID.String()),
slog.Int64("version", status.version),
slog.String("stored", string(status.stored)),
)
}
// HiddenOrganization is the record of a candidate hiding the profile from one
// organization. It belongs to the candidate: no organization reads it.
type HiddenOrganization struct {
userID uuid.UUID
organizationID uuid.UUID
hiddenAt time.Time
}
// NewHiddenOrganization builds the record of a hiding. The pair is unique in
// the database, so hiding twice is the same record.
func NewHiddenOrganization(userID, organizationID uuid.UUID, at time.Time) (HiddenOrganization, error) {
if userID == uuid.Nil || organizationID == uuid.Nil || at.IsZero() {
return HiddenOrganization{}, fmt.Errorf("domain.NewHiddenOrganization - %w: identifiers or time are missing", ErrInvalidVisibility)
}
return HiddenOrganization{userID: userID, organizationID: organizationID, hiddenAt: at}, nil
}
func (hidden HiddenOrganization) UserID() uuid.UUID { return hidden.userID }
func (hidden HiddenOrganization) OrganizationID() uuid.UUID { return hidden.organizationID }
func (hidden HiddenOrganization) HiddenAt() time.Time { return hidden.hiddenAt }
// LogValue logs only the identifiers.
func (hidden HiddenOrganization) LogValue() slog.Value {
return slog.GroupValue(
slog.String("user_id", hidden.userID.String()),
slog.String("organization_id", hidden.organizationID.String()),
)
}
// PrivacyEventKind is a kind of change that the settings history records.
type PrivacyEventKind string
const (
PrivacyEventPublicationOpened PrivacyEventKind = "publication_opened"
PrivacyEventPublicationChanged PrivacyEventKind = "publication_changed"
PrivacyEventPublicationClosed PrivacyEventKind = "publication_closed"
PrivacyEventSearchStatusConfirmed PrivacyEventKind = "search_status_confirmed"
PrivacyEventSearchStatusCleared PrivacyEventKind = "search_status_cleared"
PrivacyEventOrganizationHidden PrivacyEventKind = "organization_hidden"
PrivacyEventOrganizationUnhidden PrivacyEventKind = "organization_unhidden"
)
// Valid reports whether the kind is one the history stores.
func (kind PrivacyEventKind) Valid() bool {
switch kind {
case PrivacyEventPublicationOpened, PrivacyEventPublicationChanged, PrivacyEventPublicationClosed,
PrivacyEventSearchStatusConfirmed, PrivacyEventSearchStatusCleared,
PrivacyEventOrganizationHidden, PrivacyEventOrganizationUnhidden:
return true
default:
return false
}
}
// PrivacyEvent is one record of the settings history, in the shape the
// candidate_privacy_events table accepts.
type PrivacyEvent struct {
id uuid.UUID
userID uuid.UUID
kind PrivacyEventKind
occurredAt time.Time
fields CardFieldSet
consentRecordID uuid.UUID
organizationID uuid.UUID
}
// NewPublicationEvent records a publication change. A publication carries the
// published fields and the C2 record behind them; a closing carries neither.
func NewPublicationEvent(change PublicationChange, at time.Time) (PrivacyEvent, error) {
const location = "domain.NewPublicationEvent"
if !change.Changed {
return PrivacyEvent{}, fmt.Errorf("%s - %w: the change is empty", location, ErrInvalidVisibility)
}
event := PrivacyEvent{userID: change.Publication.userID, kind: change.Event, occurredAt: at}
switch change.Event {
case PrivacyEventPublicationOpened, PrivacyEventPublicationChanged:
event.fields = change.Publication.fields
event.consentRecordID = change.Publication.consentRecordID
case PrivacyEventPublicationClosed:
case PrivacyEventSearchStatusConfirmed, PrivacyEventSearchStatusCleared, PrivacyEventOrganizationHidden, PrivacyEventOrganizationUnhidden:
return PrivacyEvent{}, fmt.Errorf("%s - %w: kind %q is not a publication event", location, ErrInvalidVisibility, change.Event)
default:
return PrivacyEvent{}, fmt.Errorf("%s - %w: kind %q is not a publication event", location, ErrInvalidVisibility, change.Event)
}
return completeEvent(location, event)
}
// NewSearchStatusEvent records a change of the search status.
func NewSearchStatusEvent(change SearchStatusChange, at time.Time) (PrivacyEvent, error) {
const location = "domain.NewSearchStatusEvent"
if !change.Changed || (change.Event != PrivacyEventSearchStatusConfirmed && change.Event != PrivacyEventSearchStatusCleared) {
return PrivacyEvent{}, fmt.Errorf("%s - %w: the change is not a status change", location, ErrInvalidVisibility)
}
return completeEvent(location, PrivacyEvent{userID: change.Status.userID, kind: change.Event, occurredAt: at})
}
// NewOrganizationEvent records a hiding or the lifting of one. Only the
// identifier is kept; the candidate's read resolves the current name.
func NewOrganizationEvent(kind PrivacyEventKind, userID, organizationID uuid.UUID, at time.Time) (PrivacyEvent, error) {
const location = "domain.NewOrganizationEvent"
if kind != PrivacyEventOrganizationHidden && kind != PrivacyEventOrganizationUnhidden {
return PrivacyEvent{}, fmt.Errorf("%s - %w: kind %q is not an organization event", location, ErrInvalidVisibility, kind)
}
if organizationID == uuid.Nil {
return PrivacyEvent{}, fmt.Errorf("%s - %w: organization is missing", location, ErrInvalidVisibility)
}
return completeEvent(location, PrivacyEvent{
userID: userID, kind: kind, occurredAt: at, organizationID: organizationID,
})
}
func completeEvent(location string, event PrivacyEvent) (PrivacyEvent, error) {
if event.userID == uuid.Nil || event.occurredAt.IsZero() {
return PrivacyEvent{}, fmt.Errorf("%s - %w: account or time is missing", location, ErrInvalidVisibility)
}
id, err := uuid.NewV7()
if err != nil {
return PrivacyEvent{}, fmt.Errorf("%s - generate ID: %w", location, err)
}
event.id = id
return event, nil
}
func (event PrivacyEvent) ID() uuid.UUID { return event.id }
func (event PrivacyEvent) UserID() uuid.UUID { return event.userID }
func (event PrivacyEvent) Kind() PrivacyEventKind { return event.kind }
func (event PrivacyEvent) OccurredAt() time.Time { return event.occurredAt }
func (event PrivacyEvent) Fields() CardFieldSet { return event.fields }
func (event PrivacyEvent) ConsentRecordID() uuid.UUID { return event.consentRecordID }
func (event PrivacyEvent) OrganizationID() uuid.UUID { return event.organizationID }
// HasFieldSet reports whether the event stores a field set: every publication
// event does, an empty one for a closing, and no other kind does.
func (event PrivacyEvent) HasFieldSet() bool {
switch event.kind {
case PrivacyEventPublicationOpened, PrivacyEventPublicationChanged, PrivacyEventPublicationClosed:
return true
case PrivacyEventSearchStatusConfirmed, PrivacyEventSearchStatusCleared, PrivacyEventOrganizationHidden, PrivacyEventOrganizationUnhidden:
return false
default:
return false
}
}
// LogValue logs only identifiers and the kind.
func (event PrivacyEvent) LogValue() slog.Value {
return slog.GroupValue(
slog.String("id", event.id.String()),
slog.String("kind", string(event.kind)),
)
}
// Rules for the content of an anonymous card (TASK-089 builds it; these are
// the hard requirements of this task):
// - Only confirmed profile values ever reach the card. A suggestion that
// the candidate did not confirm (status extracted) and an unknown value
// never do.
// - A free text value (a stack tag, a soft skill, a location) is dropped
// when it looks like a contact, because the card must never carry a
// contact outside the contact grant (C4). CardTextLooksLikeContact is the
// check the builder must apply to every free text before it enters the
// card; it errs on the side of dropping.
// - Quasi-identifiers (a rare combination of location, stack, and
// experience) and the generalization of rare features are an acceptance
// criterion of TASK-089, not decided here.
const (
// cardWordStart and cardWordEnd are Unicode word boundaries. Go's \b is
// ASCII-only, so it cannot see the edge of a Cyrillic or other non-ASCII
// label.
cardWordStart = `(?:^|[^\p{L}\p{N}_])`
cardWordEnd = `(?:$|[^\p{L}\p{N}_])`
// cardDomainEnd also treats a hyphen as part of the label, so pro.company
// does not match the ending pro.
cardDomainEnd = `(?:$|[^\p{L}\p{N}-])`
// cardContactTLDs are the domain endings that make a dotted token a
// domain. The list is deliberately wide and errs on the side of dropping:
// Socket.io is dropped with it. "net" is not in it so that ASP.NET stays a
// stack tag; a lowercase name.net is caught separately.
cardContactTLDs = `com|ru|org|io|me|dev|app|xyz|info|su|рф|ua|by|kz|co|ai|de|uk|tv|ly|gl|dog|site|online|tech|fm|cc|gg|link|page|store|shop|blog|cloud|top|pro|biz|us|eu|fr|nl|pl|cz|moscow|бел|укр|рус|онлайн|сайт`
// cardContactWords are words that introduce or disguise a contact, with
// or without an @: messengers, contact nouns, and the spelled-out parts of
// an address. They match as whole words only.
cardContactWords = `at|dot|собака|точка|telegram|tg|whatsapp|viber|skype|телеграм|телега|вотсап|ватсап|вайбер|скайп|email|mail|e-mail|phone|tel|почта|телефон|контакт|contact`
// minCardPhoneDigits is the number of digits in one group from which a
// text is treated as a phone number. Seven is the shortest local number.
minCardPhoneDigits = 7
)
var (
cardContactEmail = regexp.MustCompile(`[^\s@]+@[^\s@]+`)
cardContactHandle = regexp.MustCompile(`@\s*[\p{L}\p{N}_]{3,}`)
cardContactURL = regexp.MustCompile(`(?:https?://|tg://|www\.|\bt\.me/)|[\p{L}\p{N}-]+\.(?:` + cardContactTLDs + `)` + cardDomainEnd)
cardContactNet = regexp.MustCompile(`[\p{Ll}\p{N}-]+\.net` + cardDomainEnd)
cardContactWord = regexp.MustCompile(cardWordStart + `(?:` + cardContactWords + `)` + cardWordEnd)
// cardPhoneGroup is a run of digits separated only by spaces, dashes,
// dots, and parentheses, so "Python 3.12, Django 4.2" are separate groups.
cardPhoneGroup = regexp.MustCompile(`[\p{Nd}+(][\p{Nd}\s().\-]*`)
)
// CardTextLooksLikeContact reports whether a free text value of the profile
// looks like a contact: an email address, a phone number, a URL or domain
// (including an internationalized one), a Telegram link or an @handle (also
// spelled "@ name"), an obfuscated address ("a [at] b dot com"), or a
// messenger or contact word ("tg: name", "почта"). The text is normalized
// with NFKC first, so fullwidth and compatibility forms of @, +, and digits
// count, and every Unicode decimal digit counts toward a phone number. A card
// builder drops such a value instead of publishing it. The check errs on the
// side of dropping; it is the barrier for free text until TASK-089 replaces
// free text by a closed taxonomy, which closes the residual risk.
func CardTextLooksLikeContact(text string) bool {
normalized := norm.NFKC.String(text)
lowered := strings.ToLower(normalized)
if cardContactEmail.MatchString(lowered) || cardContactHandle.MatchString(lowered) ||
cardContactURL.MatchString(lowered) || cardContactNet.MatchString(normalized) || cardContactWord.MatchString(lowered) {
return true
}
for _, group := range cardPhoneGroup.FindAllString(lowered, -1) {
digits := 0
for _, character := range group {
if unicode.IsDigit(character) {
digits++
}
}
if digits >= minCardPhoneDigits {
return true
}
}
return false
}
+475
View File
@@ -0,0 +1,475 @@
package domain
import (
"errors"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var visibilityNow = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func mustCardFields(t *testing.T, fields ...CardField) CardFieldSet {
t.Helper()
set, err := NewCardFieldSet(fields)
if err != nil {
t.Fatalf("NewCardFieldSet(%v) error = %v", fields, err)
}
return set
}
func mustPublicationRequest(t *testing.T, state PublicationState, fields ...CardField) PublicationRequest {
t.Helper()
request, err := NewPublicationRequest(state, fields)
if err != nil {
t.Fatalf("NewPublicationRequest(%s, %v) error = %v", state, fields, err)
}
return request
}
func newClosedPublication(t *testing.T) Publication {
t.Helper()
publication, err := NewPublication(uuid.New())
if err != nil {
t.Fatalf("NewPublication() error = %v", err)
}
return publication
}
func publish(t *testing.T, publication Publication, expectedVersion int64, consent uuid.UUID, at time.Time, fields ...CardField) Publication {
t.Helper()
change, err := publication.Apply(mustPublicationRequest(t, PublicationPublished, fields...), expectedVersion, consent, at)
if err != nil || !change.Changed {
t.Fatalf("Apply(publish) = %+v, %v, want a change", change, err)
}
return change.Publication
}
func TestNewCardFieldSetIsCanonicalAndClosed(t *testing.T) {
set := mustCardFields(t, CardFieldStack, CardFieldCategories)
if got := strings.Join(set.Codes(), ","); got != "categories,stack" {
t.Fatalf("Codes() = %q, want ascending order whatever the input order", got)
}
if empty := mustCardFields(t); !empty.IsEmpty() || empty.Codes() == nil {
t.Fatal("an empty set must be empty and encode as an empty, non-nil array")
}
for _, code := range []string{"full_name", "email", "phone", "telegram", "salary_minimum", "contacts", ""} {
if _, err := NewCardFieldSet([]CardField{CardField(code)}); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewCardFieldSet(%q) error = %v, want a refusal: the card never carries it", code, err)
}
}
if _, err := NewCardFieldSet([]CardField{CardFieldStack, CardFieldStack}); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewCardFieldSet(repeated) error = %v, want a refusal", err)
}
var fieldError *VisibilityFieldError
if _, err := NewCardFieldSet([]CardField{CardFieldStack, "contacts"}); !errors.As(err, &fieldError) || fieldError.Pointer != "/fields/1" || strings.Contains(err.Error(), "contacts") {
t.Errorf("an unknown field error = %v, want the pointer without the submitted value", err)
}
for _, field := range CardFields() {
if !field.Valid() {
t.Errorf("CardFields() lists %q, which is not valid", field)
}
}
}
func TestNewPublicationRequestChecksTheBodyAlone(t *testing.T) {
for _, test := range []struct {
name string
state PublicationState
fields []CardField
ok bool
}{
{"published with a field", PublicationPublished, []CardField{CardFieldStack}, true},
{"closed with no field", PublicationClosed, nil, true},
{"published with no field", PublicationPublished, nil, false},
{"closed with a field", PublicationClosed, []CardField{CardFieldStack}, false},
{"unknown state", "hidden", nil, false},
} {
t.Run(test.name, func(t *testing.T) {
_, err := NewPublicationRequest(test.state, test.fields)
if (err == nil) != test.ok {
t.Fatalf("NewPublicationRequest() error = %v, want ok %v", err, test.ok)
}
if err != nil && !errors.Is(err, ErrInvalidVisibility) {
t.Fatalf("error = %v, want ErrInvalidVisibility", err)
}
})
}
}
func TestAProfileIsClosedByDefault(t *testing.T) {
publication := newClosedPublication(t)
if publication.State() != PublicationClosed || publication.ClosedReason() != ClosedNeverPublished ||
publication.Version() != 0 || !publication.Fields().IsEmpty() || publication.ConsentRecordID() != uuid.Nil {
t.Fatalf("a new publication = %v %v v%d, want closed, never published, version 0, no consent", publication.State(), publication.ClosedReason(), publication.Version())
}
// Closing a profile that never opened changes nothing and stores no row.
change, err := publication.Apply(mustPublicationRequest(t, PublicationClosed), 0, uuid.Nil, visibilityNow)
if err != nil || change.Changed || change.Publication.Version() != 0 {
t.Fatalf("Apply(close of a never published profile) = %+v, %v, want no change", change, err)
}
}
func TestPublishingNeedsAnActiveC2AndNamesNoConsent(t *testing.T) {
publication := newClosedPublication(t)
request := mustPublicationRequest(t, PublicationPublished, CardFieldCategories)
if _, err := publication.Apply(request, 0, uuid.Nil, visibilityNow); !errors.Is(err, ErrPublicationConsentRequired) {
t.Fatalf("Apply(without C2) error = %v, want ErrPublicationConsentRequired", err)
}
consent := uuid.New()
change, err := publication.Apply(request, 0, consent, visibilityNow)
if err != nil || !change.Changed || change.Event != PrivacyEventPublicationOpened {
t.Fatalf("Apply(publish) = %+v, %v, want an opened publication", change, err)
}
published := change.Publication
if published.State() != PublicationPublished || published.ClosedReason() != "" || published.Version() != 1 ||
published.ConsentRecordID() != consent || !published.PublishedAt().Equal(visibilityNow) ||
!published.Fields().Equal(mustCardFields(t, CardFieldCategories)) {
t.Fatalf("published = %v v%d, want the new record bound to the C2 record", published.State(), published.Version())
}
// The input did not change.
if publication.State() != PublicationClosed || publication.Version() != 0 {
t.Fatal("Apply changed its receiver")
}
}
func TestPublicationOrderOfChecks(t *testing.T) {
consent := uuid.New()
published := publish(t, newClosedPublication(t), 0, consent, visibilityNow, CardFieldStack, CardFieldCategories)
same := mustPublicationRequest(t, PublicationPublished, CardFieldCategories, CardFieldStack)
other := mustPublicationRequest(t, PublicationPublished, CardFieldCategories)
// A version above the current one never existed, even for an unchanged body.
if _, err := published.Apply(same, 5, consent, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) {
t.Fatalf("Apply(future version) error = %v, want a version conflict", err)
}
// An unchanged body is a success over a stale version, so a lost response can be retried.
published = publish(t, published, 1, consent, visibilityNow.Add(time.Hour), CardFieldCategories)
if change, err := published.Apply(other, 1, uuid.Nil, visibilityNow); err != nil || change.Changed || change.Publication.Version() != 2 {
t.Fatalf("Apply(unchanged, stale) = %+v, %v, want no change at version 2", change, err)
}
// Any other change over a stale version is a conflict, also a closing.
if _, err := published.Apply(same, 1, consent, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) {
t.Fatalf("Apply(change, stale) error = %v, want a version conflict", err)
}
// A stale version is a conflict before the missing consent is reported.
if _, err := published.Apply(same, 1, uuid.Nil, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) {
t.Fatalf("Apply(change, stale, no consent) error = %v, want the version conflict first", err)
}
change, err := published.Apply(mustPublicationRequest(t, PublicationClosed), 2, uuid.Nil, visibilityNow.Add(2*time.Hour))
if err != nil || !change.Changed || change.Event != PrivacyEventPublicationClosed {
t.Fatalf("Apply(close) = %+v, %v, want a closing that needs no consent", change, err)
}
closed := change.Publication
if closed.State() != PublicationClosed || closed.ClosedReason() != ClosedByCandidate || !closed.Fields().IsEmpty() || closed.Version() != 3 ||
!closed.PublishedAt().Equal(visibilityNow.Add(time.Hour)) || !closed.ClosedAt().Equal(visibilityNow.Add(2*time.Hour)) {
t.Fatalf("closed = %v %v v%d, want closed by the candidate with the last published time kept", closed.State(), closed.ClosedReason(), closed.Version())
}
}
func TestPublishedFieldsChangeWithTheirOwnEvent(t *testing.T) {
consent := uuid.New()
published := publish(t, newClosedPublication(t), 0, consent, visibilityNow, CardFieldStack)
change, err := published.Apply(mustPublicationRequest(t, PublicationPublished, CardFieldStack, CardFieldLocation), 1, consent, visibilityNow.Add(time.Minute))
if err != nil || !change.Changed || change.Event != PrivacyEventPublicationChanged || change.Publication.Version() != 2 {
t.Fatalf("Apply(more fields) = %+v, %v, want a changed publication at version 2", change, err)
}
event, err := NewPublicationEvent(change, visibilityNow.Add(time.Minute))
if err != nil || event.Kind() != PrivacyEventPublicationChanged || !event.HasFieldSet() || event.ConsentRecordID() != consent ||
!event.Fields().Equal(mustCardFields(t, CardFieldLocation, CardFieldStack)) {
t.Fatalf("NewPublicationEvent() = %v, %v, want the fields and the C2 record behind them", event, err)
}
}
// A revoked C2 closes the card without any write, and a later C2 grant never
// reopens it: only an explicit publication under the new record does.
func TestARevokedConsentClosesAndNeverReopensByItself(t *testing.T) {
consent := uuid.New()
published := publish(t, newClosedPublication(t), 0, consent, visibilityNow, CardFieldStack)
stored := StoredPublication{
UserID: published.UserID(), State: string(PublicationPublished), Fields: published.StoredFields(), ConsentRecordID: consent,
PublishedAt: visibilityNow, Version: 1, ConsentRevoked: true,
}
revoked, err := RestorePublication(stored)
if err != nil {
t.Fatalf("RestorePublication() error = %v", err)
}
if revoked.State() != PublicationClosed || revoked.ClosedReason() != ClosedConsentRevoked || !revoked.Fields().IsEmpty() {
t.Fatalf("a revoked C2 left the card %v (%v) with fields %v, want closed", revoked.State(), revoked.ClosedReason(), revoked.Fields().Codes())
}
// The same body is not "unchanged": the card is closed now, so it is a new publication.
newConsent := uuid.New()
change, err := revoked.Apply(mustPublicationRequest(t, PublicationPublished, CardFieldStack), 1, newConsent, visibilityNow.Add(time.Hour))
if err != nil || !change.Changed || change.Event != PrivacyEventPublicationOpened || change.Publication.ConsentRecordID() != newConsent ||
change.Publication.State() != PublicationPublished {
t.Fatalf("Apply(publish again) = %+v, %v, want an opened publication under the new record", change, err)
}
// Closing a card that the revocation closed in effect is a real change:
// the stored row is normalized to closed and the closing is recorded.
closing, err := revoked.Apply(mustPublicationRequest(t, PublicationClosed), 1, uuid.Nil, visibilityNow.Add(2*time.Hour))
if err != nil || !closing.Changed || closing.Event != PrivacyEventPublicationClosed || closing.Publication.StoredState() != PublicationClosed ||
closing.Publication.ClosedReason() != ClosedByCandidate || closing.Publication.Version() != 2 {
t.Fatalf("Apply(close over a revoked C2) = %+v, %v, want a recorded closing at version 2", closing, err)
}
// A second closing is the repeat of the stored closing.
if again, err := closing.Publication.Apply(mustPublicationRequest(t, PublicationClosed), 1, uuid.Nil, visibilityNow); err != nil || again.Changed {
t.Fatalf("Apply(close again) = %+v, %v, want no change", again, err)
}
}
func TestRestorePublicationRejectsRowsThatBreakTheInvariants(t *testing.T) {
user, consent := uuid.New(), uuid.New()
valid := StoredPublication{UserID: user, State: "published", Fields: []string{"categories", "stack"}, ConsentRecordID: consent, PublishedAt: visibilityNow, Version: 1}
if _, err := RestorePublication(valid); err != nil {
t.Fatalf("RestorePublication(valid) error = %v", err)
}
for name, mutate := range map[string]func(*StoredPublication){
"published without fields": func(s *StoredPublication) { s.Fields = nil },
"closed with fields": func(s *StoredPublication) { s.State = "closed"; s.ClosedAt = visibilityNow },
"closed without a close time": func(s *StoredPublication) { s.State = "closed"; s.Fields = nil },
"published with a close time": func(s *StoredPublication) { s.ClosedAt = visibilityNow },
"fields out of order": func(s *StoredPublication) { s.Fields = []string{"stack", "categories"} },
"a contact as a field": func(s *StoredPublication) { s.Fields = []string{"phone"} },
"unknown state": func(s *StoredPublication) { s.State = "draft" },
"no consent record": func(s *StoredPublication) { s.ConsentRecordID = uuid.Nil },
"version zero": func(s *StoredPublication) { s.Version = 0 },
} {
t.Run(name, func(t *testing.T) {
stored := valid
mutate(&stored)
if _, err := RestorePublication(stored); !errors.Is(err, ErrInvalidVisibility) {
t.Fatalf("RestorePublication() error = %v, want ErrInvalidVisibility", err)
}
})
}
}
func demoSearchConfirmation(t *testing.T) SearchStatusConfirmation {
t.Helper()
id, err := NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
confirmation, err := NewSearchStatusConfirmation(id, DemoProductPolicyV1().SearchStatus)
if err != nil {
t.Fatalf("NewSearchStatusConfirmation() error = %v", err)
}
return confirmation
}
func newSearchStatus(t *testing.T) SearchStatus {
t.Helper()
status, err := NewSearchStatus(uuid.New())
if err != nil {
t.Fatalf("NewSearchStatus() error = %v", err)
}
return status
}
func TestSearchStatusLapsesAfterThePolicyIntervalToTheNonPublicState(t *testing.T) {
confirmation := demoSearchConfirmation(t)
initial := newSearchStatus(t)
if initial.Effective(visibilityNow) != SearchStatusNotLooking || initial.Version() != 0 || initial.Lapsed(visibilityNow) {
t.Fatal("a new account must not be looking at version 0")
}
change, err := initial.Apply(SearchStatusLooking, 0, confirmation, visibilityNow)
if err != nil || !change.Changed || change.Event != PrivacyEventSearchStatusConfirmed {
t.Fatalf("Apply(looking) = %+v, %v, want a confirmation", change, err)
}
looking := change.Status
// The interval is the 30 days of the demo policy, read from the versioned document.
if want := visibilityNow.Add(30 * 24 * time.Hour); !looking.LapsesAt().Equal(want) || !looking.ConfirmedAt().Equal(visibilityNow) ||
looking.PolicyVersionID() != confirmation.policyVersionID || looking.Version() != 1 {
t.Fatalf("looking = confirmed %v lapses %v v%d, want 30 days under the policy version", looking.ConfirmedAt(), looking.LapsesAt(), looking.Version())
}
last := looking.LapsesAt().Add(-time.Nanosecond)
if looking.Effective(last) != SearchStatusLooking || looking.Lapsed(last) {
t.Fatal("the status must hold until the lapse time")
}
for _, at := range []time.Time{looking.LapsesAt(), looking.LapsesAt().Add(365 * 24 * time.Hour)} {
if looking.Effective(at) != SearchStatusNotLooking || !looking.Lapsed(at) {
t.Fatalf("at %v the status = %v lapsed %v, want not_looking and lapsed: a lapse only narrows", at, looking.Effective(at), looking.Lapsed(at))
}
}
// A lapse is not a stored change: the stored status is still what the candidate said.
if looking.StoredValue() != SearchStatusLooking {
t.Fatal("the lapse rewrote the stored status")
}
// The candidate confirms again after the lapse with the current version.
later := looking.LapsesAt().Add(time.Hour)
again, err := looking.Apply(SearchStatusLooking, 1, confirmation, later)
if err != nil || !again.Changed || again.Status.Version() != 2 || again.Status.Effective(later) != SearchStatusLooking || !again.Status.ConfirmedAt().Equal(later) {
t.Fatalf("Apply(confirm after the lapse) = %+v, %v, want a new confirmation at version 2", again, err)
}
}
func TestSearchStatusVersionRules(t *testing.T) {
confirmation := demoSearchConfirmation(t)
initial := newSearchStatus(t)
// Not looking over a status that was never set stores nothing.
if change, err := initial.Apply(SearchStatusNotLooking, 0, SearchStatusConfirmation{}, visibilityNow); err != nil || change.Changed {
t.Fatalf("Apply(not_looking, never set) = %+v, %v, want no change", change, err)
}
if _, err := initial.Apply(SearchStatusLooking, 4, confirmation, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) {
t.Fatalf("Apply(future version) error = %v, want a version conflict", err)
}
if _, err := initial.Apply("searching", 0, confirmation, visibilityNow); !errors.Is(err, ErrInvalidVisibility) {
t.Fatalf("Apply(unknown value) error = %v, want ErrInvalidVisibility", err)
}
if _, err := initial.Apply(SearchStatusLooking, 0, SearchStatusConfirmation{}, visibilityNow); !errors.Is(err, ErrInvalidVisibility) {
t.Fatalf("Apply(looking without a policy) error = %v, want ErrInvalidVisibility", err)
}
looking := mustApplySearch(t, initial, SearchStatusLooking, 0, confirmation, visibilityNow)
// Looking again over a stale version is a conflict: a repeat of a confirmation changes the stored time.
if _, err := looking.Apply(SearchStatusLooking, 0, confirmation, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) {
t.Fatalf("Apply(looking, stale) error = %v, want a version conflict", err)
}
cleared := mustApplySearch(t, looking, SearchStatusNotLooking, 1, SearchStatusConfirmation{}, visibilityNow.Add(time.Hour))
if cleared.StoredValue() != SearchStatusNotLooking || !cleared.ConfirmedAt().IsZero() || !cleared.LapsesAt().IsZero() || !cleared.PolicyVersionID().IsZero() || cleared.Lapsed(visibilityNow.Add(100*24*time.Hour)) {
t.Fatal("not_looking must carry no confirmation, and a cleared status is never lapsed")
}
// Clearing twice is not a change, even with a stale version.
if change, err := cleared.Apply(SearchStatusNotLooking, 1, SearchStatusConfirmation{}, visibilityNow); err != nil || change.Changed {
t.Fatalf("Apply(not_looking, stale, unchanged) = %+v, %v, want no change", change, err)
}
}
func mustApplySearch(t *testing.T, status SearchStatus, value SearchStatusValue, expected int64, confirmation SearchStatusConfirmation, at time.Time) SearchStatus {
t.Helper()
change, err := status.Apply(value, expected, confirmation, at)
if err != nil || !change.Changed {
t.Fatalf("Apply(%s) = %+v, %v, want a change", value, change, err)
}
return change.Status
}
func TestSearchStatusConfirmationComesFromAValidVersionedPolicy(t *testing.T) {
id, err := NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
if _, err := NewSearchStatusConfirmation(PolicyVersionID{}, SearchStatusPolicy{SearchingConfirmationInterval: 30}); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("a confirmation without a policy version error = %v, want ErrInvalidVisibility", err)
}
for _, days := range []CalendarDays{0, -1, maxSearchingConfirmationInterval + 1} {
if _, err := NewSearchStatusConfirmation(id, SearchStatusPolicy{SearchingConfirmationInterval: days}); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("a confirmation of %d days error = %v, want a refusal", days, err)
}
}
// An owner-published interval is used as is.
confirmation, err := NewSearchStatusConfirmation(id, SearchStatusPolicy{SearchingConfirmationInterval: 14})
if err != nil {
t.Fatalf("NewSearchStatusConfirmation(14) error = %v", err)
}
looking := mustApplySearch(t, newSearchStatus(t), SearchStatusLooking, 0, confirmation, visibilityNow)
if want := visibilityNow.Add(14 * 24 * time.Hour); !looking.LapsesAt().Equal(want) {
t.Fatalf("lapses at %v, want %v", looking.LapsesAt(), want)
}
}
func TestRestoreSearchStatusRejectsRowsThatBreakTheInvariants(t *testing.T) {
policy, err := NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
user := uuid.New()
valid := StoredSearchStatus{UserID: user, Status: "looking", ConfirmedAt: visibilityNow, LapsesAt: visibilityNow.Add(time.Hour), PolicyVersionID: policy, Version: 1}
if _, err := RestoreSearchStatus(valid); err != nil {
t.Fatalf("RestoreSearchStatus(valid) error = %v", err)
}
if _, err := RestoreSearchStatus(StoredSearchStatus{UserID: user, Status: "not_looking", Version: 2}); err != nil {
t.Fatalf("RestoreSearchStatus(not_looking) error = %v", err)
}
for name, mutate := range map[string]func(*StoredSearchStatus){
"looking without a confirmation": func(s *StoredSearchStatus) { s.ConfirmedAt = time.Time{} },
"lapse not after the confirm": func(s *StoredSearchStatus) { s.LapsesAt = s.ConfirmedAt },
"looking without a policy": func(s *StoredSearchStatus) { s.PolicyVersionID = PolicyVersionID{} },
"not looking with a confirmation": func(s *StoredSearchStatus) { s.Status = "not_looking" },
"unknown status": func(s *StoredSearchStatus) { s.Status = "open" },
"version zero": func(s *StoredSearchStatus) { s.Version = 0 },
} {
t.Run(name, func(t *testing.T) {
stored := valid
mutate(&stored)
if _, err := RestoreSearchStatus(stored); !errors.Is(err, ErrInvalidVisibility) {
t.Fatalf("RestoreSearchStatus() error = %v, want ErrInvalidVisibility", err)
}
})
}
}
func TestHiddenOrganizationAndEventsNeedTheirIdentifiers(t *testing.T) {
user, organization := uuid.New(), uuid.New()
hidden, err := NewHiddenOrganization(user, organization, visibilityNow)
if err != nil || hidden.UserID() != user || hidden.OrganizationID() != organization || !hidden.HiddenAt().Equal(visibilityNow) {
t.Fatalf("NewHiddenOrganization() = %v, %v, want the record", hidden, err)
}
for _, args := range [][2]uuid.UUID{{uuid.Nil, organization}, {user, uuid.Nil}} {
if _, err := NewHiddenOrganization(args[0], args[1], visibilityNow); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewHiddenOrganization(%v) error = %v, want a refusal", args, err)
}
}
if _, err := NewHiddenOrganization(user, organization, time.Time{}); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewHiddenOrganization(no time) error = %v, want a refusal", err)
}
event, err := NewOrganizationEvent(PrivacyEventOrganizationHidden, user, organization, visibilityNow)
if err != nil || event.ID() == uuid.Nil || event.HasFieldSet() || event.OrganizationID() != organization {
t.Fatalf("NewOrganizationEvent() = %v, %v, want an event without a field set", event, err)
}
if _, err := NewOrganizationEvent(PrivacyEventPublicationClosed, user, organization, visibilityNow); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewOrganizationEvent(publication kind) error = %v, want a refusal", err)
}
if _, err := NewPublicationEvent(PublicationChange{}, visibilityNow); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewPublicationEvent(no change) error = %v, want a refusal", err)
}
if _, err := NewSearchStatusEvent(SearchStatusChange{}, visibilityNow); !errors.Is(err, ErrInvalidVisibility) {
t.Errorf("NewSearchStatusEvent(no change) error = %v, want a refusal", err)
}
}
func TestVisibilityTypesLogOnlyIdentifiers(t *testing.T) {
publication := publish(t, newClosedPublication(t), 0, uuid.New(), visibilityNow, CardFieldStack, CardFieldLocation)
event, err := NewOrganizationEvent(PrivacyEventOrganizationHidden, uuid.New(), uuid.New(), visibilityNow)
if err != nil {
t.Fatalf("NewOrganizationEvent() error = %v", err)
}
var out strings.Builder
logger := slog.New(slog.NewTextHandler(&out, nil))
logger.Info("settings", "publication", publication, "event", event)
for _, secret := range []string{"location", "stack"} {
if strings.Contains(out.String(), secret) {
t.Errorf("log output %q contains %q", out.String(), secret)
}
}
}
func TestCardTextLooksLikeContact(t *testing.T) {
for _, text := range []string{
"anna@example.com", "write to anna@mail.ru", "@anna_dev", "tg: @anna_dev", "t.me/anna", "https://github.com/anna",
"www.example.org", "anna.dev", "+7 (900) 000-00-00", "89000000000", "8 900 000 00 00", "example.com",
// Internationalized domains and wider endings.
"вася.com", "site.рф", "вася.рф", "anna.ua", "anna.by", "anna.kz", "anna.co", "anna.ai", "anna.de", "anna.tv", "anna.site",
"anna.online", "anna.tech", "bit.ly/x", "telegram.dog/anna", "tg://resolve?domain=anna", "wa.me/79000000000", "asp.net",
// Other digit scripts and compatibility forms.
"٧٩٠٠٠٠٠٠٠٠٠", "89000000000", "+7 900 000 00 00", "anna@example.com", "@anna_dev",
// Obfuscation.
"anna [at] example dot com", "vasya at gmail", "vasya собака gmail точка com", "@ vasya", "anna (dot) dev",
// Messenger and contact words without an @.
"tg: vasya_ivanov", "telegram vasya_ivanov", "whatsapp 1", "viber", "skype: vasya", "почта", "телефон", "email me",
} {
if !CardTextLooksLikeContact(text) {
t.Errorf("CardTextLooksLikeContact(%q) = false, want true", text)
}
}
for _, text := range []string{
"PostgreSQL", "Node.js", "Vue.js", "Next.js", "Python 3.12", "ASP.NET", "C++", "C#", "Kubernetes", "Казань", "Mentoring",
"Go 1.22", "Java 17", "Санкт-Петербург", "Python 3.12, Django 4.2, PostgreSQL 16", "pro.company", "Team leadership",
} {
if CardTextLooksLikeContact(text) {
t.Errorf("CardTextLooksLikeContact(%q) = true, want false", text)
}
}
}