mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-11-26 20:03:32 +08:00
- Add TerminateScope to plugin and executor after-auth interceptor responses so plugins can refuse a single selected credential with exact scope "credential" while keeping request-scoped termination as default. - Exclude refused credentials for the remainder of the request across normal, count, streaming, Home dispatch, retry rounds, and Antigravity credits fallback without mutating shared cooldown state. - Preserve real upstream error precedence over plugin credential refusals and plugin refusal precedence over local non-upstream errors, with regression tests across pluginhost, handlers, and auth conductor paths. Closes: #7656
237 lines
8.7 KiB
Go
237 lines
8.7 KiB
Go
package pluginhost
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/MoeForge/moego/json"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginabi"
|
|
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
|
|
)
|
|
|
|
func TestRequestInterceptorTerminationStopsChain(t *testing.T) {
|
|
lowCalls := 0
|
|
host := newHostWithRecords(
|
|
capabilityRecord{
|
|
id: "high",
|
|
priority: 20,
|
|
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
|
|
RequestInterceptor: requestInterceptorFunc(func(context.Context, pluginapi.RequestInterceptRequest) (pluginapi.RequestInterceptResponse, error) {
|
|
return pluginapi.RequestInterceptResponse{
|
|
Terminate: true,
|
|
StatusCode: http.StatusForbidden,
|
|
ResponseHeaders: http.Header{"Content-Type": {"application/json"}},
|
|
ResponseBody: []byte(`{"error":"blocked"}`),
|
|
}, nil
|
|
}),
|
|
}},
|
|
},
|
|
capabilityRecord{
|
|
id: "low",
|
|
priority: 10,
|
|
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
|
|
RequestInterceptor: requestInterceptorFunc(func(context.Context, pluginapi.RequestInterceptRequest) (pluginapi.RequestInterceptResponse, error) {
|
|
lowCalls++
|
|
return pluginapi.RequestInterceptResponse{}, nil
|
|
}),
|
|
}},
|
|
},
|
|
)
|
|
|
|
response := host.InterceptRequestBeforeAuth(context.Background(), pluginapi.RequestInterceptRequest{RequestID: "request-1"})
|
|
if !response.Terminate || response.StatusCode != http.StatusForbidden {
|
|
t.Fatalf("termination response = %#v", response)
|
|
}
|
|
if response.ResponseHeaders.Get("Content-Type") != "application/json" || string(response.ResponseBody) != `{"error":"blocked"}` {
|
|
t.Fatalf("termination payload = %#v", response)
|
|
}
|
|
if lowCalls != 0 {
|
|
t.Fatalf("lower-priority interceptor calls = %d, want 0", lowCalls)
|
|
}
|
|
}
|
|
|
|
func TestCompleteRequestUsesUncancelledContextAndClonesMetadata(t *testing.T) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
originalNested := map[string]any{"value": "original"}
|
|
var got pluginapi.RequestCompletion
|
|
var callbackContextError error
|
|
done := make(chan struct{})
|
|
host := newHostWithRecords(capabilityRecord{
|
|
id: "lifecycle",
|
|
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
|
|
RequestLifecyclePlugin: requestLifecyclePluginFunc(func(callbackCtx context.Context, completion pluginapi.RequestCompletion) {
|
|
callbackContextError = callbackCtx.Err()
|
|
got = completion
|
|
completion.Metadata["nested"].(map[string]any)["value"] = "mutated"
|
|
close(done)
|
|
}),
|
|
}},
|
|
})
|
|
|
|
host.CompleteRequest(ctx, pluginapi.RequestCompletion{
|
|
RequestID: "request-1",
|
|
Outcome: pluginapi.RequestCompletionCanceled,
|
|
StartedAt: time.Now().Add(-time.Second),
|
|
CompletedAt: time.Now(),
|
|
Metadata: map[string]any{"nested": originalNested},
|
|
})
|
|
<-done
|
|
|
|
if callbackContextError != nil {
|
|
t.Fatalf("callback context error = %v", callbackContextError)
|
|
}
|
|
if got.RequestID != "request-1" || got.Outcome != pluginapi.RequestCompletionCanceled {
|
|
t.Fatalf("completion = %#v", got)
|
|
}
|
|
if originalNested["value"] != "original" {
|
|
t.Fatalf("input metadata was mutated: %#v", originalNested)
|
|
}
|
|
}
|
|
|
|
func TestCompleteRequestDoesNotWaitForBlockingPlugin(t *testing.T) {
|
|
started := make(chan struct{})
|
|
release := make(chan struct{})
|
|
host := newHostWithRecords(capabilityRecord{
|
|
id: "blocking-lifecycle",
|
|
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
|
|
RequestLifecyclePlugin: requestLifecyclePluginFunc(func(context.Context, pluginapi.RequestCompletion) {
|
|
close(started)
|
|
<-release
|
|
}),
|
|
}},
|
|
})
|
|
|
|
returned := make(chan struct{})
|
|
go func() {
|
|
host.CompleteRequest(context.Background(), pluginapi.RequestCompletion{RequestID: "request-blocking"})
|
|
close(returned)
|
|
}()
|
|
select {
|
|
case <-returned:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("CompleteRequest blocked on lifecycle plugin")
|
|
}
|
|
select {
|
|
case <-started:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("lifecycle plugin was not invoked")
|
|
}
|
|
close(release)
|
|
}
|
|
|
|
func TestRPCCapabilitiesAndAdapterIncludeRequestLifecycle(t *testing.T) {
|
|
var got pluginapi.RequestCompletion
|
|
plugin := validTestPlugin("request-lifecycle")
|
|
plugin.Capabilities.RequestLifecyclePlugin = requestLifecyclePluginFunc(func(_ context.Context, completion pluginapi.RequestCompletion) {
|
|
got = completion
|
|
})
|
|
caps := rpcCapabilitiesFromPlugin(plugin)
|
|
if !caps.RequestLifecyclePlugin {
|
|
t.Fatal("RequestLifecyclePlugin = false, want true")
|
|
}
|
|
rawCaps, errMarshal := json.Marshal(caps)
|
|
if errMarshal != nil {
|
|
t.Fatalf("Marshal() error = %v", errMarshal)
|
|
}
|
|
var decoded map[string]any
|
|
if errUnmarshal := json.Unmarshal(rawCaps, &decoded); errUnmarshal != nil {
|
|
t.Fatalf("Unmarshal() error = %v", errUnmarshal)
|
|
}
|
|
if decoded["request_lifecycle_plugin"] != true {
|
|
t.Fatalf("request_lifecycle_plugin = %#v", decoded["request_lifecycle_plugin"])
|
|
}
|
|
|
|
lookup := newTestSymbolLookup(&testPlugin{registerResult: plugin})
|
|
registered, errRegister := registerRPCPlugin(context.Background(), nil, "request-lifecycle", lookup, pluginabi.MethodPluginRegister, nil)
|
|
if errRegister != nil {
|
|
t.Fatalf("registerRPCPlugin() error = %v", errRegister)
|
|
}
|
|
if registered.Capabilities.RequestLifecyclePlugin == nil {
|
|
t.Fatal("RequestLifecyclePlugin = nil, want RPC adapter")
|
|
}
|
|
if errComplete := registered.Capabilities.RequestLifecyclePlugin.HandleRequestComplete(context.Background(), pluginapi.RequestCompletion{
|
|
RequestID: "request-rpc",
|
|
Outcome: pluginapi.RequestCompletionSucceeded,
|
|
}); errComplete != nil {
|
|
t.Fatalf("HandleRequestComplete() error = %v", errComplete)
|
|
}
|
|
if got.RequestID != "request-rpc" || got.Outcome != pluginapi.RequestCompletionSucceeded {
|
|
t.Fatalf("RPC completion = %#v", got)
|
|
}
|
|
}
|
|
|
|
func TestRequestInterceptorTerminateScopePropagationAndBeforeAuthIgnores(t *testing.T) {
|
|
lowCalls := 0
|
|
host := newHostWithRecords(
|
|
capabilityRecord{
|
|
id: "high",
|
|
priority: 20,
|
|
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
|
|
RequestInterceptor: requestInterceptorFunc(func(context.Context, pluginapi.RequestInterceptRequest) (pluginapi.RequestInterceptResponse, error) {
|
|
return pluginapi.RequestInterceptResponse{
|
|
Terminate: true,
|
|
TerminateScope: "credential",
|
|
StatusCode: http.StatusForbidden,
|
|
ResponseHeaders: http.Header{"X-Scope": {"cred"}},
|
|
ResponseBody: []byte("refused"),
|
|
}, nil
|
|
}),
|
|
}},
|
|
},
|
|
capabilityRecord{
|
|
id: "low",
|
|
priority: 10,
|
|
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
|
|
RequestInterceptor: requestInterceptorFunc(func(context.Context, pluginapi.RequestInterceptRequest) (pluginapi.RequestInterceptResponse, error) {
|
|
lowCalls++
|
|
return pluginapi.RequestInterceptResponse{}, nil
|
|
}),
|
|
}},
|
|
},
|
|
)
|
|
|
|
afterResp := host.InterceptRequestAfterAuth(context.Background(), pluginapi.RequestInterceptRequest{RequestID: "req-after"})
|
|
if !afterResp.Terminate || afterResp.TerminateScope != "credential" || afterResp.StatusCode != http.StatusForbidden {
|
|
t.Fatalf("after-auth response = %#v", afterResp)
|
|
}
|
|
if lowCalls != 0 {
|
|
t.Fatalf("lower-priority interceptor calls = %d, want 0", lowCalls)
|
|
}
|
|
|
|
beforeResp := host.InterceptRequestBeforeAuth(context.Background(), pluginapi.RequestInterceptRequest{RequestID: "req-before"})
|
|
if !beforeResp.Terminate || beforeResp.TerminateScope != "" || beforeResp.StatusCode != http.StatusForbidden {
|
|
t.Fatalf("before-auth response = %#v, want empty TerminateScope", beforeResp)
|
|
}
|
|
}
|
|
|
|
func TestRPCRequestInterceptAfterAuthTerminateScopeRoundTrip(t *testing.T) {
|
|
plugin := validTestPlugin("terminate-scope-rpc")
|
|
plugin.Capabilities.RequestInterceptor = requestInterceptorFunc(func(context.Context, pluginapi.RequestInterceptRequest) (pluginapi.RequestInterceptResponse, error) {
|
|
return pluginapi.RequestInterceptResponse{
|
|
Terminate: true,
|
|
TerminateScope: "credential",
|
|
StatusCode: http.StatusForbidden,
|
|
ResponseHeaders: http.Header{"X-Plugin": {"rpc"}},
|
|
ResponseBody: []byte("rpc-refused"),
|
|
}, nil
|
|
})
|
|
lookup := newTestSymbolLookup(&testPlugin{registerResult: plugin})
|
|
registered, errRegister := registerRPCPlugin(context.Background(), nil, "terminate-scope-rpc", lookup, pluginabi.MethodPluginRegister, nil)
|
|
if errRegister != nil {
|
|
t.Fatalf("registerRPCPlugin() error = %v", errRegister)
|
|
}
|
|
resp, errAfter := registered.Capabilities.RequestInterceptor.InterceptRequestAfterAuth(context.Background(), pluginapi.RequestInterceptRequest{
|
|
RequestID: "req-rpc",
|
|
})
|
|
if errAfter != nil {
|
|
t.Fatalf("InterceptRequestAfterAuth() error = %v", errAfter)
|
|
}
|
|
if !resp.Terminate || resp.TerminateScope != "credential" || resp.StatusCode != http.StatusForbidden ||
|
|
resp.ResponseHeaders.Get("X-Plugin") != "rpc" || string(resp.ResponseBody) != "rpc-refused" {
|
|
t.Fatalf("RPC after-auth response = %#v", resp)
|
|
}
|
|
}
|