fix: config.yaml模型路径/加载模式待修改,提交了plugins目录的lua插件,以及config.yaml中的配置
This commit is contained in:
1 parent
45e45948bd
commit
d93cf2d5e5
6 files changed
+1917
-114
No files matched your search
+738
-35
@@ -1,43 +1,746 @@
|
||||
-- Demonstrates cross-event inspection. Intentionally buffers the entire SSE response.
|
||||
-- Masking keeps byte lengths, so redacted text can be placed back in original events.
|
||||
-- Full-buffer SSE redaction example.
|
||||
--
|
||||
-- Scope: SSE only. Non-streaming responses are explicitly blocked by on_response
|
||||
-- so they cannot silently bypass this streaming-only redaction rule.
|
||||
-- All configured text events are held until normal end so sensitive values split
|
||||
-- across frames/array blocks can be detected. The administrator MUST configure
|
||||
-- terminal_error_events and control_event_names from the real Agent protocol;
|
||||
-- no guessed event-name list is silently treated as authoritative.
|
||||
-- Terminal errors discard held body text. Their own data is scrubbed for the
|
||||
-- supported deterministic patterns before being sent to the client.
|
||||
--
|
||||
-- The local buffer limit counts a conservative estimated footprint, not merely
|
||||
-- raw text bytes: event.data is weighted 3x and each frame has a fixed overhead.
|
||||
-- The host's max_plugin_buffer_bytes and Lua memory limits remain authoritative.
|
||||
-- This deterministic example is not a complete DLP implementation.
|
||||
|
||||
local plugin = {}
|
||||
local frames = {}
|
||||
function plugin.on_event(ctx, event)
|
||||
frames[#frames+1] = event
|
||||
return {action='hold'}
|
||||
local states = {}
|
||||
|
||||
local DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
|
||||
local HARD_MAX_BUFFER_BYTES = 320 * 1024
|
||||
local DEFAULT_TEXT_EVENT = "text_delta"
|
||||
local DEFAULT_CONTENT_PATH = { "data", "content" }
|
||||
|
||||
local settings = nil
|
||||
|
||||
local function request_key(ctx)
|
||||
if type(ctx) ~= "table" then return nil end
|
||||
local key = ctx.request_id
|
||||
if type(key) ~= "string" or key == "" then return nil end
|
||||
return key
|
||||
end
|
||||
function plugin.on_end(ctx)
|
||||
local text = {}
|
||||
local payloads = {}
|
||||
for i, event in ipairs(frames) do
|
||||
if event.event == 'text_delta' then
|
||||
local payload = host.json.decode(event.data)
|
||||
local content = payload.data and payload.data.content
|
||||
if type(content) ~= 'string' then return {action='block'} end
|
||||
text[#text+1] = content
|
||||
payloads[i] = payload
|
||||
|
||||
local function contains_cr_lf_nul(value)
|
||||
for i = 1, #value do
|
||||
local b = string.byte(value, i)
|
||||
if b == 0 or b == 10 or b == 13 then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function parse_content_path(value)
|
||||
if value == nil then
|
||||
local out = {}
|
||||
for i, part in ipairs(DEFAULT_CONTENT_PATH) do out[i] = part end
|
||||
return out
|
||||
end
|
||||
|
||||
local parts = {}
|
||||
if type(value) == "string" then
|
||||
if value == "" or string.sub(value, 1, 1) == "."
|
||||
or string.sub(value, -1) == "." or string.find(value, "%.%.") then
|
||||
return nil
|
||||
end
|
||||
for part in string.gmatch(value, "[^%.]+") do
|
||||
if part == "" or contains_cr_lf_nul(part) then return nil end
|
||||
-- A single wildcard supports homogeneous content-block arrays,
|
||||
-- e.g. content.*.text. Every selected leaf must be a string.
|
||||
parts[#parts + 1] = part
|
||||
end
|
||||
if #parts == 0 then return nil end
|
||||
return parts
|
||||
end
|
||||
|
||||
if type(value) == "table" then
|
||||
for i, part in ipairs(value) do
|
||||
if type(part) ~= "string" or part == "" or contains_cr_lf_nul(part) then
|
||||
return nil
|
||||
end
|
||||
parts[i] = part
|
||||
end
|
||||
local count = 0
|
||||
for k in pairs(value) do
|
||||
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then return nil end
|
||||
count = count + 1
|
||||
end
|
||||
if count == 0 or count ~= #parts then return nil end
|
||||
return parts
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function event_name_set(value, label, must_be_non_empty)
|
||||
if type(value) ~= "table" then
|
||||
error("stream_redact: config." .. label .. " must be an array of event names")
|
||||
end
|
||||
local set, count, max_index = {}, 0, 0
|
||||
for k, name in pairs(value) do
|
||||
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then
|
||||
error("stream_redact: config." .. label .. " must be a dense array")
|
||||
end
|
||||
if type(name) ~= "string" or name == "" or contains_cr_lf_nul(name) then
|
||||
error("stream_redact: config." .. label .. " entries must be non-empty event names without CR/LF/NUL")
|
||||
end
|
||||
if set[name] then
|
||||
error("stream_redact: duplicate event name in config." .. label)
|
||||
end
|
||||
set[name] = true
|
||||
count = count + 1
|
||||
if k > max_index then max_index = k end
|
||||
end
|
||||
if count ~= max_index or (must_be_non_empty and count == 0) then
|
||||
error("stream_redact: config." .. label .. " must be a dense" .. (must_be_non_empty and " non-empty" or "") .. " array")
|
||||
end
|
||||
return set
|
||||
end
|
||||
|
||||
local function normalize_settings(options)
|
||||
if options == nil then
|
||||
options = {}
|
||||
end
|
||||
if type(options) ~= "table" then
|
||||
error("stream_redact: config must be a table")
|
||||
end
|
||||
|
||||
local max_buffer_bytes = options.max_buffer_bytes
|
||||
if max_buffer_bytes == nil then
|
||||
max_buffer_bytes = DEFAULT_MAX_BUFFER_BYTES
|
||||
end
|
||||
if type(max_buffer_bytes) ~= "number" or max_buffer_bytes ~= math.floor(max_buffer_bytes)
|
||||
or max_buffer_bytes < 1 or max_buffer_bytes > HARD_MAX_BUFFER_BYTES then
|
||||
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to 327680")
|
||||
end
|
||||
|
||||
local text_event = options.text_event
|
||||
if text_event == nil then
|
||||
text_event = DEFAULT_TEXT_EVENT
|
||||
end
|
||||
if type(text_event) ~= "string" or text_event == "" or contains_cr_lf_nul(text_event) then
|
||||
error("stream_redact: config.text_event must be a non-empty event name without CR/LF/NUL")
|
||||
end
|
||||
|
||||
-- These lists are intentionally required: the true Agent event protocol has
|
||||
-- not been certified, so shipping hard-coded guesses can silently hold errors.
|
||||
local terminal_error_events = event_name_set(options.terminal_error_events, "terminal_error_events", true)
|
||||
local control_event_names = event_name_set(options.control_event_names, "control_event_names", true)
|
||||
|
||||
local redact_event_names
|
||||
if options.redact_event_names == nil then
|
||||
redact_event_names = { [text_event] = true }
|
||||
else
|
||||
redact_event_names = event_name_set(options.redact_event_names, "redact_event_names", true)
|
||||
if not redact_event_names[text_event] then
|
||||
error("stream_redact: config.redact_event_names must include config.text_event")
|
||||
end
|
||||
end
|
||||
|
||||
for name in pairs(terminal_error_events) do
|
||||
if not control_event_names[name] then
|
||||
error("stream_redact: every terminal_error_event must also be listed in control_event_names")
|
||||
end
|
||||
if redact_event_names[name] then
|
||||
error("stream_redact: terminal error events are scrubbed separately and cannot be in redact_event_names")
|
||||
end
|
||||
end
|
||||
if control_event_names[text_event] then
|
||||
error("stream_redact: config.text_event cannot be a control or terminal event")
|
||||
end
|
||||
|
||||
local content_path = parse_content_path(options.content_path)
|
||||
if not content_path then
|
||||
error("stream_redact: config.content_path must be a dot path or non-empty string array (use * for a dense content array)")
|
||||
end
|
||||
|
||||
-- 新增:路径白名单(可选)。语义与 network_review/response_guard 的
|
||||
-- paths 一致:未配置时对所有 SSE 流生效;配置后只对命中路径的
|
||||
-- 请求缓冲/脱敏,其余请求由 on_request 登记 bypass 后全程放行。
|
||||
local paths = {}
|
||||
if options.paths ~= nil then
|
||||
if type(options.paths) ~= "table" then
|
||||
error("stream_redact: config.paths must be an array")
|
||||
end
|
||||
local count = 0
|
||||
for _, p in ipairs(options.paths) do
|
||||
if type(p) ~= "string" or p == "" or string.sub(p, 1, 1) ~= "/"
|
||||
or contains_cr_lf_nul(p) then
|
||||
error("stream_redact: config.paths entries must be non-empty path strings without CR/LF/NUL")
|
||||
end
|
||||
paths[p] = true
|
||||
count = count + 1
|
||||
end
|
||||
if count == 0 then
|
||||
error("stream_redact: config.paths must be non-empty when present")
|
||||
end
|
||||
end
|
||||
|
||||
return {
|
||||
max_buffer_bytes = max_buffer_bytes,
|
||||
text_event = text_event,
|
||||
content_path = content_path,
|
||||
redact_event_names = redact_event_names,
|
||||
terminal_error_events = terminal_error_events,
|
||||
control_event_names = control_event_names,
|
||||
paths = paths,
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
local function copy_set(source)
|
||||
local out = {}
|
||||
for k, v in pairs(source) do out[k] = v end
|
||||
return out
|
||||
end
|
||||
|
||||
local function copy_settings(source)
|
||||
local path = {}
|
||||
for i, part in ipairs(source.content_path) do
|
||||
path[i] = part
|
||||
end
|
||||
return {
|
||||
max_buffer_bytes = source.max_buffer_bytes,
|
||||
text_event = source.text_event,
|
||||
content_path = path,
|
||||
redact_event_names = copy_set(source.redact_event_names),
|
||||
terminal_error_events = copy_set(source.terminal_error_events),
|
||||
control_event_names = copy_set(source.control_event_names),
|
||||
paths = copy_set(source.paths),
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
local function clear_state(key)
|
||||
if key ~= nil then states[key] = nil end
|
||||
end
|
||||
|
||||
local function block_and_clear(key, reason)
|
||||
clear_state(key)
|
||||
return { action = "block", reason = reason or "stream redaction failed" }
|
||||
end
|
||||
|
||||
local function finite_number(value)
|
||||
return type(value) == "number" and value == value
|
||||
and value ~= math.huge and value ~= -math.huge
|
||||
end
|
||||
|
||||
-- Estimate retained + processing footprint rather than counting raw body bytes.
|
||||
-- The 3x data weight budgets for raw event JSON, joined text/masked text, and
|
||||
-- transient decoded/encoded structures; 128 bytes/frame budgets Lua table data.
|
||||
local function estimate_event_bytes(event)
|
||||
if type(event) ~= "table" then return nil end
|
||||
if type(event.has_data) ~= "boolean" then return nil end
|
||||
if event.event ~= nil and type(event.event) ~= "string" then return nil end
|
||||
if event.id ~= nil and type(event.id) ~= "string" then return nil end
|
||||
if event.data ~= nil and type(event.data) ~= "string" then return nil end
|
||||
if event.has_data and type(event.data) ~= "string" then return nil end
|
||||
if not event.has_data and event.data ~= nil and event.data ~= "" then return nil end
|
||||
if event.event and contains_cr_lf_nul(event.event) then return nil end
|
||||
if event.id and contains_cr_lf_nul(event.id) then return nil end
|
||||
if event.comments ~= nil and type(event.comments) ~= "table" then return nil end
|
||||
if event.retry ~= nil then
|
||||
if not finite_number(event.retry) or event.retry < 0
|
||||
or event.retry ~= math.floor(event.retry) then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
local combined = table.concat(text)
|
||||
local masked = string.gsub(combined, string.rep('%d',17)..'[%dXx]', function(v)
|
||||
return string.rep('*', #v)
|
||||
end)
|
||||
masked = string.gsub(masked, '1[3-9]'..string.rep('%d',9), function(v)
|
||||
return string.rep('*', #v)
|
||||
end)
|
||||
|
||||
local size = 128
|
||||
if event.event then size = size + #event.event end
|
||||
if event.id then size = size + #event.id end
|
||||
if event.has_data and event.data then size = size + 3 * #event.data end
|
||||
if event.retry ~= nil then size = size + #tostring(event.retry) end
|
||||
if event.comments then
|
||||
local count = 0
|
||||
for k, comment in pairs(event.comments) do
|
||||
if type(k) ~= "number" or k < 1 or k ~= math.floor(k)
|
||||
or type(comment) ~= "string" then
|
||||
return nil
|
||||
end
|
||||
count = count + 1
|
||||
end
|
||||
if count ~= #event.comments then return nil end
|
||||
for _, comment in ipairs(event.comments) do
|
||||
size = size + #comment + 16
|
||||
end
|
||||
end
|
||||
return size
|
||||
end
|
||||
|
||||
local function dense_array_length(value)
|
||||
if type(value) ~= "table" then return nil end
|
||||
local count, max_index = 0, 0
|
||||
for k in pairs(value) do
|
||||
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then return nil end
|
||||
count = count + 1
|
||||
if k > max_index then max_index = k end
|
||||
end
|
||||
if count ~= max_index then return nil end
|
||||
return count
|
||||
end
|
||||
|
||||
-- Resolve one path to one or more string leaves. `*` expands a dense array
|
||||
-- such as content.*.text. Any missing/non-string leaf fails closed to avoid
|
||||
-- silently skipping a potentially textual block.
|
||||
local function get_content_locations(payload, path)
|
||||
local found = {}
|
||||
local function walk(node, depth)
|
||||
if depth > #path then
|
||||
if type(node) ~= "string" then return false end
|
||||
found[#found + 1] = { parent = nil, key = nil, content = node }
|
||||
return true
|
||||
end
|
||||
local segment = path[depth]
|
||||
if segment == "*" then
|
||||
local length = dense_array_length(node)
|
||||
if not length or length == 0 then return false end
|
||||
for i = 1, length do
|
||||
local before = #found
|
||||
if not walk(node[i], depth + 1) or #found == before then return false end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if type(node) ~= "table" then return false end
|
||||
local child = node[segment]
|
||||
if child == nil then return false end
|
||||
if depth == #path then
|
||||
if type(child) ~= "string" then return false end
|
||||
found[#found + 1] = { parent = node, key = segment, content = child }
|
||||
return true
|
||||
end
|
||||
return walk(child, depth + 1)
|
||||
end
|
||||
if not walk(payload, 1) or #found == 0 then return nil end
|
||||
|
||||
-- For wildcard paths, resolve the parent/key pairs from the original tree
|
||||
-- through a second walk. The first walk's temporary leaf parent is unused.
|
||||
local locations = {}
|
||||
local function walk_locations(node, depth)
|
||||
if depth > #path then return end
|
||||
local segment = path[depth]
|
||||
if segment == "*" then
|
||||
local length = dense_array_length(node)
|
||||
if not length then return end
|
||||
for i = 1, length do
|
||||
if depth == #path then
|
||||
-- A terminal wildcard (e.g. content.*) makes each array
|
||||
-- element itself the string leaf, so its parent is the
|
||||
-- array and its key is the numeric index.
|
||||
if type(node[i]) ~= "string" then return end
|
||||
locations[#locations + 1] = { parent = node, key = i, content = node[i] }
|
||||
else
|
||||
walk_locations(node[i], depth + 1)
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
if type(node) ~= "table" then return end
|
||||
if depth == #path then
|
||||
locations[#locations + 1] = { parent = node, key = segment, content = node[segment] }
|
||||
return
|
||||
end
|
||||
walk_locations(node[segment], depth + 1)
|
||||
end
|
||||
walk_locations(payload, 1)
|
||||
if #locations ~= #found then return nil end
|
||||
return locations
|
||||
end
|
||||
|
||||
|
||||
local function is_leap_year(year)
|
||||
return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
|
||||
end
|
||||
|
||||
local ID_WEIGHTS = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }
|
||||
local ID_CHECK_CHARS = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }
|
||||
|
||||
local function valid_cn_resident_id(token)
|
||||
if #token ~= 18 or not string.match(token, "^%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]$") then
|
||||
return false
|
||||
end
|
||||
local year = tonumber(string.sub(token, 7, 10))
|
||||
local month = tonumber(string.sub(token, 11, 12))
|
||||
local day = tonumber(string.sub(token, 13, 14))
|
||||
if not year or not month or not day or year < 1800 or year > 2200 or month < 1 or month > 12 then
|
||||
return false
|
||||
end
|
||||
local days = { 31, is_leap_year(year) and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
|
||||
if day < 1 or day > days[month] then return false end
|
||||
|
||||
local sum = 0
|
||||
for i = 1, 17 do
|
||||
local digit = tonumber(string.sub(token, i, i))
|
||||
if not digit then return false end
|
||||
sum = sum + digit * ID_WEIGHTS[i]
|
||||
end
|
||||
local expected = ID_CHECK_CHARS[(sum % 11) + 1]
|
||||
return string.upper(string.sub(token, 18, 18)) == expected
|
||||
end
|
||||
|
||||
-- Conservative token-based patterns:
|
||||
-- * valid-format 18-char mainland resident IDs (date + checksum checked)
|
||||
-- * 11-digit mainland mobile-number candidates (prefix check only)
|
||||
-- Longer contiguous digit runs, spaced/hyphenated values, 16-digit cards,
|
||||
-- passport numbers and semantic secrets are outside this example's coverage.
|
||||
local function mask_sensitive_tokens(text)
|
||||
return (string.gsub(text, "[%dXx]+", function(token)
|
||||
if valid_cn_resident_id(token) then
|
||||
return string.rep("*", #token)
|
||||
end
|
||||
if #token == 11 and string.match(token, "^1[3-9]%d%d%d%d%d%d%d%d%d$") then
|
||||
return string.rep("*", #token)
|
||||
end
|
||||
return token
|
||||
end))
|
||||
end
|
||||
|
||||
local function redact_and_release(key, state)
|
||||
local text_parts = {}
|
||||
local entries = {}
|
||||
|
||||
-- First pass: extract all configured string leaves without retaining decoded
|
||||
-- payload tables. Wildcard paths support homogeneous content-block arrays.
|
||||
for index, event in ipairs(state.frames) do
|
||||
if state.settings.redact_event_names[event.event] and event.has_data then
|
||||
local ok, payload = pcall(host.json.decode, event.data)
|
||||
if not ok or type(payload) ~= "table" then
|
||||
return block_and_clear(key, "invalid text event payload")
|
||||
end
|
||||
local locations = get_content_locations(payload, state.settings.content_path)
|
||||
if not locations then
|
||||
return block_and_clear(key, "text event payload does not match configured content_path")
|
||||
end
|
||||
local lengths = {}
|
||||
for _, location in ipairs(locations) do
|
||||
local content = location.content
|
||||
lengths[#lengths + 1] = #content
|
||||
text_parts[#text_parts + 1] = content
|
||||
end
|
||||
entries[#entries + 1] = { frame_index = index, content_lengths = lengths }
|
||||
payload = nil
|
||||
end
|
||||
end
|
||||
|
||||
local combined = table.concat(text_parts)
|
||||
text_parts = nil
|
||||
local masked = mask_sensitive_tokens(combined)
|
||||
if #masked ~= #combined then
|
||||
return block_and_clear(key, "redaction changed byte length")
|
||||
end
|
||||
combined = nil
|
||||
|
||||
-- Second pass: decode/mutate/encode one payload at a time to lower peak memory.
|
||||
local offset = 1
|
||||
for i, event in ipairs(frames) do
|
||||
local payload = payloads[i]
|
||||
if payload then
|
||||
local length = #payload.data.content
|
||||
payload.data.content = string.sub(masked, offset, offset+length-1)
|
||||
offset = offset + length
|
||||
event.data = host.json.encode(payload)
|
||||
for _, entry in ipairs(entries) do
|
||||
local frame = state.frames[entry.frame_index]
|
||||
local ok, payload = pcall(host.json.decode, frame.data)
|
||||
if not ok or type(payload) ~= "table" then
|
||||
return block_and_clear(key, "text event re-decode failed")
|
||||
end
|
||||
local locations = get_content_locations(payload, state.settings.content_path)
|
||||
if not locations or #locations ~= #entry.content_lengths then
|
||||
return block_and_clear(key, "text event structure changed during redaction")
|
||||
end
|
||||
for j, location in ipairs(locations) do
|
||||
local old_content = location.content
|
||||
local expected_length = entry.content_lengths[j]
|
||||
if type(old_content) ~= "string" or #old_content ~= expected_length then
|
||||
return block_and_clear(key, "text event changed during redaction")
|
||||
end
|
||||
local replacement = ""
|
||||
if expected_length > 0 then
|
||||
replacement = string.sub(masked, offset, offset + expected_length - 1)
|
||||
end
|
||||
offset = offset + expected_length
|
||||
location.parent[location.key] = replacement
|
||||
end
|
||||
local encode_ok, encoded = pcall(host.json.encode, payload)
|
||||
payload = nil
|
||||
if not encode_ok or type(encoded) ~= "string" then
|
||||
return block_and_clear(key, "text event serialization failed")
|
||||
end
|
||||
frame.data = encoded
|
||||
end
|
||||
|
||||
masked = nil
|
||||
entries = nil
|
||||
local ok, released = pcall(host.json.array, state.frames)
|
||||
if not ok or type(released) ~= "table" then
|
||||
return block_and_clear(key, "event array creation failed")
|
||||
end
|
||||
|
||||
clear_state(key)
|
||||
return { action = "replace", events = released }
|
||||
end
|
||||
|
||||
local function pending_text_tail(state, limit)
|
||||
-- Maintained incrementally while frames are buffered; terminal-error handling
|
||||
-- must not re-decode every pending frame on a failure path.
|
||||
local tail = state.text_tail or ""
|
||||
if #tail > limit then return string.sub(tail, -limit) end
|
||||
return tail
|
||||
end
|
||||
|
||||
local function update_pending_text_tail(state, event)
|
||||
if event.has_data ~= true or not state.settings.redact_event_names[event.event] then
|
||||
return true
|
||||
end
|
||||
local decode_ok, payload = pcall(host.json.decode, event.data)
|
||||
if not decode_ok or type(payload) ~= "table" then return false end
|
||||
local locations = get_content_locations(payload, state.settings.content_path)
|
||||
if not locations then return false end
|
||||
|
||||
local tail = state.text_tail or ""
|
||||
for _, location in ipairs(locations) do
|
||||
local joined = tail .. location.content
|
||||
if #joined > 18 then
|
||||
tail = string.sub(joined, -18)
|
||||
else
|
||||
tail = joined
|
||||
end
|
||||
end
|
||||
local released = host.json.array(frames)
|
||||
frames = {}
|
||||
return {action='replace', events=released}
|
||||
state.text_tail = tail
|
||||
return true
|
||||
end
|
||||
function plugin.close(ctx) frames = {} end
|
||||
return plugin
|
||||
|
||||
local function mask_with_context(value, context)
|
||||
local prefix = context or ""
|
||||
local probe = prefix .. value
|
||||
local masked = mask_sensitive_tokens(probe)
|
||||
if #masked ~= #probe then return nil end
|
||||
return string.sub(masked, #prefix + 1)
|
||||
end
|
||||
|
||||
local function redact_terminal_error_event(key, state, event)
|
||||
-- Pending response text is never released after an upstream failure.
|
||||
-- Keep only a short text tail long enough to detect supported patterns
|
||||
-- split between the last held text frame and the error payload.
|
||||
local context = pending_text_tail(state, 18)
|
||||
if context == nil then
|
||||
state.frames = {}
|
||||
state.buffer_bytes = 0
|
||||
state.aborted = true
|
||||
return { action = "block", reason = "cannot safely inspect pending text before terminal error" }
|
||||
end
|
||||
state.frames = {}
|
||||
state.buffer_bytes = 0
|
||||
state.aborted = true
|
||||
|
||||
if event.has_data ~= true or type(event.data) ~= "string" or event.data == "" then
|
||||
return { action = "pass" }
|
||||
end
|
||||
|
||||
-- Error payloads are not assumed to be body-free. Prefer JSON-aware string
|
||||
-- value redaction; if this isn't JSON, scrub raw text. The last 18 bytes of
|
||||
-- held text are prepended only for matching, then removed from the output.
|
||||
local decoded_ok, payload = pcall(host.json.decode, event.data)
|
||||
if decoded_ok then
|
||||
local changed = false
|
||||
local function scrub(value)
|
||||
if type(value) == "string" then
|
||||
local masked_value = mask_with_context(value, context)
|
||||
if masked_value == nil then error("redaction length changed") end
|
||||
if masked_value ~= value then changed = true end
|
||||
return masked_value
|
||||
end
|
||||
if type(value) == "table" then
|
||||
for k, child in pairs(value) do
|
||||
if type(child) == "string" then
|
||||
local masked_value = mask_with_context(child, context)
|
||||
if masked_value == nil then error("redaction length changed") end
|
||||
if masked_value ~= child then changed = true end
|
||||
value[k] = masked_value
|
||||
elseif type(child) == "table" then
|
||||
scrub(child)
|
||||
end
|
||||
end
|
||||
end
|
||||
return value
|
||||
end
|
||||
local scrub_ok, cleaned = pcall(scrub, payload)
|
||||
if not scrub_ok then
|
||||
return { action = "block", reason = "terminal error redaction failed" }
|
||||
end
|
||||
payload = cleaned
|
||||
if not changed then return { action = "pass" } end
|
||||
local encode_ok, encoded = pcall(host.json.encode, payload)
|
||||
if not encode_ok or type(encoded) ~= "string" then
|
||||
return { action = "block", reason = "terminal error payload serialization failed" }
|
||||
end
|
||||
event.data = encoded
|
||||
else
|
||||
local masked = mask_with_context(event.data, context)
|
||||
if masked == nil then
|
||||
return { action = "block", reason = "terminal error redaction failed" }
|
||||
end
|
||||
if masked == event.data then return { action = "pass" } end
|
||||
event.data = masked
|
||||
end
|
||||
|
||||
local array_ok, single = pcall(host.json.array, { event })
|
||||
if not array_ok or type(single) ~= "table" then
|
||||
return { action = "block", reason = "terminal error event array creation failed" }
|
||||
end
|
||||
return { action = "replace", events = single }
|
||||
end
|
||||
|
||||
function plugin.init(ctx, options)
|
||||
-- init may run during startup validation and request setup; do not clear states.
|
||||
settings = normalize_settings(options)
|
||||
return nil
|
||||
end
|
||||
|
||||
function plugin.on_request(ctx, request)
|
||||
-- 新增钩子:本插件原本看不到请求路径,靠这个回调在请求阶段判断。
|
||||
-- 未命中白名单(非 AI 路径)的请求登记 bypass 标记,其 SSE 事件流
|
||||
-- 与非流式响应在 on_event/on_response/on_end 中直接放行,
|
||||
-- 不缓冲、不拦截。配置了 paths 时必须保证宿主会调用本钩子。
|
||||
if next(settings.paths) == nil then
|
||||
return nil
|
||||
end
|
||||
local key = request_key(ctx)
|
||||
if not key then
|
||||
return nil -- 与其他请求侧插件不同:这里没有审核职责,不 fail-closed
|
||||
end
|
||||
local path = type(request) == "table" and request.path or nil
|
||||
if path == nil or not settings.paths[path] then
|
||||
clear_state(key)
|
||||
states[key] = { bypass = true }
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
|
||||
function plugin.on_response(ctx, response)
|
||||
-- This example's guarantee is SSE-only. Refuse ordinary responses rather
|
||||
-- than silently passing unredacted content through the same enabled rule.
|
||||
if type(response) ~= "table" then
|
||||
return { action = "block", reason = "invalid response object" }
|
||||
end
|
||||
|
||||
-- 新增:请求阶段已判定为非 AI 路径(bypass),本插件不参与其响应处理。
|
||||
-- 非流式响应一次性结束,顺手清掉标记;流式响应交给 on_event/on_end 收尾。
|
||||
local key = request_key(ctx)
|
||||
local state = key and states[key] or nil
|
||||
if state and state.bypass then
|
||||
if response.streaming ~= true then
|
||||
clear_state(key)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
if response.streaming == true then
|
||||
return nil
|
||||
end
|
||||
return { action = "block", reason = "stream_redact only supports SSE responses" }
|
||||
end
|
||||
|
||||
function plugin.on_event(ctx, event)
|
||||
local key = request_key(ctx)
|
||||
if not key then
|
||||
return { action = "block", reason = "missing request id" }
|
||||
end
|
||||
|
||||
-- 新增:请求阶段已判定为非 AI 路径(bypass),事件流不归本插件管。
|
||||
-- 必须放在事件合法性检查和状态创建之前,否则非 AI 流量会被
|
||||
-- 无条件缓冲到流结束,甚至因事件形态不符被 fail-closed 拦截。
|
||||
local existing = states[key]
|
||||
if existing and existing.bypass then
|
||||
return nil
|
||||
end
|
||||
|
||||
local size = estimate_event_bytes(event)
|
||||
if not size then
|
||||
return block_and_clear(key, "invalid SSE event")
|
||||
end
|
||||
|
||||
local state = existing
|
||||
|
||||
-- Once a terminal failure was observed, *all* subsequent events, including
|
||||
-- duplicate terminal errors, are rejected. This check must precede name lookup.
|
||||
if state and state.aborted then
|
||||
return { action = "block", reason = "event received after terminal error" }
|
||||
end
|
||||
|
||||
if not state then
|
||||
if not settings then
|
||||
return { action = "block", reason = "plugin not initialized" }
|
||||
end
|
||||
state = {
|
||||
settings = copy_settings(settings),
|
||||
frames = {},
|
||||
buffer_bytes = 0,
|
||||
text_tail = "",
|
||||
}
|
||||
states[key] = state
|
||||
end
|
||||
|
||||
-- Terminal error names come only from the validated, request-snapshotted config.
|
||||
if event.event and state.settings.terminal_error_events[event.event] then
|
||||
return redact_terminal_error_event(key, state, event)
|
||||
end
|
||||
|
||||
-- Valid no-data SSE frames (typically comment heartbeats) carry no content.
|
||||
-- They pass immediately, but only after checking terminal state above.
|
||||
if event.has_data == false then
|
||||
return { action = "pass" }
|
||||
end
|
||||
|
||||
if state.buffer_bytes + size > state.settings.max_buffer_bytes then
|
||||
return block_and_clear(key, "estimated stream redaction buffer limit exceeded")
|
||||
end
|
||||
|
||||
-- Validate and update the <=18-byte cross-frame inspection tail as each
|
||||
-- configured text-bearing event arrives. This avoids O(frame_count) decode
|
||||
-- work if a terminal error arrives after a large buffered response.
|
||||
if not update_pending_text_tail(state, event) then
|
||||
return block_and_clear(key, "text event payload does not match configured content_path")
|
||||
end
|
||||
|
||||
state.frames[#state.frames + 1] = event
|
||||
state.buffer_bytes = state.buffer_bytes + size
|
||||
return { action = "hold" }
|
||||
end
|
||||
|
||||
function plugin.on_end(ctx)
|
||||
local key = request_key(ctx)
|
||||
if not key then
|
||||
return { action = "block", reason = "missing request id at end" }
|
||||
end
|
||||
local state = states[key]
|
||||
if not state then
|
||||
return nil
|
||||
end
|
||||
|
||||
-- 新增:bypass 请求全程未缓冲,结束钩子只需清理标记。
|
||||
if state.bypass then
|
||||
clear_state(key)
|
||||
return nil
|
||||
end
|
||||
|
||||
if state.aborted then
|
||||
clear_state(key)
|
||||
return nil
|
||||
end
|
||||
if #state.frames == 0 then
|
||||
clear_state(key)
|
||||
return nil
|
||||
end
|
||||
return redact_and_release(key, state)
|
||||
end
|
||||
|
||||
function plugin.close(ctx)
|
||||
-- Only clear this request. On abnormal close, held text is deliberately dropped.
|
||||
clear_state(request_key(ctx))
|
||||
end
|
||||
|
||||
return plugin
|
||||
Reference in new issue
Block a user