Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1774,3 +1774,7 @@ func (api *api) GetForwards() (*GetForwardsResponse, error) {
NumForwards: uint64(numForwards),
}, nil
}

func (a *api) IsShuttingDown() bool {
return a.svc.IsShuttingDown()
}
1 change: 1 addition & 0 deletions api/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ type API interface {
ExecuteCustomNodeCommand(ctx context.Context, command string) (interface{}, error)
SendEvent(event string, properties interface{})
GetForwards() (*GetForwardsResponse, error)
IsShuttingDown() bool
}

type App struct {
Expand Down
17 changes: 10 additions & 7 deletions http/http_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/golang-jwt/jwt/v5"
echojwt "github.com/labstack/echo-jwt/v4"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
echoMiddleware "github.com/labstack/echo/v4/middleware"
"github.com/sirupsen/logrus"
"gorm.io/gorm"

Expand All @@ -23,6 +23,7 @@ import (
"github.com/getAlby/hub/events"
"github.com/getAlby/hub/logger"
"github.com/getAlby/hub/service"
"github.com/getAlby/hub/middleware"

"github.com/getAlby/hub/api"
"github.com/getAlby/hub/frontend"
Expand Down Expand Up @@ -63,20 +64,20 @@ func NewHttpService(svc service.Service, eventPublisher events.EventPublisher) *
func (httpSvc *HttpService) RegisterSharedRoutes(e *echo.Echo) {
e.HideBanner = true

e.Use(middleware.SecureWithConfig(middleware.SecureConfig{
e.Use(echoMiddleware.SecureWithConfig(echoMiddleware.SecureConfig{
ContentTypeNosniff: "nosniff",
XFrameOptions: "DENY",
ContentSecurityPolicy: "default-src 'self'; img-src 'self' https://uploads.getalby-assets.com https://getalby.com; connect-src 'self' https://api.getalby.com https://getalby.com https://zapplanner.albylabs.com wss://relay.getalby.com/v1; frame-src https://embed.bitrefill.com",
ReferrerPolicy: "no-referrer",
}))
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
e.Use(echoMiddleware.RequestLoggerWithConfig(echoMiddleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
LogRemoteIP: true,
LogUserAgent: true,
LogHost: true,
LogRequestID: true,
LogValuesFunc: func(c echo.Context, values middleware.RequestLoggerValues) error {
LogValuesFunc: func(c echo.Context, values echoMiddleware.RequestLoggerValues) error {
logger.Logger.WithFields(logrus.Fields{
"uri": values.URI,
"status": values.Status,
Expand All @@ -89,15 +90,17 @@ func (httpSvc *HttpService) RegisterSharedRoutes(e *echo.Echo) {
},
}))

e.Use(middleware.Recover())
e.Use(middleware.RequestID())
e.Use(middleware.ShutdownMiddleware(httpSvc.api))

e.Use(echoMiddleware.Recover())
e.Use(echoMiddleware.RequestID())

e.GET("/api/info", httpSvc.infoHandler)
e.POST("/api/setup", httpSvc.setupHandler)
e.POST("/api/restore", httpSvc.restoreBackupHandler)

// allow one unlock request per second
unlockRateLimiter := middleware.RateLimiter(middleware.NewRateLimiterMemoryStore(1))
unlockRateLimiter := echoMiddleware.RateLimiter(echoMiddleware.NewRateLimiterMemoryStore(1))
e.POST("/api/start", httpSvc.startHandler, unlockRateLimiter)
e.POST("/api/unlock", httpSvc.unlockHandler, unlockRateLimiter)
e.POST("/api/backup", httpSvc.createBackupHandler, unlockRateLimiter)
Expand Down
147 changes: 147 additions & 0 deletions http/http_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ import (
"github.com/getAlby/hub/config"
"github.com/getAlby/hub/constants"
"github.com/getAlby/hub/events"
"github.com/getAlby/hub/lnclient"
"github.com/getAlby/hub/logger"
"github.com/getAlby/hub/tests/db"
"github.com/getAlby/hub/tests/mocks"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

Expand All @@ -41,6 +43,7 @@ func TestUnlock_IncorrectPassword(t *testing.T) {
mockSvc.On("GetKeys").Return(mocks.NewMockKeys(t))
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mocks.NewMockAlbyOAuthService(t))
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -75,6 +78,7 @@ func TestUnlock_UnknownPermission(t *testing.T) {
mockSvc.On("GetKeys").Return(mocks.NewMockKeys(t))
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mocks.NewMockAlbyOAuthService(t))
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -108,6 +112,7 @@ func TestGetApps_NoToken(t *testing.T) {
mockSvc.On("GetKeys").Return(mocks.NewMockKeys(t))
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mocks.NewMockAlbyOAuthService(t))
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -139,6 +144,7 @@ func TestGetApps_ReadonlyPermission(t *testing.T) {
mockSvc.On("GetKeys").Return(mocks.NewMockKeys(t))
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mocks.NewMockAlbyOAuthService(t))
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -192,6 +198,7 @@ func TestGetApps_FullPermission(t *testing.T) {
mockSvc.On("GetKeys").Return(mocks.NewMockKeys(t))
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mocks.NewMockAlbyOAuthService(t))
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -243,6 +250,7 @@ func TestCreateApp_NoToken(t *testing.T) {
mockSvc.On("GetKeys").Return(mocks.NewMockKeys(t))
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mocks.NewMockAlbyOAuthService(t))
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -284,6 +292,7 @@ func TestCreateApp_FullPermission(t *testing.T) {
mockSvc.On("GetKeys").Return(mockKeys)
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mockAlbyOAuthService)
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -345,6 +354,7 @@ func TestCreateApp_ReadonlyPermission(t *testing.T) {
mockSvc.On("GetKeys").Return(mockKeys)
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mockAlbyOAuthService)
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)
Expand Down Expand Up @@ -381,3 +391,140 @@ func TestCreateApp_ReadonlyPermission(t *testing.T) {

assert.Equal(t, http.StatusForbidden, rec2.Code)
}

func TestShutdown_BlockedEndpoint(t *testing.T) {
e := echo.New()
logger.Init(strconv.Itoa(int(logrus.DebugLevel)))
mockSvc := mocks.NewMockService(t)
gormDb, err := db.NewDB(t)
require.NoError(t, err)
defer db.CloseDB(gormDb)

mockEventPublisher := events.NewEventPublisher()

mockConfig := mocks.NewMockConfig(t)
mockConfig.On("GetEnv").Return(&config.AppConfig{})
mockConfig.On("CheckUnlockPassword", "123").Return(true)
mockConfig.On("GetJWTSecret").Return("dummy secret", nil)

mockKeys := mocks.NewMockKeys(t)

mockAlbyOAuthService := mocks.NewMockAlbyOAuthService(t)

mockSvc.On("GetDB").Return(gormDb)
mockSvc.On("GetConfig").Return(mockConfig)
mockSvc.On("GetKeys").Return(mockKeys)
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mockAlbyOAuthService)
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)

requestBody := api.UnlockRequest{UnlockPassword: "123", Permission: "readonly"}
jsonBody, _ := json.Marshal(requestBody)
req := httptest.NewRequest(http.MethodPost, "/api/unlock", bytes.NewBuffer(jsonBody))
req.Header.Set("Content-Type", "application/json") // Set Content-Type header
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)

// mock node sutting down after unlock
mockSvc.On("IsShuttingDown").Unset()
mockSvc.On("IsShuttingDown").Return(true)

body, err := io.ReadAll(rec.Body)
require.NoError(t, err)

type authTokenResponse struct {
Token string `json:"token"`
}

var unlockAuthTokenResponse authTokenResponse
err = json.Unmarshal(body, &unlockAuthTokenResponse)
require.NoError(t, err)
assert.NotEmpty(t, unlockAuthTokenResponse.Token)

req2 := httptest.NewRequest(http.MethodGet, "/api/peers", nil)
req2.Header.Set("Authorization", "Bearer "+unlockAuthTokenResponse.Token)
req2.Header.Set("Content-Type", "application/json")

rec2 := httptest.NewRecorder()
e.ServeHTTP(rec2, req2)

assert.Equal(t, http.StatusServiceUnavailable, rec2.Code)
assert.Contains(t, rec2.Body.String(), "Node is shutting down")

}

func TestShutdown_AllowedEndpoint(t *testing.T) {
e := echo.New()
logger.Init(strconv.Itoa(int(logrus.DebugLevel)))
mockSvc := mocks.NewMockService(t)
gormDb, err := db.NewDB(t)
require.NoError(t, err)
defer db.CloseDB(gormDb)

mockEventPublisher := events.NewEventPublisher()

mockConfig := mocks.NewMockConfig(t)
mockConfig.On("GetEnv").Return(&config.AppConfig{})
mockConfig.On("CheckUnlockPassword", "123").Return(true)
mockConfig.On("GetJWTSecret").Return("dummy secret", nil)

mockKeys := mocks.NewMockKeys(t)

mockAlbyOAuthService := mocks.NewMockAlbyOAuthService(t)

mockSvc.On("GetDB").Return(gormDb)
mockSvc.On("GetConfig").Return(mockConfig)
mockSvc.On("GetKeys").Return(mockKeys)
mockSvc.On("GetAlbySvc").Return(mocks.NewMockAlbyService(t))
mockSvc.On("GetAlbyOAuthSvc").Return(mockAlbyOAuthService)
mockSvc.On("IsShuttingDown").Return(false)

httpSvc := NewHttpService(mockSvc, mockEventPublisher)
httpSvc.RegisterSharedRoutes(e)

requestBody := api.UnlockRequest{UnlockPassword: "123", Permission: "readonly"}
jsonBody, _ := json.Marshal(requestBody)
req := httptest.NewRequest(http.MethodPost, "/api/unlock", bytes.NewBuffer(jsonBody))
req.Header.Set("Content-Type", "application/json") // Set Content-Type header
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusOK, rec.Code)

mockLNClient := mocks.NewMockLNClient(t)
mockLNClient.On("GetNodeStatus", mock.Anything).Return(&lnclient.NodeStatus{
IsReady: true, // or false, doesn't matter
InternalNodeStatus: map[string]interface{}{"running": true},
}, nil)

// mock node sutting down after unlock
mockSvc.On("IsShuttingDown").Unset()
mockSvc.On("IsShuttingDown").Return(true)
mockSvc.On("GetLNClient").Return(mockLNClient)

body, err := io.ReadAll(rec.Body)
require.NoError(t, err)

type authTokenResponse struct {
Token string `json:"token"`
}

var unlockAuthTokenResponse authTokenResponse
err = json.Unmarshal(body, &unlockAuthTokenResponse)
require.NoError(t, err)
assert.NotEmpty(t, unlockAuthTokenResponse.Token)

req2 := httptest.NewRequest(http.MethodGet, "/api/node/status", nil)
req2.Header.Set("Authorization", "Bearer "+unlockAuthTokenResponse.Token)
req2.Header.Set("Content-Type", "application/json")

rec2 := httptest.NewRecorder()
e.ServeHTTP(rec2, req2)

assert.Equal(t, http.StatusOK, rec2.Code)
}
39 changes: 39 additions & 0 deletions middleware/shutdown.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package middleware

import (
"net/http"
"strings"

"github.com/labstack/echo/v4"
)

type ShutdownNotifier interface {
IsShuttingDown() bool
}

func ShutdownMiddleware(notifier ShutdownNotifier) echo.MiddlewareFunc {

// whitelist routes that can still be called when the node is shutting down
safeRoutes := map[string]bool{
"/api/health": true,
"/api/node/status": true,
"/api/info": true,
}

return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
path := c.Request().URL.Path

if safeRoutes[path] || strings.HasPrefix(path, "/api/alby/") {
return next(c)
}

if notifier.IsShuttingDown() {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
"message": "Node is shutting down. Please wait.",
})
}
return next(c)
}
}
}
1 change: 1 addition & 0 deletions service/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ type Service interface {
GetKeys() keys.Keys
GetRelayStatuses() []RelayStatus
GetStartupState() string
IsShuttingDown() bool
}
6 changes: 6 additions & 0 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"

"github.com/adrg/xdg"
Expand Down Expand Up @@ -46,6 +47,7 @@ type service struct {
keys keys.Keys
relayStatuses []RelayStatus
startupState string
shuttingDown atomic.Bool
}

func NewService(ctx context.Context) (*service, error) {
Expand Down Expand Up @@ -279,6 +281,10 @@ func (svc *service) GetStartupState() string {
return svc.startupState
}

func (svc *service) IsShuttingDown() bool {
return svc.shuttingDown.Load()
}

func (svc *service) removeExcessEvents() {
logger.Logger.Debug("Cleaning up excess events")

Expand Down
2 changes: 2 additions & 0 deletions service/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import (
func (svc *service) StopApp() {
if svc.appCancelFn != nil {
logger.Logger.Info("Stopping app...")
svc.shuttingDown.Store(true)
svc.appCancelFn()
svc.wg.Wait()
svc.shuttingDown.Store(false)
logger.Logger.Info("app stopped")
}
}
Expand Down
Loading
Loading