Skip to content

Commit

Permalink
cleaner errors for cert validation
Browse files Browse the repository at this point in the history
  • Loading branch information
kayra1 committed Apr 18, 2024
1 parent ec1c385 commit a1fc40e
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
10 changes: 4 additions & 6 deletions internal/api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func PostCertificateRequest(env *Environment) http.HandlerFunc {
logError("given csr already recorded", http.StatusBadRequest, w)
return
} else {
logError(err.Error(), http.StatusBadRequest, w)
logError(err.Error(), http.StatusInternalServerError, w)
return
}
}
Expand Down Expand Up @@ -134,11 +134,9 @@ func PostCertificate(env *Environment) http.HandlerFunc {
id := r.PathValue("id")
insertId, err := env.DB.Update(id, string(cert))
if err != nil {
if err.Error() == "csr id not found" {
logError(err.Error(), http.StatusBadRequest, w)
return
}
if err.Error() == "certificate does not match CSR" {
if err.Error() == "csr id not found" ||
err.Error() == "certificate does not match CSR" ||
strings.Contains(err.Error(), "cert validation failed") {
logError(err.Error(), http.StatusBadRequest, w)
return
}
Expand Down
12 changes: 10 additions & 2 deletions internal/api/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,19 @@ func TestGoCertRouter(t *testing.T) {
status: http.StatusOK,
},
{
desc: "post cert2 fail",
desc: "post cert2 fail 1",
method: "POST",
path: "/api/v1/certificate_requests/4/certificate",
data: validCert2,
response: "error: certificate does not match CSR",
response: "error: cert validation failed: certificate does not match CSR",
status: http.StatusBadRequest,
},
{
desc: "post cert2 fail 2",
method: "POST",
path: "/api/v1/certificate_requests/4/certificate",
data: "some random data that's clearly not a cert",
response: "error: cert validation failed: PEM Certificate string not found or malformed",
status: http.StatusBadRequest,
},
{
Expand Down
4 changes: 2 additions & 2 deletions internal/certdb/certdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,14 @@ func (db *CertificateRequestsRepository) Create(csr string) (int64, error) {
// The given certificate must share the public key of the CSR and must be valid.
func (db *CertificateRequestsRepository) Update(id string, cert string) (int64, error) {
if err := ValidateCertificate(cert); err != nil {
return 0, err
return 0, errors.New("cert validation failed: " + err.Error())
}
csr, err := db.Retrieve(id)
if err != nil {
return 0, err
}
if err := CertificateMatchesCSR(cert, csr.CSR); err != nil {
return 0, err
return 0, errors.New("cert validation failed: " + err.Error())
}
result, err := db.conn.Exec(fmt.Sprintf(queryUpdateCSR, db.table), cert, csr.ID)
if err != nil {
Expand Down

0 comments on commit a1fc40e

Please sign in to comment.