| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package server |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "encoding/json" |
| 22 | "errors" |
| 23 | "net/http" |
| 24 | |
| 25 | "github.com/sassoftware/relic/v7/internal/httperror" |
| 26 | "github.com/sassoftware/relic/v7/internal/zhttp" |
| 27 | "github.com/sassoftware/relic/v7/signers/sigerrors" |
| 28 | "github.com/sassoftware/relic/v7/token" |
| 29 | ) |
| 30 | |
| 31 | func handleFunc(f func(http.ResponseWriter, *http.Request) error) http.HandlerFunc { |
| 32 | return func(rw http.ResponseWriter, req *http.Request) { |
| 33 | ctx := req.Context() |
| 34 | if srv, ok := ctx.Value(http.ServerContextKey).(*http.Server); ok && srv.WriteTimeout > 0 { |
| 35 | // timeout request context when WriteTimeout is reached |
| 36 | ctx, cancel := context.WithTimeout(req.Context(), srv.WriteTimeout) |
| 37 | defer cancel() |
| 38 | req = req.WithContext(ctx) |
| 39 | } |
| 40 | err := f(rw, req) |
| 41 | if err == nil { |
| 42 | return |
| 43 | } |
| 44 | if resp, ok := err.(http.Handler); ok { |
| 45 | resp.ServeHTTP(rw, req) |
| 46 | } else if h := errToProblem(err); h != nil { |
| 47 | h.ServeHTTP(rw, req) |
| 48 | } else { |
| 49 | zhttp.WriteUnhandledError(rw, req, err, "") |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | func errToProblem(err error) http.Handler { |
| 55 | if e := new(token.KeyUsageError); errors.As(err, e) { |
| 56 | return httperror.Problem{ |
| 57 | Status: http.StatusBadRequest, |
| 58 | Type: httperror.ProblemKeyUsage, |
| 59 | Title: "Incorrect Key Usage", |
| 60 | Detail: e.Error(), |
| 61 | } |
| 62 | } else if e := new(sigerrors.ErrNoCertificate); errors.As(err, e) { |
| 63 | return httperror.NoCertificateError(e.Type) |
| 64 | } |
| 65 | return nil |
| 66 | } |
| 67 | |
| 68 | func writeJSON(rw http.ResponseWriter, data interface{}) error { |
| 69 | blob, err := json.Marshal(data) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | rw.Header().Set("Content-Type", "application/json") |
| 74 | _, err = rw.Write(blob) |
| 75 | return err |
| 76 | } |