Verify webhook payments with LNbits before acting on them
The webhook listener accepted any POST as proof of payment and fired the invoice callbacks (inline receive, group tickets, satdress payout, DALL-E refund) for whatever payment hash the body named. It now: - limits the body to 1 MB and only accepts a 64-hex payment hash, - asks LNbits whether the named wallet really received a settled incoming payment for that hash, and uses the amount LNbits reports, - handles every payment hash once (bunt key "webhook:<hash>"), - refuses to dispatch an invoice event registered for another wallet, - runs the callback with a recover, so a panic can't take the bot down. The pure checks live in internal/lnbits/webhook/verify, which does not depend on the bot configuration and is unit tested. Port of kravens/BitTipBot b7e56da and 27eb079 onto our simpler handler. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
e010b31fd5
commit
f040b67597
@@ -0,0 +1,49 @@
|
||||
// Package verify holds the checks the LNbits webhook listener applies before
|
||||
// it treats a request as proof of payment. It has no dependency on the bot
|
||||
// configuration, so it can be unit tested.
|
||||
package verify
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// paymentHashFormat is the only form LNbits uses for a payment hash. The hash
|
||||
// becomes part of an LNbits URL and of the replay key, so nothing else is
|
||||
// accepted (a suffix such as "?x=1" would reach the same payment but be a new
|
||||
// replay key).
|
||||
var paymentHashFormat = regexp.MustCompile("^[0-9a-f]{64}$")
|
||||
|
||||
// ValidPaymentHash reports whether h is 64 lowercase hex characters.
|
||||
func ValidPaymentHash(h string) bool {
|
||||
return paymentHashFormat.MatchString(h)
|
||||
}
|
||||
|
||||
// Payment is what LNbits reports for a payment hash, reduced to the fields
|
||||
// the webhook needs.
|
||||
type Payment struct {
|
||||
Paid bool
|
||||
PaymentHash string
|
||||
WalletID string
|
||||
AmountMsat int64
|
||||
}
|
||||
|
||||
// SettledIncoming returns the amount in msat of a settled incoming payment of
|
||||
// walletID with paymentHash, or an error when p is not that. LNbits only
|
||||
// returns the details to the wallet that owns the payment; an outgoing payment
|
||||
// of the same wallet has a negative amount.
|
||||
func SettledIncoming(p Payment, paymentHash, walletID string) (int64, error) {
|
||||
if !p.Paid {
|
||||
return 0, fmt.Errorf("payment %s is not settled", paymentHash)
|
||||
}
|
||||
if p.PaymentHash != paymentHash {
|
||||
return 0, fmt.Errorf("payment hash mismatch: got %s, want %s", p.PaymentHash, paymentHash)
|
||||
}
|
||||
if p.WalletID != walletID {
|
||||
return 0, fmt.Errorf("payment %s does not belong to wallet %s", paymentHash, walletID)
|
||||
}
|
||||
if p.AmountMsat <= 0 {
|
||||
return 0, fmt.Errorf("payment %s is not an incoming payment", paymentHash)
|
||||
}
|
||||
return p.AmountMsat, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package verify
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidPaymentHash(t *testing.T) {
|
||||
ok := strings.Repeat("ab", 32)
|
||||
cases := map[string]bool{
|
||||
ok: true,
|
||||
strings.ToUpper(ok): false, // LNbits uses lowercase
|
||||
ok + "?x=1": false, // would reach the same payment under a new replay key
|
||||
ok[:62]: false,
|
||||
ok + "a": false,
|
||||
"": false,
|
||||
strings.Repeat("g", 64): false,
|
||||
"../" + ok[3:]: false,
|
||||
strings.Repeat("ab", 31) + "a\n": false,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := ValidPaymentHash(in); got != want {
|
||||
t.Errorf("ValidPaymentHash(%q) = %v, want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettledIncoming(t *testing.T) {
|
||||
hash := strings.Repeat("01", 32)
|
||||
good := Payment{Paid: true, PaymentHash: hash, WalletID: "w1", AmountMsat: 21000}
|
||||
|
||||
if got, err := SettledIncoming(good, hash, "w1"); err != nil || got != 21000 {
|
||||
t.Fatalf("settled payment rejected: amount=%d err=%v", got, err)
|
||||
}
|
||||
|
||||
bad := []struct {
|
||||
name string
|
||||
p Payment
|
||||
}{
|
||||
{"unpaid", Payment{Paid: false, PaymentHash: hash, WalletID: "w1", AmountMsat: 21000}},
|
||||
{"other hash", Payment{Paid: true, PaymentHash: strings.Repeat("02", 32), WalletID: "w1", AmountMsat: 21000}},
|
||||
{"other wallet", Payment{Paid: true, PaymentHash: hash, WalletID: "w2", AmountMsat: 21000}},
|
||||
{"outgoing", Payment{Paid: true, PaymentHash: hash, WalletID: "w1", AmountMsat: -21000}},
|
||||
{"zero", Payment{Paid: true, PaymentHash: hash, WalletID: "w1", AmountMsat: 0}},
|
||||
{"empty", Payment{}},
|
||||
}
|
||||
for _, c := range bad {
|
||||
if got, err := SettledIncoming(c.p, hash, "w1"); err == nil || got != 0 {
|
||||
t.Errorf("%s: accepted with amount=%d err=%v", c.name, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@ package webhook
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits/webhook/verify"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -17,11 +19,16 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/tidwall/buntdb"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/i18n"
|
||||
)
|
||||
|
||||
// maxBodyBytes bounds the webhook request body. A real LNbits payload is a
|
||||
// few hundred bytes.
|
||||
const maxBodyBytes = 1 << 20
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
bot *tb.Bot
|
||||
@@ -74,6 +81,37 @@ func (w *Server) GetUserByWalletId(walletId string) (*lnbits.User, error) {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// settledAmount returns the amount in msat that LNbits says the user's wallet
|
||||
// received for paymentHash. It fails unless that payment is settled.
|
||||
func (w *Server) settledAmount(user *lnbits.User, paymentHash string) (int64, error) {
|
||||
payment, err := w.c.Payment(*user.Wallet, paymentHash)
|
||||
// LNbits sends a webhook only once, so a short LNbits hiccup must not
|
||||
// lose the payment event.
|
||||
for try := 0; err != nil && try < 2; try++ {
|
||||
time.Sleep(time.Second)
|
||||
payment, err = w.c.Payment(*user.Wallet, paymentHash)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return verify.SettledIncoming(verify.Payment{
|
||||
Paid: payment.Paid,
|
||||
PaymentHash: payment.Details.PaymentHash,
|
||||
WalletID: payment.Details.WalletID,
|
||||
AmountMsat: payment.Details.Amount,
|
||||
}, paymentHash, user.Wallet.ID)
|
||||
}
|
||||
|
||||
// markHandled records paymentHash and reports whether this is the first time.
|
||||
func (w *Server) markHandled(paymentHash string) (first bool, err error) {
|
||||
err = w.buntdb.Update(func(tx *buntdb.Tx) error {
|
||||
_, replaced, err := tx.Set("webhook:"+paymentHash, "1", nil)
|
||||
first = !replaced
|
||||
return err
|
||||
})
|
||||
return first, err
|
||||
}
|
||||
|
||||
func (w *Server) newRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/", w.receive).Methods(http.MethodPost)
|
||||
@@ -83,21 +121,54 @@ func (w *Server) newRouter() *mux.Router {
|
||||
func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Debugln("[Webhook] Received request")
|
||||
webhookEvent := Webhook{}
|
||||
// need to delete the header otherwise the Decode will fail
|
||||
request.Header.Del("content-length")
|
||||
err := json.NewDecoder(request.Body).Decode(&webhookEvent)
|
||||
body, err := io.ReadAll(http.MaxBytesReader(writer, request.Body, maxBodyBytes))
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error reading request body: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
if err = json.Unmarshal(body, &webhookEvent); err != nil {
|
||||
log.Errorf("[Webhook] Error decoding request: %s", err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error getting user: %s", err.Error())
|
||||
// The hash becomes part of an LNbits URL and of the replay key, so only
|
||||
// the form LNbits uses is accepted.
|
||||
if !verify.ValidPaymentHash(webhookEvent.PaymentHash) {
|
||||
log.Errorf("[Webhook] Rejecting webhook with malformed payment_hash")
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, webhookEvent.Amount/1000))
|
||||
user, err := w.GetUserByWalletId(webhookEvent.WalletID)
|
||||
if err != nil || user.Wallet == nil || user.Wallet.ID == "" {
|
||||
log.Errorf("[Webhook] Error getting user for wallet_id %q: %v", webhookEvent.WalletID, err)
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
|
||||
// Anyone who can reach this port can send a webhook, so the body is only
|
||||
// a hint. Ask LNbits whether this wallet really received the payment and
|
||||
// use the amount LNbits reports.
|
||||
amountMsat, err := w.settledAmount(user, webhookEvent.PaymentHash)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Rejecting webhook for payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
|
||||
writer.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
// Handle every payment once, so a webhook can't be replayed.
|
||||
first, err := w.markHandled(webhookEvent.PaymentHash)
|
||||
if err != nil {
|
||||
log.Errorf("[Webhook] Error storing payment_hash %s: %s", webhookEvent.PaymentHash, err.Error())
|
||||
writer.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
if !first {
|
||||
log.Infof("[Webhook] Ignoring repeated webhook for payment_hash %s", webhookEvent.PaymentHash)
|
||||
writer.WriteHeader(200)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infoln(fmt.Sprintf("[⚡️ WebHook] User %s (%d) received invoice of %d sat.", telegram.GetUserStr(user.Telegram), user.Telegram.ID, amountMsat/1000))
|
||||
|
||||
writer.WriteHeader(200)
|
||||
|
||||
@@ -106,6 +177,11 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
err = w.buntdb.Get(txInvoiceEvent)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
} else if txInvoiceEvent.User != nil && txInvoiceEvent.User.Wallet != nil && txInvoiceEvent.User.Wallet.ID != user.Wallet.ID {
|
||||
// the event was registered for another wallet than the one LNbits paid
|
||||
log.Errorf("[Webhook] Invoice event for payment_hash %s belongs to wallet %s, not %s. Not dispatching.",
|
||||
webhookEvent.PaymentHash, txInvoiceEvent.User.Wallet.ID, user.Wallet.ID)
|
||||
return
|
||||
} else {
|
||||
// do something with the event
|
||||
if c := telegram.InvoiceCallback[txInvoiceEvent.Callback]; c.Function != nil {
|
||||
@@ -113,14 +189,26 @@ func (w *Server) receive(writer http.ResponseWriter, request *http.Request) {
|
||||
log.Errorln(err)
|
||||
return
|
||||
}
|
||||
go c.Function(txInvoiceEvent)
|
||||
go runCallback(c.Function, txInvoiceEvent)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// fallback: send a message to the user if there is no callback for this invoice
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), webhookEvent.Amount/1000))
|
||||
_, err = w.bot.Send(user.Telegram, fmt.Sprintf(i18n.Translate(user.Telegram.LanguageCode, "invoiceReceivedMessage"), amountMsat/1000))
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
// runCallback runs an invoice callback in its own goroutine. Telegram handlers
|
||||
// recover from panics, but these callbacks run outside of telebot, so a panic
|
||||
// in one would otherwise take the whole bot down.
|
||||
func runCallback(f func(telegram.Event), ev telegram.Event) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Errorf("[Webhook] panic in invoice callback: %v", r)
|
||||
}
|
||||
}()
|
||||
f(ev)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user