465 lines
16 KiB
Go
465 lines
16 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
firebase "firebase.google.com/go/v4"
|
|
"firebase.google.com/go/v4/messaging"
|
|
"google.golang.org/api/option"
|
|
)
|
|
|
|
const (
|
|
jensTodoPushTopic = "landwelle_it_jens_todos"
|
|
jensTodoAndroidChannel = "landwelle_monitoring"
|
|
firebaseCredentialDefaultPath = "/etc/landwelle/firebase-service-account.json"
|
|
)
|
|
|
|
type firebaseMessageSender interface {
|
|
Send(context.Context, *messaging.Message) (string, error)
|
|
}
|
|
|
|
type firebasePushService struct {
|
|
client firebaseMessageSender
|
|
database *postgresStore
|
|
logger *log.Logger
|
|
credentialPath string
|
|
initErr error
|
|
}
|
|
|
|
type firebasePushClaim struct {
|
|
TodoID int64 `json:"todo_id"`
|
|
}
|
|
|
|
type appPushCampaignInput struct {
|
|
Title string
|
|
Body string
|
|
Topic string
|
|
DeepLink string
|
|
Priority string
|
|
CreatedBy int64
|
|
Data map[string]string
|
|
}
|
|
|
|
type appPushCampaignResult struct {
|
|
CampaignID int64
|
|
Recipients int
|
|
Sent int
|
|
Failed int
|
|
}
|
|
|
|
type appPushCampaignRow struct {
|
|
ID int64 `json:"id"`
|
|
}
|
|
|
|
type appPushRecipient struct {
|
|
PushTokenID int64 `json:"push_token_id"`
|
|
InstallationID string `json:"installation_id"`
|
|
CiphertextHex string `json:"ciphertext_hex"`
|
|
}
|
|
|
|
func newFirebasePushService(logger *log.Logger, database *postgresStore) *firebasePushService {
|
|
service := &firebasePushService{database: database, logger: logger}
|
|
credentialPath, err := resolveFirebaseCredentialPath()
|
|
if err != nil {
|
|
service.initErr = err
|
|
service.logConfigurationError(err)
|
|
return service
|
|
}
|
|
service.credentialPath = credentialPath
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
app, err := firebase.NewApp(ctx, nil, option.WithCredentialsFile(credentialPath))
|
|
if err != nil {
|
|
service.initErr = fmt.Errorf("Firebase Admin SDK konnte nicht initialisiert werden: %w", err)
|
|
service.logConfigurationError(service.initErr)
|
|
return service
|
|
}
|
|
client, err := app.Messaging(ctx)
|
|
if err != nil {
|
|
service.initErr = fmt.Errorf("Firebase Messaging-Client konnte nicht initialisiert werden: %w", err)
|
|
service.logConfigurationError(service.initErr)
|
|
return service
|
|
}
|
|
service.client = client
|
|
if logger != nil {
|
|
logger.Printf("firebase_push timestamp=%s status=ready topic=%s", time.Now().UTC().Format(time.RFC3339), jensTodoPushTopic)
|
|
}
|
|
return service
|
|
}
|
|
|
|
func resolveFirebaseCredentialPath() (string, error) {
|
|
configured := strings.TrimSpace(os.Getenv("FIREBASE_SERVICE_ACCOUNT_FILE"))
|
|
if configured == "" {
|
|
configured = firebaseCredentialDefaultPath
|
|
}
|
|
if !filepath.IsAbs(configured) {
|
|
return "", errors.New("FIREBASE_SERVICE_ACCOUNT_FILE muss ein absoluter Serverpfad sein")
|
|
}
|
|
cleaned := filepath.Clean(configured)
|
|
resolved, err := filepath.EvalSymlinks(cleaned)
|
|
if err != nil {
|
|
return "", fmt.Errorf("Firebase-Service-Account-Datei nicht verfügbar: %w", err)
|
|
}
|
|
if !filepath.IsAbs(resolved) {
|
|
return "", errors.New("aufgelöster Firebase-Dateipfad ist nicht absolut")
|
|
}
|
|
info, err := os.Stat(resolved)
|
|
if err != nil {
|
|
return "", fmt.Errorf("Firebase-Service-Account-Datei nicht lesbar: %w", err)
|
|
}
|
|
if !info.Mode().IsRegular() {
|
|
return "", errors.New("Firebase-Service-Account-Pfad verweist nicht auf eine reguläre Datei")
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
func (s *firebasePushService) Ready() bool {
|
|
return s != nil && s.client != nil && s.initErr == nil
|
|
}
|
|
|
|
func (s *firebasePushService) Status() string {
|
|
if s == nil {
|
|
return "Nicht initialisiert"
|
|
}
|
|
if s.Ready() {
|
|
return "Bereit"
|
|
}
|
|
if s.initErr != nil {
|
|
return sanitizeFirebaseError(s.initErr, s.credentialPath)
|
|
}
|
|
return "Nicht konfiguriert"
|
|
}
|
|
|
|
func (s *firebasePushService) SendTodoCreated(ctx context.Context, todoID int64) (string, error) {
|
|
return s.SendTodoCreatedByAuthor(ctx, todoID, "Jens")
|
|
}
|
|
|
|
func (s *firebasePushService) SendTodoCreatedByAuthor(ctx context.Context, todoID int64, author string) (string, error) {
|
|
if todoID <= 0 {
|
|
return "", errors.New("ungültige Todo-ID")
|
|
}
|
|
claimed, err := s.claimTodoNotification(ctx, todoID)
|
|
if err != nil {
|
|
s.logPushResult(todoID, "", err)
|
|
return "", err
|
|
}
|
|
if !claimed {
|
|
if s != nil && s.logger != nil {
|
|
s.logger.Printf("firebase_push timestamp=%s todo_id=%d topic=%s status=skipped reason=idempotency", time.Now().UTC().Format(time.RFC3339), todoID, jensTodoPushTopic)
|
|
}
|
|
return "", nil
|
|
}
|
|
if !s.Ready() {
|
|
err := errors.New(s.Status())
|
|
s.recordTodoPushFailure(ctx, todoID, err)
|
|
s.logPushResult(todoID, "", err)
|
|
return "", err
|
|
}
|
|
sendCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
messageID, err := s.client.Send(sendCtx, newLandwelleITTodoMessage(todoID, author))
|
|
if err != nil {
|
|
s.recordTodoPushFailure(ctx, todoID, err)
|
|
s.logPushResult(todoID, "", err)
|
|
return "", err
|
|
}
|
|
if err := s.recordTodoPushSuccess(ctx, todoID, messageID); err != nil {
|
|
s.logPushResult(todoID, messageID, fmt.Errorf("Push versendet, Statusspeicherung fehlgeschlagen: %w", err))
|
|
return messageID, err
|
|
}
|
|
s.logPushResult(todoID, messageID, nil)
|
|
return messageID, nil
|
|
}
|
|
|
|
func (s *firebasePushService) SendAdminTest(ctx context.Context) (string, error) {
|
|
if !s.Ready() {
|
|
err := errors.New(s.Status())
|
|
s.logPushResult(0, "", err)
|
|
return "", err
|
|
}
|
|
sendCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
message := &messaging.Message{
|
|
Topic: jensTodoPushTopic,
|
|
Notification: &messaging.Notification{
|
|
Title: "Landwelle IT: Testnachricht",
|
|
Body: "Firebase Cloud Messaging ist erfolgreich verbunden.",
|
|
},
|
|
Data: map[string]string{
|
|
"type": "todo_test",
|
|
"todo_id": "test",
|
|
"author": "Jens",
|
|
},
|
|
Android: &messaging.AndroidConfig{
|
|
Priority: "high",
|
|
Notification: &messaging.AndroidNotification{
|
|
ChannelID: jensTodoAndroidChannel,
|
|
},
|
|
},
|
|
}
|
|
messageID, err := s.client.Send(sendCtx, message)
|
|
s.logPushResult(0, messageID, err)
|
|
return messageID, err
|
|
}
|
|
|
|
func newJensTodoMessage(todoID int64) *messaging.Message {
|
|
return newLandwelleITTodoMessage(todoID, "Jens")
|
|
}
|
|
|
|
func newLandwelleITTodoMessage(todoID int64, author string) *messaging.Message {
|
|
author = strings.TrimSpace(author)
|
|
if author == "" {
|
|
author = "Landwelle"
|
|
}
|
|
return &messaging.Message{
|
|
Topic: jensTodoPushTopic,
|
|
Notification: &messaging.Notification{
|
|
Title: "Neue Aufgabe von " + author,
|
|
Body: "Eine neue Landwelle-IT-Aufgabe wurde eingetragen.",
|
|
},
|
|
Data: map[string]string{
|
|
"type": "todo",
|
|
"todo_id": strconv.FormatInt(todoID, 10),
|
|
"author": author,
|
|
},
|
|
Android: &messaging.AndroidConfig{
|
|
Priority: "high",
|
|
Notification: &messaging.AndroidNotification{ChannelID: jensTodoAndroidChannel},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (s *firebasePushService) SendAppCampaign(ctx context.Context, in appPushCampaignInput) (appPushCampaignResult, error) {
|
|
var result appPushCampaignResult
|
|
if s == nil || s.database == nil || !s.database.Enabled() {
|
|
return result, errors.New("PostgreSQL ist für App-Push nicht verfügbar")
|
|
}
|
|
if !s.Ready() {
|
|
return result, errors.New(s.Status())
|
|
}
|
|
in.Title = strings.TrimSpace(in.Title)
|
|
in.Body = strings.TrimSpace(in.Body)
|
|
in.Topic = strings.ToLower(strings.TrimSpace(in.Topic))
|
|
in.DeepLink = strings.TrimSpace(in.DeepLink)
|
|
if in.Title == "" || in.Body == "" || in.Topic == "" {
|
|
return result, errors.New("Titel, Nachricht und Zielthema sind erforderlich")
|
|
}
|
|
if in.Priority != "high" {
|
|
in.Priority = "normal"
|
|
}
|
|
key, err := appPushEncryptionKey()
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
targetJSON, _ := json.Marshal(map[string]any{"topics": []string{in.Topic}})
|
|
createdBy := "NULL"
|
|
if in.CreatedBy > 0 {
|
|
createdBy = strconv.FormatInt(in.CreatedBy, 10)
|
|
}
|
|
insertSQL := `WITH created AS (` +
|
|
`INSERT INTO push_campaigns(title,body,deep_link,target,priority,status,started_at,created_by) VALUES (` +
|
|
sqlText(in.Title) + `,` + sqlText(in.Body) + `,` + sqlText(in.DeepLink) + `,` + sqlText(string(targetJSON)) + `::jsonb,` + sqlText(in.Priority) + `,'sending',now(),` + createdBy + `) RETURNING id) ` +
|
|
`SELECT COALESCE(json_agg(row_to_json(created)),'[]'::json)::text FROM created;`
|
|
var campaigns []appPushCampaignRow
|
|
if err := s.database.queryJSON(ctx, insertSQL, &campaigns); err != nil || len(campaigns) != 1 {
|
|
if err == nil {
|
|
err = errors.New("Push-Kampagne konnte nicht angelegt werden")
|
|
}
|
|
return result, err
|
|
}
|
|
result.CampaignID = campaigns[0].ID
|
|
|
|
recipientSQL := `SELECT COALESCE(json_agg(row_to_json(x)),'[]'::json)::text FROM (` +
|
|
`SELECT pt.id AS push_token_id,pt.installation_id::text AS installation_id,encode(pt.token_ciphertext,'hex') AS ciphertext_hex ` +
|
|
`FROM app_push_tokens pt ` +
|
|
`JOIN app_installations ai ON ai.id=pt.installation_id ` +
|
|
`JOIN app_installation_topics ait ON ait.installation_id=ai.id ` +
|
|
`JOIN push_topics t ON t.id=ait.topic_id ` +
|
|
`WHERE pt.active=true AND pt.provider='fcm' AND ai.status='active' AND ai.notifications_enabled=true AND t.active=true AND t.slug=` + sqlText(in.Topic) +
|
|
` ORDER BY pt.id) x;`
|
|
var recipients []appPushRecipient
|
|
if err := s.database.queryJSON(ctx, recipientSQL, &recipients); err != nil {
|
|
s.finishAppPushCampaign(ctx, result.CampaignID, 0, 0, "failed", err)
|
|
return result, err
|
|
}
|
|
result.Recipients = len(recipients)
|
|
|
|
for _, recipient := range recipients {
|
|
if err := ctx.Err(); err != nil {
|
|
s.finishAppPushCampaign(context.Background(), result.CampaignID, result.Sent, result.Failed, "failed", err)
|
|
return result, err
|
|
}
|
|
ciphertext, decodeErr := hex.DecodeString(recipient.CiphertextHex)
|
|
var token []byte
|
|
if decodeErr == nil {
|
|
token, decodeErr = decryptToken(key, ciphertext)
|
|
}
|
|
if decodeErr != nil || strings.TrimSpace(string(token)) == "" {
|
|
result.Failed++
|
|
s.recordAppPushDelivery(ctx, result.CampaignID, recipient, "failed", "", "token_decrypt_failed")
|
|
continue
|
|
}
|
|
data := make(map[string]string, len(in.Data)+3)
|
|
for key, value := range in.Data {
|
|
data[key] = value
|
|
}
|
|
data["campaign_id"] = strconv.FormatInt(result.CampaignID, 10)
|
|
data["topic"] = in.Topic
|
|
if in.DeepLink != "" {
|
|
data["deep_link"] = in.DeepLink
|
|
}
|
|
message := &messaging.Message{
|
|
Token: strings.TrimSpace(string(token)),
|
|
Notification: &messaging.Notification{Title: in.Title, Body: in.Body},
|
|
Data: data,
|
|
Android: &messaging.AndroidConfig{Priority: in.Priority, Notification: &messaging.AndroidNotification{ChannelID: "landwelle_general"}},
|
|
}
|
|
messageID, sendErr := s.client.Send(ctx, message)
|
|
if sendErr != nil {
|
|
result.Failed++
|
|
errorCode := limitString(sanitizeFirebaseError(sendErr, s.credentialPath), 250)
|
|
s.recordAppPushDelivery(ctx, result.CampaignID, recipient, "failed", "", errorCode)
|
|
_, _ = s.database.exec(ctx, `UPDATE app_push_tokens SET last_error_code=`+sqlText(errorCode)+` WHERE id=`+strconv.FormatInt(recipient.PushTokenID, 10)+`;`)
|
|
continue
|
|
}
|
|
result.Sent++
|
|
s.recordAppPushDelivery(ctx, result.CampaignID, recipient, "accepted", messageID, "")
|
|
}
|
|
|
|
status := "sent"
|
|
var campaignErr error
|
|
if result.Recipients > 0 && result.Sent == 0 && result.Failed > 0 {
|
|
status = "failed"
|
|
campaignErr = errors.New("keine Push-Nachricht konnte zugestellt werden")
|
|
}
|
|
s.finishAppPushCampaign(ctx, result.CampaignID, result.Sent, result.Failed, status, campaignErr)
|
|
if campaignErr != nil {
|
|
return result, campaignErr
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (s *firebasePushService) recordAppPushDelivery(ctx context.Context, campaignID int64, recipient appPushRecipient, status, messageID, errorCode string) {
|
|
if s == nil || s.database == nil || !s.database.Enabled() {
|
|
return
|
|
}
|
|
messageSQL := "NULL"
|
|
if messageID != "" {
|
|
messageSQL = sqlText(messageID)
|
|
}
|
|
errorSQL := "NULL"
|
|
if errorCode != "" {
|
|
errorSQL = sqlText(errorCode)
|
|
}
|
|
sentAt := "NULL"
|
|
if status == "accepted" {
|
|
sentAt = "now()"
|
|
}
|
|
_, _ = s.database.exec(ctx, `INSERT INTO push_deliveries(campaign_id,installation_id,push_token_id,status,provider_message_id,error_code,sent_at) VALUES (`+
|
|
strconv.FormatInt(campaignID, 10)+`,`+sqlText(recipient.InstallationID)+`::uuid,`+strconv.FormatInt(recipient.PushTokenID, 10)+`,`+sqlText(status)+`,`+messageSQL+`,`+errorSQL+`,`+sentAt+`);`)
|
|
}
|
|
|
|
func (s *firebasePushService) finishAppPushCampaign(ctx context.Context, campaignID int64, sent, failed int, status string, campaignErr error) {
|
|
if s == nil || s.database == nil || !s.database.Enabled() || campaignID <= 0 {
|
|
return
|
|
}
|
|
errSQL := "NULL"
|
|
if campaignErr != nil {
|
|
errSQL = sqlText(limitString(sanitizeFirebaseError(campaignErr, s.credentialPath), 1000))
|
|
}
|
|
_, _ = s.database.exec(ctx, `UPDATE push_campaigns SET status=`+sqlText(status)+`,sent_count=`+strconv.Itoa(sent)+`,failed_count=`+strconv.Itoa(failed)+`,error_message=`+errSQL+`,completed_at=now(),updated_at=now() WHERE id=`+strconv.FormatInt(campaignID, 10)+`;`)
|
|
}
|
|
|
|
func (s *firebasePushService) claimTodoNotification(ctx context.Context, todoID int64) (bool, error) {
|
|
if s == nil || s.database == nil || !s.database.Enabled() {
|
|
return false, errors.New("PostgreSQL ist für die Push-Idempotenz nicht verfügbar")
|
|
}
|
|
query := fmt.Sprintf(`WITH claimed AS (
|
|
INSERT INTO landwelle.todo_push_notifications(todo_id,topic,status)
|
|
VALUES(%d,%s,'pending')
|
|
ON CONFLICT(todo_id,topic) DO NOTHING
|
|
RETURNING todo_id
|
|
)
|
|
SELECT COALESCE(json_agg(row_to_json(claimed)),'[]'::json)::text FROM claimed;`, todoID, sqlText(jensTodoPushTopic))
|
|
var claims []firebasePushClaim
|
|
if err := s.database.queryJSON(ctx, query, &claims); err != nil {
|
|
return false, err
|
|
}
|
|
return len(claims) == 1, nil
|
|
}
|
|
|
|
func (s *firebasePushService) recordTodoPushSuccess(ctx context.Context, todoID int64, messageID string) error {
|
|
if s == nil || s.database == nil || !s.database.Enabled() {
|
|
return errors.New("PostgreSQL ist nicht verfügbar")
|
|
}
|
|
_, err := s.database.exec(ctx, fmt.Sprintf(`UPDATE landwelle.todo_push_notifications
|
|
SET status='sent',attempts=attempts+1,firebase_message_id=%s,error_message=NULL,attempted_at=now(),sent_at=now(),updated_at=now()
|
|
WHERE todo_id=%d AND topic=%s;`, sqlText(messageID), todoID, sqlText(jensTodoPushTopic)))
|
|
return err
|
|
}
|
|
|
|
func (s *firebasePushService) recordTodoPushFailure(ctx context.Context, todoID int64, pushErr error) {
|
|
if s == nil || s.database == nil || !s.database.Enabled() {
|
|
return
|
|
}
|
|
safeError := sanitizeFirebaseError(pushErr, s.credentialPath)
|
|
_, _ = s.database.exec(ctx, fmt.Sprintf(`UPDATE landwelle.todo_push_notifications
|
|
SET status='failed',attempts=attempts+1,error_message=%s,attempted_at=now(),updated_at=now()
|
|
WHERE todo_id=%d AND topic=%s;`, sqlText(safeError), todoID, sqlText(jensTodoPushTopic)))
|
|
}
|
|
|
|
func (s *firebasePushService) logConfigurationError(err error) {
|
|
if s != nil && s.logger != nil {
|
|
s.logger.Printf("firebase_push timestamp=%s status=unavailable error=%s", time.Now().UTC().Format(time.RFC3339), sanitizeFirebaseError(err, s.credentialPath))
|
|
}
|
|
}
|
|
|
|
func (s *firebasePushService) logPushResult(todoID int64, messageID string, err error) {
|
|
if s == nil || s.logger == nil {
|
|
return
|
|
}
|
|
timestamp := time.Now().UTC().Format(time.RFC3339)
|
|
if err != nil {
|
|
s.logger.Printf("firebase_push timestamp=%s todo_id=%d topic=%s status=failed error=%s", timestamp, todoID, jensTodoPushTopic, sanitizeFirebaseError(err, s.credentialPath))
|
|
return
|
|
}
|
|
s.logger.Printf("firebase_push timestamp=%s todo_id=%d topic=%s status=sent firebase_message_id=%s", timestamp, todoID, jensTodoPushTopic, messageID)
|
|
}
|
|
|
|
var firebaseCredentialPathPattern = regexp.MustCompile(`(?:/[^\s:]+)+/firebase-service-account\.json|/etc/landwelle/firebase-service-account\.json`)
|
|
var firebasePEMPrivateKeyPattern = regexp.MustCompile(`(?is)-----BEGIN PRIVATE KEY-----.*?-----END PRIVATE KEY-----`)
|
|
var firebaseBearerPattern = regexp.MustCompile(`(?i)\bbearer\s+[^\s,;]+`)
|
|
var firebaseSensitiveFieldPattern = regexp.MustCompile(`(?i)(private_key|access_token|authorization|client_secret)\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)`)
|
|
|
|
func sanitizeFirebaseError(err error, credentialPath string) string {
|
|
if err == nil {
|
|
return ""
|
|
}
|
|
message := strings.TrimSpace(err.Error())
|
|
if credentialPath != "" {
|
|
message = strings.ReplaceAll(message, credentialPath, "[credential-file]")
|
|
}
|
|
message = firebaseCredentialPathPattern.ReplaceAllString(message, "[credential-file]")
|
|
message = firebasePEMPrivateKeyPattern.ReplaceAllString(message, "[redacted-private-key]")
|
|
message = firebaseBearerPattern.ReplaceAllString(message, "Bearer [redacted]")
|
|
message = firebaseSensitiveFieldPattern.ReplaceAllString(message, "$1=[redacted]")
|
|
message = strings.ReplaceAll(message, "\r", " ")
|
|
message = strings.ReplaceAll(message, "\n", " ")
|
|
if len(message) > 1000 {
|
|
message = message[:1000]
|
|
}
|
|
return message
|
|
}
|