-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add ai-prompt-guard plugin #12008
Open
Revolyssup
wants to merge
11
commits into
apache:master
Choose a base branch
from
Revolyssup:revolyssup/ai-prompt-guard
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+649
−1
Open
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
aa8a312
feat: add ai-prompt-guard plugin
Revolyssup ca50ae4
remove redundant logs
Revolyssup 3060402
add license
Revolyssup 281e1a7
fix tests
Revolyssup b429a11
fix indent
Revolyssup e60fe9f
fix
Revolyssup 0d2fbb0
doc
Revolyssup a2dc11e
fix doc lint
Revolyssup ae547d7
fix doc lint
Revolyssup 5c1937b
fix lint
Revolyssup 88f9996
use regex
Revolyssup File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
-- | ||
-- 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. | ||
-- | ||
local core = require("apisix.core") | ||
local ngx = ngx | ||
local ipairs = ipairs | ||
local table = table | ||
|
||
local plugin_name = "ai-prompt-guard" | ||
|
||
local schema = { | ||
type = "object", | ||
properties = { | ||
match_all_roles = { | ||
type = "boolean", | ||
default = false, | ||
}, | ||
match_all_conversation_history = { | ||
type = "boolean", | ||
default = false, | ||
}, | ||
allow_patterns = { | ||
type = "array", | ||
items = {type = "string"}, | ||
default = {}, | ||
}, | ||
deny_patterns = { | ||
type = "array", | ||
items = {type = "string"}, | ||
default = {}, | ||
}, | ||
}, | ||
} | ||
|
||
local _M = { | ||
version = 0.1, | ||
priority = 1072, | ||
name = plugin_name, | ||
schema = schema, | ||
} | ||
|
||
function _M.check_schema(conf) | ||
return core.schema.check(schema, conf) | ||
end | ||
|
||
local function get_content_to_check(conf, messages) | ||
local contents = {} | ||
if conf.match_all_conversation_history then | ||
for _, msg in ipairs(messages) do | ||
if msg.content then | ||
core.table.insert(contents, msg.content) | ||
end | ||
end | ||
else | ||
if #messages > 0 then | ||
local last_msg = messages[#messages] | ||
if last_msg.content then | ||
core.table.insert(contents, last_msg.content) | ||
end | ||
end | ||
end | ||
return table.concat(contents, " ") | ||
end | ||
|
||
function _M.access(conf, ctx) | ||
local body = core.request.get_body() | ||
if not body then | ||
core.log.error("Empty request body") | ||
return 400, {message = "Empty request body"} | ||
end | ||
|
||
local json_body, err = core.json.decode(body) | ||
if err then | ||
return 400, {message = err} | ||
end | ||
|
||
|
||
local messages = json_body.messages or {} | ||
if not conf.match_all_roles and messages and messages[#messages].role ~= "user" then | ||
return | ||
end | ||
local content_to_check = get_content_to_check(conf, messages) | ||
|
||
-- Allow patterns check | ||
if #conf.allow_patterns > 0 then | ||
local any_allowed = false | ||
for _, pattern in ipairs(conf.allow_patterns) do | ||
if ngx.re.find(content_to_check, pattern, "jou") then | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the the current way is wrong |
||
any_allowed = true | ||
break | ||
end | ||
end | ||
if not any_allowed then | ||
return 400, {message = "Request doesn't match allow patterns"} | ||
end | ||
end | ||
|
||
-- Deny patterns check | ||
for _, pattern in ipairs(conf.deny_patterns) do | ||
if ngx.re.find(content_to_check, pattern, "jou") then | ||
return 400, {message = "Request contains prohibited content"} | ||
end | ||
end | ||
end | ||
|
||
return _M |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
--- | ||
title: ai-prompt-guard | ||
keywords: | ||
- Apache APISIX | ||
- API Gateway | ||
- Plugin | ||
- ai-prompt-guard | ||
description: This document contains information about the Apache APISIX ai-prompt-guard Plugin. | ||
--- | ||
|
||
<!-- | ||
# | ||
# 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. | ||
# | ||
--> | ||
|
||
## Description | ||
|
||
The `ai-prompt-guard` plugin safeguards your AI endpoints by inspecting and validating incoming prompt messages. It checks the content of requests against user-defined allowed and denied patterns to ensure that only approved inputs are processed. Based on its configuration, the plugin can either examine just the latest message or the entire conversation history, and it can be set to check prompts from all roles or only from end users. | ||
|
||
When both **allow** and **deny** patterns are configured, the plugin first ensures that at least one allowed pattern is matched. If none match, the request is rejected with a _"Request doesn't match allow patterns"_ error. If an allowed pattern is found, it then checks for any occurrences of denied patterns—rejecting the request with a _"Request contains prohibited content"_ error if any are detected. | ||
|
||
## Plugin Attributes | ||
|
||
| **Field** | **Required** | **Type** | **Description** | | ||
| ------------------------------ | ------------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| match_all_roles | No | boolean | If set to `true`, the plugin will check prompt messages from all roles. Otherwise, it only validates when its role is `"user"`. Default is `false`. | | ||
| match_all_conversation_history | No | boolean | When enabled, all messages in the conversation history are concatenated and checked. If `false`, only the content of the last message is examined. Default is `false`. | | ||
| allow_patterns | No | array | A list of regex patterns. When provided, the prompt must match **at least one** pattern to be considered valid. | | ||
| deny_patterns | No | array | A list of regex patterns. If any of these patterns match the prompt content, the request is rejected. | | ||
|
||
## Example usage | ||
|
||
Create a route with the `ai-prompt-guard` plugin like so: | ||
|
||
```shell | ||
curl "http://127.0.0.1:9180/apisix/admin/routes/1" -X PUT \ | ||
-H "X-API-KEY: ${ADMIN_API_KEY}" \ | ||
-d '{ | ||
"uri": "/v1/chat/completions", | ||
"plugins": { | ||
"ai-prompt-guard": { | ||
"match_all_roles": true, | ||
"allow_patterns": [ | ||
"goodword" | ||
], | ||
"deny_patterns": [ | ||
"badword" | ||
] | ||
} | ||
}, | ||
"upstream": { | ||
"type": "roundrobin", | ||
"nodes": { | ||
"api.openai.com:443": 1 | ||
}, | ||
"pass_host": "node", | ||
"scheme": "https" | ||
} | ||
}' | ||
``` | ||
|
||
Now send a request: | ||
|
||
```shell | ||
curl http://127.0.0.1:9080/v1/chat/completions -i -XPOST -H 'Content-Type: application/json' -d '{ | ||
"model": "gpt-4", | ||
"messages": [{ "role": "user", "content": "badword request" }] | ||
}' -H "Authorization: Bearer <your token here>" | ||
``` | ||
|
||
The request will fail with 400 error and following response. | ||
|
||
```bash | ||
{"message":"Request doesn't match allow patterns"} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
need to confirm the items in
allow_patterns[]
anddeny_patterns[]
, they should be a valid regexyou can call this function: https://github.com/openresty/lua-resty-core/blob/master/lib/resty/core/regex.lua#L639