Fix the low-severity audit findings
- price map: guard with a RWMutex (fatal concurrent map access) - InvoiceStream: stop on client disconnect, unsubscribe once, cap streams per wallet - join tickets: key the ticket event per joiner; enforce tickets that expired while the bot was down Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
6824ef5928
commit
7f49e422f4
+64
-21
@@ -4,7 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
"sync"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
@@ -141,8 +141,43 @@ type InvoiceStream struct {
|
||||
WebhookStatus interface{} `json:"webhook_status"`
|
||||
}
|
||||
|
||||
// maxStreamsPerWallet bounds the SSE connections one wallet can hold open. Each
|
||||
// one keeps a goroutine and a connection to LNbits alive.
|
||||
const maxStreamsPerWallet = 3
|
||||
|
||||
var (
|
||||
streamsMu sync.Mutex
|
||||
streams = map[string]int{}
|
||||
)
|
||||
|
||||
// acquireStream reserves a stream slot for the wallet.
|
||||
func acquireStream(walletID string) bool {
|
||||
streamsMu.Lock()
|
||||
defer streamsMu.Unlock()
|
||||
if streams[walletID] >= maxStreamsPerWallet {
|
||||
return false
|
||||
}
|
||||
streams[walletID]++
|
||||
return true
|
||||
}
|
||||
|
||||
func releaseStream(walletID string) {
|
||||
streamsMu.Lock()
|
||||
defer streamsMu.Unlock()
|
||||
if streams[walletID] <= 1 {
|
||||
delete(streams, walletID)
|
||||
return
|
||||
}
|
||||
streams[walletID]--
|
||||
}
|
||||
|
||||
func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
|
||||
user := telegram.LoadUser(r.Context())
|
||||
if !acquireStream(user.Wallet.ID) {
|
||||
http.Error(w, "Too many streams", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
defer releaseStream(user.Wallet.ID)
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
|
||||
@@ -160,29 +195,37 @@ func (s Service) InvoiceStream(w http.ResponseWriter, r *http.Request) {
|
||||
out:
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
// the client went away: do not wait for the next payment event
|
||||
break out
|
||||
case msg := <-c:
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
client.Unsubscribe(c)
|
||||
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
default:
|
||||
written, err := fmt.Fprintf(w, "event: %s\n", string(msg.Event))
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
written, err = fmt.Fprint(w, "\n")
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
flusher.Flush()
|
||||
}
|
||||
written, err = fmt.Fprintf(w, "data: %s\n", string(msg.Data))
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
written, err = fmt.Fprint(w, "\n")
|
||||
if err != nil || written == 0 {
|
||||
break out
|
||||
}
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
// Unsubscribe once. It blocks until the subscription goroutine takes the
|
||||
// request, and that goroutine may be sending an event, so keep draining.
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
client.Unsubscribe(c)
|
||||
close(done)
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-c:
|
||||
case <-done:
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
close(c)
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package api
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestStreamSlotsAreBoundedPerWallet(t *testing.T) {
|
||||
for i := 0; i < maxStreamsPerWallet; i++ {
|
||||
if !acquireStream("w1") {
|
||||
t.Fatalf("slot %d refused", i)
|
||||
}
|
||||
}
|
||||
if acquireStream("w1") {
|
||||
t.Error("slot beyond the limit was granted")
|
||||
}
|
||||
if !acquireStream("w2") {
|
||||
t.Error("another wallet must not be affected")
|
||||
}
|
||||
releaseStream("w1")
|
||||
if !acquireStream("w1") {
|
||||
t.Error("released slot was not reusable")
|
||||
}
|
||||
}
|
||||
+24
-5
@@ -7,6 +7,7 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -21,10 +22,26 @@ type PriceWatcher struct {
|
||||
}
|
||||
|
||||
var (
|
||||
Price map[string]float64
|
||||
P *PriceWatcher
|
||||
// price is written by the watcher and read by every fiat amount, so it is
|
||||
// only accessed through Get and set.
|
||||
price = make(map[string]float64)
|
||||
priceMu sync.RWMutex
|
||||
P *PriceWatcher
|
||||
)
|
||||
|
||||
// Get returns the last known price of currency, or 0 if there is none.
|
||||
func Get(currency string) float64 {
|
||||
priceMu.RLock()
|
||||
defer priceMu.RUnlock()
|
||||
return price[currency]
|
||||
}
|
||||
|
||||
func set(currency string, value float64) {
|
||||
priceMu.Lock()
|
||||
price[currency] = value
|
||||
priceMu.Unlock()
|
||||
}
|
||||
|
||||
func NewPriceWatcher() *PriceWatcher {
|
||||
pricewatcher := &PriceWatcher{
|
||||
client: &http.Client{
|
||||
@@ -47,7 +64,6 @@ func NewPriceWatcher() *PriceWatcher {
|
||||
}
|
||||
pricewatcher.Exchanges["coinbase"] = pricewatcher.GetCoinbasePrice
|
||||
pricewatcher.Exchanges["bitfinex"] = pricewatcher.GetBitfinexPrice
|
||||
Price = make(map[string]float64, 0)
|
||||
log.Infof("[PriceWatcher] Watcher started")
|
||||
P = pricewatcher
|
||||
return pricewatcher
|
||||
@@ -74,8 +90,11 @@ func (p *PriceWatcher) Watch() error {
|
||||
// log.Debugf("[PriceWatcher] %s %s price: %f", exchange, currency, fprice)
|
||||
time.Sleep(time.Second * time.Duration(2))
|
||||
}
|
||||
Price[currency] = avg_price / float64(n_responses)
|
||||
// log.Debugf("[PriceWatcher] Average %s price: %f", currency, Price[currency])
|
||||
if n_responses == 0 {
|
||||
// every exchange failed: keep the last known price
|
||||
continue
|
||||
}
|
||||
set(currency, avg_price/float64(n_responses))
|
||||
}
|
||||
time.Sleep(p.UpdateInterval)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package price
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Run with -race: a reader and a writer must not race on the price map.
|
||||
func TestPriceAccessIsRaceFree(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
set("USD", float64(i+1))
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
_ = Get("USD")
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
if Get("USD") != 2000 || Get("none") != 0 {
|
||||
t.Errorf("unexpected prices: %v %v", Get("USD"), Get("none"))
|
||||
}
|
||||
}
|
||||
@@ -103,10 +103,10 @@ func GetAmount(input string) (amount int64, err error) {
|
||||
log.Errorln(err)
|
||||
return 0, err
|
||||
}
|
||||
if !(price.Price[currency] > 0) {
|
||||
if !(price.Get(currency) > 0) {
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
}
|
||||
sats := fmount / price.Price[currency] * float64(100_000_000)
|
||||
sats := fmount / price.Get(currency) * float64(100_000_000)
|
||||
return checkAmount(sats, int64(sats))
|
||||
}
|
||||
}
|
||||
@@ -120,10 +120,10 @@ func GetAmount(input string) (amount int64, err error) {
|
||||
}
|
||||
|
||||
func SatoshisToFiat(amount int64, currency string) (fiat float64, err error) {
|
||||
if !(price.Price[currency] > 0) {
|
||||
if !(price.Get(currency) > 0) {
|
||||
return 0, fmt.Errorf("price is zero")
|
||||
}
|
||||
fiat = float64(amount) / 100_000_000 * price.Price[currency]
|
||||
fiat = float64(amount) / 100_000_000 * price.Get(currency)
|
||||
return fiat, nil
|
||||
}
|
||||
|
||||
|
||||
+30
-21
@@ -34,6 +34,9 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
|
||||
log.Traceln("[TICKET] I am not an admin of this group")
|
||||
return ctx, fmt.Errorf("no admin rights")
|
||||
}
|
||||
// state of one joiner. Joiners of the same chat must not share keys, or a
|
||||
// later joiner overwrites the payer of an earlier one.
|
||||
eventID := fmt.Sprintf("%s:%d", id, ctx.Sender().ID)
|
||||
user := LoadUser(ctx)
|
||||
// if the user does not have an account we put his Telegram user here
|
||||
// because we will need it after the invoice callback has been triggered in stopJoinTicketTimer
|
||||
@@ -72,7 +75,7 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
|
||||
ticketEvent := TicketEvent{
|
||||
// invoice event is used for invoice callbacks (do not kick if invoice is paid)
|
||||
InvoiceEvent: &InvoiceEvent{
|
||||
Base: storage.New(storage.ID(fmt.Sprintf("invoice-event:%s", id))),
|
||||
Base: storage.New(storage.ID(fmt.Sprintf("invoice-event:%s", eventID))),
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: ticket.Ticket.Price,
|
||||
@@ -84,7 +87,7 @@ func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Con
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
},
|
||||
Group: group,
|
||||
Base: storage.New(storage.ID(fmt.Sprintf("ticket-event:%s", id))),
|
||||
Base: storage.New(storage.ID(fmt.Sprintf("ticket-event:%s", eventID))),
|
||||
}
|
||||
captionText := fmt.Sprintf("⚠️ %s, this group requires you to pay *%d sat* to join. You have 15 minutes to pay or you will be kicked for one day.", GetUserStrMd(ctx.Message().Sender), ticket.Ticket.Price)
|
||||
|
||||
@@ -183,10 +186,33 @@ func (bot *TipBot) stopJoinTicketTimer(event Event) {
|
||||
}
|
||||
}
|
||||
|
||||
// expireTicket bans the member of an unpaid ticket and removes the ticket.
|
||||
func (bot *TipBot) expireTicket(ticket JoinTicket) {
|
||||
member, err := bot.Telegram.ChatMemberOf(ticket.Message.Chat, ticket.Sender)
|
||||
if err != nil {
|
||||
log.Errorln("🧨 could not fetch / ban chat member")
|
||||
return
|
||||
}
|
||||
// ban user
|
||||
err = bot.Telegram.Ban(ticket.Message.Chat, member)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
err = bot.Bunt.Delete(ticket.Key(), &ticket)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
bot.tryDeleteMessage(ticket.Message)
|
||||
}
|
||||
|
||||
// startTicketCallbackFunctionTimer will start a ticket which will ban users if the timer runs out.
|
||||
func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
|
||||
// check if ticket is already expired
|
||||
// A ticket that ran out while the bot was down is still unpaid (a paid
|
||||
// ticket is deleted), so it is enforced now instead of being skipped.
|
||||
if ticket.CreatedTimestamp.Add(defaultTicketDuration).Before(time.Now()) {
|
||||
if ticket.Message != nil && ticket.Message.Chat != nil {
|
||||
bot.expireTicket(ticket)
|
||||
}
|
||||
return
|
||||
}
|
||||
// ticket is valid. create duration until kick
|
||||
@@ -195,24 +221,7 @@ func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
|
||||
t := runtime.NewResettableFunction(ticket.Key(),
|
||||
runtime.WithTimer(time.NewTimer(ticketDuration)))
|
||||
// run the ticket callback function
|
||||
t.Do(func() {
|
||||
// ticket expired
|
||||
member, err := bot.Telegram.ChatMemberOf(ticket.Message.Chat, ticket.Sender)
|
||||
if err != nil {
|
||||
log.Errorln("🧨 could not fetch / ban chat member")
|
||||
return
|
||||
}
|
||||
// ban user
|
||||
err = bot.Telegram.Ban(ticket.Message.Chat, member)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
err = bot.Bunt.Delete(ticket.Key(), &ticket)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
bot.tryDeleteMessage(ticket.Message)
|
||||
})
|
||||
t.Do(func() { bot.expireTicket(ticket) })
|
||||
}
|
||||
|
||||
// restartPersistedTickets kicks of all ticket timers
|
||||
|
||||
Reference in New Issue
Block a user