forked from direnv/direnv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgzenv.go
64 lines (52 loc) · 1.44 KB
/
gzenv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// the gzenv format: json+gzip+base64
// a quickly designed format to export the whole environment back into itself
package gzenv
import (
"bytes"
"compress/zlib"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"strings"
)
// Marshal encodes the object into the gzenv format
func Marshal(obj interface{}) string {
jsonData, err := json.Marshal(obj)
if err != nil {
panic(fmt.Errorf("marshal(): %w", err))
}
zlibData := bytes.NewBuffer([]byte{})
w := zlib.NewWriter(zlibData)
// we assume the zlib writer would never fail
_, _ = w.Write(jsonData)
w.Close()
base64Data := base64.URLEncoding.EncodeToString(zlibData.Bytes())
return base64Data
}
// Unmarshal restores the gzenv format back into a Go object
func Unmarshal(gzenv string, obj interface{}) error {
gzenv = strings.TrimSpace(gzenv)
data, err := base64.URLEncoding.DecodeString(gzenv)
if err != nil {
return fmt.Errorf("unmarshal() base64 decoding: %w", err)
}
zlibReader := bytes.NewReader(data)
w, err := zlib.NewReader(zlibReader)
if err != nil {
return fmt.Errorf("unmarshal() zlib opening: %w", err)
}
envData := bytes.NewBuffer([]byte{})
// G110: Potential DoS vulnerability via decompression bomb (gosec)
// #nosec
_, err = io.Copy(envData, w)
if err != nil {
return fmt.Errorf("unmarshal() zlib decoding: %w", err)
}
w.Close()
err = json.Unmarshal(envData.Bytes(), &obj)
if err != nil {
return fmt.Errorf("unmarshal() json parsing: %w", err)
}
return nil
}