Skip to content

Commit

Permalink
[FAB-3581] Improve error handling (#1)
Browse files Browse the repository at this point in the history
This is the first of several change sets which will improve error handling
and logging in the fabric-ca-server.  See [FAB-3581] for a description of
the overall design points.

This change set introduces the "httpErr" object which will be used to
encapsulate errors from the server.  It is defined in servererror.go,
which also contains a list of error codes which will be used in
following change sets.

The servererrors.go file will be deleted in a later change set.

Change-Id: If8fe2e1fd127181ef71270a0f88088f3ffb3b4b5
Signed-off-by: Keith Smith <[email protected]>
  • Loading branch information
Keith Smith committed Aug 8, 2017
1 parent 843e159 commit 00caa9c
Show file tree
Hide file tree
Showing 2 changed files with 206 additions and 0 deletions.
165 changes: 165 additions & 0 deletions lib/servererror.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
Copyright IBM Corp. 2016 All Rights Reserved.
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
http://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 lib

import (
"encoding/json"
"fmt"
"net/http"

cfsslapi "github.com/cloudflare/cfssl/api"
"github.com/cloudflare/cfssl/log"
)

// Error codes
const (
// Unknown error code
ErrUnknown = 0
// HTTP method not allowed
ErrMethodNotAllowed = 1
// No authorization header was found in request
ErrNoAuthHdr = 2
// Failed reading the HTTP request body
ErrReadingReqBody = 3
// HTTP request body was empty but should not have been
ErrEmptyReqBody = 4
// HTTP request body was of the wrong format
ErrBadReqBody = 5
// The token in the authorization header was invalid
ErrBadReqToken = 6
// The caller does not have the "hf.Revoker" attibute
ErrNotRevoker = 7
// Certificate to be revoked was not found
ErrRevCertNotFound = 8
// Certificate to be revoked is not owned by expected user
ErrCertWrongOwner = 9
// Identity of certificate to be revoked was not found
ErrRevokeIDNotFound = 10
// User info was not found for issuee of revoked certificate
ErrRevokeUserInfoNotFound = 11
// Certificate revocation failed for another reason
ErrRevokeFailure = 12
// Failed to update user info when revoking identity
ErrRevokeUpdateUser = 13
// Failed to revoke any certificates by identity
ErrNoCertsRevoked = 14
// Missing fields in the revocation request
ErrMissingRevokeArgs = 15
// Failed to get user's affiliation
ErrGettingAffiliation = 16
// Revoker's affiliation not equal to or above revokee's affiliation
ErrRevokerNotAffiliated = 17
// Failed to send an HTTP response
ErrSendingResponse = 18
// The CA (Certificate Authority) name was not found
ErrCANotFound = 19
// Authorization failure
ErrAuthFailure = 20
// No username and password were in the authorization header
ErrNoUserPass = 21
// Enrollment is currently disabled for the server
ErrEnrollDisabled = 22
// Invalid user name
ErrInvalidUser = 23
// Invalid password
ErrInvalidPass = 24
// Invalid token in authorization header
ErrInvalidToken = 25
// Certificate was not issued by a trusted authority
ErrUntrustedCertificate = 26
// Certificate has expired
ErrCertExpired = 27
// Certificate has been revoked
ErrCertRevoked = 28
// Failed trying to check if certificate is revoked
ErrCertRevokeCheckFailure = 29
// Certificate was not found
ErrCertNotFound = 30
// Bad certificate signing request
ErrBadCSR = 31
// Failed to get identity's prekey
ErrNoPreKey = 32
// The caller was not authenticated
ErrCallerIsNotAuthenticated = 33
)

// Construct a new HTTP error.
func newHTTPErr(scode, code int, format string, args ...interface{}) *httpErr {
msg := fmt.Sprintf(format, args...)
return &httpErr{
scode: scode,
lcode: code,
lmsg: msg,
rcode: code,
rmsg: msg,
}
}

// Construct an HTTP error specifically indicating an authorization failure.
// The local code and message is specific, but the remote code and message is generic
// for security reasons.
func newAuthErr(code int, format string, args ...interface{}) *httpErr {
return newHTTPErr(401, code, format, args).remote(ErrAuthFailure, "Authorization failure")
}

// httpErr is an HTTP error.
// "local" refers to errors as logged in the server (local to the server).
// "remote" refers to errors as returned to the client (remote to the server).
// This allows us to log a more specific error in the server logs while
// returning a more generic error to the client, as is done for authorization
// failures.
type httpErr struct {
scode int // HTTP status code
lcode int // local error code
lmsg string // local error message
rcode int // remote error code
rmsg string // remote error message
}

// Error returns the string representation
func (he *httpErr) Error() string {
return he.String()
}

// String returns a string representation of this augmented error
func (he *httpErr) String() string {
if he.lcode == he.rcode && he.lmsg == he.rmsg {
return fmt.Sprintf("scode: %d, code: %d, msg: %s", he.scode, he.lcode, he.lmsg)
}
return fmt.Sprintf("scode: %d, local code: %d, local msg: %s, remote code: %d, remote msg: %s",
he.scode, he.lcode, he.lmsg, he.rcode, he.rmsg)
}

// Set the remote code and message to something different from that of the local code and message
func (he *httpErr) remote(code int, format string, args ...interface{}) *httpErr {
he.rcode = code
he.rmsg = fmt.Sprintf(format, args...)
return he
}

// Write the server's HTTP error response
func (he *httpErr) writeResponse(w http.ResponseWriter) error {
response := cfsslapi.NewErrorResponse(he.rmsg, he.rcode)
jsonMessage, err := json.Marshal(response)
if err != nil {
log.Errorf("Failed to marshal error to JSON: %v", err)
return err
}
msg := string(jsonMessage)
http.Error(w, msg, he.scode)
return nil
}
41 changes: 41 additions & 0 deletions lib/servererror_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
Copyright IBM Corp. 2017 All Rights Reserved.
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
http://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 lib

import (
"strings"
"testing"
)

func TestErrorString(t *testing.T) {
msg := "message"
err := newHTTPErr(400, ErrMethodNotAllowed, "%s", msg)
errMsg := err.Error()
if !strings.HasSuffix(errMsg, msg) {
t.Errorf("Error message doesn't end with %s: %s", msg, errMsg)
}
}

func TestRemoteErrorString(t *testing.T) {
lmsg := "local message"
rmsg := "remote message"
err := newHTTPErr(401, ErrMethodNotAllowed, "%s", lmsg).remote(ErrUnknown, rmsg)
errMsg := err.Error()
if !strings.HasSuffix(errMsg, rmsg) {
t.Errorf("Error message doesn't end with %s: %s", rmsg, errMsg)
}
}

0 comments on commit 00caa9c

Please sign in to comment.