feat: name change + bugfixes
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
@@ -15,7 +16,9 @@ func AdminAuth() gin.HandlerFunc {
|
||||
|
||||
return func(c *gin.Context) {
|
||||
|
||||
if c.GetHeader("X-Admin-Token") != token {
|
||||
// Without a configured token every admin request is refused, never allowed
|
||||
provided := c.GetHeader("X-Admin-Token")
|
||||
if token == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized",
|
||||
})
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func status(t *testing.T, configured, provided string) int {
|
||||
t.Setenv("ADMIN_TOKEN", configured)
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
r := gin.New()
|
||||
r.POST("/admin", AdminAuth(), func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/admin", nil)
|
||||
if provided != "" {
|
||||
req.Header.Set("X-Admin-Token", provided)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
return w.Code
|
||||
}
|
||||
|
||||
func TestAdminAuth(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, configured, provided string
|
||||
want int
|
||||
}{
|
||||
{"no token configured refuses requests without a header", "", "", http.StatusUnauthorized},
|
||||
{"no token configured refuses any header", "", "anything", http.StatusUnauthorized},
|
||||
{"wrong token", "secret", "nope", http.StatusUnauthorized},
|
||||
{"missing header", "secret", "", http.StatusUnauthorized},
|
||||
{"correct token", "secret", "secret", http.StatusOK},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := status(t, tc.configured, tc.provided); got != tc.want {
|
||||
t.Fatalf("got %d, want %d", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user