package domain import ( "errors" "fmt" "log/slog" "net" "net/url" "regexp" "slices" "strings" "time" "unicode" "unicode/utf8" "github.com/google/uuid" ) // ErrInvalidOrganization reports an organization profile, verification, or // stored organization that breaks a rule. var ErrInvalidOrganization = errors.New("invalid organization") // OrganizationFieldError reports the request field of an organization // profile that broke a rule. It matches ErrInvalidOrganization with // errors.Is, and an HTTP adapter reads Pointer with errors.As to answer 400 // with the pointer of the field. Reason is fixed text; neither field quotes // the submitted value, which can be personal data. type OrganizationFieldError struct { // Pointer is the JSON Pointer of the field in the request body, such as // "/contacts/website" or "/representatives/2/name". Pointer string // Reason says which rule the field broke. Reason string } func (err *OrganizationFieldError) Error() string { return "organization field " + err.Pointer + " " + err.Reason } func (err *OrganizationFieldError) Unwrap() error { return ErrInvalidOrganization } func invalidOrganizationField(location, pointer, reason string) error { return fmt.Errorf("%s - %w", location, &OrganizationFieldError{Pointer: pointer, Reason: reason}) } const ( // The bounds match the OrganizationDescription, OrganizationSphere, // OrganizationWebsite, and OrganizationRepresentative contract schemas // and the CHECK constraints of the organizations tables. The name bound, // maxOrganizationNameRunes, is shared with the consent snapshot of it. maxOrganizationDescriptionRunes = 2000 maxOrganizationSphereRunes = 100 maxOrganizationWebsiteRunes = 300 maxOrganizationRepresentatives = 10 maxRepresentativeNameRunes = 100 maxRepresentativeJobTitleRunes = 100 // maxHostnameBytes and maxHostnameLabelBytes follow RFC 1035. maxHostnameBytes = 253 maxHostnameLabelBytes = 63 httpsPrefix = "https://" ) var ( // organizationPhonePattern is the E.164 format of ContactPhoneNumber. organizationPhonePattern = regexp.MustCompile(`^\+[1-9][0-9]{6,14}$`) // organizationTelegramPattern is the format of ContactTelegramUsername. organizationTelegramPattern = regexp.MustCompile(`^@[A-Za-z0-9_]{5,32}$`) ) // OrganizationVerificationLevel is the trust level of an organization (PRD // FR07). It starts at e0 and changes only through a verification process of // the server, never through a profile edit. Values match the // OrganizationVerificationLevel schema of the public contract. type OrganizationVerificationLevel string const ( // OrganizationVerificationE0 is the confirmed email of the creating // account; every organization starts here. OrganizationVerificationE0 OrganizationVerificationLevel = "e0" // OrganizationVerificationE1 is a corporate email, a verified domain, and // a link with the organization. OrganizationVerificationE1 OrganizationVerificationLevel = "e1" // OrganizationVerificationE2 is a check of the requisites and the // authority. OrganizationVerificationE2 OrganizationVerificationLevel = "e2" // OrganizationVerificationE3 is a manual check or a partner status. OrganizationVerificationE3 OrganizationVerificationLevel = "e3" ) // QuotaTier returns the quota tier of the level, and false for a level that // has no quota policy yet. The PRD gives E3 a separate policy, so it has no // tier. func (level OrganizationVerificationLevel) QuotaTier() (OrganizationTier, bool) { switch level { case OrganizationVerificationE0: return OrganizationTierE0, true case OrganizationVerificationE1: return OrganizationTierE1, true case OrganizationVerificationE2: return OrganizationTierE2, true case OrganizationVerificationE3: // The PRD gives E3 a separate policy, not a quota tier. A caller that // reads quotas must fail closed on false: grant no quota // and refuse the action, never fall back to a lower or a default tier. return "", false default: return "", false } } // OrganizationVerificationBasis is the ground of a verification level. Each // level has its own bases. Values match the OrganizationVerificationBasis // schema of the public contract. type OrganizationVerificationBasis string const ( OrganizationBasisConfirmedEmail OrganizationVerificationBasis = "confirmed_email" OrganizationBasisCorporateDomain OrganizationVerificationBasis = "corporate_domain" OrganizationBasisRequisitesAndAuthority OrganizationVerificationBasis = "requisites_and_authority" OrganizationBasisManualReview OrganizationVerificationBasis = "manual_review" OrganizationBasisPartnerStatus OrganizationVerificationBasis = "partner_status" ) // OrganizationVerification is the verification level of an organization with // its ground and the time it was set. It has no setter and no constructor // but the initial one: a later verification process of the server will // construct the higher levels. type OrganizationVerification struct { level OrganizationVerificationLevel basis OrganizationVerificationBasis changedAt time.Time } // InitialOrganizationVerification returns e0 on the ground of the confirmed // email, the level every new organization starts at. func InitialOrganizationVerification(at time.Time) (OrganizationVerification, error) { return RestoreOrganizationVerification( string(OrganizationVerificationE0), string(OrganizationBasisConfirmedEmail), at) } // RestoreOrganizationVerification validates a stored level, its basis, and // the time, and that the basis belongs to the level. func RestoreOrganizationVerification(level, basis string, changedAt time.Time) (OrganizationVerification, error) { const location = "domain.RestoreOrganizationVerification" var allowed []OrganizationVerificationBasis switch OrganizationVerificationLevel(level) { case OrganizationVerificationE0: allowed = []OrganizationVerificationBasis{OrganizationBasisConfirmedEmail} case OrganizationVerificationE1: allowed = []OrganizationVerificationBasis{OrganizationBasisCorporateDomain} case OrganizationVerificationE2: allowed = []OrganizationVerificationBasis{OrganizationBasisRequisitesAndAuthority} case OrganizationVerificationE3: allowed = []OrganizationVerificationBasis{OrganizationBasisManualReview, OrganizationBasisPartnerStatus} default: return OrganizationVerification{}, fmt.Errorf("%s - unknown level: %w", location, ErrInvalidOrganization) } if !slices.Contains(allowed, OrganizationVerificationBasis(basis)) { return OrganizationVerification{}, fmt.Errorf("%s - the basis does not belong to the level: %w", location, ErrInvalidOrganization) } if changedAt.IsZero() { return OrganizationVerification{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidOrganization) } return OrganizationVerification{ level: OrganizationVerificationLevel(level), basis: OrganizationVerificationBasis(basis), changedAt: changedAt, }, nil } func (verification OrganizationVerification) Level() OrganizationVerificationLevel { return verification.level } func (verification OrganizationVerification) Basis() OrganizationVerificationBasis { return verification.basis } func (verification OrganizationVerification) ChangedAt() time.Time { return verification.changedAt } // OrganizationContactsInput holds the public contacts of an organization as // the request gave them; an empty string is a contact that is not set. type OrganizationContactsInput struct { Website string Email string Phone string Telegram string } // OrganizationContacts are the public contacts of an organization: company // channels, never the personal contacts of an employee. The zero value has // no contact set. type OrganizationContacts struct { website string email string phone string telegram string } // Website returns the https URL of the website, or "" when it is not set. func (contacts OrganizationContacts) Website() string { return contacts.website } // Email returns the public mailbox, or "" when it is not set. func (contacts OrganizationContacts) Email() string { return contacts.email } // Phone returns the E.164 phone number, or "" when it is not set. func (contacts OrganizationContacts) Phone() string { return contacts.phone } // Telegram returns the Telegram username with the leading @, or "" when it // is not set. func (contacts OrganizationContacts) Telegram() string { return contacts.telegram } // OrganizationRepresentativeInput is a representative as the request gave // it. The name is personal data of an employee: never log the value, and // never log a struct that holds it. type OrganizationRepresentativeInput struct { Name string JobTitle string } // OrganizationRepresentative is a person that speaks for the organization to // candidates, as the owner presents them. It is presentation only: no // account link and no right. The name is personal data of an employee, so // String, GoString, Format, and LogValue redact the value; the fields sit // behind a pointer so that printing an enclosing struct shows only an // address. type OrganizationRepresentative struct { value *representativeValue } type representativeValue struct { name string jobTitle string } const redactedRepresentative = "[redacted representative]" // Name returns the name as the card shows it. func (representative OrganizationRepresentative) Name() string { if representative.value == nil { return "" } return representative.value.name } // JobTitle returns the position as the card shows it. func (representative OrganizationRepresentative) JobTitle() string { if representative.value == nil { return "" } return representative.value.jobTitle } func (representative OrganizationRepresentative) String() string { return redactedRepresentative } func (representative OrganizationRepresentative) GoString() string { return redactedRepresentative } func (representative OrganizationRepresentative) LogValue() slog.Value { return slog.StringValue(redactedRepresentative) } func (representative OrganizationRepresentative) Format(state fmt.State, _ rune) { writeRedacted(state, redactedRepresentative) } // OrganizationProfileInput is the editable profile of an organization as a // request gave it. An empty Description or Sphere is a field that is not // set. It holds the names of representatives, which are personal data of // employees: never log it. type OrganizationProfileInput struct { Name string Description string Sphere string Contacts OrganizationContactsInput Representatives []OrganizationRepresentativeInput } // OrganizationProfile is the validated profile that the owner edits: the // name, the description, the field of business, the public contacts, and the // representatives. It holds no verification level, no role, and no member, // so changing it can neither raise a right nor raise the trust level. type OrganizationProfile struct { name string description string sphere string contacts OrganizationContacts representatives []OrganizationRepresentative } // NewOrganizationProfile validates input and normalizes CRLF line breaks in // the description to LF. The first rule that fails returns an error // matching ErrInvalidOrganization with an *OrganizationFieldError that names // the field. func NewOrganizationProfile(input OrganizationProfileInput) (OrganizationProfile, error) { const location = "domain.NewOrganizationProfile" if reason := singleLineTextProblem(input.Name, maxOrganizationNameRunes); reason != "" { return OrganizationProfile{}, invalidOrganizationField(location, "/name", reason) } description := strings.ReplaceAll(input.Description, "\r\n", "\n") if description != "" { if reason := multiLineTextProblem(description, maxOrganizationDescriptionRunes); reason != "" { return OrganizationProfile{}, invalidOrganizationField(location, "/description", reason) } } if input.Sphere != "" { if reason := singleLineTextProblem(input.Sphere, maxOrganizationSphereRunes); reason != "" { return OrganizationProfile{}, invalidOrganizationField(location, "/sphere", reason) } } contacts, err := newOrganizationContacts(location, input.Contacts) if err != nil { return OrganizationProfile{}, err } if len(input.Representatives) > maxOrganizationRepresentatives { return OrganizationProfile{}, invalidOrganizationField(location, "/representatives", fmt.Sprintf("must have at most %d items", maxOrganizationRepresentatives)) } representatives := make([]OrganizationRepresentative, 0, len(input.Representatives)) for index, representative := range input.Representatives { pointer := fmt.Sprintf("/representatives/%d", index) if reason := singleLineTextProblem(representative.Name, maxRepresentativeNameRunes); reason != "" { return OrganizationProfile{}, invalidOrganizationField(location, pointer+"/name", reason) } if reason := singleLineTextProblem(representative.JobTitle, maxRepresentativeJobTitleRunes); reason != "" { return OrganizationProfile{}, invalidOrganizationField(location, pointer+"/job_title", reason) } representatives = append(representatives, OrganizationRepresentative{ value: &representativeValue{name: representative.Name, jobTitle: representative.JobTitle}, }) } return OrganizationProfile{ name: input.Name, description: description, sphere: input.Sphere, contacts: contacts, representatives: representatives, }, nil } func newOrganizationContacts(location string, input OrganizationContactsInput) (OrganizationContacts, error) { var contacts OrganizationContacts if input.Website != "" { if reason := websiteProblem(input.Website); reason != "" { return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/website", reason) } contacts.website = input.Website } if input.Email != "" { email, err := NewEmailAddress(input.Email) if err != nil { return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/email", "must be an email address") } contacts.email = email.Address() } if input.Phone != "" { if !organizationPhonePattern.MatchString(input.Phone) { return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/phone", "must be an E.164 phone number") } contacts.phone = input.Phone } if input.Telegram != "" { if !organizationTelegramPattern.MatchString(input.Telegram) { return OrganizationContacts{}, invalidOrganizationField(location, "/contacts/telegram", "must be a Telegram username with the leading @") } contacts.telegram = input.Telegram } return contacts, nil } func (profile OrganizationProfile) Name() string { return profile.name } // Description returns the description, or "" when it is not set. func (profile OrganizationProfile) Description() string { return profile.description } // Sphere returns the field of business, or "" when it is not set. func (profile OrganizationProfile) Sphere() string { return profile.sphere } func (profile OrganizationProfile) Contacts() OrganizationContacts { return profile.contacts } // Representatives returns a copy of the list in the order the owner gave it. func (profile OrganizationProfile) Representatives() []OrganizationRepresentative { return slices.Clone(profile.representatives) } // Equal reports whether both profiles hold the same values, which tells a // change from a body that changes nothing. func (profile OrganizationProfile) Equal(other OrganizationProfile) bool { return profile.name == other.name && profile.description == other.description && profile.sphere == other.sphere && profile.contacts == other.contacts && slices.EqualFunc(profile.representatives, other.representatives, func(left, right OrganizationRepresentative) bool { return left.Name() == right.Name() && left.JobTitle() == right.JobTitle() }) } // singleLineTextProblem returns the rule that value breaks, or "" when it is // a valid single-line text: not empty, valid UTF-8, within maxRunes, without // surrounding whitespace, and without control characters. func singleLineTextProblem(value string, maxRunes int) string { switch { case value == "": return "must not be empty" case !utf8.ValidString(value): return "must be valid UTF-8" case utf8.RuneCountInString(value) > maxRunes: return fmt.Sprintf("must have at most %d characters", maxRunes) case strings.TrimSpace(value) != value: return "must not have leading or trailing whitespace" case strings.ContainsFunc(value, isForbiddenTextRune): return "must not contain control characters" default: return "" } } // multiLineTextProblem is singleLineTextProblem for a text that may contain // LF line breaks. func multiLineTextProblem(value string, maxRunes int) string { switch { case !utf8.ValidString(value): return "must be valid UTF-8" case utf8.RuneCountInString(value) > maxRunes: return fmt.Sprintf("must have at most %d characters", maxRunes) case strings.TrimSpace(value) != value: return "must not have leading or trailing whitespace" case strings.ContainsFunc(value, func(character rune) bool { return character != '\n' && isForbiddenTextRune(character) }): return "must not contain control characters" default: return "" } } // isForbiddenTextRune reports a control character or a Unicode line or // paragraph separator, which break one-line text and which the database // refuses in its control character class. func isForbiddenTextRune(character rune) bool { return unicode.IsControl(character) || character == '\u2028' || character == '\u2029' } // websiteProblem returns the rule that value breaks, or "" when it is an // https URL of a host name: no credentials, no port, no IP address, and a // host with at least two labels whose last one starts with a letter. The // server never fetches the address; a later feature that does must resolve // it and refuse private ranges on its own. func websiteProblem(value string) string { switch { case utf8.RuneCountInString(value) > maxOrganizationWebsiteRunes: return fmt.Sprintf("must have at most %d characters", maxOrganizationWebsiteRunes) case !strings.HasPrefix(value, httpsPrefix): return "must be an https URL" case strings.ContainsFunc(value, func(character rune) bool { return unicode.IsSpace(character) || isForbiddenTextRune(character) }): return "must not contain whitespace or control characters" } parsed, err := url.Parse(value) switch { case err != nil || parsed.Opaque != "": return "must be an https URL" case parsed.User != nil: return "must not contain credentials" case parsed.Port() != "": return "must not contain a port" } return hostnameProblem(parsed.Hostname()) } func hostnameProblem(host string) string { const notHostName = "must have a host name" if host == "" || len(host) > maxHostnameBytes || net.ParseIP(host) != nil { return notHostName } labels := strings.Split(host, ".") if len(labels) < 2 { return notHostName } for _, label := range labels { if label == "" || len(label) > maxHostnameLabelBytes || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { return notHostName } for _, character := range label { if character != '-' && !unicode.IsLetter(character) && !unicode.IsDigit(character) { return notHostName } } } // A top-level domain starts with a letter, which also refuses numeric // spellings of an IP address such as 127.1 or 0x7f.1. if first, _ := utf8.DecodeRuneInString(labels[len(labels)-1]); !unicode.IsLetter(first) { return notHostName } return "" } // OrganizationCandidateCard is the card of an organization as a candidate sees // it. It carries the profile and the verification level only: no version, no // time, no ground of the verification, no member, no role, and no account. type OrganizationCandidateCard struct { id uuid.UUID profile OrganizationProfile level OrganizationVerificationLevel } func (card OrganizationCandidateCard) ID() uuid.UUID { return card.id } func (card OrganizationCandidateCard) Profile() OrganizationProfile { return card.profile } func (card OrganizationCandidateCard) VerificationLevel() OrganizationVerificationLevel { return card.level } // Organization is a company that employer accounts work in: the profile its // owner edits and the verification level that only the server sets. It holds // no membership and no role; those belong to Membership. Storage // reconstructs it from trusted rows with RestoreOrganization; new ones come // from NewOrganization. type Organization struct { id uuid.UUID profile OrganizationProfile verification OrganizationVerification // version is the optimistic concurrency version of the profile. Storage // checks it as the expected version and advances it in the same // statement, so a domain method never changes it. version int64 createdAt time.Time updatedAt time.Time } // NewOrganization creates an organization at version 1 with a time-ordered // UUIDv7 identifier and the initial verification level e0. No input chooses // the level: a company that looks verified still starts at e0. func NewOrganization(profile OrganizationProfile, createdAt time.Time) (Organization, error) { const location = "domain.NewOrganization" if profile.name == "" { return Organization{}, fmt.Errorf("%s - profile must be built by NewOrganizationProfile: %w", location, ErrInvalidOrganization) } verification, err := InitialOrganizationVerification(createdAt) if err != nil { return Organization{}, fmt.Errorf("%s - set the initial verification: %w", location, err) } id, err := uuid.NewV7() if err != nil { return Organization{}, fmt.Errorf("%s - generate organization ID: %w", location, err) } return Organization{ id: id, profile: profile, verification: verification, version: 1, createdAt: createdAt, updatedAt: createdAt, }, nil } // StoredRepresentative carries the columns of a stored representative. The // name is personal data of an employee: never log the value, and never log a // struct that holds it. type StoredRepresentative struct { Name string JobTitle string } // StoredOrganization carries the columns of a stored organization with its // representatives in list order. An empty Description, Sphere, or contact is // a column that is NULL. type StoredOrganization struct { ID uuid.UUID Name string Description string Sphere string Website string Email string Phone string Telegram string Representatives []StoredRepresentative VerificationLevel string VerificationBasis string VerificationChangedAt time.Time Version int64 CreatedAt time.Time UpdatedAt time.Time } // RestoreOrganization validates a stored organization with the rules of // NewOrganizationProfile and the verification rules, so a row changed // outside the application fails with ErrInvalidOrganization. func RestoreOrganization(stored StoredOrganization) (Organization, error) { const location = "domain.RestoreOrganization" representatives := make([]OrganizationRepresentativeInput, 0, len(stored.Representatives)) for _, representative := range stored.Representatives { representatives = append(representatives, OrganizationRepresentativeInput(representative)) } profile, err := NewOrganizationProfile(OrganizationProfileInput{ Name: stored.Name, Description: stored.Description, Sphere: stored.Sphere, Contacts: OrganizationContactsInput{ Website: stored.Website, Email: stored.Email, Phone: stored.Phone, Telegram: stored.Telegram, }, Representatives: representatives, }) if err != nil { return Organization{}, fmt.Errorf("%s - validate profile: %w", location, err) } verification, err := RestoreOrganizationVerification(stored.VerificationLevel, stored.VerificationBasis, stored.VerificationChangedAt) if err != nil { return Organization{}, fmt.Errorf("%s - validate verification: %w", location, err) } switch { case stored.ID == uuid.Nil: return Organization{}, fmt.Errorf("%s - ID must not be nil: %w", location, ErrInvalidOrganization) case stored.Version < 1: return Organization{}, fmt.Errorf("%s - version must be positive: %w", location, ErrInvalidOrganization) case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt): return Organization{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidOrganization) } return Organization{ id: stored.ID, profile: profile, verification: verification, version: stored.Version, createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt, }, nil } func (organization Organization) ID() uuid.UUID { return organization.id } func (organization Organization) Profile() OrganizationProfile { return organization.profile } func (organization Organization) Verification() OrganizationVerification { return organization.verification } func (organization Organization) Version() int64 { return organization.version } func (organization Organization) CreatedAt() time.Time { return organization.createdAt } func (organization Organization) UpdatedAt() time.Time { return organization.updatedAt } // ApplyProfile returns the organization with profile as its profile. The // identifier, the version, and the verification stay as they are: storage // checks Version as the expected version and advances it, and only a // verification process changes the level. A time before the last update, // from clock skew between instances, is stored as the last update. func (organization Organization) ApplyProfile(profile OrganizationProfile, at time.Time) (Organization, error) { const location = "Organization.ApplyProfile" switch { case organization.id == uuid.Nil: return Organization{}, fmt.Errorf("%s - organization must be built by NewOrganization: %w", location, ErrInvalidOrganization) case profile.name == "": return Organization{}, fmt.Errorf("%s - profile must be built by NewOrganizationProfile: %w", location, ErrInvalidOrganization) case at.IsZero(): return Organization{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidOrganization) } updated := organization updated.profile = profile updated.updatedAt = at if at.Before(organization.updatedAt) { updated.updatedAt = organization.updatedAt } return updated, nil } // CandidateCard returns the card of the organization as a candidate sees it. func (organization Organization) CandidateCard() OrganizationCandidateCard { return OrganizationCandidateCard{id: organization.id, profile: organization.profile, level: organization.verification.level} } // IsZero reports an Organization not built by NewOrganization or // RestoreOrganization. func (organization Organization) IsZero() bool { return organization.id == uuid.Nil } // LogValue logs the identifier, the version, and the level only: the // profile holds representatives' names, which are personal data. func (organization Organization) LogValue() slog.Value { return slog.GroupValue( slog.String("id", organization.id.String()), slog.Int64("version", organization.version), slog.String("verification_level", string(organization.verification.level)), ) } // OrganizationSummary is an organization as the list of an account's // organizations names it. type OrganizationSummary struct { id uuid.UUID name string level OrganizationVerificationLevel } // RestoreOrganizationSummary validates a stored name and level. func RestoreOrganizationSummary(id uuid.UUID, name, level string) (OrganizationSummary, error) { const location = "domain.RestoreOrganizationSummary" if singleLineTextProblem(name, maxOrganizationNameRunes) != "" || id == uuid.Nil { return OrganizationSummary{}, fmt.Errorf("%s - ID and name must be valid: %w", location, ErrInvalidOrganization) } switch OrganizationVerificationLevel(level) { case OrganizationVerificationE0, OrganizationVerificationE1, OrganizationVerificationE2, OrganizationVerificationE3: return OrganizationSummary{id: id, name: name, level: OrganizationVerificationLevel(level)}, nil default: return OrganizationSummary{}, fmt.Errorf("%s - unknown level: %w", location, ErrInvalidOrganization) } } func (summary OrganizationSummary) ID() uuid.UUID { return summary.id } func (summary OrganizationSummary) Name() string { return summary.name } func (summary OrganizationSummary) VerificationLevel() OrganizationVerificationLevel { return summary.level }