-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
embed.go
113 lines (95 loc) · 2.34 KB
/
embed.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package jsonx
import (
"encoding/base64"
"encoding/json"
"net/url"
"strconv"
"strings"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/ory/x/osx"
"github.com/ory/x/stringslice"
)
type options struct {
ignoreKeys []string
onlySchemes []string
}
type OptionsModifier func(*options)
func newOptions(o []OptionsModifier) *options {
opt := &options{}
for _, f := range o {
f(opt)
}
return opt
}
func WithIgnoreKeys(keys ...string) OptionsModifier {
return func(o *options) {
o.ignoreKeys = keys
}
}
func WithOnlySchemes(scheme ...string) OptionsModifier {
return func(o *options) {
o.onlySchemes = scheme
}
}
func EmbedSources(in json.RawMessage, opts ...OptionsModifier) (out json.RawMessage, err error) {
out = make([]byte, len(in))
copy(out, in)
if err := embed(gjson.ParseBytes(in), nil, &out, newOptions(opts)); err != nil {
return nil, err
}
return out, nil
}
func embed(parsed gjson.Result, parents []string, result *json.RawMessage, o *options) (err error) {
if parsed.IsObject() {
parsed.ForEach(func(k, v gjson.Result) bool {
err = embed(v, append(parents, strings.ReplaceAll(k.String(), ".", "\\.")), result, o)
return err == nil
})
if err != nil {
return err
}
} else if parsed.IsArray() {
for kk, vv := range parsed.Array() {
if err = embed(vv, append(parents, strconv.Itoa(kk)), result, o); err != nil {
return err
}
}
} else if parsed.Type != gjson.String {
return nil
}
if len(parents) > 0 && stringslice.Has(o.ignoreKeys, parents[len(parents)-1]) {
return nil
}
loc, err := url.ParseRequestURI(parsed.String())
if err != nil {
// Not a URL, return
return nil
}
if len(o.onlySchemes) == 0 {
if loc.Scheme != "file" && loc.Scheme != "http" && loc.Scheme != "https" && loc.Scheme != "base64" {
// Not a known pattern, ignore
return nil
}
} else if !stringslice.Has(o.onlySchemes, loc.Scheme) {
// Not a known pattern, ignore
return nil
}
contents, err := osx.ReadFileFromAllSources(loc.String())
if err != nil {
return err
}
encoded := base64.StdEncoding.EncodeToString(contents)
key := strings.Join(parents, ".")
if key == "" {
key = "@"
}
interim, err := sjson.SetBytes(*result, key, "base64://"+encoded)
if err != nil {
return err
}
*result = interim
return
}