Skip to content

Commit

Permalink
change status code ints to use pointers to the constants in http package
Browse files Browse the repository at this point in the history
  • Loading branch information
joshblakeley committed May 15, 2018
1 parent e7f602e commit 1ed85e3
Show file tree
Hide file tree
Showing 33 changed files with 198 additions and 197 deletions.
158 changes: 79 additions & 79 deletions api.go

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion api_definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ func (a APIDefinitionLoader) FromDashboardService(endpoint, secret string) []*AP
}
defer resp.Body.Close()

if resp.StatusCode == 403 {
if resp.StatusCode == http.StatusForbidden {
body, _ := ioutil.ReadAll(resp.Body)
log.Error("Login failure, Response was: ", string(body))
reLogin()
Expand Down
6 changes: 3 additions & 3 deletions batch_requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,22 +152,22 @@ func (b *BatchRequestHandler) HandleBatchRequest(w http.ResponseWriter, r *http.
batchRequest, err := b.DecodeBatchRequest(r)
if err != nil {
log.Error("Could not decode batch request, decoding failed: ", err)
doJSONWrite(w, 400, apiError("Batch request malformed"))
doJSONWrite(w, http.StatusBadRequest, apiError("Batch request malformed"))
return
}

// Construct the requests
requestSet, err := b.ConstructRequests(batchRequest, false)
if err != nil {
doJSONWrite(w, 400, apiError(fmt.Sprintf("Batch request creation failed , request structure malformed")))
doJSONWrite(w, http.StatusBadRequest, apiError(fmt.Sprintf("Batch request creation failed , request structure malformed")))
return
}

// Run requests and collate responses
replySet := b.MakeRequests(batchRequest, requestSet)

// Respond
doJSONWrite(w, 200, replySet)
doJSONWrite(w, http.StatusOK, replySet)
}

// HandleBatchRequest is the actual http handler for a batch request on an API definition
Expand Down
14 changes: 7 additions & 7 deletions cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,17 +246,17 @@ func certHandler(w http.ResponseWriter, r *http.Request) {
orgID := r.URL.Query().Get("org_id")
var certID string
if certID, err = CertificateManager.Add(content, orgID); err != nil {
doJSONWrite(w, 403, apiError(err.Error()))
doJSONWrite(w, http.StatusForbidden, apiError(err.Error()))
return
}

doJSONWrite(w, 200, &APICertificateStatusMessage{certID, "ok", "Certificate added"})
doJSONWrite(w, http.StatusOK, &APICertificateStatusMessage{certID, "ok", "Certificate added"})
case "GET":
if certID == "" {
orgID := r.URL.Query().Get("org_id")

certIds := CertificateManager.ListAllIds(orgID)
doJSONWrite(w, 200, &APIAllCertificates{certIds})
doJSONWrite(w, http.StatusOK, &APIAllCertificates{certIds})
return
}

Expand All @@ -265,11 +265,11 @@ func certHandler(w http.ResponseWriter, r *http.Request) {

if len(certIDs) == 1 {
if certificates[0] == nil {
doJSONWrite(w, 404, apiError("Certificate with given SHA256 fingerprint not found"))
doJSONWrite(w, http.StatusNotFound, apiError("Certificate with given SHA256 fingerprint not found"))
return
}

doJSONWrite(w, 200, certs.ExtractCertificateMeta(certificates[0], certIDs[0]))
doJSONWrite(w, http.StatusOK, certs.ExtractCertificateMeta(certificates[0], certIDs[0]))
return
} else {
var meta []*certs.CertificateMeta
Expand All @@ -281,12 +281,12 @@ func certHandler(w http.ResponseWriter, r *http.Request) {
}
}

doJSONWrite(w, 200, meta)
doJSONWrite(w, http.StatusOK, meta)
return
}
case "DELETE":
CertificateManager.Delete(certID)
doJSONWrite(w, 200, &apiStatusMessage{"ok", "removed"})
doJSONWrite(w, http.StatusOK, &apiStatusMessage{"ok", "removed"})
}
}

Expand Down
4 changes: 2 additions & 2 deletions handler_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (ws *WSDialer) RoundTrip(req *http.Request) (*http.Response, error) {

d, err := dial(context.TODO(), "tcp", target)
if err != nil {
http.Error(ws.RW, "Error contacting backend server.", 500)
http.Error(ws.RW, "Error contacting backend server.", http.StatusInternalServerError)
log.WithFields(logrus.Fields{
"path": target,
"origin": ip,
Expand All @@ -75,7 +75,7 @@ func (ws *WSDialer) RoundTrip(req *http.Request) (*http.Response, error) {

hj, ok := ws.RW.(http.Hijacker)
if !ok {
http.Error(ws.RW, "Not a hijacker?", 500)
http.Error(ws.RW, "Not a hijacker?", http.StatusInternalServerError)
return nil, errors.New("Not a hjijacker?")
}

Expand Down
3 changes: 2 additions & 1 deletion host_checker_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"net/url"
"sync"
"time"
Expand Down Expand Up @@ -451,7 +452,7 @@ func (hc *HostCheckerManager) RecordUptimeAnalytics(report HostHealthReport) err
t := time.Now()

var serverError bool
if report.ResponseCode > 200 {
if report.ResponseCode > http.StatusOK {
serverError = true
}

Expand Down
6 changes: 3 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ func controlAPICheckClientCertificate(certLevel string, next http.Handler) http.
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if config.Global().Security.ControlAPIUseMutualTLS {
if err := CertificateManager.ValidateRequestCertificate(config.Global().Security.Certificates.ControlAPI, r); err != nil {
doJSONWrite(w, 403, apiError(err.Error()))
doJSONWrite(w, http.StatusForbidden, apiError(err.Error()))
return
}
}
Expand Down Expand Up @@ -420,7 +420,7 @@ func checkIsAPIOwner(next http.Handler) http.Handler {
// Error
mainLog.Warning("Attempted administrative access with invalid or missing key!")

doJSONWrite(w, 403, apiError("Forbidden"))
doJSONWrite(w, http.StatusForbidden, apiError("Forbidden"))
return
}
next.ServeHTTP(w, r)
Expand All @@ -438,7 +438,7 @@ func addOAuthHandlers(spec *APISpec, muxer *mux.Router) *OAuthManager {
clientAccessPath := spec.Proxy.ListenPath + "oauth/token{_:/?}"

serverConfig := osin.NewServerConfig()
serverConfig.ErrorStatusCode = 403
serverConfig.ErrorStatusCode = http.StatusForbidden
serverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes
serverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes
serverConfig.RedirectUriSeparator = config.Global().OauthRedirectUriSeparator
Expand Down
4 changes: 2 additions & 2 deletions mw_access_rights.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (a *AccessRightsCheck) ProcessRequest(w http.ResponseWriter, r *http.Reques
)
logEntry.Info("Attempted access to unauthorised API.")

return errors.New("Access to this API has been disallowed"), 403
return errors.New("Access to this API has been disallowed"), http.StatusForbidden
}

// Find the version in their key access details
Expand Down Expand Up @@ -70,7 +70,7 @@ func (a *AccessRightsCheck) ProcessRequest(w http.ResponseWriter, r *http.Reques
)
logEntry.Info("Attempted access to unauthorised API version.")

return errors.New("Access to this API has been disallowed"), 403
return errors.New("Access to this API has been disallowed"), http.StatusForbidden
}
}

Expand Down
4 changes: 2 additions & 2 deletions mw_api_rate_limit.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (k *RateLimitForAPI) handleRateLimitFailure(r *http.Request, token string)
// Report in health check
reportHealthValue(k.Spec, Throttle, "-1")

return errors.New("API Rate limit exceeded"), 429
return errors.New("API Rate limit exceeded"), http.StatusTooManyRequests
}

// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
Expand All @@ -75,5 +75,5 @@ func (k *RateLimitForAPI) ProcessRequest(w http.ResponseWriter, r *http.Request,
}

// Request is valid, carry on
return nil, 200
return nil, http.StatusOK
}
10 changes: 5 additions & 5 deletions mw_basic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (k *BasicAuthKeyIsValid) requestForBasicAuth(w http.ResponseWriter, msg str
authReply := "Basic realm=\"" + k.Spec.Name + "\""

w.Header().Add("WWW-Authenticate", authReply)
return errors.New(msg), 401
return errors.New(msg), http.StatusUnauthorized
}

// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
Expand All @@ -49,23 +49,23 @@ func (k *BasicAuthKeyIsValid) ProcessRequest(w http.ResponseWriter, r *http.Requ
// Header malformed
logEntry.Info("Attempted access with malformed header, header not in basic auth format.")

return errors.New("Attempted access with malformed header, header not in basic auth format"), 400
return errors.New("Attempted access with malformed header, header not in basic auth format"), http.StatusBadRequest
}

// Decode the username:password string
authvaluesStr, err := base64.StdEncoding.DecodeString(bits[1])
if err != nil {
logEntry.Info("Base64 Decoding failed of basic auth data: ", err)

return errors.New("Attempted access with malformed header, auth data not encoded correctly"), 400
return errors.New("Attempted access with malformed header, auth data not encoded correctly"), http.StatusBadRequest
}

authValues := strings.Split(string(authvaluesStr), ":")
if len(authValues) != 2 {
// Header malformed
logEntry.Info("Attempted access with malformed header, values not in basic auth format.")

return errors.New("Attempted access with malformed header, values not in basic auth format"), 400
return errors.New("Attempted access with malformed header, values not in basic auth format"), http.StatusBadRequest
}

// Check if API key valid
Expand Down Expand Up @@ -118,5 +118,5 @@ func (k *BasicAuthKeyIsValid) ProcessRequest(w http.ResponseWriter, r *http.Requ
}

// Request is valid, carry on
return nil, 200
return nil, http.StatusOK
}
4 changes: 2 additions & 2 deletions mw_certificate_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ func (m *CertificateCheckMW) ProcessRequest(w http.ResponseWriter, r *http.Reque
certIDs := append(m.Spec.ClientCertificates, m.Spec.GlobalConfig.Security.Certificates.API...)

if err := CertificateManager.ValidateRequestCertificate(certIDs, r); err != nil {
return err, 403
return err, http.StatusForbidden
}
}
return nil, 200
return nil, http.StatusOK
}
10 changes: 5 additions & 5 deletions mw_granular_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http
sessionVersionData, foundAPI := session.AccessRights[m.Spec.APIID]
if !foundAPI {
log.Debug("Version not found")
return nil, 200
return nil, http.StatusOK
}

if len(sessionVersionData.AllowedURLs) == 0 {
log.Debug("No allowed URLS")
return nil, 200
return nil, http.StatusOK
}

for _, accessSpec := range sessionVersionData.AllowedURLs {
Expand All @@ -36,15 +36,15 @@ func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http
asRegex, err := regexp.Compile(accessSpec.URL)
if err != nil {
log.Error("Regex error: ", err)
return nil, 200
return nil, http.StatusOK
}

match := asRegex.MatchString(r.URL.Path)
if match {
log.Debug("Match!")
for _, method := range accessSpec.Methods {
if method == r.Method {
return nil, 200
return nil, http.StatusOK
}
}
}
Expand All @@ -55,6 +55,6 @@ func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http
logEntry := getLogEntryForRequest(r, token, map[string]interface{}{"api_found": false})
logEntry.Info("Attempted access to unauthorised endpoint (Granular).")

return errors.New("Access to this resource has been disallowed"), 403
return errors.New("Access to this resource has been disallowed"), http.StatusForbidden

}
4 changes: 2 additions & 2 deletions mw_hmac.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (hm *HMACMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request,
}

// Everything seems in order let the request through
return nil, 200
return nil, http.StatusOK

}

Expand Down Expand Up @@ -172,7 +172,7 @@ func (hm *HMACMiddleware) authorizationError(r *http.Request) (error, int) {

AuthFailed(hm, r, r.Header.Get("Authorization"))

return errors.New("Authorization field missing, malformed or invalid"), 400
return errors.New("Authorization field missing, malformed or invalid"), http.StatusBadRequest
}

func (hm HMACMiddleware) checkClockSkew(dateHeaderValue string) bool {
Expand Down
18 changes: 9 additions & 9 deletions mw_js_plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
log.WithFields(logrus.Fields{
"prefix": "jsvm",
}).Error("Failed to read request body! ", err)
return nil, 200
return nil, http.StatusOK
}

headers := r.Header
Expand Down Expand Up @@ -129,7 +129,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
log.WithFields(logrus.Fields{
"prefix": "jsvm",
}).Error("Failed to encode request object for dynamic middleware: ", err)
return nil, 200
return nil, http.StatusOK
}

specAsJson := specToJson(d.Spec)
Expand All @@ -147,7 +147,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
log.WithFields(logrus.Fields{
"prefix": "jsvm",
}).Error("Failed to encode session for VM: ", err)
return nil, 200
return nil, http.StatusOK
}

// Run the middleware
Expand Down Expand Up @@ -180,7 +180,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
log.WithFields(logrus.Fields{
"prefix": "jsvm",
}).Error("Failed to run JS middleware: ", err)
return nil, 200
return nil, http.StatusOK
}
t.Stop()
case <-t.C:
Expand All @@ -193,7 +193,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
// that panics.
panic("stop")
}
return nil, 200
return nil, http.StatusOK
}
returnDataStr, _ := returnRaw.ToString()

Expand All @@ -206,7 +206,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
log.WithFields(logrus.Fields{
"prefix": "jsvm",
}).Debug(returnDataStr)
return nil, 200
return nil, http.StatusOK
}

// Reconstruct the request parts
Expand Down Expand Up @@ -257,11 +257,11 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
"prefix": "jsvm",
}).Debug("JSVM middleware execution took: (ns) ", time.Now().UnixNano()-t1)

if newRequestData.Request.ReturnOverrides.ResponseCode >= 400 {
if newRequestData.Request.ReturnOverrides.ResponseCode >= http.StatusBadRequest {
return errors.New(newRequestData.Request.ReturnOverrides.ResponseError), newRequestData.Request.ReturnOverrides.ResponseCode
}

if newRequestData.Request.ReturnOverrides.ResponseCode != 0 && newRequestData.Request.ReturnOverrides.ResponseCode < 300 {
if newRequestData.Request.ReturnOverrides.ResponseCode != 0 && newRequestData.Request.ReturnOverrides.ResponseCode < http.StatusMultipleChoices {

responseObject := VMResponseObject{
Response: ResponseObject{
Expand All @@ -280,7 +280,7 @@ func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Reques
ctxSetAuthToken(r, newRequestData.AuthValue)
}

return nil, 200
return nil, http.StatusOK
}

func mapStrsToIfaces(m map[string]string) map[string]interface{} {
Expand Down

0 comments on commit 1ed85e3

Please sign in to comment.