Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-pii/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,21 @@ extraction and configurable actions.
truncating it or installing a partial custom policy. Every detector runs under a
per-direction deadline enforced by a deadline-aware `CharSequence`; the deadline
bounds matching work, not regex compilation.
- Protocol profiles extract only the message text fields, so a redaction never touches
tool definitions, function arguments or other members: `openai-chat`
- Protocol profiles extract the message text of the payload: `openai-chat`
(`messages[].content` / `choices[].message.content`) and `openai-responses` (`input` /
`output[].content[].text`). The extraction containers and text member types are
`output[].content[].text`). Within a `content` part array, besides the plain `text` of a
part, the nested text of a `document` part (`source.data` of a `text` source) and of a
`file` part (a textual `file_data`, base64 decoded for scanning and re encoded after a
redaction) is extracted too, and so are the `arguments` of a tool call
(`tool_calls[].function.arguments`, the legacy `function_call.arguments`, and the
`arguments` of a responses `function_call` item). Binary content — an `image_url`,
`input_audio`, a base64 `document` source and a non textual `file_data` — is left out of
scope, since it cannot be meaningfully regex scanned; tool definitions and other nontext
members are never reported. The extraction containers and text member types are
validated before scanning. Unknown or malformed shapes are unsupported enforcement
modes: fail-closed rules reject them and fail-open rules warn and pass them through.
Validation is limited to extraction shape, not the complete provider schema. Valid
textless messages, such as tool calls or image-only content, remain supported.
textless messages, such as image-only content, remain supported.
- Redaction happens on the parsed JSON tree and only inside the extracted fields, so the
JSON structure and the escaping of everything else are preserved. Overlapping detections
are merged on the original coordinates before anything is replaced, the merged range
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.shenyu.plugin.ai.pii.profile;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
import java.util.Objects;

/**
* The base64 {@code data:} URL text carriers of a payload, for example the
* {@code file_data} of an OpenAI file content part. Only a textual media type
* is scannable, so {@code text/*} and {@code application/json} are decoded and
* every other media type, a plain non data URL string and a corrupt payload are
* reported as not scannable and left untouched. Decoding tolerates the two
* base64 flavours real clients emit: MIME wrapped payloads with line breaks and
* the URL safe alphabet, so a wrapped or URL safe {@code file_data} is scanned
* instead of silently passed through.
*/
final class Base64TextData {

private static final String DATA_SCHEME = "data:";

private static final String BASE64_PARAMETER = ";base64";

private Base64TextData() {
}

/**
* The header of a textual base64 {@code data:} URL, up to and including the
* comma that separates it from the payload.
*
* @param value the member value
* @return the header, or null when the value is not a textual base64 data URL
*/
static String prefix(final String value) {
if (Objects.isNull(value) || !value.startsWith(DATA_SCHEME)) {
return null;
}
int comma = value.indexOf(',');
if (comma < 0) {
return null;
}
String meta = value.substring(DATA_SCHEME.length(), comma).toLowerCase(Locale.ROOT);
if (!meta.endsWith(BASE64_PARAMETER)) {
return null;
}
int semicolon = meta.indexOf(';');
String mediaType = semicolon < 0 ? meta : meta.substring(0, semicolon);
return isTextualMediaType(mediaType) ? value.substring(0, comma + 1) : null;
}

/**
* Whether the value is a textual base64 {@code data:} URL, so its payload is
* text this plugin claims to scan.
*
* @param value the member value
* @return true when the payload is scannable text
*/
static boolean isTextualDataUrl(final String value) {
return Objects.nonNull(prefix(value));
}

/**
* Decode the payload of a textual base64 {@code data:} URL to text.
*
* @param value the member value
* @return the decoded text, or null when the value is not a textual base64
* data URL or its payload is corrupt
*/
static String decode(final String value) {
String header = prefix(value);
if (Objects.isNull(header)) {
return null;
}
byte[] bytes = decodePayload(value.substring(header.length()));
return Objects.isNull(bytes) ? null : new String(bytes, StandardCharsets.UTF_8);
}

/**
* Encode text back under a data URL header, keeping the member a valid
* base64 {@code data:} URL. The standard padded alphabet is used, so a MIME
* wrapped or URL safe original is normalised by a redaction.
*
* @param prefix the data URL header of the original value
* @param text the redacted text
* @return the re encoded data URL
*/
static String encode(final String prefix, final String text) {
return prefix + Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
}

/**
* Whether the value is a textual base64 {@code data:} URL whose payload
* cannot be decoded. Such a member is a malformed extraction shape: the text
* is claimed to be scanned, so passing it through silently would leak it. A
* binary media type is out of scope instead and is not malformed.
*
* @param value the member value
* @return true when the payload is textual but undecodable
*/
static boolean isUndecodableTextualData(final String value) {
return isTextualDataUrl(value) && Objects.isNull(decode(value));
}

private static byte[] decodePayload(final String payload) {
try {
if (payload.indexOf('-') >= 0 || payload.indexOf('_') >= 0) {
// the URL safe decoder is strict about separators, so drop the wrapping first
return Base64.getUrlDecoder().decode(payload.replaceAll("\\s", ""));
}
// the MIME decoder tolerates line breaks and skips other non alphabet characters
return Base64.getMimeDecoder().decode(payload);
} catch (IllegalArgumentException e) {
return null;
}
}

private static boolean isTextualMediaType(final String mediaType) {
return mediaType.startsWith("text/") || "application/json".equals(mediaType);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.shenyu.plugin.ai.pii.profile;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.Objects;

/**
* The slot of a textual base64 {@code data:} URL member, created by
* {@link PiiTextSlot#ofBase64TextData}. The payload is decoded once and cached
* for the lifetime of the slot, so a large payload is not decoded again per
* read; a replacement re encodes the redacted text under the original data URL
* header, keeping the member a valid base64 {@code data:} URL.
*/
final class Base64TextDataSlot implements PiiTextSlot {

private final JsonObject parent;

private final String member;

private String cached;

private boolean decoded;

Base64TextDataSlot(final JsonObject parent, final String member) {
this.parent = parent;
this.member = member;
}

@Override
public String text() {
if (!decoded) {
JsonElement current = parent.get(member);
cached = Objects.nonNull(current) && current.isJsonPrimitive()
? Base64TextData.decode(current.getAsString())
: null;
decoded = true;
}
return cached;
}

@Override
public void replace(final String newText) {
JsonElement current = parent.get(member);
if (Objects.nonNull(current) && current.isJsonPrimitive()) {
String prefix = Base64TextData.prefix(current.getAsString());
if (Objects.nonNull(prefix)) {
parent.addProperty(member, Base64TextData.encode(prefix, newText));
}
}
// keep the cache coherent with the tree for a later read of the same slot
cached = newText;
decoded = true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.apache.shenyu.plugin.ai.pii.profile;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

Expand All @@ -27,9 +26,11 @@

/**
* The OpenAI chat completions profile. A request carries {@code messages}
* whose {@code content} is either a string or an array of typed parts with a
* {@code text} member; a non streaming response carries the same shape below
* {@code choices[].message.content}.
* whose {@code content} is either a string or an array of typed parts, and a
* non streaming response carries the same shape below
* {@code choices[].message.content}. Besides the plain {@code text} of a part,
* the nested text of {@code document} and {@code file} parts and the arguments
* of the tool calls of a message are extracted too.
*/
public class OpenAiChatProfile implements PiiProtocolProfile {

Expand Down Expand Up @@ -75,30 +76,17 @@ public List<PiiTextSlot> responseSlots(final JsonObject root) {

private void collectContentSlots(final JsonObject message, final List<PiiTextSlot> slots) {
JsonElement content = message.get("content");
if (Objects.isNull(content)) {
return;
}
if (content.isJsonPrimitive() && content.getAsJsonPrimitive().isString()) {
PiiTextSlot slot = PiiTextSlot.ofMember(message, "content");
if (Objects.nonNull(slot)) {
slots.add(slot);
}
return;
}
if (content.isJsonArray()) {
collectPartTextSlots(content.getAsJsonArray(), slots);
}
}

private void collectPartTextSlots(final JsonArray parts, final List<PiiTextSlot> slots) {
for (JsonElement part : parts) {
if (!part.isJsonObject()) {
continue;
}
PiiTextSlot slot = PiiTextSlot.ofMember(part.getAsJsonObject(), "text");
if (Objects.nonNull(slot)) {
slots.add(slot);
if (Objects.nonNull(content)) {
if (content.isJsonPrimitive() && content.getAsJsonPrimitive().isString()) {
PiiTextSlot slot = PiiTextSlot.ofMember(message, "content");
if (Objects.nonNull(slot)) {
slots.add(slot);
}
} else if (content.isJsonArray()) {
PiiContentParts.collectPartSlots(content.getAsJsonArray(), slots);
}
}
// an assistant message can embed identifiers in the tool call arguments
PiiContentParts.collectToolCallSlots(message, slots);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@
/**
* The OpenAI responses profile. A request carries {@code input}, either a
* string or an array of items whose message text lives in {@code content},
* itself a string, an array of typed parts with a {@code text} member, or a
* plain {@code text} member. A non streaming response carries the message
* text below {@code output[].content[].text}.
* itself a string, an array of typed parts, or a plain {@code text} member. A
* non streaming response carries the message text below
* {@code output[].content[].text}. Besides the plain {@code text} of a part,
* the nested text of {@code document} and {@code file} parts and the
* {@code arguments} of a {@code function_call} item are extracted too.
*/
public class OpenAiResponsesProfile implements PiiProtocolProfile {

Expand Down Expand Up @@ -95,20 +97,14 @@ private void collectItemSlots(final JsonObject object, final List<PiiTextSlot> s
slots.add(slot);
}
} else if (content.isJsonArray()) {
for (JsonElement part : content.getAsJsonArray()) {
if (!part.isJsonObject()) {
continue;
}
PiiTextSlot slot = PiiTextSlot.ofMember(part.getAsJsonObject(), "text");
if (Objects.nonNull(slot)) {
slots.add(slot);
}
}
PiiContentParts.collectPartSlots(content.getAsJsonArray(), slots);
}
}
PiiTextSlot text = PiiTextSlot.ofMember(object, "text");
if (Objects.nonNull(text)) {
slots.add(text);
}
// a function_call item embeds its identifiers in the arguments JSON string
PiiContentParts.collectFunctionCallArguments(object, slots);
}
}
Loading
Loading