57 lines
1.9 KiB
Go
57 lines
1.9 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
// The ban rewrites only the admin key. Every key of a banned user must be
|
|
// refused, the invoice key included, and a normal user must still pass.
|
|
func TestAuthorizationMiddlewareRefusesBannedUsersKeys(t *testing.T) {
|
|
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared&_banmw=1"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.AutoMigrate(&lnbits.User{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
users := []*lnbits.User{
|
|
{ID: "u1", Name: "111", Banned: true, Wallet: &lnbits.Wallet{ID: "w1", Adminkey: "banned_aaaaaaaaaaaaaaaa", Inkey: "bbbbbbbbbbbbbbbb"}},
|
|
{ID: "u2", Name: "222", Wallet: &lnbits.Wallet{ID: "w2", Adminkey: "cccccccccccccccc", Inkey: "dddddddddddddddd"}},
|
|
}
|
|
for _, u := range users {
|
|
if err := db.Create(u).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
call := func(access AccessKeyType, key string) int {
|
|
h := AuthorizationMiddleware(db, AuthTypeBasic, access, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })
|
|
req := httptest.NewRequest("GET", "/api/v1/balance", nil)
|
|
req.Header.Set("Authorization", "Basic "+key)
|
|
rr := httptest.NewRecorder()
|
|
h(rr, req)
|
|
return rr.Code
|
|
}
|
|
for _, c := range []struct {
|
|
access AccessKeyType
|
|
key string
|
|
want int
|
|
}{
|
|
{AccessKeyTypeInvoice, "bbbbbbbbbbbbbbbb", 401}, // banned user's invoice key
|
|
{AccessKeyTypeInvoice, "aaaaaaaaaaaaaaaa", 401}, // banned user's old admin key
|
|
{AccessKeyTypeAdmin, "aaaaaaaaaaaaaaaa", 401},
|
|
{AccessKeyTypeInvoice, "dddddddddddddddd", 200}, // normal user still works
|
|
{AccessKeyTypeAdmin, "cccccccccccccccc", 200},
|
|
} {
|
|
if got := call(c.access, c.key); got != c.want {
|
|
t.Errorf("%s key %s: got %d, want %d", c.access.Type, c.key, got, c.want)
|
|
}
|
|
}
|
|
}
|