package middleware

import (
	"crypto/subtle"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// InternalTokenAuth returns a Gin middleware that rejects requests whose
// Authorization header does not carry "Bearer <expected>". Used only for
// /internal/* routes consumed by trusted ops services (e.g. sentry).
//
// The comparison is constant-time to prevent timing oracles, even though
// the token is static — no harm, no cost.
func InternalTokenAuth(expected string) gin.HandlerFunc {
	expectedBytes := []byte(expected)
	return func(c *gin.Context) {
		auth := c.GetHeader("Authorization")
		const prefix = "Bearer "
		if !strings.HasPrefix(auth, prefix) {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		got := []byte(strings.TrimPrefix(auth, prefix))
		if subtle.ConstantTimeCompare(got, expectedBytes) != 1 {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		c.Next()
	}
}
