feat(notify): branded notification mail through an outbox #35
No files matched your search
@@ -47,6 +47,11 @@ Env vars (override at the shell):
|
||||
| `KEYCLOAK_CLIENT_SECRET` | empty | Service-account client secret |
|
||||
| `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route |
|
||||
| `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` |
|
||||
| `DOCUMENTS_S3_ENDPOINT` / `_REGION` / `_BUCKET` / `_ACCESS_KEY` / `_SECRET_KEY` | empty (document routes 503) | Object storage for tenant documents; the bucket is created in the region when missing |
|
||||
| `DOCUMENTS_MAX_MB` | `200` | Upload limit per document |
|
||||
| `SMTP_HOST` / `SMTP_PORT` / `SMTP_USER` / `SMTP_PASSWORD` | empty (mail queues up unsent) | Relay for platform mail (STARTTLS on 587, TLS on 465) |
|
||||
| `MAIL_FROM` / `MAIL_FROM_NAME` | `noreply@breakpilot.com` / `BreakPilot` | Sender of platform mail |
|
||||
| `PORTAL_URL` | `https://app.breakpilot.com` | Portal origin for links in mail |
|
||||
| `INVITE_CLIENT_ID` / `INVITE_REDIRECT_URI` | `dev-portal` / `https://breakpilot.com/onboard` | Keycloak invite mail client + landing URL (stage: `portal-stage`, `https://app-stage.breakpilot.com/start?invited=1`) |
|
||||
| `ERP_BASE_URL` / `ERP_API_KEY` / `ERP_API_SECRET` | empty (outbox idle) | ERPNext / erpmock base URL + `token key:secret` credentials |
|
||||
| `ERP_LEAD_DOCTYPE` | `Lead` | `CRM Lead` when the Frappe CRM app is used |
|
||||
|
||||
+7
-1
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -152,7 +153,11 @@ func main() {
|
||||
} else {
|
||||
logger.Warn("DOCUMENTS_S3_* not set; document routes answer 503")
|
||||
}
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Objects: objects}
|
||||
var mailer mail.Sender
|
||||
if mc := (mail.Config{Host: cfg.SMTPHost, Port: cfg.SMTPPort, User: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom, FromName: cfg.MailFromName}); mc.Configured() {
|
||||
mailer = &mail.SMTP{Cfg: mc}
|
||||
}
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Objects: objects, Mail: mailer}
|
||||
handler := server.NewRouter(app)
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
@@ -167,6 +172,7 @@ func main() {
|
||||
|
||||
go app.RunOutbox(ctx, cfg.ErpOutboxInterval)
|
||||
go app.RunReconcile(ctx, cfg.ErpReconcileEvery)
|
||||
go app.RunMail(ctx, 20*time.Second)
|
||||
|
||||
go func() {
|
||||
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", storeKind(s))
|
||||
|
||||
@@ -76,6 +76,16 @@ type Config struct {
|
||||
// DocumentsMaxBytes caps one upload (default 200 MiB).
|
||||
DocumentsMaxBytes int64
|
||||
|
||||
// Platform mail (F3). SMTPHost empty ⇒ notifications queue up unsent.
|
||||
SMTPHost string
|
||||
SMTPPort int
|
||||
SMTPUser string
|
||||
SMTPPassword string
|
||||
MailFrom string
|
||||
MailFromName string
|
||||
// PortalURL is the portal's public origin, for links in mail.
|
||||
PortalURL string
|
||||
|
||||
LiteLLMBaseURL string
|
||||
LiteLLMMasterKey string
|
||||
LiteLLMModels []string
|
||||
@@ -134,6 +144,14 @@ func Load() (*Config, error) {
|
||||
DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"),
|
||||
DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20,
|
||||
|
||||
SMTPHost: os.Getenv("SMTP_HOST"),
|
||||
SMTPPort: getint("SMTP_PORT", 587),
|
||||
SMTPUser: os.Getenv("SMTP_USER"),
|
||||
SMTPPassword: os.Getenv("SMTP_PASSWORD"),
|
||||
MailFrom: getenv("MAIL_FROM", "noreply@breakpilot.com"),
|
||||
MailFromName: getenv("MAIL_FROM_NAME", "BreakPilot"),
|
||||
PortalURL: getenv("PORTAL_URL", "https://app.breakpilot.com"),
|
||||
|
||||
LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"),
|
||||
LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"),
|
||||
LiteLLMModels: getlist("LITELLM_MODELS", []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b", "Qwen3.8-27B"}),
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// Package mail sends the platform's own emails (document published, new
|
||||
// findings) through an SMTP relay (Strato in production), rendered from
|
||||
// embedded German and English templates with the BreakPilot layout.
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"mime/quotedprintable"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Message is one email to one recipient.
|
||||
type Message struct {
|
||||
To string
|
||||
Subject string
|
||||
Text string
|
||||
HTML string
|
||||
}
|
||||
|
||||
// Sender delivers a Message.
|
||||
type Sender interface {
|
||||
Send(ctx context.Context, m Message) error
|
||||
}
|
||||
|
||||
// Config of the SMTP relay.
|
||||
type Config struct {
|
||||
Host string // smtp.strato.de
|
||||
Port int // 587 (STARTTLS) or 465 (implicit TLS)
|
||||
User string
|
||||
Password string
|
||||
From string // noreply@breakpilot.com
|
||||
FromName string // BreakPilot
|
||||
}
|
||||
|
||||
// Configured reports whether mail can be sent.
|
||||
func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
|
||||
|
||||
// SMTP sends through a relay with STARTTLS (or implicit TLS on 465).
|
||||
type SMTP struct {
|
||||
Cfg Config
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (s *SMTP) Send(ctx context.Context, m Message) error {
|
||||
timeout := s.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
addr := net.JoinHostPort(s.Cfg.Host, fmt.Sprint(s.Cfg.Port))
|
||||
d := net.Dialer{Timeout: timeout}
|
||||
var conn net.Conn
|
||||
var err error
|
||||
tlsCfg := &tls.Config{ServerName: s.Cfg.Host, MinVersion: tls.VersionTLS12}
|
||||
if s.Cfg.Port == 465 {
|
||||
conn, err = tls.DialWithDialer(&d, "tcp", addr, tlsCfg)
|
||||
} else {
|
||||
conn, err = d.DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("mail: dial %s: %w", addr, err)
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(timeout))
|
||||
c, err := smtp.NewClient(conn, s.Cfg.Host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return fmt.Errorf("mail: hello: %w", err)
|
||||
}
|
||||
defer func() { _ = c.Close() }()
|
||||
if s.Cfg.Port != 465 {
|
||||
if ok, _ := c.Extension("STARTTLS"); !ok {
|
||||
return errors.New("mail: relay does not offer STARTTLS")
|
||||
}
|
||||
if err := c.StartTLS(tlsCfg); err != nil {
|
||||
return fmt.Errorf("mail: starttls: %w", err)
|
||||
}
|
||||
}
|
||||
if s.Cfg.User != "" {
|
||||
if err := c.Auth(smtp.PlainAuth("", s.Cfg.User, s.Cfg.Password, s.Cfg.Host)); err != nil {
|
||||
return fmt.Errorf("mail: auth: %w", err)
|
||||
}
|
||||
}
|
||||
if err := c.Mail(s.Cfg.From); err != nil {
|
||||
return fmt.Errorf("mail: from: %w", err)
|
||||
}
|
||||
if err := c.Rcpt(m.To); err != nil {
|
||||
return fmt.Errorf("mail: rcpt: %w", err)
|
||||
}
|
||||
w, err := c.Data()
|
||||
if err != nil {
|
||||
return fmt.Errorf("mail: data: %w", err)
|
||||
}
|
||||
if _, err := w.Write(Build(m, s.Cfg, time.Now())); err != nil {
|
||||
return fmt.Errorf("mail: write: %w", err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return fmt.Errorf("mail: send: %w", err)
|
||||
}
|
||||
return c.Quit()
|
||||
}
|
||||
|
||||
// Build renders the RFC 5322 message: multipart/alternative with a text and
|
||||
// an HTML part, both UTF-8 quoted-printable.
|
||||
func Build(m Message, cfg Config, now time.Time) []byte {
|
||||
boundary := "bp-" + randomHex(12)
|
||||
domain := "breakpilot.com"
|
||||
if i := strings.LastIndex(cfg.From, "@"); i >= 0 {
|
||||
domain = cfg.From[i+1:]
|
||||
}
|
||||
from := cfg.From
|
||||
if cfg.FromName != "" {
|
||||
from = mime.QEncoding.Encode("utf-8", cfg.FromName) + " <" + cfg.From + ">"
|
||||
}
|
||||
var b bytes.Buffer
|
||||
h := func(k, v string) { fmt.Fprintf(&b, "%s: %s\r\n", k, v) }
|
||||
h("From", from)
|
||||
h("To", m.To)
|
||||
h("Subject", mime.QEncoding.Encode("utf-8", m.Subject))
|
||||
h("Date", now.UTC().Format(time.RFC1123Z))
|
||||
h("Message-ID", "<"+randomHex(16)+"@"+domain+">")
|
||||
h("MIME-Version", "1.0")
|
||||
h("Auto-Submitted", "auto-generated")
|
||||
h("Content-Type", `multipart/alternative; boundary="`+boundary+`"`)
|
||||
b.WriteString("\r\n")
|
||||
part := func(ctype, body string) {
|
||||
fmt.Fprintf(&b, "--%s\r\nContent-Type: %s; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n", boundary, ctype)
|
||||
qp := quotedprintable.NewWriter(&b)
|
||||
_, _ = qp.Write([]byte(strings.ReplaceAll(body, "\n", "\r\n")))
|
||||
_ = qp.Close()
|
||||
b.WriteString("\r\n")
|
||||
}
|
||||
part("text/plain", m.Text)
|
||||
if m.HTML != "" {
|
||||
part("text/html", m.HTML)
|
||||
}
|
||||
fmt.Fprintf(&b, "--%s--\r\n", boundary)
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func randomHex(n int) string {
|
||||
buf := make([]byte, n)
|
||||
_, _ = rand.Read(buf)
|
||||
return hex.EncodeToString(buf)
|
||||
}
|
||||
|
||||
// Recorder is a Sender for tests and for environments without a relay.
|
||||
type Recorder struct {
|
||||
mu sync.Mutex
|
||||
Sent []Message
|
||||
Fail error
|
||||
}
|
||||
|
||||
func (r *Recorder) Send(_ context.Context, m Message) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.Fail != nil {
|
||||
return r.Fail
|
||||
}
|
||||
r.Sent = append(r.Sent, m)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Messages returns a copy of what was sent.
|
||||
func (r *Recorder) Messages() []Message {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]Message(nil), r.Sent...)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRender_documentPublished(t *testing.T) {
|
||||
m, err := Render(KindDocumentPublished, "de", View{Tenant: "Acme <GmbH>", URL: "https://app/acme/documents",
|
||||
D: map[string]any{"title": "CRA-Dossier", "description": "Q3 & <b>"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Subject != "Neues Dokument für Acme <GmbH>: CRA-Dossier" {
|
||||
t.Fatalf("subject %q", m.Subject)
|
||||
}
|
||||
if !strings.Contains(m.HTML, "Acme <GmbH>") || strings.Contains(m.HTML, "<b>") {
|
||||
t.Fatal("html not escaped")
|
||||
}
|
||||
if !strings.Contains(m.HTML, `href="https://app/acme/documents"`) || !strings.Contains(m.HTML, `lang="de"`) {
|
||||
t.Fatalf("html: %s", m.HTML)
|
||||
}
|
||||
if !strings.Contains(m.Text, "https://app/acme/documents") || !strings.Contains(m.Text, "Q3 & <b>") {
|
||||
t.Fatalf("text: %s", m.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRender_findingsEnglishAndDefaults(t *testing.T) {
|
||||
m, err := Render(KindFindingsNew, "en", View{Tenant: "Acme", URL: "https://x", D: map[string]any{"target_name": "Pump", "new_count": 3, "critical": 1}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Subject != "3 new findings in Pump" || !strings.Contains(m.Text, "Critical 1") || !strings.Contains(m.Text, "High 0") {
|
||||
t.Fatalf("%q\n%s", m.Subject, m.Text)
|
||||
}
|
||||
if de, _ := Render(KindFindingsNew, "fr", View{D: map[string]any{"new_count": 1}}); !strings.Contains(de.Subject, "neue Befunde") {
|
||||
t.Fatalf("fallback locale: %q", de.Subject)
|
||||
}
|
||||
if _, err := Render("nope", "de", View{}); err == nil {
|
||||
t.Fatal("unknown kind rendered")
|
||||
}
|
||||
if m, _ := Render(KindDocumentPublished, "en", View{}); m.Subject == "" {
|
||||
t.Fatal("nil data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuild_isAValidMultipartMessage(t *testing.T) {
|
||||
raw := Build(Message{To: "it@acme.de", Subject: "Prüfwerk: 3 neue Befunde", Text: "Hallo\nWelt ä", HTML: "<p>ä</p>"},
|
||||
Config{From: "noreply@breakpilot.com", FromName: "BreakPilot"}, time.Unix(0, 0))
|
||||
msg, err := mail.ReadMessage(strings.NewReader(string(raw)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := new(mime.WordDecoder)
|
||||
subj, _ := dec.DecodeHeader(msg.Header.Get("Subject"))
|
||||
if subj != "Prüfwerk: 3 neue Befunde" || msg.Header.Get("To") != "it@acme.de" || !strings.Contains(msg.Header.Get("From"), "<noreply@breakpilot.com>") {
|
||||
t.Fatalf("headers: %v %q", msg.Header, subj)
|
||||
}
|
||||
if !strings.HasSuffix(strings.Trim(msg.Header.Get("Message-ID"), "<>"), "@breakpilot.com") {
|
||||
t.Fatalf("message id %q", msg.Header.Get("Message-ID"))
|
||||
}
|
||||
_, params, _ := mime.ParseMediaType(msg.Header.Get("Content-Type"))
|
||||
mr := multipart.NewReader(msg.Body, params["boundary"])
|
||||
var types []string
|
||||
for {
|
||||
p, err := mr.NextPart()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
types = append(types, p.Header.Get("Content-Type"))
|
||||
b, _ := io.ReadAll(p) // multipart decodes quoted-printable
|
||||
if !strings.Contains(string(b), "ä") {
|
||||
t.Fatalf("part not decoded: %q", b)
|
||||
}
|
||||
}
|
||||
if len(types) != 2 || !strings.HasPrefix(types[0], "text/plain") || !strings.HasPrefix(types[1], "text/html") {
|
||||
t.Fatalf("parts: %v", types)
|
||||
}
|
||||
// without a display name or an HTML part
|
||||
raw = Build(Message{To: "a@b", Subject: "s", Text: "t"}, Config{From: "x"}, time.Now())
|
||||
if !strings.Contains(string(raw), "From: x\r\n") || strings.Contains(string(raw), "text/html") || !strings.Contains(string(raw), "@breakpilot.com>") {
|
||||
t.Fatalf("minimal: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecorderAndConfig(t *testing.T) {
|
||||
r := &Recorder{}
|
||||
_ = r.Send(context.Background(), Message{To: "a"})
|
||||
if len(r.Messages()) != 1 {
|
||||
t.Fatal("not recorded")
|
||||
}
|
||||
r.Fail = errors.New("x")
|
||||
if r.Send(context.Background(), Message{}) == nil {
|
||||
t.Fatal("fail ignored")
|
||||
}
|
||||
if (Config{}).Configured() || !(Config{Host: "h", From: "f"}).Configured() {
|
||||
t.Fatal("Configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTP_dialFailure(t *testing.T) {
|
||||
s := &SMTP{Cfg: Config{Host: "127.0.0.1", Port: 1, From: "x"}, Timeout: time.Second}
|
||||
if err := s.Send(context.Background(), Message{To: "a@b"}); err == nil || !strings.Contains(err.Error(), "dial") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"fmt"
|
||||
htmltpl "html/template"
|
||||
"strings"
|
||||
texttpl "text/template"
|
||||
)
|
||||
|
||||
//go:embed templates/*
|
||||
var templates embed.FS
|
||||
|
||||
// Kinds the registry can send.
|
||||
const (
|
||||
KindDocumentPublished = "document.published"
|
||||
KindFindingsNew = "findings.new"
|
||||
)
|
||||
|
||||
// Kinds lists every kind with templates, for validating requests.
|
||||
var Kinds = map[string]bool{KindDocumentPublished: true, KindFindingsNew: true}
|
||||
|
||||
// View is what a template sees.
|
||||
type View struct {
|
||||
Lang string
|
||||
Tenant string
|
||||
URL string
|
||||
Subject string
|
||||
D map[string]any
|
||||
}
|
||||
|
||||
// Render builds the subject, text and HTML body of kind in locale ("de"
|
||||
// unless "en"). HTML values are escaped by html/template; the text body and
|
||||
// subject are plain.
|
||||
func Render(kind, locale string, v View) (Message, error) {
|
||||
if !Kinds[kind] {
|
||||
return Message{}, fmt.Errorf("mail: unknown kind %q", kind)
|
||||
}
|
||||
if locale != "en" {
|
||||
locale = "de"
|
||||
}
|
||||
v.Lang = locale
|
||||
if v.D == nil {
|
||||
v.D = map[string]any{}
|
||||
}
|
||||
file := "templates/" + locale + "_" + kind + ".tmpl"
|
||||
tt, err := texttpl.ParseFS(templates, file)
|
||||
if err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
var subj, text bytes.Buffer
|
||||
if err := tt.ExecuteTemplate(&subj, "subject", v); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
if err := tt.ExecuteTemplate(&text, "text", v); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
v.Subject = strings.Join(strings.Fields(subj.String()), " ")
|
||||
ht, err := htmltpl.ParseFS(templates, "templates/layout.html", file)
|
||||
if err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
var html bytes.Buffer
|
||||
if err := ht.ExecuteTemplate(&html, "layout", v); err != nil {
|
||||
return Message{}, err
|
||||
}
|
||||
return Message{Subject: v.Subject, Text: strings.TrimSpace(text.String()) + "\n", HTML: html.String()}, nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{{define "subject"}}Neues Dokument für {{.Tenant}}: {{.D.title}}{{end}}
|
||||
{{define "button"}}Dokument öffnen{{end}}
|
||||
{{define "footer"}}Sie erhalten diese E-Mail, weil Sie im Arbeitsbereich {{.Tenant}} Unterlagen einsehen dürfen.{{end}}
|
||||
{{define "html"}}<p style="margin:0 0 12px 0;font-size:18px;font-weight:bold;">Ein neues Dokument liegt für Sie bereit</p>
|
||||
<p style="margin:0 0 12px 0;">BreakPilot hat im Arbeitsbereich <strong>{{.Tenant}}</strong> ein Dokument veröffentlicht:</p>
|
||||
<p style="margin:0 0 4px 0;font-weight:bold;">{{.D.title}}</p>
|
||||
{{if .D.description}}<p style="margin:0 0 12px 0;color:#57526b;">{{.D.description}}</p>{{end}}
|
||||
<p style="margin:0 0 12px 0;">Sie finden es im Portal unter <em>Dokumente</em>. Jeder Download wird im Audit-Log festgehalten.</p>{{end}}
|
||||
{{define "text"}}Ein neues Dokument liegt für Sie bereit
|
||||
|
||||
BreakPilot hat im Arbeitsbereich {{.Tenant}} ein Dokument veröffentlicht:
|
||||
|
||||
{{.D.title}}
|
||||
{{if .D.description}} {{.D.description}}
|
||||
{{end}}
|
||||
Sie finden es im Portal unter "Dokumente":
|
||||
{{.URL}}
|
||||
|
||||
--
|
||||
Sie erhalten diese E-Mail, weil Sie im Arbeitsbereich {{.Tenant}} Unterlagen einsehen dürfen.
|
||||
BreakPilot GmbH · https://breakpilot.com/impressum{{end}}
|
||||
@@ -0,0 +1,27 @@
|
||||
{{define "subject"}}{{.D.new_count}} neue Befunde in {{.D.target_name}}{{end}}
|
||||
{{define "button"}}Befunde ansehen{{end}}
|
||||
{{define "footer"}}Sie erhalten diese E-Mail, weil Sie den Arbeitsbereich {{.Tenant}} verwalten.{{end}}
|
||||
{{define "html"}}<p style="margin:0 0 12px 0;font-size:18px;font-weight:bold;">Prüfwerk hat neue Befunde gefunden</p>
|
||||
<p style="margin:0 0 12px 0;">Die letzte Prüfung von <strong>{{.D.target_name}}</strong> im Arbeitsbereich {{.Tenant}} hat <strong>{{.D.new_count}}</strong> Befunde ergeben, die es vorher nicht gab.</p>
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 0 14px 0;font-size:13px;">
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#b42318;font-weight:bold;">Kritisch</td><td style="padding:3px 0;">{{or .D.critical 0}}</td></tr>
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#c4320a;font-weight:bold;">Hoch</td><td style="padding:3px 0;">{{or .D.high 0}}</td></tr>
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#b54708;">Mittel</td><td style="padding:3px 0;">{{or .D.medium 0}}</td></tr>
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#57526b;">Niedrig / Info</td><td style="padding:3px 0;">{{or .D.low 0}}</td></tr>
|
||||
</table>
|
||||
<p style="margin:0 0 12px 0;">Jeder Befund hat eine KI-Bewertung, einen Beleg im Code und einen Behebungsvorschlag.</p>{{end}}
|
||||
{{define "text"}}Prüfwerk hat neue Befunde gefunden
|
||||
|
||||
Die letzte Prüfung von {{.D.target_name}} im Arbeitsbereich {{.Tenant}} hat {{.D.new_count}} Befunde ergeben, die es vorher nicht gab:
|
||||
|
||||
Kritisch {{or .D.critical 0}}
|
||||
Hoch {{or .D.high 0}}
|
||||
Mittel {{or .D.medium 0}}
|
||||
Niedrig / Info {{or .D.low 0}}
|
||||
|
||||
Befunde ansehen:
|
||||
{{.URL}}
|
||||
|
||||
--
|
||||
Sie erhalten diese E-Mail, weil Sie den Arbeitsbereich {{.Tenant}} verwalten.
|
||||
BreakPilot GmbH · https://breakpilot.com/impressum{{end}}
|
||||
@@ -0,0 +1,21 @@
|
||||
{{define "subject"}}New document for {{.Tenant}}: {{.D.title}}{{end}}
|
||||
{{define "button"}}Open the document{{end}}
|
||||
{{define "footer"}}You receive this email because you may view documents in the {{.Tenant}} workspace.{{end}}
|
||||
{{define "html"}}<p style="margin:0 0 12px 0;font-size:18px;font-weight:bold;">A new document is ready for you</p>
|
||||
<p style="margin:0 0 12px 0;">BreakPilot published a document in the <strong>{{.Tenant}}</strong> workspace:</p>
|
||||
<p style="margin:0 0 4px 0;font-weight:bold;">{{.D.title}}</p>
|
||||
{{if .D.description}}<p style="margin:0 0 12px 0;color:#57526b;">{{.D.description}}</p>{{end}}
|
||||
<p style="margin:0 0 12px 0;">You find it in the portal under <em>Documents</em>. Every download is recorded in the audit log.</p>{{end}}
|
||||
{{define "text"}}A new document is ready for you
|
||||
|
||||
BreakPilot published a document in the {{.Tenant}} workspace:
|
||||
|
||||
{{.D.title}}
|
||||
{{if .D.description}} {{.D.description}}
|
||||
{{end}}
|
||||
You find it in the portal under "Documents":
|
||||
{{.URL}}
|
||||
|
||||
--
|
||||
You receive this email because you may view documents in the {{.Tenant}} workspace.
|
||||
BreakPilot GmbH · https://breakpilot.com/impressum{{end}}
|
||||
@@ -0,0 +1,27 @@
|
||||
{{define "subject"}}{{.D.new_count}} new findings in {{.D.target_name}}{{end}}
|
||||
{{define "button"}}View the findings{{end}}
|
||||
{{define "footer"}}You receive this email because you administer the {{.Tenant}} workspace.{{end}}
|
||||
{{define "html"}}<p style="margin:0 0 12px 0;font-size:18px;font-weight:bold;">Prüfwerk found new findings</p>
|
||||
<p style="margin:0 0 12px 0;">The latest scan of <strong>{{.D.target_name}}</strong> in the {{.Tenant}} workspace produced <strong>{{.D.new_count}}</strong> findings that were not there before.</p>
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 0 14px 0;font-size:13px;">
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#b42318;font-weight:bold;">Critical</td><td style="padding:3px 0;">{{or .D.critical 0}}</td></tr>
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#c4320a;font-weight:bold;">High</td><td style="padding:3px 0;">{{or .D.high 0}}</td></tr>
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#b54708;">Medium</td><td style="padding:3px 0;">{{or .D.medium 0}}</td></tr>
|
||||
<tr><td style="padding:3px 14px 3px 0;color:#57526b;">Low / info</td><td style="padding:3px 0;">{{or .D.low 0}}</td></tr>
|
||||
</table>
|
||||
<p style="margin:0 0 12px 0;">Every finding comes with an AI assessment, the code evidence and a suggested fix.</p>{{end}}
|
||||
{{define "text"}}Prüfwerk found new findings
|
||||
|
||||
The latest scan of {{.D.target_name}} in the {{.Tenant}} workspace produced {{.D.new_count}} findings that were not there before:
|
||||
|
||||
Critical {{or .D.critical 0}}
|
||||
High {{or .D.high 0}}
|
||||
Medium {{or .D.medium 0}}
|
||||
Low / info {{or .D.low 0}}
|
||||
|
||||
View the findings:
|
||||
{{.URL}}
|
||||
|
||||
--
|
||||
You receive this email because you administer the {{.Tenant}} workspace.
|
||||
BreakPilot GmbH · https://breakpilot.com/impressum{{end}}
|
||||
@@ -0,0 +1,28 @@
|
||||
{{define "layout"}}<!doctype html>
|
||||
<html lang="{{.Lang}}">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{{.Subject}}</title></head>
|
||||
<body style="margin:0;padding:0;background:#f4f3f8;font-family:Arial,Helvetica,sans-serif;color:#1d1a2e;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f3f8;padding:24px 12px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#ffffff;border-radius:8px;border:1px solid #e4e1ef;">
|
||||
<tr><td style="padding:20px 28px;border-bottom:1px solid #eeecf5;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0"><tr>
|
||||
<td style="width:28px;height:28px;background:#6d3fe0;border-radius:6px;color:#ffffff;font-weight:bold;font-size:16px;text-align:center;vertical-align:middle;">B</td>
|
||||
<td style="padding-left:10px;font-size:15px;font-weight:bold;letter-spacing:-0.2px;">BreakPilot</td>
|
||||
</tr></table>
|
||||
</td></tr>
|
||||
<tr><td style="padding:28px 28px 8px 28px;font-size:14px;line-height:1.6;">
|
||||
{{template "html" .}}
|
||||
</td></tr>
|
||||
<tr><td style="padding:8px 28px 28px 28px;">
|
||||
<a href="{{.URL}}" style="display:inline-block;background:#6d3fe0;color:#ffffff;text-decoration:none;font-weight:bold;font-size:14px;padding:10px 18px;border-radius:6px;">{{template "button" .}}</a>
|
||||
</td></tr>
|
||||
<tr><td style="padding:18px 28px;border-top:1px solid #eeecf5;font-size:11.5px;line-height:1.6;color:#7a7590;">
|
||||
{{template "footer" .}}<br>
|
||||
BreakPilot GmbH · <a href="https://breakpilot.com/impressum" style="color:#7a7590;">{{if eq .Lang "de"}}Impressum{{else}}Imprint{{end}}</a> · <a href="https://breakpilot.com/datenschutz" style="color:#7a7590;">{{if eq .Lang "de"}}Datenschutz{{else}}Privacy{{end}}</a>
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>{{end}}
|
||||
@@ -69,6 +69,8 @@ func routeGroup(method, path string) string {
|
||||
switch {
|
||||
case strings.HasPrefix(path, "/v1/admin/"):
|
||||
return "admin"
|
||||
case strings.HasPrefix(path, "/v1/notifications"):
|
||||
return "notify"
|
||||
case strings.HasPrefix(path, "/v1/internal/entitlements/"):
|
||||
return "entitlements"
|
||||
case strings.HasPrefix(path, "/v1/internal/api-keys/verify"):
|
||||
|
||||
@@ -276,9 +276,6 @@ func (s *Server) adminPublishDocument(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
}
|
||||
|
||||
// documentPublished is where F3 hangs the tenant notification.
|
||||
func (s *Server) documentPublished(_ context.Context, _ *store.Document) {}
|
||||
|
||||
// adminDeleteDocument is DELETE /v1/admin/documents/{doc}.
|
||||
func (s *Server) adminDeleteDocument(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.documentsReady(w) {
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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: document readers about documents, the people
|
||||
// who run the workspace about findings.
|
||||
notifyRoles = map[string][]string{
|
||||
mail.KindDocumentPublished: {"IT_ADMIN", "OWNER", "CXO", "FINANCE", "LEGAL"},
|
||||
mail.KindFindingsNew: {"IT_ADMIN", "OWNER", "CXO", "LEGAL"},
|
||||
}
|
||||
)
|
||||
|
||||
func (s *Server) portalURL() string {
|
||||
u := strings.TrimRight(s.cfg().PortalURL, "/")
|
||||
if u == "" {
|
||||
u = "https://app.breakpilot.com"
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// notifyTenant queues kind for every enabled member of t whose org role is
|
||||
// allowed to receive it. 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
|
||||
}
|
||||
allowed := map[string]bool{}
|
||||
for _, r := range notifyRoles[kind] {
|
||||
allowed[r] = true
|
||||
}
|
||||
if data == nil {
|
||||
data = map[string]interface{}{}
|
||||
}
|
||||
data["tenant_name"] = t.Name
|
||||
queued := 0
|
||||
for _, m := range members {
|
||||
if !m.Enabled || m.Email == "" || !hasAnyRole(m.OrgRoles, allowed) {
|
||||
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
|
||||
}
|
||||
|
||||
func hasAnyRole(roles []string, allowed map[string]bool) bool {
|
||||
for _, r := range roles {
|
||||
if allowed[strings.ToUpper(r)] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 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})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
msg.To = it.Recipient
|
||||
return s.Mail.Send(ctx, msg)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
func seedMembers(h *testHarness, slug string) {
|
||||
h.kcMock.Members[slug] = []keycloak.OrgMember{
|
||||
{UserID: "u1", Email: "IT@acme.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: true},
|
||||
{UserID: "u2", Email: "legal@acme.test", OrgRoles: []string{"LEGAL"}, Enabled: true},
|
||||
{UserID: "u3", Email: "dev@acme.test", OrgRoles: []string{"USER"}, Enabled: true},
|
||||
{UserID: "u4", Email: "gone@acme.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: false},
|
||||
{UserID: "u5", Email: "fin@acme.test", OrgRoles: []string{"FINANCE"}, Enabled: true},
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotify_documentPublishedMailsTheReaders(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
h.app.Objects = storage.NewMemory()
|
||||
rec := &mail.Recorder{}
|
||||
h.app.Mail = rec
|
||||
h.app.Cfg.PortalURL = "https://app-stage.breakpilot.com"
|
||||
seedMembers(h, "acme")
|
||||
|
||||
_, raw := upload(t, h, h.tenant.ID, map[string]string{"title": "CRA-Dossier"}, "dossier.pdf", "%PDF")
|
||||
var d store.Document
|
||||
_ = json.Unmarshal(raw, &d)
|
||||
h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil)
|
||||
n, err := h.app.DrainMail(context.Background())
|
||||
if err != nil || n != 3 {
|
||||
t.Fatalf("drained %d, %v", n, err)
|
||||
}
|
||||
to := map[string]bool{}
|
||||
for _, m := range rec.Messages() {
|
||||
to[m.To] = true
|
||||
if !strings.Contains(m.Subject, "CRA-Dossier") || !strings.Contains(m.Text, "https://app-stage.breakpilot.com/acme/documents") {
|
||||
t.Fatalf("message: %+v", m)
|
||||
}
|
||||
}
|
||||
if !to["it@acme.test"] || !to["legal@acme.test"] || !to["fin@acme.test"] || to["dev@acme.test"] || to["gone@acme.test"] {
|
||||
t.Fatalf("recipients: %v", to)
|
||||
}
|
||||
// nothing left, and nothing new for a second publish
|
||||
h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil)
|
||||
if n, _ := h.app.DrainMail(context.Background()); n != 0 {
|
||||
t.Fatalf("second drain: %d", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNotify_productFindings(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
rec := &mail.Recorder{}
|
||||
h.app.Mail = rec
|
||||
seedMembers(h, "acme")
|
||||
body := map[string]any{"tenant_id": h.tenant.ID, "kind": "findings.new", "idempotency_key": "scan-42",
|
||||
"data": map[string]any{"target_name": "Pumpstation", "new_count": 3, "critical": 1, "high": 2, "url": "https://pruefwerk-stage.breakpilot.com/targets/t1"}}
|
||||
resp, raw := h.do("POST", "/v1/notifications", body)
|
||||
if resp.StatusCode != 202 || !strings.Contains(string(raw), `"queued":2`) {
|
||||
t.Fatalf("queue: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
if resp, raw := h.do("POST", "/v1/notifications", body); resp.StatusCode != 202 || !strings.Contains(string(raw), `"queued":0`) {
|
||||
t.Fatalf("repeat: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
if _, err := h.app.DrainMail(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msgs := rec.Messages()
|
||||
if len(msgs) != 2 || msgs[0].Subject != "3 neue Befunde in Pumpstation" || !strings.Contains(msgs[0].HTML, "https://pruefwerk-stage.breakpilot.com/targets/t1") {
|
||||
t.Fatalf("messages: %+v", msgs)
|
||||
}
|
||||
|
||||
for _, bad := range []map[string]any{
|
||||
{"tenant_id": h.tenant.ID, "kind": "document.published", "idempotency_key": "x", "data": map[string]any{"target_name": "a", "new_count": 1}},
|
||||
{"tenant_id": h.tenant.ID, "kind": "findings.new", "data": map[string]any{"target_name": "a", "new_count": 1}},
|
||||
{"tenant_id": h.tenant.ID, "kind": "findings.new", "idempotency_key": "y", "data": map[string]any{"target_name": "a", "new_count": 0}},
|
||||
{"tenant_id": h.tenant.ID, "kind": "findings.new", "idempotency_key": "z", "data": map[string]any{"new_count": 2}},
|
||||
} {
|
||||
if resp, raw := h.do("POST", "/v1/notifications", bad); resp.StatusCode != 400 {
|
||||
t.Fatalf("accepted %v: %d %s", bad, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
if resp, _ := h.do("POST", "/v1/notifications", map[string]any{"tenant_id": "00000000-0000-0000-0000-00000000dead", "kind": "findings.new",
|
||||
"idempotency_key": "k", "data": map[string]any{"target_name": "a", "new_count": 1}}); resp.StatusCode != 404 {
|
||||
t.Fatalf("unknown tenant: %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNotify_demoAndOrglessTenantsGetNothing(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
h.app.Mail = &mail.Recorder{}
|
||||
demo := newTenant(t, h, "demo-co")
|
||||
if _, err := h.store.UpdateTenant(context.Background(), demo.ID, store.TenantUpdate{Status: ptr("demo")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedMembers(h, "demo-co")
|
||||
for _, id := range []string{demo.ID, newTenant(t, h, "no-org-3").ID} {
|
||||
resp, raw := h.do("POST", "/v1/notifications", map[string]any{"tenant_id": id, "kind": "findings.new", "idempotency_key": "k-" + id,
|
||||
"data": map[string]any{"target_name": "a", "new_count": 1}})
|
||||
if resp.StatusCode != 202 || !strings.Contains(string(raw), `"queued":0`) {
|
||||
t.Fatalf("%s: %d %s", id, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNotify_retriesWithBackoff(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
rec := &mail.Recorder{Fail: errors.New("relay down")}
|
||||
h.app.Mail = rec
|
||||
seedMembers(h, "acme")
|
||||
h.do("POST", "/v1/notifications", map[string]any{"tenant_id": h.tenant.ID, "kind": "findings.new", "idempotency_key": "r1",
|
||||
"data": map[string]any{"target_name": "a", "new_count": 1}})
|
||||
if n, err := h.app.DrainMail(context.Background()); err != nil || n != 2 {
|
||||
t.Fatalf("first attempt: %d %v", n, err)
|
||||
}
|
||||
// not due again right away
|
||||
if n, _ := h.app.DrainMail(context.Background()); n != 0 {
|
||||
t.Fatalf("retried immediately: %d", n)
|
||||
}
|
||||
rec.Fail = nil
|
||||
h.app.Now = func() time.Time { return time.Now().Add(2 * time.Minute) }
|
||||
if n, _ := h.app.DrainMail(context.Background()); n != 2 || len(rec.Messages()) != 2 {
|
||||
t.Fatalf("after backoff: %d sent %d", n, len(rec.Messages()))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -53,6 +53,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"},
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/invites/resend"},
|
||||
{"GET", "/v1/admin/audit?limit=10"},
|
||||
{"POST", "/v1/notifications"},
|
||||
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/documents"},
|
||||
{"POST", "/v1/admin/documents/00000000-0000-0000-0000-000000000002/publish"},
|
||||
{"DELETE", "/v1/admin/documents/00000000-0000-0000-0000-000000000002"},
|
||||
|
||||
@@ -6,6 +6,7 @@ package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -36,6 +37,7 @@ type Server struct {
|
||||
Licences *licence.Signer // nil ⇒ licence endpoints return 503
|
||||
LLMKeys *llmkeys.Client // nil / disabled ⇒ Werkpilot grants carry no LiteLLM key (D6)
|
||||
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
||||
Mail mail.Sender // nil ⇒ notifications queue up unsent (F3)
|
||||
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
||||
}
|
||||
|
||||
@@ -157,6 +159,9 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument)
|
||||
mux.HandleFunc("DELETE /v1/admin/documents/{doc}", s.adminDeleteDocument)
|
||||
|
||||
// Notifications from products (F3; group "notify").
|
||||
mux.HandleFunc("POST /v1/notifications", s.postNotification)
|
||||
|
||||
// Tenant documents (F2): the list is a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/documents/{doc}/download", s.downloadTenantDocument)
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@ type Memory struct {
|
||||
licences map[string]*Licence
|
||||
|
||||
documents map[string]*Document
|
||||
mail []*MailItem
|
||||
mailID int64
|
||||
}
|
||||
|
||||
type apiKeyWithHash struct {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (m *Memory) EnqueueMail(_ context.Context, it MailItem) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if it.IdempotencyKey == "" || it.Recipient == "" || it.Kind == "" {
|
||||
return false, ErrInvalidInput
|
||||
}
|
||||
for _, x := range m.mail {
|
||||
if x.IdempotencyKey == it.IdempotencyKey {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
m.mailID++
|
||||
now := time.Now().UTC()
|
||||
it.ID, it.CreatedAt, it.Attempts, it.SentAt = m.mailID, now, 0, nil
|
||||
if it.NextAttemptAt.IsZero() {
|
||||
it.NextAttemptAt = now
|
||||
}
|
||||
if it.Locale == "" {
|
||||
it.Locale = "de"
|
||||
}
|
||||
if it.Data == nil {
|
||||
it.Data = map[string]interface{}{}
|
||||
}
|
||||
row := it
|
||||
m.mail = append(m.mail, &row)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ClaimMail(_ context.Context, limit int, now time.Time, lease time.Duration) ([]MailItem, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := []MailItem{}
|
||||
for _, x := range m.mail {
|
||||
if len(out) >= limit {
|
||||
break
|
||||
}
|
||||
if x.SentAt != nil || x.NextAttemptAt.After(now) {
|
||||
continue
|
||||
}
|
||||
x.NextAttemptAt = now.Add(lease)
|
||||
out = append(out, *x)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CompleteMail(_ context.Context, id int64, at time.Time) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for _, x := range m.mail {
|
||||
if x.ID == id {
|
||||
at = at.UTC()
|
||||
x.SentAt, x.LastError = &at, ""
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
func (m *Memory) FailMail(_ context.Context, id int64, errMsg string, next time.Time) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for _, x := range m.mail {
|
||||
if x.ID == id {
|
||||
x.Attempts++
|
||||
x.LastError, x.NextAttemptAt = errMsg, next.UTC()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
// MailItems is a test helper: a copy of the outbox.
|
||||
func (m *Memory) MailItems() []MailItem {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := make([]MailItem, len(m.mail))
|
||||
for i, x := range m.mail {
|
||||
out[i] = *x
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (p *Postgres) EnqueueMail(ctx context.Context, it MailItem) (bool, error) {
|
||||
if it.IdempotencyKey == "" || it.Recipient == "" || it.Kind == "" {
|
||||
return false, ErrInvalidInput
|
||||
}
|
||||
if it.Locale == "" {
|
||||
it.Locale = "de"
|
||||
}
|
||||
if it.Data == nil {
|
||||
it.Data = map[string]interface{}{}
|
||||
}
|
||||
data, err := json.Marshal(it.Data)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var tenant any
|
||||
if it.TenantID != "" {
|
||||
tenant = it.TenantID
|
||||
}
|
||||
next := it.NextAttemptAt
|
||||
if next.IsZero() {
|
||||
next = time.Now().UTC()
|
||||
}
|
||||
tag, err := p.pool.Exec(ctx, `
|
||||
INSERT INTO mail_outbox (tenant_id, kind, recipient, locale, data, idempotency_key, next_attempt_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (idempotency_key) DO NOTHING`,
|
||||
tenant, it.Kind, it.Recipient, it.Locale, data, it.IdempotencyKey, next)
|
||||
if err != nil {
|
||||
if isFKViolation(err) || isInvalidUUID(err) {
|
||||
return false, ErrNotFound
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) ClaimMail(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]MailItem, error) {
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
UPDATE mail_outbox SET next_attempt_at = $2
|
||||
WHERE id IN (
|
||||
SELECT id FROM mail_outbox
|
||||
WHERE sent_at IS NULL AND next_attempt_at <= $1
|
||||
ORDER BY next_attempt_at, id
|
||||
LIMIT $3
|
||||
FOR UPDATE SKIP LOCKED)
|
||||
RETURNING id, COALESCE(tenant_id::text, ''), kind, recipient, locale, data, idempotency_key,
|
||||
attempts, next_attempt_at, sent_at, COALESCE(last_error, ''), created_at`,
|
||||
now.UTC(), now.UTC().Add(lease), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []MailItem{}
|
||||
for rows.Next() {
|
||||
var it MailItem
|
||||
var raw []byte
|
||||
if err := rows.Scan(&it.ID, &it.TenantID, &it.Kind, &it.Recipient, &it.Locale, &raw, &it.IdempotencyKey,
|
||||
&it.Attempts, &it.NextAttemptAt, &it.SentAt, &it.LastError, &it.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &it.Data); err != nil {
|
||||
it.Data = map[string]interface{}{}
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (p *Postgres) CompleteMail(ctx context.Context, id int64, at time.Time) error {
|
||||
tag, err := p.pool.Exec(ctx, `UPDATE mail_outbox SET sent_at = $2, last_error = NULL WHERE id = $1`, id, at.UTC())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) FailMail(ctx context.Context, id int64, errMsg string, next time.Time) error {
|
||||
tag, err := p.pool.Exec(ctx, `
|
||||
UPDATE mail_outbox SET attempts = attempts + 1, last_error = $2, next_attempt_at = $3 WHERE id = $1`,
|
||||
id, errMsg, next.UTC())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -135,6 +135,13 @@ type Store interface {
|
||||
PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error)
|
||||
DeleteDocument(ctx context.Context, id string) error
|
||||
|
||||
// Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey
|
||||
// (false when the key existed). ClaimMail leases due unsent rows.
|
||||
EnqueueMail(ctx context.Context, m MailItem) (bool, error)
|
||||
ClaimMail(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]MailItem, error)
|
||||
CompleteMail(ctx context.Context, id int64, at time.Time) error
|
||||
FailMail(ctx context.Context, id int64, errMsg string, next time.Time) error
|
||||
|
||||
// Lifecycle
|
||||
Close()
|
||||
Ping(ctx context.Context) error
|
||||
|
||||
@@ -270,3 +270,19 @@ const (
|
||||
DocumentDraft = "draft"
|
||||
DocumentPublished = "published"
|
||||
)
|
||||
|
||||
// MailItem — one platform email to one recipient (migration 0009).
|
||||
type MailItem struct {
|
||||
ID int64 `json:"id"`
|
||||
TenantID string `json:"tenant_id,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
Recipient string `json:"recipient"`
|
||||
Locale string `json:"locale"`
|
||||
Data map[string]interface{} `json:"data"`
|
||||
IdempotencyKey string `json:"idempotency_key"`
|
||||
Attempts int `json:"attempts"`
|
||||
NextAttemptAt time.Time `json:"next_attempt_at"`
|
||||
SentAt *time.Time `json:"sent_at,omitempty"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS mail_outbox;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- F3 (go-live 2026-09): platform emails (document published, new findings)
|
||||
-- go through an outbox, one row per recipient, so a relay outage delays mail
|
||||
-- instead of losing it. The body is rendered when the row is sent, from kind,
|
||||
-- locale and data, so a template fix reaches queued mail too.
|
||||
CREATE TABLE mail_outbox (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL,
|
||||
recipient TEXT NOT NULL,
|
||||
locale TEXT NOT NULL DEFAULT 'de',
|
||||
data JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
idempotency_key TEXT NOT NULL UNIQUE,
|
||||
attempts INT NOT NULL DEFAULT 0,
|
||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
sent_at TIMESTAMPTZ,
|
||||
last_error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX mail_outbox_due ON mail_outbox (next_attempt_at) WHERE sent_at IS NULL;
|
||||
@@ -114,8 +114,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}} {
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}} {
|
||||
var exists bool
|
||||
err := db.QueryRow(
|
||||
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
|
||||
|
||||
@@ -501,6 +501,45 @@ paths:
|
||||
expires_at: { type: string, format: date-time }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/notifications:
|
||||
post:
|
||||
summary: Ask the platform to tell a workspace something (route group notify).
|
||||
description: |
|
||||
Products report news for a workspace; the platform mails the members
|
||||
whose org role should hear it (findings.new: IT_ADMIN, OWNER, CXO,
|
||||
LEGAL), in the BreakPilot layout, through an outbox. Demo tenants and
|
||||
tenants without an organization get nothing. Idempotent per
|
||||
idempotency_key.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [tenant_id, kind, idempotency_key, data]
|
||||
properties:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
kind: { type: string, enum: [findings.new] }
|
||||
idempotency_key: { type: string, maxLength: 200 }
|
||||
data:
|
||||
type: object
|
||||
required: [target_name, new_count]
|
||||
properties:
|
||||
target_name: { type: string, maxLength: 200 }
|
||||
new_count: { type: integer, minimum: 1 }
|
||||
critical: { type: integer }
|
||||
high: { type: integer }
|
||||
medium: { type: integer }
|
||||
low: { type: integer }
|
||||
url: { type: string, description: "https link into the product; defaults to the portal dashboard" }
|
||||
responses:
|
||||
"202":
|
||||
description: Queued (queued = number of recipients, 0 for a repeat).
|
||||
content:
|
||||
application/json: { schema: { type: object, properties: { queued: { type: integer } } } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/entitlements:
|
||||
get:
|
||||
summary: List product entitlements for a tenant.
|
||||
|
||||
Reference in new issue
Block a user