Repository navigation
Expand file tree
/
Copy pathvalidators.go
More file actions
422 lines (387 loc) · 11.6 KB
/
Copy pathvalidators.go
File metadata and controls
422 lines (387 loc) · 11.6 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package portcullis
import (
"encoding/base64"
"encoding/json"
"hash/crc32"
"net/url"
"strconv"
"strings"
"time"
"unicode"
)
const (
githubChecksumLen = 6
base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
awsKeyIDAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
bech32Alphabet = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
)
// validGitHubChecksum verifies a GitHub token's trailing 6-char base62
// CRC32. GitHub computes the checksum over the random body that follows
// the prefix (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, or `github_pat_`),
// not over the prefix itself.
func validGitHubChecksum(token string) bool {
body, ok := stripGitHubPrefix(token)
if !ok || len(body) <= githubChecksumLen {
return false
}
provided := body[len(body)-githubChecksumLen:]
return provided == base62CRC32(body[:len(body)-githubChecksumLen])
}
var gitHubTokenPrefixes = []string{"ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_"}
func stripGitHubPrefix(token string) (string, bool) {
for _, p := range gitHubTokenPrefixes {
if rest, ok := strings.CutPrefix(token, p); ok {
return rest, true
}
}
return "", false
}
// validGitHubStatelessToken accepts the post-2026 stateless GitHub
// App installation-token format: a `ghs_` prefix followed by a JWT.
// The legacy stateful format (random body + base62 CRC32 trailer) is
// still validated by [validGitHubChecksum] via the github-app-token
// rule; this one covers the new shape that GitHub is rolling out per
// their 2026 changelog (`X-GitHub-Stateless-S2S-Token`).
func validGitHubStatelessToken(token string) bool {
rest, ok := strings.CutPrefix(token, "ghs_")
return ok && validJWT(rest)
}
func validJWT(token string) bool {
parts := strings.Split(token, ".")
if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" {
return false
}
var header struct {
Alg string `json:"alg"`
Typ string `json:"typ"`
}
if !decodeJSON(parts[0], &header) || header.Alg == "" || strings.EqualFold(header.Alg, "none") {
return false
}
var payload map[string]any
if !decodeJSON(parts[1], &payload) || len(payload) == 0 {
return false
}
return true
}
func decodeJSON(segment string, v any) bool {
decoded, err := base64.RawURLEncoding.DecodeString(segment)
if err != nil {
return false
}
return json.Unmarshal(decoded, v) == nil
}
func validAgeSecretKey(token string) bool {
if strings.ToUpper(token) != token || !strings.HasPrefix(token, "AGE-SECRET-KEY-1") {
return false
}
data, ok := bech32Decode(strings.ToLower(token), "age-secret-key-")
if !ok {
return false
}
decoded, ok := convertBits(data, 5, 8, false)
return ok && len(decoded) == 32
}
func bech32Decode(s, expectedHRP string) ([]byte, bool) {
pos := strings.LastIndexByte(s, '1')
if pos < 1 || pos+7 > len(s) || s[:pos] != expectedHRP {
return nil, false
}
data := make([]byte, len(s)-pos-1)
for i, c := range s[pos+1:] {
idx := strings.IndexRune(bech32Alphabet, c)
if idx < 0 {
return nil, false
}
data[i] = byte(idx)
}
if !validBech32Checksum(s[:pos], data) {
return nil, false
}
return data[:len(data)-6], true
}
func validBech32Checksum(hrp string, data []byte) bool {
return bech32Polymod(append(bech32HRPExpand(hrp), data...)) == 1
}
func bech32HRPExpand(hrp string) []byte {
expanded := make([]byte, 0, len(hrp)*2+1)
for _, c := range hrp {
expanded = append(expanded, byte(c>>5))
}
expanded = append(expanded, 0)
for _, c := range hrp {
expanded = append(expanded, byte(c&31))
}
return expanded
}
func bech32Polymod(values []byte) uint32 {
chk := uint32(1)
for _, v := range values {
top := chk >> 25
chk = (chk&0x1ffffff)<<5 ^ uint32(v)
for i, generator := range []uint32{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} {
if (top>>i)&1 != 0 {
chk ^= generator
}
}
}
return chk
}
func convertBits(data []byte, from, to uint, pad bool) ([]byte, bool) {
var acc, bits uint
maxv := uint((1 << to) - 1)
maxAcc := uint((1 << (from + to - 1)) - 1)
var ret []byte
for _, value := range data {
v := uint(value)
if v>>from != 0 {
return nil, false
}
acc = ((acc << from) | v) & maxAcc
bits += from
for bits >= to {
bits -= to
ret = append(ret, byte((acc>>bits)&maxv))
}
}
if pad {
if bits > 0 {
ret = append(ret, byte((acc<<(to-bits))&maxv))
}
} else if bits >= from || ((acc<<(to-bits))&maxv) != 0 {
return nil, false
}
return ret, true
}
func validDiscordWebhookURL(token string) bool {
u, err := url.Parse(token)
if err != nil {
return false
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) != 4 || parts[0] != "api" || parts[1] != "webhooks" || parts[3] == "" {
return false
}
id, err := strconv.ParseUint(parts[2], 10, 64)
if err != nil {
return false
}
timestamp := time.UnixMilli(int64((id >> 22) + 1_420_070_400_000))
now := time.Now()
return !timestamp.Before(time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)) && !timestamp.After(now.Add(24*time.Hour))
}
func validAzureStorageAccountKey(token string) bool {
decoded, err := base64.StdEncoding.DecodeString(token)
return err == nil && len(decoded) == 64
}
func validDockerConfigSecret(token string) bool {
decoded, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return false
}
var cfg struct {
Auths map[string]struct {
Auth string `json:"auth"`
} `json:"auths"`
}
if err := json.Unmarshal(decoded, &cfg); err != nil || len(cfg.Auths) == 0 {
return false
}
for registry, auth := range cfg.Auths {
if registry == "" || auth.Auth == "" {
return false
}
if _, err := base64.StdEncoding.DecodeString(auth.Auth); err != nil {
return false
}
}
return true
}
func validCloudflareAPIKey(token string) bool {
return !strings.ContainsAny(token, "-_")
}
func validAWSBedrockLongLivedKey(token string) bool {
if len(token) != 132 || len(token)%4 != 0 {
return false
}
decoded, err := base64.StdEncoding.DecodeString(token[4:])
if err != nil {
return false
}
return strings.HasPrefix(string(decoded), "BedrockAPIKey-")
}
// The keywordless PII rules (credit card, IBAN, SSN) can't hide
// behind the Aho–Corasick keyword pre-filter, so without a cheap gate
// their expensive regexes would run over every clean input. Each
// prefilter below is a necessary condition for its rule's regex to
// match — it may pass inputs the regex ultimately rejects, but it
// never rejects an input the regex would accept — so clean prose
// (which has no long digit runs) skips the regex entirely.
// hasSeparatedDigitRun reports whether text contains a run of at
// least minDigits decimal digits in which consecutive digits are
// split by at most one separator byte. Separators are '-' and ' ';
// the wider ASCII-whitespace set (tab / newline / …) is folded in
// when ws is true, to mirror the card rule's [-\s] separator class.
func hasSeparatedDigitRun(text string, minDigits int, ws bool) bool {
for i := 0; i < len(text); {
// Skip prose without maintaining digit-run state for every byte.
for i < len(text) && (text[i] < '0' || text[i] > '9') {
i++
}
run := 0
for i < len(text) && text[i] >= '0' && text[i] <= '9' {
run++
if run >= minDigits {
return true
}
i++
if i < len(text) {
c := text[i]
if c == '-' || c == ' ' ||
(ws && (c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f')) {
i++
}
}
}
}
return false
}
// maybeCreditCard gates the card rule: its regex consumes at least 13
// digits (a 4-digit issuer group plus 9+ more) in a single [-\s]-
// separated run.
func maybeCreditCard(text string) bool { return hasSeparatedDigitRun(text, 13, true) }
// maybeSSN gates the SSN rule: its regex is 9 digits split by at most
// single '-'/' ' separators.
func maybeSSN(text string) bool { return hasSeparatedDigitRun(text, 9, false) }
// maybeIBAN gates the IBAN rule on its mandatory country-code +
// check-digit anchor: two ASCII letters immediately followed by two
// ASCII digits.
func maybeIBAN(text string) bool {
for i := 0; i+3 < len(text); i++ {
if isASCIILetter(text[i]) && isASCIILetter(text[i+1]) &&
text[i+2] >= '0' && text[i+2] <= '9' &&
text[i+3] >= '0' && text[i+3] <= '9' {
return true
}
}
return false
}
func isASCIILetter(c byte) bool {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
}
func validLuhn(value string) bool {
digits, total := 0, 0
for i := len(value) - 1; i >= 0; i-- {
c := value[i]
if c < '0' || c > '9' {
continue
}
d := int(c - '0')
if digits%2 == 1 {
d *= 2
if d > 9 {
d -= 9
}
}
total += d
digits++
if digits > 19 {
return false
}
}
return digits >= 13 && total%10 == 0
}
// ibanLengths maps an ISO 3166 country code to the total IBAN length the
// ISO 13616 registry defines for it. The mod-97 checksum alone passes one
// random string in 97, so a 4-character-grouped hex ID (a UUID tail, say)
// would otherwise read as an IBAN about once per hundred tries.
var ibanLengths = map[string]int{
"AD": 24, "AE": 23, "AL": 28, "AT": 20, "AZ": 28, "BA": 20, "BE": 16,
"BG": 22, "BH": 22, "BI": 27, "BR": 29, "BY": 28, "CH": 21, "CR": 22,
"CY": 28, "CZ": 24, "DE": 22, "DJ": 27, "DK": 18, "DO": 28, "EE": 20,
"EG": 29, "ES": 24, "FI": 18, "FK": 18, "FO": 18, "FR": 27, "GB": 22,
"GE": 22, "GI": 23, "GL": 18, "GR": 27, "GT": 28, "HR": 21, "HU": 28,
"IE": 22, "IL": 23, "IQ": 23, "IS": 26, "IT": 27, "JO": 30, "KW": 30,
"KZ": 20, "LB": 28, "LC": 32, "LI": 21, "LT": 20, "LU": 20, "LV": 21,
"LY": 25, "MC": 27, "MD": 24, "ME": 22, "MK": 19, "MN": 20, "MR": 27,
"MT": 31, "MU": 30, "NI": 28, "NL": 18, "NO": 15, "OM": 23, "PK": 24,
"PL": 28, "PS": 29, "PT": 25, "QA": 29, "RO": 24, "RS": 22, "RU": 33,
"SA": 24, "SC": 31, "SD": 18, "SE": 24, "SI": 19, "SK": 24, "SM": 27,
"SO": 23, "ST": 25, "SV": 28, "TL": 23, "TN": 24, "TR": 26, "UA": 29,
"VA": 22, "VG": 24, "XK": 20, "YE": 30,
}
// validIBAN accepts a value whose country code is a registered IBAN country,
// whose length is the one that country defines, and whose mod-97 checksum
// is 1.
func validIBAN(value string) bool {
s := strings.ToUpper(strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, value))
if want, ok := ibanLengths[s[:min(len(s), 2)]]; !ok || len(s) != want {
return false
}
mod := 0
for _, r := range s[4:] + s[:4] {
switch {
case r >= '0' && r <= '9':
mod = (mod*10 + int(r-'0')) % 97
case r >= 'A' && r <= 'Z':
mod = (mod*100 + int(r-'A'+10)) % 97
default:
return false
}
}
return mod == 1
}
func validUSSSN(value string) bool {
digits := make([]byte, 0, 9)
for _, r := range value {
if r >= '0' && r <= '9' {
digits = append(digits, byte(r))
}
}
if len(digits) != 9 {
return false
}
area, _ := strconv.Atoi(string(digits[:3]))
group, _ := strconv.Atoi(string(digits[3:5]))
serial, _ := strconv.Atoi(string(digits[5:]))
return area != 0 && area != 666 && area < 900 && group != 0 && serial != 0
}
func validAWSAccessKeyID(token string) bool {
if len(token) != 20 {
return false
}
encoded := base32Index(token[4:12]) - base32Index("QAAAAAAA")
if encoded < 0 {
return false
}
accountID := encoded * 2
if strings.IndexByte(awsKeyIDAlphabet, token[12]) >= strings.IndexByte(awsKeyIDAlphabet, 'Q') {
accountID++
}
return accountID <= 999_999_999_999
}
func base32Index(s string) int64 {
var n int64
for _, c := range s {
idx := strings.IndexRune(awsKeyIDAlphabet, c)
if idx < 0 {
return -1
}
n = n*32 + int64(idx)
}
return n
}
func base62CRC32(s string) string {
var out [githubChecksumLen]byte
checksum := uint64(crc32.ChecksumIEEE([]byte(s)))
for i := len(out) - 1; i >= 0; i-- {
out[i] = base62Alphabet[checksum%62]
checksum /= 62
}
return string(out[:])
}