fix: auth stateless com HMAC — sessões sobrevivem restarts do container
Tokens assinados com APP_PASSWORD via HMAC-SHA256 eliminam o in-memory sessions map. Também corrige env vars (_USERNAME→APP_USERNAME). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
@@ -1,42 +1,64 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const cookieName = "cf_session"
|
const cookieName = "cf_session"
|
||||||
|
const sessionDuration = 30 * 24 * time.Hour
|
||||||
|
|
||||||
var (
|
func secret() []byte {
|
||||||
mu sync.RWMutex
|
// Use APP_PASSWORD as signing secret so tokens survive container restarts.
|
||||||
sessions = map[string]time.Time{}
|
return []byte(os.Getenv("APP_PASSWORD"))
|
||||||
)
|
|
||||||
|
|
||||||
func newToken() string {
|
|
||||||
b := make([]byte, 32)
|
|
||||||
rand.Read(b)
|
|
||||||
return hex.EncodeToString(b)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func validSession(token string) bool {
|
func signToken(expiry int64) string {
|
||||||
mu.RLock()
|
nonce := make([]byte, 8)
|
||||||
defer mu.RUnlock()
|
rand.Read(nonce)
|
||||||
exp, ok := sessions[token]
|
payload := fmt.Sprintf("%s.%d", hex.EncodeToString(nonce), expiry)
|
||||||
return ok && time.Now().Before(exp)
|
mac := hmac.New(sha256.New, secret())
|
||||||
|
mac.Write([]byte(payload))
|
||||||
|
sig := hex.EncodeToString(mac.Sum(nil))
|
||||||
|
return payload + "." + sig
|
||||||
|
}
|
||||||
|
|
||||||
|
func validToken(token string) bool {
|
||||||
|
parts := strings.SplitN(token, ".", 3)
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
payload := parts[0] + "." + parts[1]
|
||||||
|
expiry, err := strconv.ParseInt(parts[1], 10, 64)
|
||||||
|
if err != nil || time.Now().Unix() > expiry {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, secret())
|
||||||
|
mac.Write([]byte(payload))
|
||||||
|
expected := hex.EncodeToString(mac.Sum(nil))
|
||||||
|
return hmac.Equal([]byte(parts[2]), []byte(expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonErr(w http.ResponseWriter, status int, msg string) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"error": msg})
|
||||||
}
|
}
|
||||||
|
|
||||||
func RequireAuth(next http.Handler) http.Handler {
|
func RequireAuth(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
cookie, err := r.Cookie(cookieName)
|
cookie, err := r.Cookie(cookieName)
|
||||||
if err != nil || !validSession(cookie.Value) {
|
if err != nil || !validToken(cookie.Value) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
jsonErr(w, http.StatusUnauthorized, "unauthorized")
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
@@ -49,33 +71,28 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
jsonErr(w, http.StatusBadRequest, "corpo inválido")
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"error": "corpo inválido"})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
wantUser := os.Getenv("APP_USERNAME")
|
wantUser := os.Getenv("APP_USERNAME")
|
||||||
wantPass := os.Getenv("APP_PASSWORD")
|
wantPass := os.Getenv("APP_PASSWORD")
|
||||||
if wantUser == "" || body.Username != wantUser || body.Password != wantPass {
|
if wantUser == "" || body.Username != wantUser || body.Password != wantPass {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
jsonErr(w, http.StatusUnauthorized, "credenciais inválidas")
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"error": "credenciais inválidas"})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
token := newToken()
|
expiry := time.Now().Add(sessionDuration).Unix()
|
||||||
mu.Lock()
|
token := signToken(expiry)
|
||||||
sessions[token] = time.Now().Add(30 * 24 * time.Hour)
|
|
||||||
mu.Unlock()
|
|
||||||
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: cookieName,
|
Name: cookieName,
|
||||||
Value: token,
|
Value: token,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
|
Secure: true,
|
||||||
SameSite: http.SameSiteStrictMode,
|
SameSite: http.SameSiteStrictMode,
|
||||||
MaxAge: 30 * 24 * 60 * 60,
|
MaxAge: int(sessionDuration.Seconds()),
|
||||||
})
|
})
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
@@ -83,11 +100,6 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
if cookie, err := r.Cookie(cookieName); err == nil {
|
|
||||||
mu.Lock()
|
|
||||||
delete(sessions, cookie.Value)
|
|
||||||
mu.Unlock()
|
|
||||||
}
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: cookieName,
|
Name: cookieName,
|
||||||
Value: "",
|
Value: "",
|
||||||
@@ -99,10 +111,8 @@ func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func MeHandler(w http.ResponseWriter, r *http.Request) {
|
func MeHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
cookie, err := r.Cookie(cookieName)
|
cookie, err := r.Cookie(cookieName)
|
||||||
if err != nil || !validSession(cookie.Value) {
|
if err != nil || !validToken(cookie.Value) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
jsonErr(w, http.StatusUnauthorized, "unauthorized")
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
|||||||
Reference in New Issue
Block a user