Files
mpc/pkg/api/middleware.go
T
zeekay 657674f4ce security: fix 15 custody audit findings, add regression + fuzz tests
Fixes all findings from the Blue Team defensive security review of the
redacted → redacted custody architecture transition.

HIGH:
- S-1: Implement P-256 ECDH + AES-256-GCM encryption of passkey backup shards
- W-2: Reject unparseable WebAuthn public keys (was silently skipping verification)
- O-1: Add Ed25519 binary signature verification package (pkg/integrity)

MEDIUM:
- W-1: Validate attestation is a real P-256 curve point, not raw attestation object
- W-3: Add origin validation to all WebAuthn flows (register, verify, trade approve)
- N-2: Remove plaintext TCP fallback from MPC node transport (TLS mandatory)
- K-1: Fail-closed on empty/whitespace orgID (prevents cross-tenant key leakage)
- A-1: Make AuditEntry immutable (Update/Delete return error)
- A-2: Add MPC-level signing audit log (wallet, message hash, intent, trigger)
- O-3: Invalidate backup shards after key reshare (stale shares are useless)
- O-2: Reject env/file password providers in production (require cloud HSM)

LOW:
- T-1: Add error handling + MarkSignFailed to signing goroutine
- T-2: Verify caller authorization in handleTradeSubmit
- K-2: Secret erasure stub now calls runtime.GC() instead of no-op
- N-1: Add VerifyConnection callback to reject peers without TLS certs

Tests: 69 unit + 7 fuzz targets, ~900K fuzz executions, 19/19 packages green.
Makefile: add -tags json1 for SQLite JSON function support in ORM tests.
2026-04-01 09:00:06 -07:00

196 lines
5.1 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/hanzoai/orm"
"github.com/luxfi/mpc/pkg/db"
)
type contextKey string
const (
ctxUserID contextKey = "user_id"
ctxOrgID contextKey = "org_id"
ctxRole contextKey = "role"
ctxPermissions contextKey = "permissions"
)
func getUserID(ctx context.Context) string {
v, _ := ctx.Value(ctxUserID).(string)
return v
}
func getOrgID(ctx context.Context) string {
v, _ := ctx.Value(ctxOrgID).(string)
return v
}
func getRole(ctx context.Context) string {
v, _ := ctx.Value(ctxRole).(string)
return v
}
func getPermissions(ctx context.Context) []string {
v, _ := ctx.Value(ctxPermissions).([]string)
return v
}
func hasPermission(ctx context.Context, perm string) bool {
for _, p := range getPermissions(ctx) {
if p == perm || p == "*" {
return true
}
}
return false
}
func urlParam(r *http.Request, key string) string {
return chi.URLParam(r, key)
}
func (s *Server) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Try JWT from Authorization header
auth := r.Header.Get("Authorization")
if strings.HasPrefix(auth, "Bearer ") {
token := strings.TrimPrefix(auth, "Bearer ")
claims, err := s.validateJWT(token)
if err != nil {
writeError(w, http.StatusUnauthorized, "invalid token")
return
}
ctx := context.WithValue(r.Context(), ctxUserID, claims.UserID)
ctx = context.WithValue(ctx, ctxOrgID, claims.OrgID)
ctx = context.WithValue(ctx, ctxRole, claims.Role)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Try API key from X-API-Key header
apiKeyHeader := r.Header.Get("X-API-Key")
if apiKeyHeader != "" {
key, err := s.validateAPIKey(r.Context(), apiKeyHeader)
if err != nil {
writeError(w, http.StatusUnauthorized, "invalid api key")
return
}
ctx := context.WithValue(r.Context(), ctxOrgID, key.OrgID)
ctx = context.WithValue(ctx, ctxRole, "api")
ctx = context.WithValue(ctx, ctxPermissions, key.Permissions)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
writeError(w, http.StatusUnauthorized, "missing authorization")
})
}
func (s *Server) auditMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
// Fire-and-forget audit log for mutating operations
if r.Method != http.MethodGet {
go s.writeAuditLog(r.Context(), r)
}
})
}
func requireRole(roles ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role := getRole(r.Context())
for _, allowed := range roles {
if role == allowed {
next.ServeHTTP(w, r)
return
}
}
writeError(w, http.StatusForbidden, "insufficient permissions")
})
}
}
// requirePermission gates API key requests by checking their permissions slice.
// JWT-authenticated users (non-"api" role) pass through — role-based checks handle them.
func requirePermission(perm string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role := getRole(r.Context())
// JWT users: check role-based access, not per-permission
if role != "api" {
next.ServeHTTP(w, r)
return
}
// API key users: must have the specific permission
if !hasPermission(r.Context(), perm) {
writeError(w, http.StatusForbidden, "api key missing permission: "+perm)
return
}
next.ServeHTTP(w, r)
})
}
}
func writeJSON(w http.ResponseWriter, code int, v interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"error": msg})
}
func (s *Server) writeAuditLog(ctx context.Context, r *http.Request) {
orgID := getOrgID(ctx)
userID := getUserID(ctx)
if orgID == "" {
return
}
action := r.Method + " " + r.URL.Path
ip := r.RemoteAddr
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
ip = strings.Split(xff, ",")[0]
}
entry := orm.New[db.AuditEntry](s.db.ORM)
entry.OrgID = orgID
entry.UserID = nilIfEmpty(userID)
entry.Action = action
entry.IPAddress = nilIfEmpty(ip)
entry.Create()
}
func nilIfEmpty(s string) *string {
if s == "" {
return nil
}
return &s
}
// Dedicated signing audit log — records every MPC signing operation
// with wallet ID, message hash, intent ID, and trigger source.
func (s *Server) writeSigningAuditLog(ctx context.Context, orgID, walletID, messageHash, intentID, trigger string) {
entry := orm.New[db.AuditEntry](s.db.ORM)
entry.OrgID = orgID
entry.Action = "mpc.sign"
resType := "wallet"
entry.ResourceType = &resType
entry.ResourceID = &walletID
details, _ := json.Marshal(map[string]string{
"wallet_id": walletID,
"message_hash": messageHash,
"intent_id": intentID,
"trigger": trigger,
})
entry.Details = details
entry.Create()
}