droboticflow/internal/api/api_token.go

89 lines
2.3 KiB
Go

package api
import (
"context"
"crypto/subtle"
"net/http"
"strings"
)
type apiTokenContextKey struct{}
func isPublicEndpoint(request *http.Request) bool {
if request.URL.Path == "/api/health" || request.URL.Path == "/api/ready" || isWorkerAPIHealthEndpoint(request) {
return true
}
if request.URL.Path == "/api/public/settings" {
return true
}
if isExternalBusinessWriteEndpoint(request.URL.Path) {
return true
}
if strings.HasPrefix(request.URL.Path, "/api/external/object-sync/") {
return true
}
if strings.HasPrefix(request.URL.Path, "/api/auth/") {
return true
}
return false
}
func bearerToken(value string) string {
const prefix = "Bearer "
if !strings.HasPrefix(value, prefix) {
return ""
}
return strings.TrimSpace(strings.TrimPrefix(value, prefix))
}
func constantTimeEqual(left string, right string) bool {
if left == "" || right == "" {
return false
}
if len(left) != len(right) {
return false
}
return subtle.ConstantTimeCompare([]byte(left), []byte(right)) == 1
}
func apiTokenAuthenticated(request *http.Request) bool {
value, _ := request.Context().Value(apiTokenContextKey{}).(bool)
return value
}
func (server *server) apiTokenAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
requiredToken := strings.TrimSpace(server.apiToken)
if requiredToken == "" || isPublicEndpoint(request) {
next.ServeHTTP(writer, request)
return
}
{
if _, ok := currentPrincipal(request); ok {
next.ServeHTTP(writer, request)
return
}
principal, err := server.authenticateRequest(request)
if err != nil {
renderError(writer, http.StatusInternalServerError, err)
return
}
if principal != nil {
next.ServeHTTP(writer, request.WithContext(context.WithValue(request.Context(), authContextKey{}, principal)))
return
}
}
candidates := []string{
bearerToken(request.Header.Get("Authorization")),
strings.TrimSpace(request.Header.Get("X-Droboticflow-API-Token")),
}
for _, candidate := range candidates {
if constantTimeEqual(candidate, requiredToken) {
next.ServeHTTP(writer, request.WithContext(context.WithValue(request.Context(), apiTokenContextKey{}, true)))
return
}
}
renderJSON(writer, http.StatusUnauthorized, map[string]string{"error": "API token is required"})
})
}