auth refactor

This commit is contained in:
callebtc
2022-08-22 09:09:53 +02:00
parent f11ac3d807
commit 8180d3cfae
6 changed files with 45 additions and 80 deletions
+1
View File
@@ -9,6 +9,7 @@ bot:
lnurl_public_host_name: "mylnurl.com"
lnurl_server: "https://mylnurl.com"
lnurl_image: true
admin_api_host: localhost:6060
telegram:
message_dispose_duration: 10
api_key: "1234"
+27 -15
View File
@@ -30,15 +30,24 @@ type AuthType struct {
}
var AuthTypeBasic = AuthType{Type: "Basic"}
var AuthTypeBearerBase64 = AuthType{Type: "Basic", Decoder: base64.StdEncoding.DecodeString}
var AuthTypeBearerBase64 = AuthType{Type: "Bearer", Decoder: base64.StdEncoding.DecodeString}
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, next http.HandlerFunc) http.HandlerFunc {
// invoice key or admin key requirement
type AccessKeyType struct {
Type string
}
var AccessKeyTypeInvoice = AccessKeyType{Type: "invoice"}
var AccessKeyTypeAdmin = AccessKeyType{Type: "admin"}
var AccessKeyTypeNone = AccessKeyType{Type: "none"} // no authorization required
func AuthorizationMiddleware(database *gorm.DB, authType AuthType, accessType AccessKeyType, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
// check if the user is banned
if auth == "" {
w.WriteHeader(401)
log.Warn("[AuthorizationMiddleware] no auth")
log.Warn("[api] no auth")
return
}
_, password, ok := parseAuth(authType, auth)
@@ -49,26 +58,29 @@ func AuthorizationMiddleware(database *gorm.DB, authType AuthType, next http.Han
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
w.WriteHeader(401)
log.Warnf("[AuthorizationMiddleware] Banned user %s. Not forwarding request", password)
log.Warnf("[api] Banned user %s. Not forwarding request", password)
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
tx := database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
if tx.Error != nil {
var tx *gorm.DB
if accessType.Type == "admin" {
tx = database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
} else if accessType.Type == "invoice" {
tx = database.Where("wallet_inkey = ? COLLATE NOCASE", password).First(user)
if tx.Error != nil {
log.Warnf("[AuthorizationMiddleware] could not load key: %v", tx.Error)
return
}
if r.URL.Path == "/api/v1/payinvoice" {
log.Warnf("[AuthorizationMiddleware] need admin key to pay invoice %s: %v", password, tx.Error)
return
}
} else {
log.Errorf("[api] route without access type")
w.WriteHeader(401)
return
}
if tx.Error != nil {
log.Warnf("[api] could not load access key: %v", tx.Error)
w.WriteHeader(401)
return
}
log.Debugf("[AuthorizationMiddleware] User: %s Path: %s", telegram.GetUserStr(user.Telegram), r.URL.Path)
log.Debugf("[api] User: %s Endpoint: %s %s", telegram.GetUserStr(user.Telegram), r.Method, r.URL.Path)
r = r.WithContext(context.WithValue(r.Context(), "user", user))
next.ServeHTTP(w, r)
}
+5 -4
View File
@@ -2,10 +2,11 @@ package api
import (
"encoding/json"
"gorm.io/gorm"
"net/http"
"time"
"gorm.io/gorm"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
@@ -33,7 +34,7 @@ func NewServer(address string) *Server {
apiServer.router = mux.NewRouter()
apiServer.httpServer.Handler = apiServer.router
go apiServer.httpServer.ListenAndServe()
log.Infof("[API] Server started at %s", address)
log.Infof("[api] Server started at %s", address)
return apiServer
}
@@ -43,8 +44,8 @@ func (w *Server) ListenAndServe() {
func (w *Server) PathPrefix(path string, handler http.Handler) {
w.router.PathPrefix(path).Handler(handler)
}
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, handler)))
func (w *Server) AppendAuthorizedRoute(path string, authType AuthType, accessType AccessKeyType, database *gorm.DB, handler func(http.ResponseWriter, *http.Request), methods ...string) {
r := w.router.HandleFunc(path, LoggingMiddleware("API", AuthorizationMiddleware(database, authType, accessType, handler)))
if len(methods) > 0 {
r.Methods(methods...)
}
+1
View File
@@ -30,6 +30,7 @@ type BotConfiguration struct {
LNURLHostName string `yaml:"lnurl_public_host_name"`
LNURLHostUrl *url.URL `yaml:"-"`
LNURLSendImage bool `yaml:"lnurl_image"`
AdminAPIHost string `yaml:"admin_api_host"`
}
type TelegramConfiguration struct {
-47
View File
@@ -1,15 +1,11 @@
package lndhub
import (
"encoding/base64"
"net/http"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal"
"github.com/LightningTipBot/LightningTipBot/internal/api"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/telegram"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
@@ -21,48 +17,5 @@ func New(bot *telegram.TipBot) LndHub {
return LndHub{database: bot.DB.Users}
}
func (w LndHub) Handle(writer http.ResponseWriter, request *http.Request) {
auth := request.Header.Get("Authorization")
// check if the user is banned
if auth != "" {
_, password, ok := parseBearerAuth(auth)
if !ok {
return
}
// first we make sure that the password is not already "banned_"
if strings.Contains(password, "_") || strings.HasPrefix(password, "banned_") {
log.Warnf("[LNDHUB] Banned user %s. Not forwarding request", password)
return
}
// then we check whether the "normal" password provided is in the database (it should be not if the user is banned)
user := &lnbits.User{}
tx := w.database.Where("wallet_adminkey = ? COLLATE NOCASE", password).First(user)
if tx.Error != nil {
log.Warnf("[LNDHUB] Could not get wallet admin key %s: %v", password, tx.Error)
return
}
log.Debugf("[LNDHUB] User: %s", telegram.GetUserStr(user.Telegram))
}
// if not, proxy the request
api.Proxy(writer, request, internal.Configuration.Lnbits.Url)
}
// parseBearerAuth parses an HTTP Basic Authentication string.
// "Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
func parseBearerAuth(auth string) (username, password string, ok bool) {
const prefix = "Bearer "
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
+11 -14
View File
@@ -60,23 +60,23 @@ func startApiServer(bot *telegram.TipBot) {
// append lndhub ctx functions
hub := lndhub.New(bot)
s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
s.AppendRoute(`/lndhub/ext`, hub.Handle)
//s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearer, bot.DB.Users, hub.Handle)
//s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearer, bot.DB.Users, hub.Handle)
//s.AppendRoute(`/lndhub/ext/{.*}`, hub.Handle)
// s.AppendRoute(`/lndhub/ext`, hub.Handle)
s.AppendAuthorizedRoute(`/lndhub/ext/{.*}`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
s.AppendAuthorizedRoute(`/lndhub/ext`, api.AuthTypeBearerBase64, api.AccessKeyTypeAdmin, bot.DB.Users, hub.Handle)
// starting api service
apiService := api.Service{Bot: bot}
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/invoicestream`, api.AuthTypeBasic, bot.DB.Users, apiService.InvoiceStream, http.MethodGet)
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, bot.DB.Users, apiService.Balance, http.MethodGet)
s.AppendAuthorizedRoute(`/api/v1/paymentstatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.PaymentStatus, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/invoicestatus/{payment_hash}`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStatus, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/payinvoice`, api.AuthTypeBasic, api.AccessKeyTypeAdmin, bot.DB.Users, apiService.PayInvoice, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/invoicestream`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.InvoiceStream, http.MethodGet)
s.AppendAuthorizedRoute(`/api/v1/createinvoice`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.CreateInvoice, http.MethodPost)
s.AppendAuthorizedRoute(`/api/v1/balance`, api.AuthTypeBasic, api.AccessKeyTypeInvoice, bot.DB.Users, apiService.Balance, http.MethodGet)
// start internal admin server
adminService := admin.New(bot)
internalAdminServer := api.NewServer("0.0.0.0:6060")
internalAdminServer := api.NewServer(internal.Configuration.Bot.AdminAPIHost)
internalAdminServer.AppendRoute("/mutex", mutex.ServeHTTP)
internalAdminServer.AppendRoute("/mutex/unlock/{id}", mutex.UnlockHTTP)
internalAdminServer.AppendRoute("/admin/ban/{id}", adminService.BanUser)
@@ -85,9 +85,6 @@ func startApiServer(bot *telegram.TipBot) {
}
func withMiddleware(mw func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return mw
}
func withRecovery() {
if r := recover(); r != nil {
log.Errorln("Recovered panic: ", r)