package server import ( "context" "errors" "net/http" "strings" "time" "git.breakpilot.com/platform/tenant-registry/internal/authz" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/mail" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // Platform notifications (F3): branded emails to the people of a workspace // when BreakPilot publishes a document or a product finds something new. // Every mail goes through mail_outbox, one row per recipient, and is rendered // when sent. var ( mailBackoff = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute, 2 * time.Hour, 6 * time.Hour} mailMaxAttempts = 12 // Who is told about what: the members whose bundle grants the // capability (RBAC catalogue). notifyCapability = map[string]string{ mail.KindDocumentPublished: "registry:notify.documents", mail.KindFindingsNew: "registry:notify.findings", } ) func (s *Server) portalURL() string { u := strings.TrimRight(s.cfg().PortalURL, "/") if u == "" { u = "https://app.breakpilot.com" } return u } // mailSite is who the registry's mails come from (mail.Site): the cloud // company, or the customer's installation with their legal pages and contact. func (s *Server) mailSite() mail.Site { c := s.cfg() return mail.Site{OnPrem: c.OnPrem(), Imprint: c.LegalImprintURL, Privacy: c.LegalPrivacyURL, Contact: c.MailContact} } // notifyTenant queues kind for every enabled member of t whose bundle grants // the kind's capability. Demo tenants get nothing. Returns how many rows were // queued (0 for a repeat of the same key). func (s *Server) notifyTenant(ctx context.Context, t *store.Tenant, kind, key string, data map[string]interface{}) (int, error) { if t.Kind == "demo" || t.Status == store.StatusDemo { return 0, nil } if s.Keycloak == nil { return 0, errors.New("no identity provider to resolve recipients") } members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug) if err != nil { if errors.Is(err, keycloak.ErrOrgNotFound) { return 0, nil } return 0, err } capability, known := notifyCapability[kind] if !known { return 0, errors.New("no recipients defined for " + kind) } if data == nil { data = map[string]interface{}{} } data["tenant_name"] = t.Name queued := 0 for _, m := range members { if !m.Enabled || m.Email == "" || !authz.AnyGrants(m.OrgRoles, capability) { continue } ok, err := s.Store.EnqueueMail(ctx, store.MailItem{ TenantID: t.ID, Kind: kind, Recipient: strings.ToLower(m.Email), Locale: "de", Data: data, IdempotencyKey: key + ":" + strings.ToLower(m.Email), }) if err != nil { return queued, err } if ok { queued++ } } return queued, nil } // documentPublished tells the workspace about a newly published document. func (s *Server) documentPublished(ctx context.Context, d *store.Document) { t, err := s.Store.GetTenant(ctx, d.TenantID) if err != nil { s.Log.Warn("document notification: tenant lookup failed", "document_id", d.ID, "err", err) return } n, err := s.notifyTenant(ctx, t, mail.KindDocumentPublished, "document.published:"+d.ID, map[string]interface{}{ "title": d.Title, "description": d.Description, "filename": d.Filename, "url": s.portalURL() + "/" + t.Slug + "/documents", }) if err != nil { s.Log.Warn("document notification not queued", "document_id", d.ID, "err", err) return } s.Log.Info("document notification queued", "document_id", d.ID, "recipients", n) } type notificationReq struct { TenantID string `json:"tenant_id"` Kind string `json:"kind"` IdempotencyKey string `json:"idempotency_key"` Data map[string]interface{} `json:"data"` } // postNotification is POST /v1/notifications (route group "notify"): a // product asks the platform to tell a workspace something. Only // findings.new is accepted from products; data carries target_name, // new_count, critical/high/medium/low and an optional url into the product. func (s *Server) postNotification(w http.ResponseWriter, r *http.Request) { var in notificationReq if !decodeJSON(w, r, &in) { return } if in.Kind != mail.KindFindingsNew { writeError(w, http.StatusBadRequest, "invalid_kind", "kind must be findings.new") return } if in.IdempotencyKey == "" || len(in.IdempotencyKey) > 200 { writeError(w, http.StatusBadRequest, "invalid_idempotency_key", "idempotency_key is required (≤ 200 chars)") return } data := map[string]interface{}{} str := func(k string, max int) string { v, _ := in.Data[k].(string) v = strings.TrimSpace(v) if len(v) > max { v = v[:max] } return v } num := func(k string) int { f, _ := in.Data[k].(float64) if f < 0 || f > 1e6 { return 0 } return int(f) } data["target_name"] = str("target_name", 200) data["new_count"] = num("new_count") for _, k := range []string{"critical", "high", "medium", "low"} { data[k] = num(k) } if data["target_name"] == "" || data["new_count"] == 0 { writeError(w, http.StatusBadRequest, "invalid_data", "data.target_name and a positive data.new_count are required") return } url := str("url", 500) if !strings.HasPrefix(url, "https://") { url = "" } ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) defer cancel() t, err := s.Store.GetTenant(ctx, in.TenantID) if err != nil { if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } if url == "" { url = s.portalURL() + "/" + t.Slug + "/dashboard" } data["url"] = url n, err := s.notifyTenant(ctx, t, in.Kind, "product:"+in.IdempotencyKey, data) if err != nil { s.writeKeycloakError(w, t.ID, "resolve notification recipients", err) return } writeJSON(w, http.StatusAccepted, map[string]int{"queued": n}) } // RunMail sends queued mail until ctx is done. Without a mail sender rows // accumulate and are sent once one is configured. func (s *Server) RunMail(ctx context.Context, every time.Duration) { if s.Mail == nil { s.Log.Warn("SMTP_HOST not set — mail worker idle (notifications accumulate)") return } if every <= 0 { every = 20 * time.Second } t := time.NewTicker(every) defer t.Stop() for { if n, err := s.DrainMail(ctx); err != nil { s.Log.Error("mail drain failed", "err", err) } else if n > 0 { s.Log.Info("mail drained", "processed", n) } select { case <-ctx.Done(): return case <-t.C: } } } // DrainMail sends one batch; returns the number of rows attempted. func (s *Server) DrainMail(ctx context.Context) (int, error) { items, err := s.Store.ClaimMail(ctx, 20, s.now(), 5*time.Minute) if err != nil { return 0, err } for _, it := range items { err := s.sendMail(ctx, it) if err == nil { if cerr := s.Store.CompleteMail(ctx, it.ID, s.now()); cerr != nil { return len(items), cerr } continue } next := s.now().Add(mailBackoff[min(it.Attempts, len(mailBackoff)-1)]) if it.Attempts+1 >= mailMaxAttempts { next = s.now().AddDate(100, 0, 0) // parked with its error; a person looks at it s.Log.Error("mail given up", "id", it.ID, "kind", it.Kind, "recipient", it.Recipient, "err", err) } else { s.Log.Warn("mail failed", "id", it.ID, "kind", it.Kind, "attempt", it.Attempts+1, "err", err) } if ferr := s.Store.FailMail(ctx, it.ID, err.Error(), next); ferr != nil { return len(items), ferr } } return len(items), nil } func (s *Server) sendMail(ctx context.Context, it store.MailItem) error { tenant, _ := it.Data["tenant_name"].(string) url, _ := it.Data["url"].(string) msg, err := mail.Render(it.Kind, it.Locale, mail.View{Tenant: tenant, URL: url, D: it.Data, Site: s.mailSite()}) if err != nil { return err } msg.To = it.Recipient return s.Mail.Send(ctx, msg) }