Skip to content

Commit 89e48bb

Browse files
committed
refactor: wrap all package errors
1 parent 02454d4 commit 89e48bb

14 files changed

Lines changed: 215 additions & 85 deletions

File tree

.golangci.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ linters:
2020
- dupword
2121
- durationcheck
2222
- embeddedstructfieldcheck
23-
#- err113
23+
- err113
2424
- errcheck
2525
- errchkjson
2626
- errname
@@ -87,7 +87,7 @@ linters:
8787
- varnamelen
8888
- wastedassign
8989
- whitespace
90-
#- wrapcheck
90+
- wrapcheck
9191
- wsl_v5
9292
settings:
9393
lll:
@@ -135,6 +135,7 @@ linters:
135135
- wsl_v5
136136
- varnamelen
137137
- goconst
138+
- err113
138139
path: _test\.go
139140
- linters:
140141
- gochecknoinits

cmd/certpicker/main.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,5 +120,10 @@ func getEntry(jsonClient *client.LogClient, certID int64) (*ct.GetEntriesRespons
120120
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
121121
defer cancel()
122122

123-
return jsonClient.GetRawEntries(ctx, certID, certID)
123+
entries, err := jsonClient.GetRawEntries(ctx, certID, certID)
124+
if err != nil {
125+
return nil, fmt.Errorf("error getting raw entries: %w", err)
126+
}
127+
128+
return entries, nil
124129
}

cmd/certstream-server-go/createIndex.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,30 +22,30 @@ create-index will create and pre fill the ct-index.json file with the current va
2222
RunE: func(cmd *cobra.Command, _ []string) error {
2323
configPath, err := cmd.Flags().GetString("config")
2424
if err != nil {
25-
return err
25+
return fmt.Errorf("failed to obtain 'config' flag: %w", err)
2626
}
2727

2828
conf, readConfErr := config.ReadConfig(configPath)
2929
if readConfErr != nil {
30-
return readConfErr
30+
return fmt.Errorf("failed to read config file: %w", readConfErr)
3131
}
3232

3333
certstreamServer := certstream.NewRawCertstream(conf)
3434

3535
force, err := cmd.Flags().GetBool("force")
3636
if err != nil {
37-
return err
37+
return fmt.Errorf("failed to obtain 'force' flag: %w", err)
3838
}
3939

4040
outFilePath, err := cmd.Flags().GetString("out")
4141
if err != nil {
42-
return err
42+
return fmt.Errorf("failed to obtain 'out' flag: %w", err)
4343
}
4444

4545
// Check if outfile already exists
4646
outFileAbsPath, err := filepath.Abs(outFilePath)
4747
if err != nil {
48-
return err
48+
return fmt.Errorf("failed to obtain absolute path: %w", err)
4949
}
5050

5151
if _, statErr := os.Stat(outFileAbsPath); statErr == nil {

cmd/certstream-server-go/root.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ certificate transparency logs via websocket connections to connected clients.`,
2222
// Handle --version flag
2323
versionBool, err := cmd.Flags().GetBool("version")
2424
if err != nil {
25-
return err
25+
return fmt.Errorf("failed to obtain 'version' flag: %w", err)
2626
}
2727

2828
if versionBool {
@@ -33,13 +33,13 @@ certificate transparency logs via websocket connections to connected clients.`,
3333
// Handle --config flag
3434
configPath, err := cmd.Flags().GetString("config")
3535
if err != nil {
36-
return err
36+
return fmt.Errorf("failed to obtain 'config' flag: %w", err)
3737
}
3838

3939
// Check if path exists and is a file
4040
_, statErr := os.Stat(configPath)
4141
if os.IsNotExist(statErr) {
42-
return fmt.Errorf("config file '%s' does not exist", configPath)
42+
return fmt.Errorf("config file '%s' does not exist: %w", configPath, statErr)
4343
}
4444

4545
certstreamServer, err := certstream.NewCertstreamFromConfigFile(configPath)

cmd/certstream-server-go/validate.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,21 @@ This command deserializes the config and checks for errors.`,
2121
// Check if config file exists
2222
configPath, err := cmd.Flags().GetString("config")
2323
if err != nil {
24-
return err
24+
return fmt.Errorf("failed to obtain 'config' flag: %w", err)
2525
}
2626

2727
// Check if path exists and is a file
2828
_, statErr := os.Stat(configPath)
2929
if os.IsNotExist(statErr) {
30-
return fmt.Errorf("config file '%s' does not exist", configPath)
30+
return fmt.Errorf("config file '%s' does not exist: %w", configPath, statErr)
3131
}
3232

3333
return nil
3434
},
3535
RunE: func(cmd *cobra.Command, _ []string) error {
3636
configPath, err := cmd.Flags().GetString("config")
3737
if err != nil {
38-
return err
38+
return fmt.Errorf("failed to obtain 'config' flag: %w", err)
3939
}
4040

4141
readConfErr := config.ValidateConfig(configPath)

internal/certificatetransparency/ct-parser.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"crypto/sha256"
77
"encoding/base64"
88
"encoding/hex"
9-
"errors"
109
"fmt"
1110
"hash"
1211
"log"
@@ -50,7 +49,7 @@ func parseData(entry *ct.RawLogEntry, operatorName, logName, ctURL, logType stri
5049
logEntry, conversionErr := entry.ToLogEntry()
5150
if conversionErr != nil {
5251
log.Println("Could not convert entry to LogEntry: ", conversionErr)
53-
return models.Data{}, conversionErr
52+
return models.Data{}, fmt.Errorf("could not convert entry to logentry: %w", conversionErr)
5453
}
5554

5655
var cert *x509.Certificate
@@ -67,7 +66,7 @@ func parseData(entry *ct.RawLogEntry, operatorName, logName, ctURL, logType stri
6766
rawData = logEntry.Precert.Submitted.Data
6867
isPrecert = true
6968
default:
70-
return models.Data{}, errors.New("could not parse entry: no certificate found")
69+
return models.Data{}, ErrNoCertFound
7170
}
7271

7372
// Calculate certificate hash from the raw DER bytes of the certificate
@@ -109,8 +108,7 @@ func parseCertificateChain(logEntry *ct.LogEntry) ([]models.LeafCert, error) {
109108
for i, chainEntry := range logEntry.Chain {
110109
myCert, parseErr := x509.ParseCertificate(chainEntry.Data)
111110
if parseErr != nil || myCert == nil {
112-
log.Println("Error parsing certificate: ", parseErr)
113-
return nil, parseErr
111+
return nil, fmt.Errorf("could not parse certificate: %w", parseErr)
114112
}
115113

116114
leafCert := leafCertFromX509cert(*myCert)
@@ -426,7 +424,7 @@ func keyUsageToString(k x509.KeyUsage) string {
426424
// ParseCertstreamEntry creates an Entry from a ct.RawLogEntry.
427425
func ParseCertstreamEntry(rawEntry *ct.RawLogEntry, operatorName, logname, ctURL, logType string) (models.Entry, error) {
428426
if rawEntry == nil {
429-
return models.Entry{}, errors.New("certstream entry is nil")
427+
return models.Entry{}, ErrEntryNil
430428
}
431429

432430
data, err := parseData(rawEntry, operatorName, logname, ctURL, logType)

internal/certificatetransparency/ct-tiled.go

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package certificatetransparency
33
import (
44
"bufio"
55
"context"
6-
"errors"
76
"fmt"
87
"io"
98
"net/http"
@@ -67,21 +66,21 @@ func FetchCheckpoint(ctx context.Context, client *http.Client, baseURL string) (
6766
baseURL = strings.TrimRight(baseURL, "/")
6867
url := baseURL + "/checkpoint"
6968

70-
req, parseErr := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
71-
if parseErr != nil {
72-
return nil, fmt.Errorf("creating request: %w", parseErr)
69+
req, newReqErr := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
70+
if newReqErr != nil {
71+
return nil, fmt.Errorf("failed to create checkpoint request: %w", newReqErr)
7372
}
7473

75-
req.Header.Set("User-Agent", userAgent)
74+
req.Header.Set("User-Agent", UserAgent)
7675

77-
resp, parseErr := client.Do(req)
78-
if parseErr != nil {
79-
return nil, fmt.Errorf("fetching checkpoint: %w", parseErr)
76+
resp, reqErr := client.Do(req)
77+
if reqErr != nil {
78+
return nil, fmt.Errorf("failed to execute checkpoint request: %w", reqErr)
8079
}
8180
defer resp.Body.Close()
8281

8382
if resp.StatusCode != http.StatusOK {
84-
return nil, fmt.Errorf("checkpoint request failed with status: %d", resp.StatusCode)
83+
return nil, fmt.Errorf("%w: unexpected status code %d", ErrRequestFailed, resp.StatusCode)
8584
}
8685

8786
lines := make([]string, 0, 3)
@@ -92,16 +91,16 @@ func FetchCheckpoint(ctx context.Context, client *http.Client, baseURL string) (
9291
}
9392

9493
if scanErr := scanner.Err(); scanErr != nil {
95-
return nil, fmt.Errorf("reading checkpoint response: %w", scanErr)
94+
return nil, fmt.Errorf("failed reading response body: %w", scanErr)
9695
}
9796

9897
if len(lines) < 3 {
99-
return nil, fmt.Errorf("invalid checkpoint format: expected at least 3 lines, got %d", len(lines))
98+
return nil, fmt.Errorf("%w: invalid checkpoint format: expected at least 3 lines, got %d", ErrCheckpointInvalidFormat, len(lines))
10099
}
101100

102101
size, parseErr := strconv.ParseUint(lines[1], 10, 64)
103102
if parseErr != nil {
104-
return nil, fmt.Errorf("parsing tree size: %w", parseErr)
103+
return nil, fmt.Errorf("failed parsing tree size: %w", parseErr)
105104
}
106105

107106
return &TiledCheckpoint{
@@ -123,21 +122,21 @@ func FetchTile(ctx context.Context, client *http.Client, baseURL string, tileInd
123122

124123
url := fmt.Sprintf("%s/tile/data/%s", baseURL, tilePath)
125124

126-
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
127-
if err != nil {
128-
return nil, fmt.Errorf("creating request: %w", err)
125+
req, newReqErr := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
126+
if newReqErr != nil {
127+
return nil, fmt.Errorf("failed to create tile request: %w", newReqErr)
129128
}
130129

131-
req.Header.Set("User-Agent", userAgent)
130+
req.Header.Set("User-Agent", UserAgent)
132131

133-
resp, err := client.Do(req)
134-
if err != nil {
135-
return nil, fmt.Errorf("fetching tile %d: %w", tileIndex, err)
132+
resp, reqErr := client.Do(req)
133+
if reqErr != nil {
134+
return nil, fmt.Errorf("fetching tile %d: %w", tileIndex, reqErr)
136135
}
137136
defer resp.Body.Close()
138137

139138
if resp.StatusCode != http.StatusOK {
140-
return nil, fmt.Errorf("tile request failed with status: %d", resp.StatusCode)
139+
return nil, fmt.Errorf("%w: unexpected status code %d", ErrRequestFailed, resp.StatusCode)
141140
}
142141

143142
data, err := io.ReadAll(resp.Body)
@@ -157,7 +156,7 @@ func ParseTileData(data []byte) ([]TileLeaf, error) {
157156
var leaf TileLeaf
158157

159158
if !parser.ReadUint64(&leaf.Timestamp) || !parser.ReadUint16(&leaf.EntryType) {
160-
return nil, errors.New("invalid data tile header")
159+
return nil, fmt.Errorf("header: %w", ErrInvalidDataTile)
161160
}
162161

163162
switch leaf.EntryType {
@@ -168,15 +167,15 @@ func ParseTileData(data []byte) ([]TileLeaf, error) {
168167
if !parser.ReadUint24LengthPrefixed(&cert) ||
169168
!parser.ReadUint16LengthPrefixed(&extensions) ||
170169
!parser.ReadUint16LengthPrefixed(&fingerprints) {
171-
return nil, errors.New("invalid data tile x509_entry")
170+
return nil, fmt.Errorf("x509_entry: %w", ErrInvalidDataTile)
172171
}
173172

174173
leaf.X509Entry = append([]byte(nil), cert...)
175174

176175
for !fingerprints.Empty() {
177176
var fp [32]byte
178177
if !fingerprints.CopyBytes(fp[:]) {
179-
return nil, errors.New("invalid fingerprints: truncated")
178+
return nil, ErrInvalidFingerprint
180179
}
181180

182181
leaf.Chain = append(leaf.Chain, fp[:])
@@ -191,7 +190,7 @@ func ParseTileData(data []byte) ([]TileLeaf, error) {
191190
!parser.ReadUint16LengthPrefixed(&extensions) ||
192191
!parser.ReadUint24LengthPrefixed(&entry) ||
193192
!parser.ReadUint16LengthPrefixed(&fingerprints) {
194-
return nil, errors.New("invalid data tile precert_entry")
193+
return nil, fmt.Errorf("precert_entry: %w", ErrInvalidDataTile)
195194
}
196195

197196
leaf.PrecertEntry = append([]byte(nil), defangedCrt...)
@@ -200,14 +199,14 @@ func ParseTileData(data []byte) ([]TileLeaf, error) {
200199
for !fingerprints.Empty() {
201200
var fp [32]byte
202201
if !fingerprints.CopyBytes(fp[:]) {
203-
return nil, errors.New("invalid fingerprints: truncated")
202+
return nil, ErrInvalidFingerprint
204203
}
205204

206205
leaf.Chain = append(leaf.Chain, fp[:])
207206
}
208207

209208
default:
210-
return nil, fmt.Errorf("unknown entry type: %d", leaf.EntryType)
209+
return nil, fmt.Errorf("%w: %d", ErrUnknownEntryType, leaf.EntryType)
211210
}
212211

213212
leaves = append(leaves, leaf)

0 commit comments

Comments
 (0)