Add full monorepo: virtual-banker, backend, frontend, docs, scripts, deployment
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
123
backend/api/middleware/auth.go
Normal file
123
backend/api/middleware/auth.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/explorer/backend/auth"
|
||||
"github.com/explorer/backend/featureflags"
|
||||
)
|
||||
|
||||
// AuthMiddleware handles authentication and authorization
|
||||
type AuthMiddleware struct {
|
||||
walletAuth *auth.WalletAuth
|
||||
}
|
||||
|
||||
// NewAuthMiddleware creates a new auth middleware
|
||||
func NewAuthMiddleware(walletAuth *auth.WalletAuth) *AuthMiddleware {
|
||||
return &AuthMiddleware{
|
||||
walletAuth: walletAuth,
|
||||
}
|
||||
}
|
||||
|
||||
// RequireAuth is middleware that requires authentication
|
||||
func (m *AuthMiddleware) RequireAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
address, track, err := m.extractAuth(r)
|
||||
if err != nil {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
|
||||
// Add user context
|
||||
ctx := context.WithValue(r.Context(), "user_address", address)
|
||||
ctx = context.WithValue(ctx, "user_track", track)
|
||||
ctx = context.WithValue(ctx, "authenticated", true)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// RequireTrack is middleware that requires a specific track level
|
||||
func (m *AuthMiddleware) RequireTrack(requiredTrack int) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Extract track from context (set by RequireAuth or OptionalAuth)
|
||||
track, ok := r.Context().Value("user_track").(int)
|
||||
if !ok {
|
||||
track = 1 // Default to Track 1 (public)
|
||||
}
|
||||
|
||||
if !featureflags.HasAccess(track, requiredTrack) {
|
||||
writeForbidden(w, requiredTrack)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// OptionalAuth is middleware that optionally authenticates (for Track 1 endpoints)
|
||||
func (m *AuthMiddleware) OptionalAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
address, track, err := m.extractAuth(r)
|
||||
if err != nil {
|
||||
// No auth provided, default to Track 1 (public)
|
||||
ctx := context.WithValue(r.Context(), "user_address", "")
|
||||
ctx = context.WithValue(ctx, "user_track", 1)
|
||||
ctx = context.WithValue(ctx, "authenticated", false)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
|
||||
// Auth provided, add user context
|
||||
ctx := context.WithValue(r.Context(), "user_address", address)
|
||||
ctx = context.WithValue(ctx, "user_track", track)
|
||||
ctx = context.WithValue(ctx, "authenticated", true)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// extractAuth extracts authentication information from request
|
||||
func (m *AuthMiddleware) extractAuth(r *http.Request) (string, int, error) {
|
||||
// Get Authorization header
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return "", 0, http.ErrMissingFile
|
||||
}
|
||||
|
||||
// Check for Bearer token
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
return "", 0, http.ErrMissingFile
|
||||
}
|
||||
|
||||
token := parts[1]
|
||||
|
||||
// Validate JWT token
|
||||
address, track, err := m.walletAuth.ValidateJWT(token)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
return address, track, nil
|
||||
}
|
||||
|
||||
// writeUnauthorized writes a 401 Unauthorized response
|
||||
func writeUnauthorized(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"error":{"code":"unauthorized","message":"Authentication required"}}`))
|
||||
}
|
||||
|
||||
// writeForbidden writes a 403 Forbidden response
|
||||
func writeForbidden(w http.ResponseWriter, requiredTrack int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"error":{"code":"forbidden","message":"Insufficient permissions","required_track":` + fmt.Sprintf("%d", requiredTrack) + `}}`))
|
||||
}
|
||||
|
||||
63
backend/api/middleware/security.go
Normal file
63
backend/api/middleware/security.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SecurityMiddleware adds security headers
|
||||
type SecurityMiddleware struct{}
|
||||
|
||||
// NewSecurityMiddleware creates a new security middleware
|
||||
func NewSecurityMiddleware() *SecurityMiddleware {
|
||||
return &SecurityMiddleware{}
|
||||
}
|
||||
|
||||
// AddSecurityHeaders adds security headers to responses
|
||||
func (m *SecurityMiddleware) AddSecurityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Content Security Policy
|
||||
// unsafe-eval required by ethers.js v5 UMD from CDN (ABI decoding)
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:; connect-src 'self' https://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org http://192.168.11.221:8545 ws://192.168.11.221:8546;")
|
||||
|
||||
// X-Frame-Options (click-jacking protection)
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
|
||||
// X-Content-Type-Options
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
|
||||
// X-XSS-Protection
|
||||
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
||||
|
||||
// Strict-Transport-Security
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
|
||||
// Referrer-Policy
|
||||
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
|
||||
// Permissions-Policy
|
||||
w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// BlockWriteCalls blocks contract write calls except WETH operations
|
||||
func (m *SecurityMiddleware) BlockWriteCalls(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Only apply to POST requests (write operations)
|
||||
if r.Method == http.MethodPost {
|
||||
// Check if this is a WETH operation (allowed)
|
||||
path := r.URL.Path
|
||||
if !strings.Contains(path, "weth") && !strings.Contains(path, "wrap") && !strings.Contains(path, "unwrap") {
|
||||
// Block other write operations for Track 1
|
||||
if strings.HasPrefix(path, "/api/v1/track1") {
|
||||
http.Error(w, "Write operations not allowed for Track 1 (public)", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user