227 lines
5.7 KiB
Go
227 lines
5.7 KiB
Go
/*
|
|
Copyright 2020-2023 CAcert Inc.
|
|
SPDX-License-Identifier: Apache-2.0
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
https://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package handlers
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"html/template"
|
|
"io/fs"
|
|
"net/http"
|
|
|
|
"github.com/nicksnyder/go-i18n/v2/i18n"
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"code.cacert.org/cacert/oidc-idp/internal/services"
|
|
"code.cacert.org/cacert/oidc-idp/ui"
|
|
)
|
|
|
|
type errorKey int
|
|
|
|
const (
|
|
errorBucketKey errorKey = iota
|
|
)
|
|
|
|
type ErrorDetails struct {
|
|
ErrorMessage string
|
|
ErrorDetails []string
|
|
ErrorCode string
|
|
Error error
|
|
}
|
|
|
|
type ErrorBucket struct {
|
|
errorDetails *ErrorDetails
|
|
templates *template.Template
|
|
logger *log.Logger
|
|
bundle *i18n.Bundle
|
|
messageCatalog *services.MessageCatalog
|
|
}
|
|
|
|
func (b *ErrorBucket) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if b.errorDetails != nil {
|
|
accept := r.Header.Get("Accept-Language")
|
|
localizer := i18n.NewLocalizer(b.bundle, accept)
|
|
err := b.templates.Lookup("base").Execute(w, map[string]interface{}{
|
|
"Title": b.messageCatalog.LookupMessage(
|
|
"ErrorTitle",
|
|
nil,
|
|
localizer,
|
|
),
|
|
"details": b.errorDetails,
|
|
})
|
|
|
|
if err != nil {
|
|
log.Errorf("error rendering error template: %v", err)
|
|
http.Error(
|
|
w,
|
|
http.StatusText(http.StatusInternalServerError),
|
|
http.StatusInternalServerError,
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
func GetErrorBucket(r *http.Request) *ErrorBucket {
|
|
if bucket, ok := r.Context().Value(errorBucketKey).(*ErrorBucket); ok {
|
|
return bucket
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// AddError can be called to add error details from your application's handler.
|
|
func (b *ErrorBucket) AddError(details *ErrorDetails) {
|
|
b.errorDetails = details
|
|
}
|
|
|
|
type errorResponseWriter struct {
|
|
http.ResponseWriter
|
|
errorBucket *ErrorBucket
|
|
statusCode int
|
|
}
|
|
|
|
func (w *errorResponseWriter) WriteHeader(code int) {
|
|
w.statusCode = code
|
|
|
|
if code >= http.StatusBadRequest {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
|
|
w.errorBucket.AddError(&ErrorDetails{
|
|
ErrorMessage: http.StatusText(code),
|
|
})
|
|
}
|
|
|
|
w.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (w *errorResponseWriter) Write(content []byte) (int, error) {
|
|
if w.statusCode >= http.StatusBadRequest {
|
|
if w.errorBucket.errorDetails.ErrorDetails == nil {
|
|
w.errorBucket.errorDetails.ErrorDetails = make([]string, 0)
|
|
}
|
|
|
|
w.errorBucket.errorDetails.ErrorDetails = append(
|
|
w.errorBucket.errorDetails.ErrorDetails, string(content),
|
|
)
|
|
|
|
return len(content), nil
|
|
}
|
|
|
|
code, err := w.ResponseWriter.Write(content)
|
|
if err != nil {
|
|
return code, fmt.Errorf("error writing response: %w", err)
|
|
}
|
|
|
|
return code, nil
|
|
}
|
|
|
|
func ErrorHandling(
|
|
logger *log.Logger,
|
|
templateFS fs.FS,
|
|
bundle *i18n.Bundle,
|
|
messageCatalog *services.MessageCatalog,
|
|
) (func(http.Handler) http.Handler, error) {
|
|
errorTemplates, err := template.ParseFS(
|
|
templateFS,
|
|
"templates/base.gohtml",
|
|
"templates/errors.gohtml",
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("could not parse templates: %w", err)
|
|
}
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
errorBucket := &ErrorBucket{
|
|
templates: errorTemplates,
|
|
logger: logger,
|
|
bundle: bundle,
|
|
messageCatalog: messageCatalog,
|
|
}
|
|
next.ServeHTTP(
|
|
&errorResponseWriter{w, errorBucket, http.StatusOK},
|
|
r.WithContext(context.WithValue(r.Context(), errorBucketKey, errorBucket)),
|
|
)
|
|
errorBucket.serveHTTP(w, r)
|
|
})
|
|
}, nil
|
|
}
|
|
|
|
type ErrorHandler struct {
|
|
logger *log.Logger
|
|
bundle *i18n.Bundle
|
|
messageCatalog *services.MessageCatalog
|
|
template *template.Template
|
|
}
|
|
|
|
func (h *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
}
|
|
|
|
accept := r.Header.Get("Accept-Language")
|
|
localizer := i18n.NewLocalizer(h.bundle, accept)
|
|
|
|
errorName := r.URL.Query().Get("error")
|
|
errorDescription := r.URL.Query().Get("error_description")
|
|
|
|
h.logger.WithFields(log.Fields{
|
|
"error_name": errorName,
|
|
"error_description": errorDescription,
|
|
}).Debug("error from Hydra")
|
|
|
|
rendered := bytes.NewBuffer(make([]byte, 0))
|
|
|
|
msg := h.messageCatalog.LookupMessage
|
|
msgMarkdown := h.messageCatalog.LookupMarkdownMessage
|
|
|
|
err := h.template.Lookup("base").Execute(rendered, map[string]interface{}{
|
|
"Title": msg("AuthServerErrorTitle", nil, localizer),
|
|
"Explanation": template.HTML( //nolint:gosec
|
|
msgMarkdown("AuthServerErrorExplanation", nil, localizer),
|
|
),
|
|
"ErrorMessage": errorDescription,
|
|
})
|
|
if err != nil {
|
|
h.logger.WithError(err).Error("template rendering failed")
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
w.Header().Add("Pragma", "no-cache")
|
|
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
|
|
_, _ = w.Write(rendered.Bytes())
|
|
}
|
|
|
|
func NewErrorHandler(logger *log.Logger, bundle *i18n.Bundle, messageCatalog *services.MessageCatalog) *ErrorHandler {
|
|
return &ErrorHandler{
|
|
logger: logger,
|
|
bundle: bundle,
|
|
messageCatalog: messageCatalog,
|
|
template: template.Must(template.ParseFS(
|
|
ui.Templates,
|
|
"templates/base.gohtml",
|
|
"templates/hydra_error.gohtml"),
|
|
),
|
|
}
|
|
}
|