Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/config/read_api_key_file.go
3431 views
1
package config
2
3
import (
4
"errors"
5
"fmt"
6
"io"
7
"os"
8
"path/filepath"
9
"strings"
10
)
11
12
const maxAPIKeyFileBytes int64 = 10 * 1024 // 10KB
13
14
func ReadAPIKeyFile(path string) (string, error) {
15
clean := filepath.Clean(path)
16
17
f, err := os.Open(clean)
18
if err != nil {
19
return "", fmt.Errorf("failed to open api key file: %w", err)
20
}
21
defer f.Close()
22
23
st, err := f.Stat()
24
if err != nil {
25
return "", fmt.Errorf("failed to stat api key file: %w", err)
26
}
27
28
if !st.Mode().IsRegular() {
29
return "", errors.New("api key file must be a regular file")
30
}
31
32
if st.Size() > maxAPIKeyFileBytes {
33
return "", fmt.Errorf("api key file too large (max %d bytes)", maxAPIKeyFileBytes)
34
}
35
36
r := io.LimitReader(f, maxAPIKeyFileBytes+1)
37
b, err := io.ReadAll(r)
38
if err != nil {
39
return "", fmt.Errorf("failed to read api key file: %w", err)
40
}
41
if int64(len(b)) > maxAPIKeyFileBytes {
42
return "", fmt.Errorf("api key file too large (max %d bytes)", maxAPIKeyFileBytes)
43
}
44
45
key := strings.TrimSpace(string(b))
46
if key == "" {
47
return "", errors.New("api key file is empty")
48
}
49
return key, nil
50
}
51
52
func MaxAPIKeyFileBytesForTest() int64 { return maxAPIKeyFileBytes }
53
54