2023-10-21 19:35:41 +02:00
|
|
|
package middleware
|
2021-11-12 14:16:24 +03:00
|
|
|
|
|
|
|
|
import (
|
2023-10-21 19:35:41 +02:00
|
|
|
"github.com/containrrr/watchtower/pkg/api/prelude"
|
2021-11-12 14:16:24 +03:00
|
|
|
"net/http"
|
|
|
|
|
"net/http/httptest"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
. "github.com/onsi/ginkgo"
|
|
|
|
|
. "github.com/onsi/gomega"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
2023-10-21 19:35:41 +02:00
|
|
|
token = "123123123"
|
2021-11-12 14:16:24 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func TestAPI(t *testing.T) {
|
|
|
|
|
RegisterFailHandler(Fail)
|
2023-10-21 19:35:41 +02:00
|
|
|
RunSpecs(t, "Middleware Suite")
|
2021-11-12 14:16:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var _ = Describe("API", func() {
|
2023-10-21 19:35:41 +02:00
|
|
|
requireToken := RequireToken(token)
|
2021-11-12 14:16:24 +03:00
|
|
|
|
|
|
|
|
Describe("RequireToken middleware", func() {
|
|
|
|
|
It("should return 401 Unauthorized when token is not provided", func() {
|
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
|
req := httptest.NewRequest("GET", "/hello", nil)
|
|
|
|
|
|
2023-10-21 19:35:41 +02:00
|
|
|
requireToken(testHandler).ServeHTTP(rec, req)
|
2021-11-12 14:16:24 +03:00
|
|
|
|
|
|
|
|
Expect(rec.Code).To(Equal(http.StatusUnauthorized))
|
2023-10-21 19:35:41 +02:00
|
|
|
Expect(rec.Body).To(MatchJSON(`{
|
|
|
|
|
"code": "MISSING_TOKEN",
|
|
|
|
|
"error": "No authentication token was supplied"
|
|
|
|
|
}`))
|
2021-11-12 14:16:24 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
It("should return 401 Unauthorized when token is invalid", func() {
|
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
|
req := httptest.NewRequest("GET", "/hello", nil)
|
|
|
|
|
req.Header.Set("Authorization", "Bearer 123")
|
|
|
|
|
|
2023-10-21 19:35:41 +02:00
|
|
|
requireToken(testHandler).ServeHTTP(rec, req)
|
2021-11-12 14:16:24 +03:00
|
|
|
|
|
|
|
|
Expect(rec.Code).To(Equal(http.StatusUnauthorized))
|
2023-10-21 19:35:41 +02:00
|
|
|
Expect(rec.Body).To(MatchJSON(`{
|
|
|
|
|
"code": "INVALID_TOKEN",
|
|
|
|
|
"error": "The supplied token does not match the configured auth token"
|
|
|
|
|
}`))
|
2021-11-12 14:16:24 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
It("should return 200 OK when token is valid", func() {
|
|
|
|
|
|
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
|
req := httptest.NewRequest("GET", "/hello", nil)
|
2023-10-21 19:35:41 +02:00
|
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
2021-11-12 14:16:24 +03:00
|
|
|
|
2023-10-21 19:35:41 +02:00
|
|
|
requireToken(testHandler).ServeHTTP(rec, req)
|
2021-11-12 14:16:24 +03:00
|
|
|
|
|
|
|
|
Expect(rec.Code).To(Equal(http.StatusOK))
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
|
2023-10-21 19:35:41 +02:00
|
|
|
func testHandler(_ *prelude.Context) prelude.Response {
|
|
|
|
|
return prelude.OK("Hello!")
|
2021-11-12 14:16:24 +03:00
|
|
|
}
|