Files
magpie/internal/gateway/refusal_forbidden_test.go
T
yetone 750bd1bb69 gateway: Factory's usage policy refusal reaches agents as a refused request, not a failed sign-in
sweanng (Discord #general, ZCode + Factory + GLM 5.3) got Factory's
usage policy refusal shown as "Provider authentication failed"
(reason=auth_failed status=403). The refusal is Factory's own; the label
was wrong. Factory refuses at 403 with code content_policy_rejected. The
Factory plugin (up to 0.1.39) handed it on as a 403 permission_error
with no code, magpie didn't know the code as a refusal, so the 403 went
through as is and the agent read it as an auth failure.

- policyRefusal knows content_policy_rejected (Factory's code, in its
  own top-level and error.code shapes and the plugin's), so the existing
  refusal path answers every protocol with 400 and its own request
  error: Anthropic invalid_request_error, OpenAI chat and Responses
  invalid_request_error, Gemini INVALID_ARGUMENT. Not asked again of the
  same account; other accounts/members follow the Refusal retries
  setting as for any refusal.
- restAfter leaves the account unrested for a policy refusal at 403 too,
  not only 400 (it rested "other by backoff" before).
- The refusal note keeps up to 1000 bytes of the vendor's message, not
  300: Factory's advice (start a new session or drop the quoted text)
  and OpenAI's Daybreak link were cut.
- Factory mover min 0.1.40 (plugins #494, on npm as latest): the plugin
  now answers this refusal as a 400 invalid_request_error carrying code
  content_policy_rejected; its other 403s stay permission_error.

Siblings checked: Devin's plugin maps its content policy to 400, Qoder's
sensitive codes and Zhipu's 1301 are request errors already; Factory was
the one content refusal sent as a 403.

Run (mote, rebased on origin/main 96a703a59, with the next commit):
  go test -timeout 45m -count=1 ./internal/provider: ok
  go test -timeout 45m -count=1 ./internal/gateway: ok (768s)
  (the first gateway run at this commit alone failed only
  TestUnroutedUnknownHoldAnsweredSooner's TempDir cleanup, a race in
  the test fixed in the next commit)
  gofmt -l internal/: clean
  plugins: HOME=$(mktemp -d) bun test packages/factory 178 pass;
  bun scripts/check.mjs ok.
Broken by hand: with fallback.go and routing.go reverted, all three new
tests fail (403 permission_error / PERMISSION_DENIED reaches every
protocol; policyRefusal false; rests "other by backoff"). With the note
cap back at 300, TestFactoryPolicyRejectedIsARefusal and
TestFactoryPolicyRefusalReachesAgentsAsARefusal fail (advice cut). With
the plugin's index.mjs reverted, content-policy.test.mjs fails 3 of 6.
Not tried: a real Factory content_policy_rejected (no way to trip it on
purpose), and ZCode itself reading the 400: its error mapping isn't in
any source I could find, so ZCode showing it as a refusal is expected
from the Anthropic invalid_request_error, not seen.
2026-10-29 18:31:42 +08:00

112 lines
5.7 KiB
Go

package gateway
import (
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// factoryPolicyMsg is what the Factory plugin says of Factory's usage
// policy check refusing a request, as sweanng's ZCode showed it from magpie
// (Discord #general, 10-29), magpie's "Factory: " left off.
const factoryPolicyMsg = `This request was blocked by Factory's usage policy check. (upstream request id 8d1f0c2a3b4e5f60::LAX, code content_policy_rejected) — Factory's usage policy check reads the whole conversation, so this session's requests are refused again until the text that tripped it is gone: start a new session, or remove or reword what the conversation quotes (another agent's system prompt or instructions pasted in a message or a tool's output are the usual cause)`
// factoryPolicy403 is that refusal as the Factory plugin answers it, in
// the shape of the API the request was for: Anthropic's on /llm/a, OpenAI's
// on the others, the code kept on the error.
func factoryPolicy403(anthropic bool) string {
e := map[string]any{"type": "permission_error", "message": factoryPolicyMsg, "code": "content_policy_rejected"}
var v any = map[string]any{"error": e}
if anthropic {
v = map[string]any{"type": "error", "error": e, "request_id": "8d1f0c2a3b4e5f60::LAX"}
}
b, _ := json.Marshal(v)
return string(b)
}
// Factory's 403 content_policy_rejected is its usage policy check, not the
// account: in Factory's own two shapes and in the plugin's. Its other 403s
// (an org the user can't reach, a model the org's policy leaves out) are
// the account's still.
func TestFactoryPolicyRejectedIsARefusal(t *testing.T) {
for body, want := range map[string]bool{
`{"code":"content_policy_rejected","detail":"This request was blocked by Factory's usage policy check."}`: true,
`{"error":{"code":"content_policy_rejected","message":"This request was blocked by Factory's usage policy check."}}`: true,
factoryPolicy403(true): true,
factoryPolicy403(false): true,
`{"detail":"Requested active organization is not accessible by this user"}`: false,
`{"error":{"type":"permission_error","message":"Model not allowed by your organization's model policy"}}`: false,
`{"error":{"type":"permission_error","code":"org_policy_denied","message":"Model not allowed by your org"}}`: false,
} {
note, got := policyRefusal([]byte(body))
if got != want {
t.Errorf("%s: refusal %v, want %v", body, got, want)
}
if got && strings.Contains(body, "start a new session") && !strings.Contains(note, "are the usual cause") {
t.Errorf("the vendor's advice was cut from the note: %q", note)
}
}
}
// sweanng's ZCode, asking Factory through magpie, was handed Factory's
// usage policy refusal as the plugin's 403 permission_error, and showed
// "Provider authentication failed" (reason=auth_failed status=403). Each
// agent protocol is now told it as a refusal of the request: 400, the
// protocol's invalid-request error, Factory's words and advice kept, not
// asked again of the same account, and the account not rested.
func TestFactoryPolicyRefusalReachesAgentsAsARefusal(t *testing.T) {
asks := []struct{ name, path, body, inShape string }{
{"messages", "/v1/messages", `{"model":"f/m","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`, `"type":"invalid_request_error"`},
{"messages stream", "/v1/messages", `{"model":"f/m","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`, `"type":"invalid_request_error"`},
{"chat", "/v1/chat/completions", `{"model":"f/m","messages":[{"role":"user","content":"hi"}]}`, `"type":"invalid_request_error"`},
{"responses", "/v1/responses", `{"model":"f/m","input":"hi"}`, `"type":"invalid_request_error"`},
{"responses stream", "/v1/responses", `{"model":"f/m","stream":true,"input":"hi"}`, `"type":"invalid_request_error"`},
{"gemini", "/v1beta/models/f/m:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, `"status":"INVALID_ARGUMENT"`},
}
for _, up := range []provider.Protocol{provider.Anthropic, provider.Chat} {
for _, ask := range asks {
t.Run(string(up)+"/"+ask.name, func(t *testing.T) {
fresh(t)
f := &scripted{replies: []reply{{403, "application/json", factoryPolicy403(up == provider.Anthropic)}}}
scriptedOn(t, "f", up, f)
s := New()
code, out := sendTo(s, ask.path, ask.body)
if code != http.StatusBadRequest {
t.Fatalf("status %d, want 400: %s", code, out)
}
if !strings.Contains(out, ask.inShape) || strings.Contains(out, "permission_error") || strings.Contains(out, "PERMISSION_DENIED") {
t.Errorf("not the protocol's request error: %s", out)
}
if !strings.Contains(out, "content_policy_rejected") || !strings.Contains(out, "are the usual cause") {
t.Errorf("Factory's words or advice lost: %s", out)
}
if f.n != 1 {
t.Errorf("Factory asked %d times, want once", f.n)
}
r := lastRoute(s)
if n := len(r.Tries); n == 0 || r.Tries[n-1].Fail != failRefused || r.Tries[n-1].Rest != nil {
t.Errorf("tries: %+v", r.Tries)
}
if rests := liveRests(); len(rests) != 0 {
t.Errorf("rested for a refusal of the request: %v", rests)
}
})
}
}
}
// Any route that rests a candidate after a failure leaves it be for
// Factory's 403 refusal, as for a 400 one.
func TestFactoryPolicyRefusalRestsNobody(t *testing.T) {
fresh(t)
s := &Server{}
p := provider.Provider{ID: "f", Name: "Factory", Chat: "https://api.factory.ai/api/llm/o/v1", Key: "k"}
c := candidate{p: p, model: "glm-5.3", rest: p.ID}
if r := s.restAfter(c, 403, http.Header{}, []byte(factoryPolicy403(false))); r.Why != failRefused || r.By != "off" {
t.Errorf("rests as %s by %s, want %s by off", r.Why, r.By, failRefused)
}
}