Add auth-managed proxy UI improvements

This commit is contained in:
2026-04-03 20:58:54 -04:00
parent 7ed709ad3d
commit f2a246ce6b
9 changed files with 1384 additions and 82 deletions

278
internal/web/auth.go Normal file
View File

@ -0,0 +1,278 @@
package web
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"time"
"infinite-noodle/internal/assets"
"infinite-noodle/internal/noodle"
)
const sessionCookieName = "infinite_noodle_session"
var errInvalidCredentials = errors.New("invalid credentials")
type Auth struct {
db *noodle.Database
secret []byte
}
type loginPageData struct {
Error string
}
type authUser struct {
Username string
Role string
}
func NewAuth(db *noodle.Database) (*Auth, error) {
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
return &Auth{
db: db,
secret: secret,
}, nil
}
func HashPassword(password string) string {
sum := sha256.Sum256([]byte(password))
return hex.EncodeToString(sum[:])
}
func (a *Auth) EnsureDefaultUser() error {
users := a.db.GetAllUsers()
if len(users) == 0 {
user := noodle.User{
Id: a.db.MakeID(),
Username: "admin",
Role: noodle.UserRoleAdmin,
PasswordHash: HashPassword("admin"),
CreatedAt: time.Now().UTC(),
}
if err := a.db.AddUser(user); err != nil {
return err
}
log.Printf("Created default user username=%q password=%q", user.Username, "admin")
return nil
}
var hasAdmin bool
for _, user := range users {
updated := false
if user.Role == "" {
user.Role = noodle.UserRoleRegular
updated = true
}
if user.Username == "admin" {
user.Role = noodle.UserRoleAdmin
updated = true
}
if updated {
if err := a.db.UpdateUser(user); err != nil {
return err
}
}
if user.Role == noodle.UserRoleAdmin {
hasAdmin = true
}
}
if hasAdmin {
return nil
}
user := noodle.User{
Id: a.db.MakeID(),
Username: "admin",
Role: noodle.UserRoleAdmin,
PasswordHash: HashPassword("admin"),
CreatedAt: time.Now().UTC(),
}
if err := a.db.AddUser(user); err != nil {
return err
}
log.Printf("Created fallback admin user username=%q password=%q", user.Username, "admin")
return nil
}
func (a *Auth) RequireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if _, ok := a.CurrentUser(req); !ok {
http.Redirect(w, req, "/login", http.StatusSeeOther)
return
}
next(w, req)
}
}
func (a *Auth) RequireAdmin(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
user, ok := a.CurrentUser(req)
if !ok {
http.Redirect(w, req, "/login", http.StatusSeeOther)
return
}
if user.Role != noodle.UserRoleAdmin {
http.Error(w, "admin access required", http.StatusForbidden)
return
}
next(w, req)
}
}
func (a *Auth) CurrentUser(req *http.Request) (authUser, bool) {
cookie, err := req.Cookie(sessionCookieName)
if err != nil {
return authUser{}, false
}
username, ok := a.verifyCookieValue(cookie.Value)
if !ok {
return authUser{}, false
}
user, err := a.db.GetUserByUsername(username)
if err != nil || user.Username == "" {
return authUser{}, false
}
role := user.Role
if role == "" {
role = noodle.UserRoleRegular
}
return authUser{
Username: user.Username,
Role: role,
}, true
}
func (a *Auth) HandleLogin() http.HandlerFunc {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodGet {
if _, ok := a.CurrentUser(req); ok {
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
if err := tmpl.ExecuteTemplate(w, "login.html", loginPageData{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
username := strings.TrimSpace(req.FormValue("username"))
password := req.FormValue("password")
if username == "" || password == "" {
w.WriteHeader(http.StatusUnauthorized)
if err := tmpl.ExecuteTemplate(w, "login.html", loginPageData{Error: "Username and password are required."}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
if err := a.Login(w, username, password); err != nil {
w.WriteHeader(http.StatusUnauthorized)
if err := tmpl.ExecuteTemplate(w, "login.html", loginPageData{Error: "Invalid username or password."}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
http.Redirect(w, req, "/", http.StatusSeeOther)
}
}
func (a *Auth) HandleLogout() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
a.ClearSession(w)
http.Redirect(w, req, "/login", http.StatusSeeOther)
}
}
func (a *Auth) Login(w http.ResponseWriter, username, password string) error {
user, err := a.db.GetUserByUsername(username)
if err != nil {
return errInvalidCredentials
}
if user.PasswordHash != HashPassword(password) {
return errInvalidCredentials
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: a.cookieValue(username),
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: int((24 * time.Hour).Seconds()),
})
return nil
}
func (a *Auth) ClearSession(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
}
func (a *Auth) cookieValue(username string) string {
mac := hmac.New(sha256.New, a.secret)
mac.Write([]byte(username))
sig := mac.Sum(nil)
payload := fmt.Sprintf("%s:%s", username, hex.EncodeToString(sig))
return base64.RawURLEncoding.EncodeToString([]byte(payload))
}
func (a *Auth) verifyCookieValue(value string) (string, bool) {
decoded, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return "", false
}
parts := strings.SplitN(string(decoded), ":", 2)
if len(parts) != 2 || parts[0] == "" {
return "", false
}
expected := a.cookieValue(parts[0])
return parts[0], hmac.Equal([]byte(expected), []byte(value))
}

View File

@ -19,17 +19,29 @@ func StaticFiles() fs.FS {
}
type indexPageData struct {
Username string
Role string
ClientIP string
Noodles []noodle.Noodle
}
func HandleMain(db *noodle.Database, pc *chan noodle.Noodle) func(w http.ResponseWriter, req *http.Request) {
type userConfigPageData struct {
Username string
Role string
Users []noodle.User
Error string
}
func HandleMain(db *noodle.Database, pc *chan noodle.Noodle, auth *Auth) func(w http.ResponseWriter, req *http.Request) {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
data := indexPageData{
Username: currentUser.Username,
Role: currentUser.Role,
ClientIP: clientIPFromRequest(req),
Noodles: db.GetAll(),
}
@ -39,25 +51,231 @@ func HandleMain(db *noodle.Database, pc *chan noodle.Noodle) func(w http.Respons
}
}
func HandleUsers(auth *Auth, db *noodle.Database) func(w http.ResponseWriter, req *http.Request) {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
data := userConfigPageData{
Username: currentUser.Username,
Role: currentUser.Role,
}
if currentUser.Role == noodle.UserRoleAdmin {
data.Users = db.GetAllUsers()
}
if err := tmpl.ExecuteTemplate(w, "users.html", data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func HandleAddUser(auth *Auth, db *noodle.Database) func(w http.ResponseWriter, req *http.Request) {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
username := strings.TrimSpace(req.FormValue("username"))
password := req.FormValue("password")
role := normalizeUserRole(req.FormValue("role"))
if username == "" || password == "" {
renderUsersPage(w, tmpl, db, currentUser, "username and password are required", http.StatusBadRequest)
return
}
if role == "" {
renderUsersPage(w, tmpl, db, currentUser, "invalid user role", http.StatusBadRequest)
return
}
user := noodle.User{
Id: db.MakeID(),
Username: username,
Role: role,
PasswordHash: HashPassword(password),
CreatedAt: time.Now().UTC(),
}
if err := db.AddUser(user); err != nil {
renderUsersPage(w, tmpl, db, currentUser, err.Error(), http.StatusBadRequest)
return
}
http.Redirect(w, req, "/users", http.StatusSeeOther)
}
}
func HandleSetUserRole(auth *Auth, db *noodle.Database) func(w http.ResponseWriter, req *http.Request) {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
username := strings.TrimSpace(req.FormValue("username"))
role := normalizeUserRole(req.FormValue("role"))
if username == "" {
renderUsersPage(w, tmpl, db, currentUser, "username is required", http.StatusBadRequest)
return
}
if role == "" {
renderUsersPage(w, tmpl, db, currentUser, "invalid user role", http.StatusBadRequest)
return
}
if _, err := db.SetUserRole(username, role); err != nil {
renderUsersPage(w, tmpl, db, currentUser, err.Error(), http.StatusBadRequest)
return
}
http.Redirect(w, req, "/users", http.StatusSeeOther)
}
}
func HandleChangePassword(auth *Auth, db *noodle.Database) func(w http.ResponseWriter, req *http.Request) {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
targetUsername := strings.TrimSpace(req.FormValue("username"))
password := req.FormValue("password")
confirmPassword := req.FormValue("confirm_password")
if targetUsername == "" || password == "" {
renderUsersPage(w, tmpl, db, currentUser, "username and password are required", http.StatusBadRequest)
return
}
if confirmPassword != "" && password != confirmPassword {
renderUsersPage(w, tmpl, db, currentUser, "password confirmation does not match", http.StatusBadRequest)
return
}
if currentUser.Role != noodle.UserRoleAdmin && targetUsername != currentUser.Username {
http.Error(w, "cannot change another user's password", http.StatusForbidden)
return
}
if _, err := db.SetUserPassword(targetUsername, HashPassword(password)); err != nil {
renderUsersPage(w, tmpl, db, currentUser, err.Error(), http.StatusBadRequest)
return
}
http.Redirect(w, req, "/users", http.StatusSeeOther)
}
}
func HandleDeleteUser(auth *Auth, db *noodle.Database) func(w http.ResponseWriter, req *http.Request) {
tmpl, err := template.ParseFS(assets.FS, "templates/*.html")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
}
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if currentUser.Role != noodle.UserRoleAdmin {
http.Error(w, "admin access required", http.StatusForbidden)
return
}
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
username := strings.TrimSpace(req.FormValue("username"))
if username == "" {
renderUsersPage(w, tmpl, db, currentUser, "username is required", http.StatusBadRequest)
return
}
if _, err := db.DeleteUser(username); err != nil {
renderUsersPage(w, tmpl, db, currentUser, err.Error(), http.StatusBadRequest)
return
}
if username == currentUser.Username {
auth.ClearSession(w)
http.Redirect(w, req, "/login", http.StatusSeeOther)
return
}
http.Redirect(w, req, "/users", http.StatusSeeOther)
}
}
func HandleDelete(db *noodle.Database, pc *chan noodle.Noodle) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
vals, ok := q["id"]
if ok {
id := vals[0]
item := db.Get(id)
item.IsUp = false
*pc <- item
log.Printf("Deleting noodle=%v", item)
db.Delete(item.Id)
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
}
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
id := strings.TrimSpace(req.FormValue("id"))
if id == "" {
http.Error(w, "missing noodle id", http.StatusBadRequest)
return
}
item, err := db.DeleteByID(id)
if err != nil {
http.Error(w, "noodle not found", http.StatusNotFound)
return
}
item.IsUp = false
*pc <- item
log.Printf("Deleting noodle=%v", item)
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
}
}
func HandleAdd(db *noodle.Database, pc *chan noodle.Noodle) func(w http.ResponseWriter, req *http.Request) {
func HandleAdd(db *noodle.Database, pc *chan noodle.Noodle, auth *Auth) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
currentUser, _ := auth.CurrentUser(req)
if req.Method != http.MethodPost {
http.Error(w, "", http.StatusMethodNotAllowed)
return
@ -73,12 +291,20 @@ func HandleAdd(db *noodle.Database, pc *chan noodle.Noodle) func(w http.Response
http.Error(w, "invalid listen port", http.StatusBadRequest)
return
}
if !isValidPort(listenPort) {
http.Error(w, "listen port must be between 1 and 65535", http.StatusBadRequest)
return
}
destPort, err := strconv.Atoi(strings.TrimSpace(req.FormValue("dest_port")))
if err != nil {
http.Error(w, "invalid destination port", http.StatusBadRequest)
return
}
if !isValidPort(destPort) {
http.Error(w, "destination port must be between 1 and 65535", http.StatusBadRequest)
return
}
expiration, err := time.ParseDuration(strings.TrimSpace(req.FormValue("expiration")))
if err != nil {
@ -92,16 +318,18 @@ func HandleAdd(db *noodle.Database, pc *chan noodle.Noodle) func(w http.Response
return
}
clientIP := clientIPFromRequest(req)
src := strings.TrimSpace(req.FormValue("src"))
if src == clientIP {
src = clientIP
}
if src != "All" && net.ParseIP(src) == nil {
src, err := normalizeSourceList(req.FormValue("src"))
if err != nil {
http.Error(w, "invalid source restriction", http.StatusBadRequest)
return
}
destHost := strings.TrimSpace(req.FormValue("dest_host"))
if destHost == "" {
http.Error(w, "destination host is required", http.StatusBadRequest)
return
}
item := noodle.Noodle{
Id: db.MakeID(),
Name: strings.TrimSpace(req.FormValue("name")),
@ -109,9 +337,10 @@ func HandleAdd(db *noodle.Database, pc *chan noodle.Noodle) func(w http.Response
Src: src,
ListenPort: listenPort,
DestPort: destPort,
DestHost: strings.TrimSpace(req.FormValue("dest_host")),
DestHost: destHost,
Expiration: expiration,
IsUp: true,
CreatedBy: currentUser.Username,
}
if err := db.Add(item); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
@ -141,17 +370,11 @@ func HandleToggle(db *noodle.Database, pc *chan noodle.Noodle) func(w http.Respo
return
}
item := db.Get(id)
if item.Id == "" {
item, err := db.SetIsUp(id, req.FormValue("is_up") == "on")
if err != nil {
http.Error(w, "noodle not found", http.StatusNotFound)
return
}
item.IsUp = req.FormValue("is_up") == "on"
if err := db.Update(item); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
*pc <- item
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
@ -188,3 +411,69 @@ func clientIPFromRequest(req *http.Request) string {
return "127.0.0.1"
}
func isValidPort(port int) bool {
return port >= 1 && port <= 65535
}
func normalizeSourceList(raw string) (string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", nil
}
if strings.EqualFold(raw, "All") {
return "All", nil
}
parts := strings.Split(raw, ",")
normalized := make([]string, 0, len(parts))
for _, part := range parts {
entry := strings.TrimSpace(part)
if entry == "" {
return "", net.InvalidAddrError("empty source")
}
if strings.Contains(entry, "/") {
_, network, err := net.ParseCIDR(entry)
if err != nil {
return "", err
}
normalized = append(normalized, network.String())
continue
}
parsed := net.ParseIP(entry)
if parsed == nil {
return "", net.InvalidAddrError(entry)
}
normalized = append(normalized, parsed.String())
}
return strings.Join(normalized, ", "), nil
}
func normalizeUserRole(role string) string {
switch strings.ToLower(strings.TrimSpace(role)) {
case noodle.UserRoleAdmin:
return noodle.UserRoleAdmin
case noodle.UserRoleRegular:
return noodle.UserRoleRegular
default:
return ""
}
}
func renderUsersPage(w http.ResponseWriter, tmpl *template.Template, db *noodle.Database, currentUser authUser, message string, status int) {
w.WriteHeader(status)
data := userConfigPageData{
Username: currentUser.Username,
Role: currentUser.Role,
Error: message,
}
if currentUser.Role == noodle.UserRoleAdmin {
data.Users = db.GetAllUsers()
}
if err := tmpl.ExecuteTemplate(w, "users.html", data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}