oidc-idp/internal/handlers/error.go

197 lines
4.8 KiB
Go
Raw Normal View History

/*
Copyright CAcert Inc.
2023-05-13 11:27:19 +00:00
SPDX-License-Identifier: Apache-2.0
2023-05-13 11:27:19 +00:00
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
2023-05-13 11:27:19 +00:00
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"
"log/slog"
"net/http"
2023-07-29 20:00:53 +00:00
"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 {
logger *slog.Logger
trans *services.I18NService
errorDetails *ErrorDetails
templates TemplateCache
}
func (b *ErrorBucket) serveHTTP(w http.ResponseWriter, r *http.Request) {
if b.errorDetails != nil {
localizer := getLocalizer(b.trans, r)
b.templates.render(b.logger, w, Error, map[string]interface{}{
"Title": b.trans.LookupMessage(
"ErrorTitle",
nil,
localizer,
),
"details": b.errorDetails,
})
}
}
func GetErrorBucket(r *http.Request) *ErrorBucket {
2023-05-13 11:27:19 +00:00
if bucket, ok := r.Context().Value(errorBucketKey).(*ErrorBucket); ok {
return bucket
}
return nil
}
2023-05-13 11:27:19 +00:00
// 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
2023-05-13 11:27:19 +00:00
errorBucket *ErrorBucket
statusCode int
}
func (w *errorResponseWriter) WriteHeader(code int) {
w.statusCode = code
2023-05-13 11:27:19 +00:00
if code >= http.StatusBadRequest {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
2023-05-13 11:27:19 +00:00
w.errorBucket.AddError(&ErrorDetails{ErrorCode: "HTTP error"})
}
2023-05-13 11:27:19 +00:00
w.ResponseWriter.WriteHeader(code)
}
func (w *errorResponseWriter) Write(content []byte) (int, error) {
2023-05-13 11:27:19 +00:00
if w.statusCode >= http.StatusBadRequest {
if w.errorBucket.errorDetails.ErrorDetails == nil {
w.errorBucket.errorDetails.ErrorDetails = make([]string, 0)
}
2023-05-13 11:27:19 +00:00
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)
}
2023-05-13 11:27:19 +00:00
return code, nil
}
2023-05-13 11:27:19 +00:00
func ErrorHandling(
logger *slog.Logger, templateCache TemplateCache, trans *services.I18NService,
2023-05-13 11:27:19 +00:00
) (func(http.Handler) http.Handler, error) {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
errorBucket := &ErrorBucket{
logger: logger,
trans: trans,
templates: templateCache,
}
next.ServeHTTP(
2023-05-13 11:27:19 +00:00
&errorResponseWriter{w, errorBucket, http.StatusOK},
r.WithContext(context.WithValue(r.Context(), errorBucketKey, errorBucket)),
)
errorBucket.serveHTTP(w, r)
})
}, nil
}
2023-05-13 11:27:19 +00:00
type ErrorHandler struct {
logger *slog.Logger
trans *services.I18NService
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
}
localizer := getLocalizer(h.trans, r)
errorName := r.URL.Query().Get("error")
errorDescription := r.URL.Query().Get("error_description")
h.logger.Debug(
"error from Hydra",
"error_name", errorName, "error_description", errorDescription,
)
rendered := bytes.NewBuffer(make([]byte, 0))
msg := h.trans.LookupMessage
msgMarkdown := h.trans.LookupMarkdownMessage
err := h.template.Lookup("base").Execute(rendered, map[string]interface{}{
2023-07-29 20:00:53 +00:00
"Title": msg("AuthServerErrorTitle", nil, localizer),
"Explanation": template.HTML( //nolint:gosec
msgMarkdown("AuthServerErrorExplanation", nil, localizer),
),
"ErrorMessage": errorDescription,
})
if err != nil {
h.logger.Error("template rendering failed", "error", err)
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 *slog.Logger, trans *services.I18NService) *ErrorHandler {
return &ErrorHandler{
logger: logger,
trans: trans,
template: template.Must(template.ParseFS(
ui.Templates,
"templates/base.gohtml",
"templates/hydra_error.gohtml"),
),
}
}