1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
|
package admin
import (
"embed"
"fmt"
"html/template"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/adrian-lorenz/noxway/global"
"github.com/adrian-lorenz/noxway/middleware"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
//go:embed templates/*
var templateFiles embed.FS
const cookieName = "noxway_session"
// βββ Login rate limiter βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
type loginCounter struct {
count int
resetAt time.Time
}
var (
loginAttempts = make(map[string]*loginCounter)
loginMu sync.Mutex
)
const (
maxLoginAttempts = 10
loginWindow = 15 * time.Minute
)
func checkLoginRateLimit(ip string) bool {
loginMu.Lock()
defer loginMu.Unlock()
now := time.Now()
entry := loginAttempts[ip]
if entry == nil || now.After(entry.resetAt) {
loginAttempts[ip] = &loginCounter{count: 1, resetAt: now.Add(loginWindow)}
return true
}
entry.count++
return entry.count <= maxLoginAttempts
}
// βββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
func RegisterRoutes(r *gin.Engine) {
r.GET("/web/*any", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/admin/")
})
g := r.Group("/admin")
g.Use(middleware.SecurityHeaders())
g.GET("", func(c *gin.Context) {
_, err := c.Cookie(cookieName)
if err != nil {
c.Redirect(http.StatusFound, "/admin/login")
return
}
c.Redirect(http.StatusFound, "/admin/dashboard")
})
g.GET("/login", showLogin)
g.POST("/login", handleLogin)
g.GET("/logout", handleLogout)
auth := g.Group("", authMiddleware(), csrfMiddleware())
auth.GET("/dashboard", showDashboard)
auth.GET("/gateway", showGateway)
auth.POST("/gateway", saveGateway)
auth.GET("/endpoints", showEndpoints)
auth.GET("/logs", showLogs)
auth.GET("/reload", reloadConfig)
// HTMX partials
auth.GET("/htmx/dashboard", htmxDashboard)
auth.GET("/htmx/logs", htmxLogs)
auth.GET("/htmx/endpoint/edit/:svc/:ep", htmxEndpointEdit)
auth.POST("/htmx/endpoint/save", htmxEndpointSave)
auth.DELETE("/htmx/service/:uuid", htmxDeleteService)
auth.POST("/htmx/service/add", htmxAddService)
auth.POST("/htmx/endpoint/add/:svc", htmxAddEndpoint)
auth.DELETE("/htmx/endpoint/:svc/:ep", htmxDeleteEndpoint)
auth.GET("/htmx/endpoint/cancel", htmxCancelEdit)
auth.GET("/htmx/endpoints-table", htmxEndpointsTable)
auth.GET("/htmx/waf/edit/:svc", htmxWAFEdit)
auth.POST("/htmx/waf/save/:svc", htmxWAFSave)
auth.POST("/htmx/gateway", htmxSaveGateway)
auth.POST("/htmx/cert/retrieve", htmxRetrieveCert)
}
// βββ Middleware βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
func authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token, err := c.Cookie(cookieName)
if err != nil || !validateToken(token) {
if c.GetHeader("HX-Request") == "true" {
c.Header("HX-Redirect", "/admin/login")
c.AbortWithStatus(http.StatusUnauthorized)
} else {
c.Redirect(http.StatusFound, "/admin/login")
c.Abort()
}
return
}
c.Next()
}
}
// csrfMiddleware protects HTMX state-changing endpoints from CSRF.
// All POST/DELETE/PATCH/PUT requests under /admin/htmx/* must carry the
// HX-Request: true header, which cross-origin form submissions cannot set.
func csrfMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
if method == http.MethodGet || method == http.MethodHead || method == http.MethodOptions {
c.Next()
return
}
if strings.HasPrefix(c.Request.URL.Path, "/admin/htmx/") {
if c.GetHeader("HX-Request") != "true" {
c.AbortWithStatus(http.StatusForbidden)
return
}
}
c.Next()
}
}
func validateToken(tokenStr string) bool {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
return []byte(os.Getenv("JWTSECRET")), nil
})
if err != nil || !token.Valid {
return false
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return false
}
if exp, ok := claims["exp"].(float64); ok {
if time.Now().Unix() > int64(exp) {
return false
}
}
return claims["role"] == "admin"
}
// βββ Auth handlers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
func showLogin(c *gin.Context) {
renderLogin(c, "")
}
func handleLogin(c *gin.Context) {
ip := middleware.GetIP(c)
if !checkLoginRateLimit(ip) {
renderLoginError(c, "Too many login attempts. Please try again later.")
return
}
username := c.PostForm("username")
password := c.PostForm("password")
cfg := global.GetConfig()
if len(cfg.SystemWhitelist) > 0 || len(cfg.SystemWhitelistDNS) > 0 {
allowed := false
for _, w := range cfg.SystemWhitelist {
if w == ip {
allowed = true
break
}
}
if !allowed {
renderLoginError(c, "Access not allowed from your IP")
return
}
}
for _, u := range global.Auth.Users {
if u.Username == username {
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)); err == nil && u.Role == "admin" {
tokenStr, err := createToken(username, u.Role)
if err != nil {
renderLoginError(c, "Internal error")
return
}
setSessionCookie(c, tokenStr, int((8 * time.Hour).Seconds()))
c.Header("HX-Redirect", "/admin/dashboard")
c.Status(http.StatusOK)
return
}
}
}
renderLoginError(c, "Invalid username or password")
}
func handleLogout(c *gin.Context) {
setSessionCookie(c, "", -1)
c.Redirect(http.StatusFound, "/admin/login")
}
// setSessionCookie writes the session cookie with SameSite=Strict.
// Secure flag is enabled when SSL is configured.
func setSessionCookie(c *gin.Context, value string, maxAge int) {
http.SetCookie(c.Writer, &http.Cookie{
Name: cookieName,
Value: value,
MaxAge: maxAge,
Path: "/",
HttpOnly: true,
Secure: global.GetConfig().SSL,
SameSite: http.SameSiteStrictMode,
})
}
func createToken(username, role string) (string, error) {
claims := jwt.MapClaims{
"issuer": "api-gateway",
"username": username,
"role": role,
"exp": time.Now().Add(8 * time.Hour).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(os.Getenv("JWTSECRET")))
}
func renderLogin(c *gin.Context, errMsg string) {
t, err := template.ParseFS(templateFiles, "templates/login.html")
if err != nil {
c.String(http.StatusInternalServerError, "template error: %v", err)
return
}
c.Header("Content-Type", "text/html; charset=utf-8")
_ = t.ExecuteTemplate(c.Writer, "login", gin.H{"Error": errMsg})
}
func renderLoginError(c *gin.Context, msg string) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusUnauthorized, `<div class="error">%s</div>`, msg)
}
// βββ Template helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
var funcMap = template.FuncMap{
"toJSON": toJSON,
"fmtTime": fmtTime,
"fmtMs": fmtMs,
"rateWindowMin": rateWindowMin,
"dict": templateDict,
}
func renderPage(c *gin.Context, page string, data any) {
t, err := template.New("").Funcs(funcMap).ParseFS(templateFiles,
"templates/layout.html",
"templates/components.html",
"templates/"+page+".html",
)
if err != nil {
c.String(http.StatusInternalServerError, "template error: %v", err)
return
}
c.Header("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(c.Writer, "layout", data); err != nil {
c.String(http.StatusInternalServerError, "render error: %v", err)
}
}
func renderPartial(c *gin.Context, tmplName string, data any, files ...string) {
fullPaths := make([]string, len(files))
for i, f := range files {
fullPaths[i] = "templates/" + f
}
t, err := template.New("").Funcs(funcMap).ParseFS(templateFiles, fullPaths...)
if err != nil {
c.String(http.StatusInternalServerError, "template error: %v", err)
return
}
c.Header("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(c.Writer, tmplName, data); err != nil {
c.String(http.StatusInternalServerError, "render error: %v", err)
}
}
|