837 lines
36 KiB
Go
837 lines
36 KiB
Go
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):
|
|
// 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:
|
|
// - 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 must be handled
|
|
// by the card builder; they are 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; a closed taxonomy in the card builder is still needed
|
|
// to replace free text and address 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
|
|
}
|