istio.io/istio@v0.0.0-20240520182934-d79c90f27776/security/pkg/pki/error/error.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package error
    16  
    17  import "google.golang.org/grpc/codes"
    18  
    19  // ErrType is the type for CA errors.
    20  type ErrType int
    21  
    22  const (
    23  	// CANotReady means the CA is not ready to sign CSRs.
    24  	CANotReady ErrType = iota
    25  	// CSRError means the CA cannot sign CSR due to CSR error.
    26  	CSRError
    27  	// TTLError means the required TTL is invalid.
    28  	TTLError
    29  	// CertGenError means an error happened during the certificate generation.
    30  	CertGenError
    31  	// CAIllegalConfig means the configuration/deployment parameters for CA are incorrect
    32  	CAIllegalConfig
    33  	// CAInitFail means some other unexpected and fatal initilization failure
    34  	CAInitFail
    35  )
    36  
    37  // Error encapsulates the short and long errors.
    38  type Error struct {
    39  	t   ErrType
    40  	err error
    41  }
    42  
    43  // Error returns the string error message.
    44  func (e Error) Error() string {
    45  	return e.err.Error()
    46  }
    47  
    48  // ErrorType returns a short string representing the error type.
    49  func (e Error) ErrorType() string {
    50  	switch e.t {
    51  	case CANotReady:
    52  		return "CA_NOT_READY"
    53  	case CSRError:
    54  		return "CSR_ERROR"
    55  	case TTLError:
    56  		return "TTL_ERROR"
    57  	case CertGenError:
    58  		return "CERT_GEN_ERROR"
    59  	}
    60  	return "UNKNOWN"
    61  }
    62  
    63  // HTTPErrorCode returns an HTTP error code representing the error type.
    64  func (e Error) HTTPErrorCode() codes.Code {
    65  	switch e.t {
    66  	case CANotReady:
    67  		return codes.Internal
    68  	case CertGenError:
    69  		return codes.Internal
    70  	case CSRError:
    71  		return codes.InvalidArgument
    72  	case TTLError:
    73  		return codes.InvalidArgument
    74  	}
    75  	return codes.Internal
    76  }
    77  
    78  // NewError creates a new Error instance.
    79  func NewError(t ErrType, err error) *Error {
    80  	return &Error{
    81  		t:   t,
    82  		err: err,
    83  	}
    84  }