-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsanitization.go
More file actions
234 lines (220 loc) · 6.14 KB
/
Copy pathsanitization.go
File metadata and controls
234 lines (220 loc) · 6.14 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package main
import (
"bytes"
"encoding/json"
"sort"
"strings"
)
type orderedReplacement struct {
src string
dst string
order int
seq int
}
func sanitizeRequest(body []byte, cfg sanitizationConfig, model, sourceFormat, toFormat string) ([]byte, int, error) {
return sanitizeRequestForStage(body, cfg, model, sourceFormat, toFormat, false)
}
func sanitizeRequestAfterAuth(body []byte, cfg sanitizationConfig, model, sourceFormat, toFormat string) ([]byte, int, error) {
return sanitizeRequestForStage(body, cfg, model, sourceFormat, toFormat, true)
}
func sanitizeRequestForStage(body []byte, cfg sanitizationConfig, model, sourceFormat, toFormat string, afterAuth bool) ([]byte, int, error) {
if !cfg.Enabled || len(cfg.ReplacementGroups) == 0 || len(body) == 0 {
return body, 0, nil
}
rules := matchingReplacements(cfg, model, sourceFormat, toFormat, afterAuth)
if len(rules) == 0 {
return body, 0, nil
}
root, err := decodeJSON(body)
if err != nil {
return nil, 0, err
}
// request.intercept_after runs after credential selection but before CPA
// translates the payload. toFormat selects provider-scoped rules; the body
// is still in the original client format and must use the source adapter.
count := sanitizeProtocolRequest(root, rules, sourceFormat)
if count == 0 {
return body, 0, nil
}
out, err := marshalJSON(root)
return out, count, err
}
func matchingReplacements(cfg sanitizationConfig, model, sourceFormat, toFormat string, afterAuth bool) []orderedReplacement {
var out []orderedReplacement
seq := 0
for _, group := range cfg.ReplacementGroups {
if afterAuth != (len(group.ToFormats) != 0) {
continue
}
if !matchesAnyOrEmpty(group.Models, model) || !matchesAnyOrEmpty(group.SourceFormats, sourceFormat) || !matchesAnyOrEmpty(group.ToFormats, toFormat) {
continue
}
// Octopus base_urls cannot be evaluated through CPA's public interceptor
// contract. Do not silently broaden a legacy URL-scoped rule.
if len(group.BaseURLs) != 0 {
continue
}
for index, item := range group.Replacements {
if item.Src == "" {
continue
}
order := index
if item.Order != nil {
order = *item.Order
}
out = append(out, orderedReplacement{src: item.Src, dst: item.Dst, order: order, seq: seq})
seq++
}
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].order == out[j].order {
return out[i].seq < out[j].seq
}
return out[i].order < out[j].order
})
return out
}
func sanitizeNode(value any, rules []orderedReplacement) int {
switch node := value.(type) {
case map[string]any:
count := 0
role, _ := node["role"].(string)
if sanitizableRole(role) {
for _, key := range []string{"content", "text", "parts", "reasoning", "reasoning_content"} {
if child, ok := node[key]; ok {
updated, n := sanitizeTextContainer(child, rules, true)
node[key] = updated
count += n
}
}
}
for _, key := range []string{"system", "instructions", "systemInstruction", "system_instruction"} {
if child, ok := node[key]; ok {
updated, n := sanitizeTextContainer(child, rules, true)
node[key] = updated
count += n
}
}
for key, child := range node {
switch key {
case "content", "text", "parts", "reasoning", "reasoning_content", "system", "instructions", "systemInstruction", "system_instruction":
continue
}
count += sanitizeNode(child, rules)
}
return count
case []any:
count := 0
for _, child := range node {
count += sanitizeNode(child, rules)
}
return count
default:
return 0
}
}
func sanitizeTextContainer(value any, rules []orderedReplacement, allowString bool) (any, int) {
switch node := value.(type) {
case string:
if !allowString {
return node, 0
}
return applyLiteralReplacements(node, rules)
case []any:
count := 0
for index, child := range node {
updated, n := sanitizeTextContainer(child, rules, true)
node[index] = updated
count += n
}
return node, count
case map[string]any:
count := 0
for key, child := range node {
allowed := key == "text" || key == "content" || key == "input_text" || key == "output_text" || key == "parts"
updated, n := sanitizeTextContainer(child, rules, allowed)
node[key] = updated
count += n
}
return node, count
default:
return value, 0
}
}
func applyLiteralReplacements(text string, rules []orderedReplacement) (string, int) {
result := text
count := 0
for _, rule := range rules {
if !strings.Contains(result, rule.src) {
continue
}
count += strings.Count(result, rule.src)
result = strings.ReplaceAll(result, rule.src, rule.dst)
}
return result, count
}
func sanitizableRole(role string) bool {
switch strings.ToLower(strings.TrimSpace(role)) {
case "system", "developer", "assistant", "model":
return true
default:
return false
}
}
func matchesAnyOrEmpty(patterns []string, value string) bool {
if len(patterns) == 0 {
return true
}
for _, pattern := range patterns {
if globMatch(pattern, value) {
return true
}
}
return false
}
func globMatch(pattern, value string) bool {
patternIndex, valueIndex := 0, 0
starIndex, starValueIndex := -1, -1
for valueIndex < len(value) {
if patternIndex < len(pattern) && (pattern[patternIndex] == '?' || pattern[patternIndex] == value[valueIndex]) {
patternIndex++
valueIndex++
continue
}
if patternIndex < len(pattern) && pattern[patternIndex] == '*' {
starIndex = patternIndex
starValueIndex = valueIndex
patternIndex++
continue
}
if starIndex >= 0 {
patternIndex = starIndex + 1
starValueIndex++
valueIndex = starValueIndex
continue
}
return false
}
for patternIndex < len(pattern) && pattern[patternIndex] == '*' {
patternIndex++
}
return patternIndex == len(pattern)
}
func decodeJSON(body []byte) (any, error) {
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.UseNumber()
var root any
if err := decoder.Decode(&root); err != nil {
return nil, err
}
return root, nil
}
func marshalJSON(value any) ([]byte, error) {
var buffer bytes.Buffer
encoder := json.NewEncoder(&buffer)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(value); err != nil {
return nil, err
}
return bytes.TrimSuffix(buffer.Bytes(), []byte("\n")), nil
}