|
| 1 | +// SPDX-FileCopyrightText: (C) 2024 Intel Corporation |
| 2 | +// SPDX-License-Identifier: Apache 2.0 |
| 3 | + |
| 4 | +package handlers |
| 5 | + |
| 6 | +import ( |
| 7 | + "encoding/base64" |
| 8 | + "encoding/hex" |
| 9 | + "encoding/json" |
| 10 | + "errors" |
| 11 | + "fmt" |
| 12 | + "io" |
| 13 | + "log/slog" |
| 14 | + "net/http" |
| 15 | + |
| 16 | + "github.com/fido-device-onboard/go-fdo-server/api/openapi" |
| 17 | + "github.com/fido-device-onboard/go-fdo-server/internal/utils" |
| 18 | + "gorm.io/gorm" |
| 19 | +) |
| 20 | + |
| 21 | +// Use generated types instead of custom types |
| 22 | +// VoucherResponse and VoucherInsertResponse are now imported from openapi package |
| 23 | + |
| 24 | +// ErrorResponse represents a standard error response |
| 25 | +type ErrorResponse struct { |
| 26 | + Error string `json:"error"` |
| 27 | + Details string `json:"details,omitempty"` |
| 28 | +} |
| 29 | + |
| 30 | +// WriteJSONVoucher writes a voucher response in JSON format |
| 31 | +func WriteJSONVoucher(w http.ResponseWriter, voucherData []byte, encoding string, guid []byte) error { |
| 32 | + response := openapi.VoucherResponse{ |
| 33 | + Voucher: base64.StdEncoding.EncodeToString(voucherData), |
| 34 | + Encoding: encoding, |
| 35 | + Guid: hex.EncodeToString(guid), |
| 36 | + } |
| 37 | + |
| 38 | + w.Header().Set("Content-Type", ContentTypeJSON) |
| 39 | + return json.NewEncoder(w).Encode(response) |
| 40 | +} |
| 41 | + |
| 42 | +// WriteJSONError writes a standard error response in JSON format |
| 43 | +func WriteJSONError(w http.ResponseWriter, statusCode int, errorMsg, details string) { |
| 44 | + response := ErrorResponse{ |
| 45 | + Error: errorMsg, |
| 46 | + Details: details, |
| 47 | + } |
| 48 | + |
| 49 | + w.Header().Set("Content-Type", ContentTypeJSON) |
| 50 | + w.WriteHeader(statusCode) |
| 51 | + json.NewEncoder(w).Encode(response) |
| 52 | +} |
| 53 | + |
| 54 | +// WriteJSONVoucherInsertResponse writes a voucher insert response in JSON format |
| 55 | +func WriteJSONVoucherInsertResponse(w http.ResponseWriter, response openapi.VoucherInsertResponse) error { |
| 56 | + w.Header().Set("Content-Type", ContentTypeJSON) |
| 57 | + if response.Errors != nil && len(*response.Errors) > 0 && response.Inserted == 0 { |
| 58 | + w.WriteHeader(http.StatusBadRequest) |
| 59 | + } else { |
| 60 | + w.WriteHeader(http.StatusOK) |
| 61 | + } |
| 62 | + return json.NewEncoder(w).Encode(response) |
| 63 | +} |
| 64 | + |
| 65 | +// ShouldReturnJSON checks if the client prefers JSON response |
| 66 | +// This allows for backward compatibility with existing PEM clients |
| 67 | +func ShouldReturnJSON(r *http.Request) bool { |
| 68 | + accept := r.Header.Get("Accept") |
| 69 | + |
| 70 | + // If client specifically requests PEM, honor it for backward compatibility |
| 71 | + if accept == ContentTypePEM { |
| 72 | + return false |
| 73 | + } |
| 74 | + |
| 75 | + // Default to JSON for everything else (including no preference) |
| 76 | + return true |
| 77 | +} |
| 78 | + |
| 79 | +// WriteErrorResponse writes an error response in JSON or text format based on Accept header |
| 80 | +func WriteErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, jsonMsg, jsonDetails, textMsg string) { |
| 81 | + if ShouldReturnJSON(r) { |
| 82 | + WriteJSONError(w, statusCode, jsonMsg, jsonDetails) |
| 83 | + } else { |
| 84 | + http.Error(w, textMsg, statusCode) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +// ValidateAndDecodeGUID validates a GUID string and returns the decoded bytes |
| 89 | +// Returns the decoded GUID bytes or an error response written to the writer |
| 90 | +func ValidateAndDecodeGUID(w http.ResponseWriter, r *http.Request, guidHex string) ([]byte, bool) { |
| 91 | + if !utils.IsValidGUID(guidHex) { |
| 92 | + WriteErrorResponse(w, r, http.StatusBadRequest, "Invalid GUID", "GUID must be 32 hexadecimal characters", "Invalid GUID") |
| 93 | + return nil, false |
| 94 | + } |
| 95 | + |
| 96 | + guid, err := hex.DecodeString(guidHex) |
| 97 | + if err != nil { |
| 98 | + WriteErrorResponse(w, r, http.StatusBadRequest, "Invalid GUID format", err.Error(), "Invalid GUID format") |
| 99 | + return nil, false |
| 100 | + } |
| 101 | + |
| 102 | + return guid, true |
| 103 | +} |
| 104 | + |
| 105 | +// FormatGUID formats a GUID byte array as hex string for error messages |
| 106 | +func FormatGUID(guid []byte) string { |
| 107 | + return hex.EncodeToString(guid) |
| 108 | +} |
| 109 | + |
| 110 | +// AppendError adds an error message to the voucher insert response |
| 111 | +func AppendError(response *openapi.VoucherInsertResponse, format string, args ...interface{}) { |
| 112 | + if response.Errors == nil { |
| 113 | + errors := make([]string, 0) |
| 114 | + response.Errors = &errors |
| 115 | + } |
| 116 | + *response.Errors = append(*response.Errors, fmt.Sprintf(format, args...)) |
| 117 | +} |
| 118 | + |
| 119 | +// ReadRequestBody reads the request body and handles errors consistently |
| 120 | +func ReadRequestBody(w http.ResponseWriter, r *http.Request) ([]byte, bool) { |
| 121 | + body, err := io.ReadAll(r.Body) |
| 122 | + if err != nil { |
| 123 | + slog.Error("Error reading body", "error", err) |
| 124 | + http.Error(w, "Error reading body", http.StatusInternalServerError) |
| 125 | + return nil, false |
| 126 | + } |
| 127 | + return body, true |
| 128 | +} |
| 129 | + |
| 130 | +// HandleDuplicateKeyError handles GORM duplicate key errors consistently |
| 131 | +func HandleDuplicateKeyError(w http.ResponseWriter, entityName string, err error) bool { |
| 132 | + if errors.Is(err, gorm.ErrDuplicatedKey) { |
| 133 | + slog.Error(entityName+" already exists (constraint)", "error", err) |
| 134 | + http.Error(w, entityName+" already exists", http.StatusConflict) |
| 135 | + return true |
| 136 | + } |
| 137 | + return false |
| 138 | +} |
| 139 | + |
| 140 | +// HandleNotFoundError handles GORM not found errors consistently |
| 141 | +func HandleNotFoundError(w http.ResponseWriter, r *http.Request, entityName string, err error) bool { |
| 142 | + if errors.Is(err, gorm.ErrRecordNotFound) { |
| 143 | + slog.Error("No " + entityName + " found") |
| 144 | + WriteErrorResponse(w, r, http.StatusNotFound, "No "+entityName+" found", entityName+" has not been configured", "No "+entityName+" found") |
| 145 | + return true |
| 146 | + } |
| 147 | + return false |
| 148 | +} |
0 commit comments