Files

110 lines
4.4 KiB
Go

package securityaudit
import (
"bytes"
"encoding/base64"
"encoding/binary"
"regexp"
"strings"
)
const (
// promptInlineImagePlaceholder replaces a stripped base64 image payload.
// The data URI header stays in place so nothing but verified image bytes
// leaves the scan.
promptInlineImagePlaceholder = "[image data omitted]"
// promptInlineImageMinPayloadChars keeps short payloads in the scan. Only
// large blobs threaten the shared audit deadline, and a short run of
// base64-alphabet characters is cheap to scan as ordinary text.
promptInlineImageMinPayloadChars = 256
)
// inlineImageDataURIPattern finds base64 image data URI candidates embedded in
// plain text, including the JSON-escaped form where "/" is written as "\/".
// Only the header is case-insensitive. The payload (group 1) is limited to the
// standard base64 alphabet with padding only at the end, so prose with spaces
// or punctuation is never captured.
var inlineImageDataURIPattern = regexp.MustCompile(
`(?i:data:image(?:/|\\/)[a-z0-9][a-z0-9.+-]*(?:;[a-z0-9._+-]+=[a-z0-9._+-]*)*;base64,)[ \t\r\n]*((?:[A-Za-z0-9+/]|\\/)+={0,2})`,
)
// sanitizePromptAuditText prepares one extracted text segment for the prompt
// guard. A base64 payload is replaced by a placeholder only when it decodes,
// as a whole, to a complete PNG/JPEG/GIF/WEBP file (signature and trailer).
// Structured input_image parts are already skipped during extraction. The
// data URI header and everything that is not a verified image stays in the
// scan, and the text is never truncated: an over-long prompt keeps the
// existing fail-closed timeout path.
//
// Accepted residual: only the format signature and trailer are verified, not
// the inner structure. A sender can wrap base64-alphabet text (for example
// words joined by "+") in roughly 20 characters of forged framing and hide it
// from the guard. This is accepted because the sender controls the request
// anyway: instructions can already be base64-encoded or sent as structured
// images, which are not audited at all.
func sanitizePromptAuditText(value string) string {
if value == "" || (!strings.Contains(value, ";base64,") && !strings.Contains(value, ";BASE64,")) {
return value
}
matches := inlineImageDataURIPattern.FindAllStringSubmatchIndex(value, -1)
if len(matches) == 0 {
return value
}
var out strings.Builder
last := 0
for _, match := range matches {
payloadStart, payloadEnd := match[2], match[3]
if payloadStart < 0 || !inlineBase64PayloadIsImage(value[payloadStart:payloadEnd]) {
continue
}
_, _ = out.WriteString(value[last:payloadStart])
_, _ = out.WriteString(promptInlineImagePlaceholder)
last = payloadEnd
}
if last == 0 {
return value
}
_, _ = out.WriteString(value[last:])
return out.String()
}
// inlineBase64PayloadIsImage strictly decodes the whole payload and requires a
// binary raster image framed by its format signature and trailer. Text-based
// formats such as SVG are deliberately excluded: their decoded content is
// readable markup and must stay in the audit scan.
func inlineBase64PayloadIsImage(payload string) bool {
if len(payload) < promptInlineImageMinPayloadChars {
return false
}
payload = strings.ReplaceAll(payload, `\/`, "/")
// Cheap signature check on the first bytes before decoding the whole blob.
head, err := base64.StdEncoding.DecodeString(payload[:16])
if err != nil || !hasInlineImageSignature(head) {
return false
}
data, err := base64.StdEncoding.Strict().DecodeString(payload)
if err != nil {
return false
}
switch {
case bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")):
return bytes.HasSuffix(data, []byte("IEND\xaeB`\x82"))
case bytes.HasPrefix(data, []byte{0xff, 0xd8, 0xff}):
return bytes.HasSuffix(data, []byte{0xff, 0xd9})
case bytes.HasPrefix(data, []byte("GIF87a")), bytes.HasPrefix(data, []byte("GIF89a")):
return data[len(data)-1] == 0x3b
case len(data) >= 12 && bytes.Equal(data[:4], []byte("RIFF")) && bytes.Equal(data[8:12], []byte("WEBP")):
return int(binary.LittleEndian.Uint32(data[4:8])) == len(data)-8
default:
return false
}
}
func hasInlineImageSignature(head []byte) bool {
return bytes.HasPrefix(head, []byte("\x89PNG\r\n\x1a\n")) ||
bytes.HasPrefix(head, []byte{0xff, 0xd8, 0xff}) ||
bytes.HasPrefix(head, []byte("GIF87a")) || bytes.HasPrefix(head, []byte("GIF89a")) ||
(len(head) >= 12 && bytes.Equal(head[:4], []byte("RIFF")) && bytes.Equal(head[8:12], []byte("WEBP")))
}