mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-28 08:05:45 +00:00
885 lines
35 KiB
Go
885 lines
35 KiB
Go
// Package sendingdomain is the workspace's view of the domains it sends from:
|
|
// their custom tracking host, and an optional redirect of the bare domain to
|
|
// the company's main website, served by this instance (or by Warmbly Cloud for
|
|
// a linked self-hosted instance) once DNS proves the workspace controls the
|
|
// domain.
|
|
package sendingdomain
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"github.com/warmbly/warmbly/internal/app/customhost"
|
|
"github.com/warmbly/warmbly/internal/app/edgehost"
|
|
"github.com/warmbly/warmbly/internal/app/owndomain"
|
|
"github.com/warmbly/warmbly/internal/config"
|
|
"github.com/warmbly/warmbly/internal/errx"
|
|
"github.com/warmbly/warmbly/internal/jobrun"
|
|
"github.com/warmbly/warmbly/internal/models"
|
|
"github.com/warmbly/warmbly/internal/pkg/cfsaas"
|
|
"github.com/warmbly/warmbly/internal/pkg/domainproof"
|
|
"github.com/warmbly/warmbly/internal/pkg/mailhost"
|
|
"github.com/warmbly/warmbly/internal/pkg/trackdns"
|
|
"github.com/warmbly/warmbly/internal/repository"
|
|
"github.com/warmbly/warmbly/internal/utils/validate"
|
|
)
|
|
|
|
// Stable codes for refusals a client branches on.
|
|
const (
|
|
ErrIDNotYours = "sending_domain_not_in_workspace"
|
|
ErrIDConsumerDomain = "sending_domain_shared_provider"
|
|
ErrIDTarget = "domain_redirect_invalid_target"
|
|
ErrIDTaken = "domain_redirect_taken"
|
|
ErrIDNoTracking = "tracking_host_not_configured"
|
|
// ErrIDLinked refuses a change, from Cloud's own dashboard, to a redirect a linked instance manages.
|
|
ErrIDLinked = "domain_redirect_linked"
|
|
// ErrIDCloudUnavailable refuses serving from Cloud when this instance is not linked or Cloud does not offer it.
|
|
ErrIDCloudUnavailable = "domain_redirect_cloud_unavailable"
|
|
// ErrIDCloudUnreachable refuses a move or removal Cloud could not be told about.
|
|
ErrIDCloudUnreachable = "domain_redirect_cloud_unreachable"
|
|
// ErrIDLimit refuses a linked instance's redirect past config.PoolLinkRedirectLimit.
|
|
ErrIDLimit = "domain_redirect_limit"
|
|
// ErrIDRemoteNotFound is Cloud's answer for a redirect the linked instance does not have there.
|
|
ErrIDRemoteNotFound = "pool_link_redirect_not_found"
|
|
)
|
|
|
|
// Mailboxes is the mailbox store's side.
|
|
type Mailboxes interface {
|
|
DomainsOverview(ctx context.Context, orgID uuid.UUID) ([]models.SendingDomain, *errx.Error)
|
|
CountDomainMailboxes(ctx context.Context, orgID uuid.UUID, domain string) (int, *errx.Error)
|
|
SetDomainTracking(ctx context.Context, orgID uuid.UUID, domain, host string, verified bool, verifiedAt *time.Time) (int, *errx.Error)
|
|
OwnedDomains(ctx context.Context, orgID uuid.UUID) ([]string, *errx.Error)
|
|
}
|
|
|
|
// Resolver is the DNS the checks read; net.DefaultResolver in production.
|
|
type Resolver interface {
|
|
LookupTXT(ctx context.Context, name string) ([]string, error)
|
|
LookupCNAME(ctx context.Context, host string) (string, error)
|
|
LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
|
|
}
|
|
|
|
// Auditor records a redirect changing state, which also refreshes every teammate's dashboard.
|
|
type Auditor interface {
|
|
LogAction(ctx context.Context, orgID, actorID uuid.UUID, action models.AuditAction, entityType models.AuditEntityType, entityID *uuid.UUID, ipAddress, userAgent string, changes, metadata map[string]string)
|
|
}
|
|
|
|
// WireAuditor attaches the audit log; optional.
|
|
func (s *Service) WireAuditor(a Auditor) { s.auditor = a }
|
|
|
|
type Service struct {
|
|
auditor Auditor
|
|
vendors VendorDomains
|
|
cloud CloudRedirects
|
|
reach ReachProber
|
|
redirects repository.DomainRedirectRepository
|
|
mailboxes Mailboxes
|
|
own *owndomain.Resolver
|
|
resolver Resolver
|
|
proof *domainproof.Prover
|
|
// customHosts gates a new tracking host on the workspace's TXT proof.
|
|
customHosts *customhost.Checker
|
|
// edge registers served names at the provider in front of the tracking host; nil when there is none.
|
|
edge *edgehost.Service
|
|
// target is this instance's tracking host; "" when tracking is not set up.
|
|
target func() string
|
|
}
|
|
|
|
// WireCustomHosts attaches the custom-domain ownership checks.
|
|
func (s *Service) WireCustomHosts(c *customhost.Checker) { s.customHosts = c }
|
|
|
|
// WireEdge attaches the edge registration; optional.
|
|
func (s *Service) WireEdge(e *edgehost.Service) { s.edge = e }
|
|
|
|
func NewService(redirects repository.DomainRedirectRepository, mailboxes Mailboxes, resolver Resolver, proof *domainproof.Prover) *Service {
|
|
if resolver == nil {
|
|
resolver = net.DefaultResolver
|
|
}
|
|
return &Service{redirects: redirects, mailboxes: mailboxes, resolver: resolver, proof: proof, target: config.TrackingHostname, reach: NewHTTPReach()}
|
|
}
|
|
|
|
// WireOwnDomains replaces the default definition of the workspace's own domains (mailbox domains only) with the shared one.
|
|
func (s *Service) WireOwnDomains(r *owndomain.Resolver) { s.own = r }
|
|
|
|
func (s *Service) ownDomains() *owndomain.Resolver {
|
|
if s.own != nil {
|
|
return s.own
|
|
}
|
|
return owndomain.New(s.mailboxes, nil)
|
|
}
|
|
|
|
// ownTarget refuses a redirect destination outside the workspace's own domains, looking for a website's TXT proof first.
|
|
func (s *Service) ownTarget(ctx context.Context, orgID uuid.UUID, target string) *errx.Error {
|
|
ok, xerr := s.ownDomains().Admit(ctx, orgID, target)
|
|
if xerr != nil {
|
|
return xerr
|
|
}
|
|
if !ok {
|
|
return owndomain.Refusal()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// markTarget records on the row whether its destination is on one of the workspace's own domains, and so served,
|
|
// with the website's TXT record when that is what proves it.
|
|
func (s *Service) markTarget(r *models.DomainRedirect, own owndomain.Set) {
|
|
if r == nil || r.LinkedInstanceID != nil || r.TargetURL == "" {
|
|
return
|
|
}
|
|
host := owndomain.TargetHost(r.TargetURL)
|
|
active := own.Allows(host)
|
|
r.TargetActive = &active
|
|
if !owndomain.Within(host, own.Base) {
|
|
r.Website = s.website(r.OrganizationID, r.TargetURL, active)
|
|
}
|
|
if !active {
|
|
r.TargetInactiveReason = targetInactiveMessage
|
|
if r.Website != nil {
|
|
r.TargetInactiveReason = websiteUnprovedMessage(r.Website.Domain)
|
|
}
|
|
}
|
|
}
|
|
|
|
// website is the destination's proof as the dashboard shows it, nil when websites cannot be proved here.
|
|
func (s *Service) website(orgID uuid.UUID, target string, verified bool) *models.RedirectWebsite {
|
|
p := s.ownDomains().Record(orgID, target)
|
|
if p == nil {
|
|
return nil
|
|
}
|
|
return &models.RedirectWebsite{Domain: p.Domain, Verified: verified,
|
|
Record: &models.DNSRecord{Purpose: "website", Type: "TXT", Name: p.Name, Value: p.Value, OK: verified}}
|
|
}
|
|
|
|
const targetInactiveMessage = "Not in use: the destination is no longer on one of this workspace's own domains, so visitors get the domain's default page instead. This happens when the mailbox or verified domain it relied on was removed. Point the redirect at a page on a domain the workspace has a mailbox on, its verified tracking domain, or its verified forms domain, or reconnect that domain."
|
|
|
|
func websiteUnprovedMessage(site string) string {
|
|
return "Not served yet: add the TXT record for " + site + " at its DNS provider to prove the website is this workspace's. Until then visitors get the domain's default page."
|
|
}
|
|
|
|
// WebsiteProof is the TXT record that makes the destination's website the workspace's, checked now.
|
|
func (s *Service) WebsiteProof(ctx context.Context, orgID uuid.UUID, domain, target string) (*models.RedirectWebsite, *errx.Error) {
|
|
domain = normalizeDomain(domain)
|
|
if xerr := s.ownDomain(ctx, orgID, domain); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
cleaned, xerr := cleanTarget(target, domain)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
set, xerr := s.ownDomains().Set(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
host := owndomain.TargetHost(cleaned)
|
|
if owndomain.Within(host, set.Base) {
|
|
return &models.RedirectWebsite{Domain: owndomain.Website(host), Verified: true}, nil
|
|
}
|
|
proof, xerr := s.ownDomains().Prove(ctx, orgID, cleaned)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if proof == nil {
|
|
return nil, owndomain.Refusal()
|
|
}
|
|
return s.website(orgID, cleaned, proof.Verified || set.Allows(host)), nil
|
|
}
|
|
|
|
func normalizeDomain(d string) string {
|
|
return mailhost.NormalizeDomain(strings.TrimPrefix(strings.ToLower(strings.TrimSpace(d)), "www."))
|
|
}
|
|
|
|
// Overview is every sending domain with its tracking hosts and redirect.
|
|
func (s *Service) Overview(ctx context.Context, orgID uuid.UUID) ([]models.SendingDomain, *errx.Error) {
|
|
domains, xerr := s.mailboxes.DomainsOverview(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
redirects, err := s.redirects.List(ctx, orgID)
|
|
if err != nil {
|
|
return nil, errx.InternalError()
|
|
}
|
|
own, xerr := s.ownDomains().Set(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
ptrs := make([]*models.DomainRedirect, len(redirects))
|
|
for i := range redirects {
|
|
ptrs[i] = &redirects[i]
|
|
}
|
|
pending := s.edgePending(ctx, ptrs...)
|
|
byDomain := map[string]*models.DomainRedirect{}
|
|
for i := range redirects {
|
|
r := redirects[i]
|
|
s.decorate(&r, nil, pending)
|
|
s.markTarget(&r, own)
|
|
byDomain[r.Domain] = &r
|
|
}
|
|
var links map[string]models.VendorDomainLink
|
|
if s.vendors != nil {
|
|
links, _ = s.vendors.DomainLinks(ctx, orgID)
|
|
}
|
|
for i := range domains {
|
|
domains[i].Redirect = byDomain[domains[i].Domain]
|
|
if l, ok := links[domains[i].Domain]; ok {
|
|
domains[i].VendorDomain = &l
|
|
}
|
|
}
|
|
return domains, nil
|
|
}
|
|
|
|
// trackingLabels are the names people and vendors usually give a tracking host.
|
|
var trackingLabels = []string{config.DefaultTrackingLabel, "links", "track", "t", "click", "go", "email", "trk"}
|
|
|
|
// TrackingSuggestion is the tracking host to offer a domain: one already in
|
|
// use and verified, one whose DNS already points here, or link.<domain>.
|
|
func (s *Service) TrackingSuggestion(ctx context.Context, domain string, inUse []models.TrackingDomainUse) *models.TrackingSuggestion {
|
|
target := s.target()
|
|
if target == "" {
|
|
return nil
|
|
}
|
|
for _, t := range inUse {
|
|
if t.Verified {
|
|
return &models.TrackingSuggestion{Host: t.Host, Status: "active", CNAMETarget: target}
|
|
}
|
|
}
|
|
for _, label := range trackingLabels {
|
|
host := label + "." + domain
|
|
cctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
res := trackdns.VerifyWith(cctx, s.resolver, host, target)
|
|
cancel()
|
|
if res.Verified {
|
|
return &models.TrackingSuggestion{Host: host, Status: "found", CNAMETarget: target}
|
|
}
|
|
}
|
|
return &models.TrackingSuggestion{Host: config.DefaultTrackingHost(domain), Status: "suggested", CNAMETarget: target}
|
|
}
|
|
|
|
// ApplyTracking puts one tracking host on every workspace mailbox on the domain.
|
|
// It is saved even before DNS is in place: the tracking sweep verifies it and
|
|
// links switch to it the moment the CNAME resolves.
|
|
func (s *Service) ApplyTracking(ctx context.Context, orgID uuid.UUID, domain, host string) (*models.TrackingDomainStatus, int, *errx.Error) {
|
|
domain = normalizeDomain(domain)
|
|
if n, xerr := s.mailboxes.CountDomainMailboxes(ctx, orgID, domain); xerr != nil {
|
|
return nil, 0, xerr
|
|
} else if n == 0 {
|
|
return nil, 0, errx.NewWithIdentifier(errx.NotFound, ErrIDNotYours, "The workspace has no mailbox on this domain.")
|
|
}
|
|
host = config.NormalizeTrackingHost(host)
|
|
if host != "" {
|
|
if s.target() == "" {
|
|
return nil, 0, errx.NewWithIdentifier(errx.BadRequest, ErrIDNoTracking, "Open and click tracking is not set up on this instance.")
|
|
}
|
|
if xerr := validate.ValidateTrackingDomain(host); xerr != nil {
|
|
return nil, 0, xerr
|
|
}
|
|
}
|
|
status := &models.TrackingDomainStatus{TrackingDomain: host, CNAMETarget: s.target()}
|
|
if host != "" {
|
|
res := s.customHosts.Gate(ctx, trackdns.VerifyWith(ctx, s.resolver, host, s.target()), orgID, false)
|
|
status.TrackingDomainVerified, status.Status, status.Message, status.Observed = res.Verified, res.Code, res.Reason, res.Observed
|
|
status.TrackingHostUnresolvable = res.TargetUnresolvable
|
|
status.TXTName, status.TXTValue = s.customHosts.Record(orgID, host)
|
|
if res.Verified {
|
|
now := time.Now().UTC()
|
|
status.TrackingDomainVerifiedAt = &now
|
|
}
|
|
}
|
|
n, xerr := s.mailboxes.SetDomainTracking(ctx, orgID, domain, host, status.TrackingDomainVerified, status.TrackingDomainVerifiedAt)
|
|
if xerr != nil {
|
|
return nil, 0, xerr
|
|
}
|
|
return status, n, nil
|
|
}
|
|
|
|
// RedirectInput sets a domain's redirect; an empty ServedBy keeps where it is served from.
|
|
type RedirectInput = models.DomainRedirectRequest
|
|
|
|
// SetRedirect records (or updates) the redirect and checks it once: DNS here, or Cloud's verdict when Cloud serves it.
|
|
func (s *Service) SetRedirect(ctx context.Context, orgID, userID uuid.UUID, domain string, in RedirectInput) (*models.DomainRedirect, *errx.Error) {
|
|
domain = normalizeDomain(domain)
|
|
if xerr := s.ownDomain(ctx, orgID, domain); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
target, xerr := cleanTarget(in.TargetURL, domain)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
www := true
|
|
if in.IncludeWWW != nil {
|
|
www = *in.IncludeWWW
|
|
}
|
|
existing, err := s.redirects.Get(ctx, orgID, domain)
|
|
if err != nil {
|
|
return nil, errx.InternalError()
|
|
}
|
|
if existing != nil && existing.LinkedInstanceID != nil {
|
|
return nil, errx.NewWithIdentifier(errx.Conflict, ErrIDLinked, "This domain's redirect is managed by a linked self-hosted instance. Change it there.")
|
|
}
|
|
if xerr := s.ownTarget(ctx, orgID, target); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
server := in.ServedBy
|
|
if server == "" && existing != nil {
|
|
server = existing.ServedBy
|
|
}
|
|
if server == "" {
|
|
server = models.RedirectServedByInstance
|
|
}
|
|
switch server {
|
|
case models.RedirectServedByInstance:
|
|
if s.target() == "" {
|
|
return nil, errx.NewWithIdentifier(errx.BadRequest, ErrIDNoTracking, "Domain redirects are served by the tracking service, which is not set up on this instance.")
|
|
}
|
|
case models.RedirectServedByCloud:
|
|
if xerr := s.cloudServable(ctx, orgID, domain, existing != nil && existing.ServedBy == models.RedirectServedByCloud); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
default:
|
|
return nil, errx.ErrInvalid
|
|
}
|
|
|
|
if server == models.RedirectServedByInstance && existing != nil && existing.ServedBy == models.RedirectServedByCloud {
|
|
if xerr := s.releaseCloud(ctx, orgID, domain); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
}
|
|
|
|
// The row is written first, so it claims the domain before Cloud hears of it and the sweep can always finish the job.
|
|
r := &models.DomainRedirect{ID: uuid.New(), OrganizationID: orgID, Domain: domain, TargetURL: target, IncludeWWW: www,
|
|
VerifyToken: s.proof.Value(orgID, domain), ServedBy: server}
|
|
if err := s.redirects.Upsert(ctx, r, &userID); err != nil {
|
|
switch {
|
|
case errors.Is(err, repository.ErrRedirectOwned):
|
|
return nil, errx.NewWithIdentifier(errx.Conflict, ErrIDLinked, "This domain's redirect is managed by a linked self-hosted instance. Change it there.")
|
|
case errors.Is(err, repository.ErrRedirectTaken):
|
|
return nil, errx.NewWithIdentifier(errx.Conflict, ErrIDTaken, "Another workspace on this instance already redirects this domain.")
|
|
}
|
|
return nil, errx.InternalError()
|
|
}
|
|
if server != models.RedirectServedByCloud {
|
|
return s.check(ctx, r, true)
|
|
}
|
|
remote, xerr := s.cloud.PutRedirect(ctx, orgID, domain, models.DomainRedirectRequest{TargetURL: target, IncludeWWW: &www})
|
|
if xerr == nil {
|
|
return s.mirror(ctx, r, remote)
|
|
}
|
|
if !cloudOutage(xerr) {
|
|
s.rollback(ctx, r, existing, userID)
|
|
return nil, cloudRefusal(xerr)
|
|
}
|
|
// Cloud may have taken it before the answer was lost; the sweep asks again and sends it if not.
|
|
return s.stop(ctx, r, pendingCloudMessage)
|
|
}
|
|
|
|
// rollback puts a row Cloud refused back to what it was before the save.
|
|
func (s *Service) rollback(ctx context.Context, r, before *models.DomainRedirect, userID uuid.UUID) {
|
|
if before == nil {
|
|
_, _ = s.redirects.Delete(ctx, r.OrganizationID, r.Domain)
|
|
return
|
|
}
|
|
prev := *before
|
|
if err := s.redirects.Upsert(ctx, &prev, &userID); err == nil && prev.ServedBy == models.RedirectServedByInstance {
|
|
_, _ = s.check(ctx, &prev, false)
|
|
}
|
|
}
|
|
|
|
// ownDomain refuses a domain the workspace sends nothing from, and the shared providers anyone has an address on.
|
|
func (s *Service) ownDomain(ctx context.Context, orgID uuid.UUID, domain string) *errx.Error {
|
|
if domain == "" {
|
|
return errx.NewWithIdentifier(errx.BadRequest, ErrIDNotYours, "Enter a domain.")
|
|
}
|
|
if mailhost.SharedProvider(domain) {
|
|
return errx.NewWithIdentifier(errx.BadRequest, ErrIDConsumerDomain, "A shared email provider's domain cannot be redirected.")
|
|
}
|
|
n, xerr := s.mailboxes.CountDomainMailboxes(ctx, orgID, domain)
|
|
if xerr != nil {
|
|
return xerr
|
|
}
|
|
if n == 0 {
|
|
return errx.NewWithIdentifier(errx.NotFound, ErrIDNotYours, "The workspace has no mailbox on this domain.")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// cleanTarget accepts a website address a person pastes and refuses one that would loop.
|
|
func cleanTarget(raw, domain string) (string, *errx.Error) {
|
|
raw = strings.TrimSpace(raw)
|
|
if raw != "" && !strings.Contains(raw, "://") {
|
|
raw = "https://" + raw
|
|
}
|
|
u, err := url.Parse(raw)
|
|
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || u.User != nil || len(raw) > 2048 {
|
|
return "", errx.NewWithIdentifier(errx.BadRequest, ErrIDTarget, "Enter the website address to send visitors to, like https://yourcompany.com.")
|
|
}
|
|
host := strings.ToLower(u.Hostname())
|
|
if host == domain || host == "www."+domain {
|
|
return "", errx.NewWithIdentifier(errx.BadRequest, ErrIDTarget, "The redirect cannot point back at the same domain.")
|
|
}
|
|
u.Fragment = ""
|
|
return u.String(), nil
|
|
}
|
|
|
|
// VerifyRedirect checks DNS now.
|
|
func (s *Service) VerifyRedirect(ctx context.Context, orgID uuid.UUID, domain string) (*models.DomainRedirect, *errx.Error) {
|
|
domain = normalizeDomain(domain)
|
|
if xerr := s.ownDomain(ctx, orgID, domain); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
r, err := s.redirects.Get(ctx, orgID, domain)
|
|
if err != nil {
|
|
return nil, errx.InternalError()
|
|
}
|
|
if r == nil || r.LinkedInstanceID != nil {
|
|
return nil, errx.ErrNotFound
|
|
}
|
|
return s.check(ctx, r, true)
|
|
}
|
|
|
|
// DeleteRedirect stops serving the redirect, on Cloud too when Cloud serves it.
|
|
func (s *Service) DeleteRedirect(ctx context.Context, orgID uuid.UUID, domain string) *errx.Error {
|
|
domain = normalizeDomain(domain)
|
|
r, err := s.redirects.Get(ctx, orgID, domain)
|
|
if err != nil {
|
|
return errx.InternalError()
|
|
}
|
|
if r == nil || r.LinkedInstanceID != nil {
|
|
return errx.ErrNotFound
|
|
}
|
|
if r.ServedBy == models.RedirectServedByCloud {
|
|
if xerr := s.releaseCloud(ctx, orgID, domain); xerr != nil {
|
|
return xerr
|
|
}
|
|
}
|
|
ok, err := s.redirects.Delete(ctx, orgID, domain)
|
|
if err != nil {
|
|
return errx.InternalError()
|
|
}
|
|
if !ok {
|
|
return errx.ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// probe is one DNS check's findings.
|
|
type probe struct {
|
|
txt, apex, www bool
|
|
txtMissing, apexMissing bool
|
|
apexReason, targetReason string
|
|
}
|
|
|
|
func (s *Service) probe(ctx context.Context, r *models.DomainRedirect) probe {
|
|
var p probe
|
|
cctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
|
defer cancel()
|
|
txts, err := s.resolver.LookupTXT(cctx, domainproof.Name(r.Domain))
|
|
p.txt = s.proof.Matches(txts, r.OrganizationID, r.Domain)
|
|
var dnsErr *net.DNSError
|
|
p.txtMissing = !p.txt && (err == nil || (errors.As(err, &dnsErr) && dnsErr.IsNotFound))
|
|
target := s.target()
|
|
apex := trackdns.VerifyWith(cctx, s.resolver, r.Domain, target)
|
|
p.apex = apex.Verified
|
|
p.apexMissing = !p.apex && (apex.Code == trackdns.CodeNotFound || apex.Code == trackdns.CodeWrongTarget)
|
|
p.apexReason = apex.Reason
|
|
if apex.TargetUnresolvable {
|
|
p.targetReason = "The tracking host " + target + " does not resolve, so no address can be compared."
|
|
}
|
|
if r.IncludeWWW {
|
|
p.www = s.wwwPoints(cctx, r.Domain, target, p.apex)
|
|
}
|
|
return p
|
|
}
|
|
|
|
// wwwPoints accepts www as a CNAME to the root (when the root points here) or anything that reaches the tracking host.
|
|
func (s *Service) wwwPoints(ctx context.Context, domain, target string, apex bool) bool {
|
|
if cname, err := s.resolver.LookupCNAME(ctx, "www."+domain); err == nil && apex && strings.TrimSuffix(strings.ToLower(cname), ".") == domain {
|
|
return true
|
|
}
|
|
return trackdns.VerifyWith(ctx, s.resolver, "www."+domain, target).Verified
|
|
}
|
|
|
|
// check verifies one redirect and records the verdict. A verified redirect
|
|
// only drops when DNS says so definitively, never on a lookup that failed.
|
|
// force asks Cloud to check again rather than report its last verdict.
|
|
func (s *Service) check(ctx context.Context, r *models.DomainRedirect, force bool) (*models.DomainRedirect, *errx.Error) {
|
|
ownTarget, ownErr := s.ownDomains().Admit(ctx, r.OrganizationID, r.TargetURL)
|
|
if r.ServedBy == models.RedirectServedByCloud {
|
|
// Cloud cannot see this workspace's domains, so a destination that is no longer its own stops being served there from here.
|
|
if ownErr == nil && !ownTarget {
|
|
if xerr := s.releaseCloud(ctx, r.OrganizationID, r.Domain); xerr != nil {
|
|
log.Warn().Str("domain", r.Domain).Str("code", xerr.ResponseCode()).Msg("domain redirect: could not stop Cloud serving a destination off the workspace's domains")
|
|
}
|
|
msg := targetInactiveMessage
|
|
if w := s.website(r.OrganizationID, r.TargetURL, false); w != nil {
|
|
msg = websiteUnprovedMessage(w.Domain)
|
|
}
|
|
return s.stop(ctx, r, msg)
|
|
}
|
|
return s.checkCloud(ctx, r, force)
|
|
}
|
|
p := s.probe(ctx, r)
|
|
verified := p.txt && p.apex
|
|
msg := ""
|
|
switch {
|
|
case p.targetReason != "":
|
|
msg = p.targetReason
|
|
case !p.txt:
|
|
msg = "The TXT record " + domainproof.Name(r.Domain) + " is not there yet. DNS changes can take a while to appear."
|
|
case !p.apex:
|
|
msg = p.apexReason
|
|
}
|
|
if r.Verified && !verified && !(p.txtMissing || p.apexMissing) {
|
|
verified, msg = true, ""
|
|
}
|
|
if err := s.redirects.SetCheck(ctx, r.ID, verified, msg); err != nil {
|
|
if errors.Is(err, repository.ErrRedirectTaken) {
|
|
return nil, errx.NewWithIdentifier(errx.Conflict, ErrIDTaken, "Another workspace on this instance already redirects this domain.")
|
|
}
|
|
return nil, errx.InternalError()
|
|
}
|
|
// The edge in front of the tracking host has to know the names before a visit can reach it; a slow edge is left to the sweep.
|
|
if verified && s.edge.Enabled() {
|
|
hosts := []string{r.Domain}
|
|
if r.IncludeWWW {
|
|
hosts = append(hosts, "www."+r.Domain)
|
|
}
|
|
ectx, cancel := context.WithTimeout(ctx, edgeRegisterTimeout)
|
|
s.edge.Register(ectx, hosts...)
|
|
cancel()
|
|
}
|
|
// DNS proves the name points here; opening it proves a visitor gets the redirect, which is withheld until the destination is the workspace's.
|
|
var reach *models.RedirectReach
|
|
if verified && s.reach != nil && ownErr == nil && ownTarget {
|
|
got := s.reach.Probe(ctx, r.Domain, r.TargetURL)
|
|
// Tracking forgets a miss within a minute, so one that outlasts that is a real answer: this tracking service has no redirect for the name.
|
|
if got.Hint == models.RedirectHintSettling && r.Verified && r.VerifiedAt != nil && time.Since(*r.VerifiedAt) > settleGrace {
|
|
got = models.RedirectReach{Status: models.RedirectReachNotReaching, Hint: models.RedirectHintNotRouted, Proxy: got.Proxy,
|
|
Detail: "Warmbly's tracking service answers for " + r.Domain + " but serves no redirect for it, so the domain may point at a different Warmbly instance."}
|
|
}
|
|
if got.Hint == models.RedirectHintEdgeInactive {
|
|
if s.edge.Enabled() {
|
|
got.Detail += " Warmbly activates a verified domain there by itself within a few minutes."
|
|
} else {
|
|
got.Detail += " Cloudflare only serves names its own zone knows, so point the domain's records straight at this server, or add the domain to that zone as a custom hostname."
|
|
}
|
|
}
|
|
reach = &got
|
|
}
|
|
if err := s.redirects.SetReach(ctx, r.ID, reach); err != nil {
|
|
return nil, errx.InternalError()
|
|
}
|
|
return s.finish(ctx, r, &p)
|
|
}
|
|
|
|
// sweepConcurrency bounds the checks one sweep runs at once.
|
|
const sweepConcurrency = 8
|
|
|
|
// edgeRegisterTimeout is what one check may spend registering its names, leaving the rest of a request's deadline to finish it.
|
|
const edgeRegisterTimeout = 5 * time.Second
|
|
|
|
// settleGrace is how long after verifying a tracking miss is put down to its cache rather than to the setup.
|
|
const settleGrace = 3 * time.Minute
|
|
|
|
// finish reads the row back, tells the workspace when it went live or stopped, and fills what the dashboard shows.
|
|
func (s *Service) finish(ctx context.Context, before *models.DomainRedirect, p *probe) (*models.DomainRedirect, *errx.Error) {
|
|
fresh, err := s.redirects.Get(ctx, before.OrganizationID, before.Domain)
|
|
if err != nil || fresh == nil {
|
|
return nil, errx.InternalError()
|
|
}
|
|
if s.auditor != nil && fresh.CreatedBy != nil && (fresh.Verified != before.Verified || blocked(fresh) != blocked(before)) {
|
|
s.auditor.LogAction(ctx, fresh.OrganizationID, *fresh.CreatedBy, models.AuditActionUpdate, models.AuditEntityDomainRedirect, &fresh.ID, "", "",
|
|
map[string]string{"verified": strconv.FormatBool(fresh.Verified), "reaching": strconv.FormatBool(!blocked(fresh))}, map[string]string{"domain": fresh.Domain})
|
|
}
|
|
s.decorate(fresh, p, s.edgePending(ctx, fresh))
|
|
if fresh.LinkedInstanceID == nil {
|
|
if own, xerr := s.ownDomains().Set(ctx, fresh.OrganizationID); xerr == nil {
|
|
s.markTarget(fresh, own)
|
|
}
|
|
}
|
|
return fresh, nil
|
|
}
|
|
|
|
// blocked is a verified redirect visitors do not get; an unconfirmed visit is not one.
|
|
func blocked(r *models.DomainRedirect) bool {
|
|
return r.Verified && r.Reach != nil &&
|
|
(r.Reach.Status == models.RedirectReachNotReaching || r.Reach.Status == models.RedirectReachHTTPSError)
|
|
}
|
|
|
|
// decorate fills the records to add and the host that answers, from Cloud's mirror when Cloud serves it.
|
|
// pending is the edge's outstanding TXT per hostname, from edgePending.
|
|
func (s *Service) decorate(r *models.DomainRedirect, p *probe, pending map[string]cfsaas.TXTRecord) {
|
|
if r.ServedBy == models.RedirectServedByCloud {
|
|
r.Records, r.ServeHost = r.RemoteRecords, r.RemoteHost
|
|
if r.Records == nil {
|
|
r.Records = []models.DNSRecord{}
|
|
}
|
|
return
|
|
}
|
|
r.Records, r.ServeHost = s.records(r, p, pending), s.target()
|
|
}
|
|
|
|
// edgePending is the edge's outstanding TXT for each verified redirect's names, in one read.
|
|
func (s *Service) edgePending(ctx context.Context, rs ...*models.DomainRedirect) map[string]cfsaas.TXTRecord {
|
|
if !s.edge.Enabled() {
|
|
return nil
|
|
}
|
|
var hosts []string
|
|
for _, r := range rs {
|
|
if r != nil && r.Verified && r.ServedBy != models.RedirectServedByCloud {
|
|
hosts = append(hosts, r.Domain, "www."+r.Domain)
|
|
}
|
|
}
|
|
if len(hosts) == 0 {
|
|
return nil
|
|
}
|
|
return s.edge.Pending(ctx, hosts...)
|
|
}
|
|
|
|
// records are what the customer adds at their DNS provider.
|
|
func (s *Service) records(r *models.DomainRedirect, p *probe, pending map[string]cfsaas.TXTRecord) []models.DNSRecord {
|
|
target := s.target()
|
|
ok := func(v bool) bool { return p != nil && v }
|
|
out := []models.DNSRecord{
|
|
{Purpose: "ownership", Type: "TXT", Name: domainproof.Name(r.Domain), Value: s.proof.Value(r.OrganizationID, r.Domain), OK: ok(p != nil && p.txt) || r.Verified},
|
|
}
|
|
rootOK := ok(p != nil && p.apex) || r.Verified
|
|
// Behind an edge the tracking host's addresses are the provider's shared ones, which change, so the root follows the name.
|
|
var addrs []string
|
|
if !s.edge.Enabled() {
|
|
addrs = s.targetAddresses(target)
|
|
}
|
|
switch {
|
|
case s.edge.Enabled():
|
|
out = append(out, models.DNSRecord{Purpose: "root", Type: "CNAME", Name: r.Domain, Value: target, OK: rootOK})
|
|
case len(addrs) > 0:
|
|
for _, a := range addrs {
|
|
kind := "A"
|
|
if strings.Contains(a, ":") {
|
|
kind = "AAAA"
|
|
}
|
|
out = append(out, models.DNSRecord{Purpose: "root", Type: kind, Name: r.Domain, Value: a, OK: rootOK})
|
|
}
|
|
default:
|
|
out = append(out, models.DNSRecord{Purpose: "root", Type: "ALIAS", Name: r.Domain, Value: target, OK: rootOK})
|
|
}
|
|
if r.IncludeWWW {
|
|
out = append(out, models.DNSRecord{Purpose: "www", Type: "CNAME", Name: "www." + r.Domain, Value: r.Domain, OK: ok(p != nil && p.www), Optional: true})
|
|
}
|
|
names := []string{r.Domain}
|
|
if r.IncludeWWW {
|
|
names = append(names, "www."+r.Domain)
|
|
}
|
|
for _, n := range names {
|
|
if txt, waiting := pending[n]; waiting {
|
|
out = append(out, models.DNSRecord{Purpose: "edge", Type: "TXT", Name: txt.Name, Value: txt.Value})
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (s *Service) targetAddresses(target string) []string {
|
|
if target == "" {
|
|
return nil
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
ips, err := s.resolver.LookupIPAddr(ctx, target)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
out := make([]string, 0, len(ips))
|
|
for _, ip := range ips {
|
|
if ip.IP.IsLoopback() || ip.IP.IsPrivate() || ip.IP.IsUnspecified() {
|
|
continue
|
|
}
|
|
out = append(out, ip.IP.String())
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Lookup is the redirect target for a host the tracking service was asked for.
|
|
// A destination off the workspace's own domains answers as no redirect.
|
|
func (s *Service) Lookup(ctx context.Context, host string) (string, bool, error) {
|
|
got, ok, err := s.redirects.LookupServed(ctx, host)
|
|
if err != nil || !ok {
|
|
return "", false, err
|
|
}
|
|
// Cloud has no view of a linked instance's domains; the instance holds its redirects to the rule before and after Cloud takes them.
|
|
if got.LinkedInstanceID == nil {
|
|
allowed, xerr := s.ownDomains().Allows(ctx, got.OrganizationID, got.TargetURL)
|
|
if xerr != nil {
|
|
return "", false, errOwnDomainsUnavailable
|
|
}
|
|
if !allowed {
|
|
return "", false, nil
|
|
}
|
|
}
|
|
return got.TargetURL, true, nil
|
|
}
|
|
|
|
var errOwnDomainsUnavailable = errors.New("domain redirect lookup: own domains unavailable")
|
|
|
|
// StartSweep re-checks pending redirects often and verified ones a few times a
|
|
// day, so DNS added later verifies by itself and DNS removed stops the redirect.
|
|
func (s *Service) StartSweep(ctx context.Context) {
|
|
jobrun.Loop(ctx, "domain_redirect_sweep", 10*time.Minute, false, func(ctx context.Context) error {
|
|
due, err := s.redirects.Due(ctx, 100)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// A few at a time: each check can wait seconds on DNS and on a visit that times out.
|
|
sem := make(chan struct{}, sweepConcurrency)
|
|
var wg sync.WaitGroup
|
|
for i := range due {
|
|
sem <- struct{}{}
|
|
wg.Add(1)
|
|
go func(r *models.DomainRedirect) {
|
|
defer func() { <-sem; wg.Done() }()
|
|
if _, xerr := s.check(ctx, r, false); xerr != nil && xerr.Identifier != ErrIDTaken {
|
|
log.Warn().Str("domain", r.Domain).Str("error", xerr.Message).Msg("domain redirect sweep: check failed")
|
|
}
|
|
}(&due[i])
|
|
}
|
|
wg.Wait()
|
|
s.reconcileCloud(ctx)
|
|
s.ownDomains().Recheck(ctx)
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// VendorDomains is the inbox vendor side: domains a vendor account holds and what its API can do for them.
|
|
type VendorDomains interface {
|
|
DomainLinks(ctx context.Context, orgID uuid.UUID) (map[string]models.VendorDomainLink, *errx.Error)
|
|
SetForwarding(ctx context.Context, orgID uuid.UUID, domain, target string) (*models.VendorDomainLink, *errx.Error)
|
|
UpsertDNS(ctx context.Context, orgID uuid.UUID, domain, typ, name, value string) *errx.Error
|
|
}
|
|
|
|
// WireVendors attaches the inbox vendor accounts; optional.
|
|
func (s *Service) WireVendors(v VendorDomains) { s.vendors = v }
|
|
|
|
// VendorLinks maps every domain the workspace's vendor accounts hold; empty when none is connected.
|
|
func (s *Service) VendorLinks(ctx context.Context, orgID uuid.UUID) map[string]models.VendorDomainLink {
|
|
if s.vendors == nil {
|
|
return nil
|
|
}
|
|
links, xerr := s.vendors.DomainLinks(ctx, orgID)
|
|
if xerr != nil {
|
|
return nil
|
|
}
|
|
return links
|
|
}
|
|
|
|
// VendorLink is the vendor account holding the domain, or nil.
|
|
func (s *Service) VendorLink(ctx context.Context, orgID uuid.UUID, domain string) *models.VendorDomainLink {
|
|
if l, ok := s.VendorLinks(ctx, orgID)[normalizeDomain(domain)]; ok {
|
|
return &l
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// VendorForward points the domain's root at a website through the vendor that
|
|
// sold it, with no DNS for the customer to add. An empty target removes it where the vendor allows.
|
|
func (s *Service) VendorForward(ctx context.Context, orgID, userID uuid.UUID, domain, target string) (*models.VendorDomainLink, *errx.Error) {
|
|
domain = normalizeDomain(domain)
|
|
if xerr := s.ownDomain(ctx, orgID, domain); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if s.vendors == nil {
|
|
return nil, errx.ErrNotFound
|
|
}
|
|
if target != "" {
|
|
cleaned, xerr := cleanTarget(target, domain)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if xerr := s.ownTarget(ctx, orgID, cleaned); xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
target = cleaned
|
|
}
|
|
link, xerr := s.vendors.SetForwarding(ctx, orgID, domain, target)
|
|
if xerr != nil {
|
|
return nil, xerr
|
|
}
|
|
if s.auditor != nil {
|
|
s.auditor.LogAction(ctx, orgID, userID, models.AuditActionUpdate, models.AuditEntityDomainRedirect, nil, "", "",
|
|
map[string]string{"forwarding": target}, map[string]string{"domain": domain, "via": link.Vendor})
|
|
}
|
|
return link, nil
|
|
}
|
|
|
|
// VendorTracking writes the tracking CNAME through the vendor that holds the
|
|
// domain, then points every mailbox on the domain at it.
|
|
func (s *Service) VendorTracking(ctx context.Context, orgID uuid.UUID, domain, host string) (*models.TrackingDomainStatus, int, *errx.Error) {
|
|
domain = normalizeDomain(domain)
|
|
host = config.NormalizeTrackingHost(host)
|
|
if xerr := s.writeTrackingCNAME(ctx, orgID, domain, host); xerr != nil {
|
|
return nil, 0, xerr
|
|
}
|
|
return s.ApplyTracking(ctx, orgID, domain, host)
|
|
}
|
|
|
|
func (s *Service) writeTrackingCNAME(ctx context.Context, orgID uuid.UUID, domain, host string) *errx.Error {
|
|
if xerr := s.ownDomain(ctx, orgID, domain); xerr != nil {
|
|
return xerr
|
|
}
|
|
// Checked before any vendor write: the upsert replaces whatever record sits at the name.
|
|
if xerr := validate.ValidateTrackingDomain(host); xerr != nil {
|
|
return xerr
|
|
}
|
|
target := s.target()
|
|
if target == "" {
|
|
return errx.NewWithIdentifier(errx.BadRequest, ErrIDNoTracking, "Open and click tracking is not set up on this instance.")
|
|
}
|
|
if !strings.Contains(target, ".") {
|
|
return errx.NewWithIdentifier(errx.BadRequest, ErrIDNoTracking, "This instance's tracking host ("+target+") is not a public name, so no DNS record can point at it.")
|
|
}
|
|
if !strings.HasSuffix(host, "."+domain) {
|
|
return errx.NewWithIdentifier(errx.BadRequest, ErrIDTarget, "The tracking domain has to be a subdomain of "+domain+" to be written through its vendor.")
|
|
}
|
|
if s.vendors == nil {
|
|
return errx.ErrNotFound
|
|
}
|
|
if xerr := s.vendors.UpsertDNS(ctx, orgID, domain, "CNAME", host, target); xerr != nil {
|
|
return xerr
|
|
}
|
|
// Best effort: a vendor that cannot write TXT leaves the ownership record to the customer.
|
|
if name, value := s.customHosts.Record(orgID, host); name != "" && !s.customHosts.Holds(ctx, orgID, host) {
|
|
_ = s.vendors.UpsertDNS(ctx, orgID, domain, "TXT", name, value)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AutoRedirect sets a domain's root redirect the easiest way available: the
|
|
// vendor's own forwarding when a vendor account holds the domain, else a
|
|
// redirect served here once DNS is in place.
|
|
func (s *Service) AutoRedirect(ctx context.Context, orgID, userID uuid.UUID, domain, target string) *errx.Error {
|
|
domain = normalizeDomain(domain)
|
|
if l := s.VendorLink(ctx, orgID, domain); l != nil && l.CanForward {
|
|
_, xerr := s.VendorForward(ctx, orgID, userID, domain, target)
|
|
return xerr
|
|
}
|
|
_, xerr := s.SetRedirect(ctx, orgID, userID, domain, RedirectInput{TargetURL: target})
|
|
return xerr
|
|
}
|
|
|
|
// AutoTracking writes the tracking CNAME through the domain's vendor when it
|
|
// can; otherwise the customer adds it and the tracking sweep picks it up.
|
|
func (s *Service) AutoTracking(ctx context.Context, orgID uuid.UUID, domain, host string) {
|
|
domain = normalizeDomain(domain)
|
|
l := s.VendorLink(ctx, orgID, domain)
|
|
if l == nil || !l.CanDNS {
|
|
return
|
|
}
|
|
if xerr := s.writeTrackingCNAME(ctx, orgID, domain, config.NormalizeTrackingHost(host)); xerr != nil {
|
|
log.Info().Str("domain", domain).Str("code", xerr.ResponseCode()).Msg("sending domain: vendor could not write the tracking record")
|
|
}
|
|
}
|