diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b7f7599c8..b8863919c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -137,7 +137,7 @@ recorded as a prediction failure (`noPrediction`). ## Runtime path 1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`. -2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, 32 hex digits or more, or a digest of 16 to 31 hex digits in one case with letters and digits both, a cache key or a short commit, which went as a key before: _kaichen on X, 10-28; `digestShaped`), or an element token cua-driver hands the model for computer use (`s0000002a:14`, #3782), goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), nor cua-driver's own `element_token` (any other name with `element` in it, `element_api_key`, is a credential's as before), a bare `key` (not after api, access, secret, private, signing or license: `keyPhrase`), a field named for a cache, commit, object, blob, file, content, revision, partition, shard, bucket, dedup, lookup, row or sort key, a serial number, or what the model takes a UUID or an element token for, nor an element token known from before (one the model labelled in prose a turn earlier) (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then on the same route (the providers the request can reach: its model's, its fallbacks', or a group's members'; `maskedFor`, `masking.WithRoute`, `redact.Options.Route`), so neither a value a rule first finds later in a conversation nor a name the local model reads in a tool's output only after its first send (the default model's 2s wait, `pii.Partial`; vvrfxyz on X, dsh's cache hits) changes the prompt the vendor has cached and rewrites all of it to the cache; such a late find is masked in new text (`learnLate`), and another route, never sent the text, gets it masked with what is known and found now, `sentSpans`, `TestModelReadingLateKeepsTheSentPrefix`, `TestMaskedPrefixKeptOnlyOnItsRoute`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end, before the writer outside it that names the member, `memberWriter`, writes what it holds: the other way round a whole reply with a value masked in its request went out a 200 with an empty body, #4129, `TestMaskedWholeReplyNamesMember`): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it and isn't masked on its way, since a request is masked only once its route is known (#3973: masking a body whose masked copy was thrown away took up to minutes of magpie's own time). The log, recent calls and the request archive keep it as it went (the archive's bodies have their secrets taken out, `redact.ScrubJSON`, as every call's do), whether the archive is on or off; an observer that wants the bodies (the OTLP export, a JS plugin's) is handed it masked, masked once when it is first handed it after a try (`Call.maskIn`, `laterMasked`), never before the request is sent. A request turned away before it is routed is logged masked (`maskedCopy`). count_tokens and embeddings follow the same rule. A request masking would change can go to such a model instead (jessyoungyu on X: 「{{百度}}这家公司怎么样」 can't be answered from a placeholder): with Settings › Privacy's *Instead of masking, send to* set (`RedactRouteTo`, `POST /api/settings/redact-route`, which takes only a model `MaskRoute` passes: `unredactedRoute` for its provider and fallbacks, or its group), an agent's turn that masking would change (`maskHits.n` > 0: a warn-only hit doesn't count, and a held-back one stays held back) goes as written to that model, the model asked for left alone, in `serve` after the request is masked (`maskRouteFor` in [`redact.go`](../../internal/gateway/redact.go); the masked copy is thrown away, so streaming and every API go as for any route). If it fails, the request fails: its fallbacks are all unmasked ones by `unredactedRoute`, and nothing is masked and sent to the model asked for. It is judged again on each request, so a route that has since got a vendor's address, a fallback elsewhere, was turned off, or isn't one of a gateway key's models is ignored and the request is masked as before. Only an agent's own turn is moved (`agentTurn`, set in `serveAgent` and cleared by `ownAsk`): a title, a search stand-in, a picture described, System One and Jev stay masked. count_tokens is counted on the route (`countTokens`), and a turn of Codex's own model on its ChatGPT sign-in goes there too (`codexMaskRoute` in `codexBackend`; masked once to decide, only while it is set). Unset, as by default, nothing changes. Tests: `TestMaskedRequestGoesToTheModelSet`, `TestCodexSigninTurnGoesToTheModelSet`, `TestMaskRouteOnlyForTheAgentsTurn`, `TestMaskRouteTakesOnlyUnmaskedRoutes` ([`mask_route_test.go`](../../internal/gateway/mask_route_test.go)) and `TestRedactRouteSetting` in internal/gui. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`). A request masking swapped a value in (`maskHits.n`) is told, on each try, that the placeholders are used as written and filled in before anything runs (`placeholderNote`, [`placeholder_note.go`](../../internal/gateway/placeholder_note.go); treeMan on Discord: weaker models refused to search with one, asked to verify it, or rewrote it as an example). The note names neither magpie nor a vendor or client. It goes where placeholders first appear, after what is there, so it is new text the first time and the same on every later turn: in the instructions when they or the tools hold one (the last block of Anthropic's `system`, the end of Chat's first system or developer message, a part after Gemini's `systemInstruction`'s), else on the earliest message that holds one (a text block or part after its content; on Responses a developer message after that item and the tool outputs that follow it). Responses `instructions` (Codex's base_instructions) is never touched. A conversation's values are masked again each turn and a value found later is masked only in new text, so the note never lands in text the vendor has cached (`TestMaskedConversationKeepsItsCachedPrefix` goes red with the note in the system prompt). It is not added for a Claude subscription (the bridge puts the caller's instructions in the run's first message, which Anthropic classifies), for a ChatGPT account (Codex's own turns, `codexUpstreamOn`, never pass here either), or for a Responses turn with `previous_response_id`, where it would pile up in the stored conversation (`notesPlaceholders`; `TestPlaceholderNotePlaces`, `TestPlaceholderNoteNotOnClientPaths`, `TestMaskedRequestTold`, `TestPlaceholderNoteIsNeutral`). count_tokens counts without it. +2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, 32 hex digits or more, or a digest of 16 to 31 hex digits in one case with letters and digits both, a cache key or a short commit, which went as a key before: _kaichen on X, 10-28; `digestShaped`), or an element token cua-driver hands the model for computer use (`s0000002a:14`, #3782), goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), nor cua-driver's own `element_token` (any other name with `element` in it, `element_api_key`, is a credential's as before), a bare `key` (not after api, access, secret, private, signing or license: `keyPhrase`), a field named for a cache, commit, object, blob, file, content, revision, partition, shard, bucket, dedup, lookup, row or sort key, a serial number, or what the model takes a UUID or an element token for, nor an element token known from before (one the model labelled in prose a turn earlier) (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then on the same route (the providers the request can reach: its model's, its fallbacks', or a group's members'; `maskedFor`, `masking.WithRoute`, `redact.Options.Route`), so neither a value a rule first finds later in a conversation nor a name the local model reads in a tool's output only after its first send (the default model's 2s wait, `pii.Partial`; vvrfxyz on X, dsh's cache hits) changes the prompt the vendor has cached and rewrites all of it to the cache; such a late find is masked in new text (`learnLate`), and another route, never sent the text, gets it masked with what is known and found now, `sentSpans`, `TestModelReadingLateKeepsTheSentPrefix`, `TestMaskedPrefixKeptOnlyOnItsRoute`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end, before the writer outside it that names the member, `memberWriter`, writes what it holds: the other way round a whole reply with a value masked in its request went out a 200 with an empty body, #4129, `TestMaskedWholeReplyNamesMember`): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, and has an address: the user's switch for each provider whatever its address, AcMilan on Discord, `http://llm.corp.lan:8000`; nothing is looked up to decide, `TestSkipsRedaction`, `TestLANNameUnredactedProvider`. The editor shows it for every provider but a signed-in account and another magpie, and, while it is on, a caution under it naming an address not on this computer or the local network (`awayHost` in app.js; a name of the user's own DNS is asked about, only while it is on, through `POST /api/local-hosts`, `provider.LocalHost`, which takes a name every address of which, looked up in 400ms and kept a minute, is loopback, private or link-local, `netproxy.LocalName`; no request asks it)) goes to them as the agent wrote it and isn't masked on its way, since a request is masked only once its route is known (#3973: masking a body whose masked copy was thrown away took up to minutes of magpie's own time). The log, recent calls and the request archive keep it as it went (the archive's bodies have their secrets taken out, `redact.ScrubJSON`, as every call's do), whether the archive is on or off; an observer that wants the bodies (the OTLP export, a JS plugin's) is handed it masked, masked once when it is first handed it after a try (`Call.maskIn`, `laterMasked`), never before the request is sent. A request turned away before it is routed is logged masked (`maskedCopy`). count_tokens and embeddings follow the same rule. A request masking would change can go to such a model instead (jessyoungyu on X: 「{{百度}}这家公司怎么样」 can't be answered from a placeholder): with Settings › Privacy's *Instead of masking, send to* set (`RedactRouteTo`, `POST /api/settings/redact-route`, which takes only a model `MaskRoute` passes: `unredactedRoute` for its provider and fallbacks, or its group), an agent's turn that masking would change (`maskHits.n` > 0: a warn-only hit doesn't count, and a held-back one stays held back) goes as written to that model, the model asked for left alone, in `serve` after the request is masked (`maskRouteFor` in [`redact.go`](../../internal/gateway/redact.go); the masked copy is thrown away, so streaming and every API go as for any route). If it fails, the request fails: its fallbacks are all unmasked ones by `unredactedRoute`, and nothing is masked and sent to the model asked for. It is judged again on each request, so a route that has since got a vendor's address, a fallback elsewhere, was turned off, or isn't one of a gateway key's models is ignored and the request is masked as before. Only an agent's own turn is moved (`agentTurn`, set in `serveAgent` and cleared by `ownAsk`): a title, a search stand-in, a picture described, System One and Jev stay masked. count_tokens is counted on the route (`countTokens`), and a turn of Codex's own model on its ChatGPT sign-in goes there too (`codexMaskRoute` in `codexBackend`; masked once to decide, only while it is set). Unset, as by default, nothing changes. Tests: `TestMaskedRequestGoesToTheModelSet`, `TestCodexSigninTurnGoesToTheModelSet`, `TestMaskRouteOnlyForTheAgentsTurn`, `TestMaskRouteTakesOnlyUnmaskedRoutes` ([`mask_route_test.go`](../../internal/gateway/mask_route_test.go)) and `TestRedactRouteSetting` in internal/gui. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`). A request masking swapped a value in (`maskHits.n`) is told, on each try, that the placeholders are used as written and filled in before anything runs (`placeholderNote`, [`placeholder_note.go`](../../internal/gateway/placeholder_note.go); treeMan on Discord: weaker models refused to search with one, asked to verify it, or rewrote it as an example). The note names neither magpie nor a vendor or client. It goes where placeholders first appear, after what is there, so it is new text the first time and the same on every later turn: in the instructions when they or the tools hold one (the last block of Anthropic's `system`, the end of Chat's first system or developer message, a part after Gemini's `systemInstruction`'s), else on the earliest message that holds one (a text block or part after its content; on Responses a developer message after that item and the tool outputs that follow it). Responses `instructions` (Codex's base_instructions) is never touched. A conversation's values are masked again each turn and a value found later is masked only in new text, so the note never lands in text the vendor has cached (`TestMaskedConversationKeepsItsCachedPrefix` goes red with the note in the system prompt). It is not added for a Claude subscription (the bridge puts the caller's instructions in the run's first message, which Anthropic classifies), for a ChatGPT account (Codex's own turns, `codexUpstreamOn`, never pass here either), or for a Responses turn with `previous_response_id`, where it would pile up in the stored conversation (`notesPlaceholders`; `TestPlaceholderNotePlaces`, `TestPlaceholderNoteNotOnClientPaths`, `TestMaskedRequestTold`, `TestPlaceholderNoteIsNeutral`). count_tokens counts without it. - With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so (a date over a year ago: one in the last year or ahead is the day an agent runs on, `dateOK`); the word must be right before the date, so a log line's or a file name's date is none, and a time beside the date doesn't make it a log's: a date of birth stored as a time (`1990-05-11T16:00:00.000Z`) is one (`TestBirthdayLogDates`; #3878), MAC addresses, and serial numbers next to S/N or the like. Eleven digits from 13 to 19 are a mainland mobile's form and an id's too, so they are a phone only with +86 or 86 before them, as the value of a field whose name says phone (phone, mobile, tel, cell, contact, 手机, 电话, a field named `number`), or in prose with no id's word right before them (order, id, no., #, 订单号, 编号, 单号, 流水号); under order_id or uid, after 订单号, or with a letter or digit against them they go as written (`phoneAt` in [`internal/redact/phone.go`](../../internal/redact/phone.go); _kaichen on X, 10-28). Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. When the user name is on, it goes as a made-up name of 8 lowercase letters, the same for that name every turn and put back in replies like any placeholder (`standIn` in [`shape.go`](../../internal/redact/shape.go)), not as `{{USERNAME_…}}`: with mimo-v2.6-flash a model read `C:\Users\{{…}}` as a temporary folder and set out to delete it (eerttreeeert on X, 10-28). A public IP address goes the same way as an address from the documentation ranges (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24, host .101 to .254; 2001:db8::/32 for IPv6), the same one for that address while magpie runs and never another address's, put back only where it stands as a whole address, in a streamed tool call's arguments too (`ipStandIn`, `restoreAddr`; `TestIPGoesAsADocumentationAddress`). Told `{{IP_…}}`, models asked the user for the real address or searched `~/.ssh` for it instead of running ssh (0x0_air on X, 10-28); past the 462 IPv4 stand-ins an address goes as its placeholder. An EVM address (`0x` and 40 hex digits) is public, so the local model's finds leave it as written unless a key's name is right before it; a 64-digit private key is still masked (`evmRe` in `modelFits`; `TestEVMAddressGoesAsWritten`). Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `strings@base.json`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`icon@2x.zip`, `intro@1.5x.mov`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). A domain needs a dot and labels a host can have, so a disassembly's symbols go as written for both too: `system@plt`, `puts@got.plt`, `memcpy@GLIBC_2.14`, `foo@@GLIBC_2.2.5`, and `system@got` (`.got` is a top-level domain; `mailHost` in `realEmail`, `TestSymbolIsNoEmail`; ch35tnut_ on X, 10-28). `ops@files.zip` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults. - With *Find with a local model* on (`masking.ModelWanted`: on by default since 10-28, `settings.RedactModel` the user turning it on and `RedactModelOff` off, this computer's own, kept by `KeepOwn`; a user with a model downloaded or picked and neither flag turned it off before the default, and `RedactModelAuto` marks the default's own download), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`), but for what the agent defines (its tools' and schemas' descriptions, under `defKeys`), which the rules alone mask, as with the model off, after the rest of the request so a value the model found in a message is masked there too as known: those were 52,577 of Claude Code 2.1.296's 67,532 bytes the model read, and a 4-core server's first request waited out the gateway's 2 minutes (niuniu_8964 on X; 11.5s cold at 4 procs on a Ryzen AI Max+, 2.6s without them, and on three real Claude Code requests the model masked nothing there the rules didn't); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). A package's name goes as written, for the model and the rules alike (dniray on Discord, v0.1.1917): the module a line of code loads (`from ' drizzle-orm '`, `require('jsonwebtoken')`, `from x import`, `use x::`, with an editor's line number or a diff's mark before it; `moduleAt`, `codeHead`), a manifest's dependency pinned at a version (`"drizzle-orm": "^0.36.4"`, TOML's `x = "9"`; `dependencyAt`), a folder under node_modules or site-packages, the module an error could not find (`Cannot find module 'x'`, `No module named 'x'`; `missingModuleAt`), a package an install names (`pnpm add x`; `installedAt`) or pins with @ (`x@0.36.4`; `pinnedAt`), all in `packageAt`; a value known from an earlier mask (`knownSpans`) goes as written there too, since once the model took the name for a secret anywhere in a request it was masked on the import line as known (dniray, v0.1.1965), a requirement's name before its pinned version (`django-rest-passwordreset==1.4.0`; `pinnedAfter`), a lock file's integrity hash (`sha512-…`; `sriRe` in `namesThing`), a version as the value of a field named for a secret (`"js-tokens": "^4.0.0-beta.1"`; `versionValue` in `fieldAt` and `keyAt`), and a package pinned at its version as user@host has it (`js-tokens@4.0.0:` in pnpm-lock.yaml; `notPackagePin`); `TestPackageNamesGoAsWritten` and `TestModelPackageNamesNotMasked` hold them. The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with Privacy Filter a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name; 和 or 与 says so only after a person, 吴敏和郑浩 but not 判断和边界, 发 or 打 only as the verb, 发了个 but not 关键发现, and a sentence starts after punctuation, not after a space after code, `gh pr view` 易触发; xuanwo on X; 一下 only after a verb that asks a person, 问一下张伟 but not 改一下文案, a word any subject takes after it, 已经, 明天 or 他, only with a person's cue before it, and 说明 is no 说; zeewell on X), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left, and so is a common word that starts with one (`zhWords`: 文案, 文档, 方案; 毛利, 毛重, 毛巾, since 毛利 is a margin far more often than the Japanese surname, so 毛利低 goes as written: _kaichen on X, 10-28; the model still finds 毛利兰, and neither model nor rule masks 毛利小五郎), the model's own name too when it is that word whole. A name the model or the cues take is also no name when it is an ordinary word (`zhWordShaped`, `zhWordNotName`, the one check both go through): a colour (黄绿色, 红色, any that ends in 色 or is colour characters alone: hh05928822 on X after v0.1.1850), a word that starts with a surname from `zhWords` or `zhDict` (about 1,550 two-character words from jieba's dictionary, [`zhdict.txt`](../../internal/redact/zhdict.txt), its header saying how they were chosen; 边界, 应该, 尚可), or such a word with what makes a longer word after it (关键词, 关键字: wangjunxiao128 on X; 应用层, 毛利率), unless a role before it or a title after it says a person is meant (客户方圆, 江山老师), where a name that is also a word is masked. The surnames stay (黄 starts 黄绿色 and 黄晓明), and 毛利兰, 关羽 and 黄晓明 are still masked. With AstrLink Guard only a nickname is (小王, 老李, `zhNick`; `redact.Options.NamesByModel`): Guard at 0.8 finds the full names those cues did in zhname_test's sentences (张伟, 陈建国, 欧阳娜娜…), and misses the nicknames, 孙经理, and all but the surname of 王老板 and 邓总; the cues took words for names (关键发现; xuanwo on X). The model is the user's pick (`settings.RedactModelName`, `pii.Choose`; the app's menu beside the switch, `pmPick`): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by [`internal/pii/guard`](../../internal/pii/guard) (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, `guardLabels`); a text over one window, 510 tokens, is read in windows that overlap by 128, and on the CPU as many windows at once as it has cores, half of `GOMAXPROCS` and 4 at most (`guard.Cores`: on every core a long history unread kept a 32-core Linux box at 13 cores' worth for as long as requests came, xinvxueyuan and shensmart on Discord, 10-28): one window's matmuls split over the cores left them idle between, and a 4-core server's first Claude Code request waited minutes (niuniu_8964 on X; 22,488 tokens took 23.9s at 4 procs, 17.9s at once, and 48.8s against 30.5s at 2), and on a Mac through CoreML on the Neural Engine or the GPU ([`coreml.go`](../../internal/pii/guard/coreml.go), [`internal/pii/guard/coreml`](../../internal/pii/guard/coreml); yyhhyyyyyy on X; Settings › Privacy names which, from CoreML's own compute plan of the compiled model, `MLComputePlan` on macOS 14.4 and later, the device most of its program's estimated cost is on (`coreml.Plan`, `Model.Backend`, `Status.Via` and `Device`): it said "on the CPU" under CoreML, yyhhyyyyyy on Discord, 10-27; an M5 Pro's plan puts all of it on the GPU; after a CoreML read fails it says the CPU and why until one doesn't): the same network from the same int8 weights in float16, written from the downloaded model into a program made by `coreml_gen.py` and compiled once into the model's folder, 512 tokens in about 12 ms where the CPU takes 400, its probabilities within .07 of the publisher's fp32 model where the CPU's are within .13 (the CPU quantizes activations as the int8 model does, CoreML doesn't), so a span near the threshold can fall the other side (a go.mod module path is a secret at .81 on CoreML, .79 on the CPU, .785 in fp32); a window under 16 tokens (`coremlMin`), a Mac before macOS 13 or any failure goes to the CPU, loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick it is AstrLink Guard, the default; a user who had Privacy Filter on before there was a choice keeps it only while AstrLink Guard downloads, which the first masked request starts and which then saves AstrLink Guard as the pick (`masking.picked`, `toGuard`; an hour between tries after a failure). Measured for that default (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (`backend`). AstrLink Guard's turn has `guard.Cores()` places (`guardTurn`), so that many requests read at once, and they share those cores: every window, of any request, takes one of `guard.Cores()` tokens before it reads and more only while they are free (`guard.take`), so requests together never read on more cores than one did (the 4 promised xinvxueyuan and shensmart above); the model loads once (`guardLoading`), the idle timer lets go only when no place is held (`guardIdle`), and a text one request is reading another waits for rather than reading it too (`backend.reading`). Before, one request read at a time, and an agent's parallel requests queued behind it (yyhhyyyyyy on Discord, 10-28, who asked for 16 at once). Measured at 1, 2, 4 and 8 requests at once (a Ryzen AI Max+ 395 under WSL, 4 cores): 512-byte requests 4.2, 6.1, 8.1 and 8.4 a second where one at a time was 4.2 whatever came, on 1.9 to 3.9 cores, memory flat at about 150 MB; 4 KB requests already read their 3 windows on 3.6 cores alone, so they stay at 0.6 a second (Windows on the same box: 7.5 to 12.1 a second at 1 to 8, 4 KB 0.7 to 0.8, on at most 3.8 cores). Each request on cores of its own would read 20 a second at 8, on 12 cores, and 4 KB at 8 took 20 cores and 521 MB (953 MB on an M5 Pro), so the bound is the cores, not the count, and there is no setting for it. Through CoreML the GPU is the bound: on an M5 Pro 4 KB requests read 23, 20, 25 and 25 a second at 1, 2, 4 and 8, a model per request no faster, so CoreML reads one window at a time, and only the windows under `coremlMin` or after a failure use the CPU's tokens. Both find at a floor of 0.5 (`pii.Floor`) and give each span its score (AstrLink Guard: the least of its tokens' probabilities, rounded to a float32 so a cached span reads back the same; Privacy Filter: pf-serve's own), and masking keeps those at the model's threshold or over (`pii.Threshold` in `masking.model`): the user's for that model (`settings.RedactModelScore`, this computer's own; Settings → Privacy's Confidence threshold, `pmScore`, 0.5 to 0.95), else the model's own (`MinScore`: Privacy Filter 0.5, AstrLink Guard 0.8, its publisher's). A value known from before follows the same threshold: each value masked remembers the highest score anything found it with (a rule's counts as sure), and one only the model found, under the threshold now, is no longer masked again as known (`noteScores`, `knownSpans` in [`known.go`](../../internal/redact/known.go); before, a raised slider changed nothing for a value masked once: _kaichen on X, 10-28). The defaults stay because on the eval a higher one mostly loses values the checks after the model would have kept (Privacy Filter at 0.85 lost a Chinese name; AstrLink Guard at 0.9 a phone in a tool result), while the false alarms it would drop are mostly dropped by those checks already (Yayoi_no_yume on X). Measured again on 2000 segments of real agent traffic (Codex and Claude Code sessions: prompts, tool arguments and results, a quarter with Chinese) and 30 more labelled cases: AstrLink Guard at 0.88 rather than 0.8 drops 3 false alarms (a model id, a sandbox path word, a token counter) and lets a colleague's name and a signed name through; Privacy Filter at 0.88 rather than 0.5 drops 11 (timestamps in paths, log lines, a plugin id) and lets 6 real names and a phone through (4 of the names in the real traffic). Lowering Guard to 0.5 finds 2 more names in the real traffic and 3 more labelled values, for 10 more false alarms (9 of them Claude Code's `` counter). Those false alarms are shapes a check can turn away; a threshold can't without losing real values. Privacy Filter is a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; every pf-serve keeps the engine's own MoE chunk, `PF_MOE_CHUNK` at the window's 4096, which an RX 470 through Vulkan read 6-9% faster than 2048 in interleaved runs and Metal ~6% faster, and inherits a value the user set): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, through magpie's proxy (`netproxy.Func`, as its other requests; hh0592821 on Discord, whose download went direct before), from hf-mirror first in China (`source.chinaFirst`) and from hf-mirror after Hugging Face everywhere else, the switch off too (`source.modelMirror`), so a poisoned or blocked huggingface.co doesn't stop it; hf-mirror serves AstrLink Guard's files itself and sends Privacy Filter's back to Hugging Face) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request, in the model's folder and given the model's file name, never its path (a Windows C program's argv is in the ANSI code page and ggml reads it as UTF-8, so a user folder named in Chinese failed every load with the path in mojibake, AIMetaPhD on X; a pf-serve error that names the file is shown with the whole path) (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, of those in the piece's second half the one whose 48 bytes before it hash least (`landmark`), so a line edited early in a text leaves the pieces after it as they were, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and a value of 8 bytes or more found in a text is found wherever else it is in it, as sure as its surest find (`spread`: the model scored an address on 400 lines alike 0.9 on some and 0.5 on most, wangwu25685333 on X), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-.bin` beside the model: hashes, offsets, labels and each span's score, never text; a `pfound01` file from before scores is read with every span sure, so it masks as it did; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, by the request waiting with the least left to read (`takeTurn`, `queue`), so a short request goes before the rest of every long one (wangwu25685333 on X: a 5 KB request behind two long ones on 4 cores waited 8.3s in the order they came, 4.5s now). The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). Until the model is on disk the rules mask alone, and its download starts (`masking.fetch`, an hour between tries; the default's, done, saved by `settings.UseDefaultRedactModel` unless the user picked or turned it off meanwhile; cancelling it is turning it off). A model the user turned on that fails (didn't start, isn't on disk, held back after a failure) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`, strict); the default's finds nothing then, and the rules mask alone. A model that is only slow is waited for at most 2 seconds from the request's masking start when on by default (`masking.defaultWait`) and 15 seconds when the user turned it on (`masking.strictWait`): its turn, its load and its reading. Past that, or when the request's context ends first, `pii.FindContext` answers with what was known of the request's texts by then (its cache: the history read on earlier turns, and the chunks read meanwhile) and a `*pii.Partial` saying how many it hadn't read; `masking.model` masks those with the model's finds and the rest with the rules alone, logging it at most once a minute (`notePartial`), and the request goes. Nothing the rules mask goes as written. Before, the user's model was waited for with no bound and any end of the wait held the request back whole, its known finds thrown away: in a burst of requests with text the model hadn't read, xRayySummers on X (0.1.1877, Linux) saw masking take 1.2s to 290s in one minute and each request it ended was "masking failed, so nothing was sent". Reproduced on 8 cores of a Linux CPU: AstrLink Guard reads about 6 KB a second there (a 125 KB history 20.8s), and six requests at once with 67 to 145 KB of new tool results each took 62 to 110s, all ending near the last, since the turn goes round between chunks; with the bound each went at 15.0s with the history's finds and the model's for 1 to 4 of its 9 texts. `masking.find` gives a model that doesn't stop for its context 100ms to answer with what it knew (`handBack`) before giving up on it. AstrLink Guard reads on the CPU, so a long Codex history it hasn't seen took minutes there, and every request queued behind it showed masking with no bound (shensmart on Discord, 10-28, magpie in Docker). The wait is given up even where `Find` doesn't stop for its context. A request that stops waiting leaves the chunks after the one being read (`backend.find`), so it doesn't hold the turn; that chunk's answers are kept for the next request. Each model reads a request's unread texts newest first, the last text and a long one's last piece before the rest (`backend.missing`), since an agent's history is oldest first and what a request adds is at its end; AstrLink Guard joins them into chunks of 4 KB, not Privacy Filter's 12 KB (`backend.chunk`, `guardChunk`), so the chunk a request leaves the model finishing past its wait is about a second on 4 cores. The default's request is `pii.Bounded`: what one went without the model's reading is remembered by hash (`backend.sent`), and a request after it reads what it adds first and that backlog `backlogCap` (4 KB) at most, nothing found for the rest, so a history resumed or never read is read a little a request rather than on every core for each one. Measured on a 2 MB, 200-turn Codex history never read, 30 requests 3s apart (`TestLiveHistoryCost`, gated on `MAGPIE_GUARD_FILES`): on a 32-core Linux box 33 to 60 CPU seconds a request before, 23 minutes of CPU over the session's 108s (13 cores busy), 6 to 10 after, 4 minutes over 90s (2.7 cores), and on an M5 Pro's CoreML 2.2 CPU seconds a request for the first three before, the first alone after; nothing runs on after the last request either way. A request the user turned the model on for still reads all of it, waited for `strictWait`. - With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request. diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 5df7ed949..0e964f8e8 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -135,8 +135,8 @@ const providerUsage = `usage: (Ollama, LM Studio, oMLX or MLX-Serve on another port or computer: each of its URLs moves there, keeping its path; address= alone puts it back at the default) magpie provider set ollama unmasked=yes - (a model on this computer or the local network: Settings' redaction leaves its - requests as written; not for a local relay that passes them on to a vendor) + (Settings' redaction leaves its requests as written, at any address: your call, + so mind a relay that passes them on to a vendor; never a signed-in account) magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000' magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %' magpie provider set my-relay balance.method=POST @@ -840,9 +840,9 @@ func showProvider(p provider.Provider) error { kv("user-agent", "agent's"+muted.Render(why)) } if p.Unredacted { - why := " local: Settings' redaction leaves its requests as written" + why := " Settings' redaction leaves its requests as written" if !p.SkipsRedaction() { - why = " but masked: not every address of it is on this computer or the local network" + why = " but masked: a signed-in account, another magpie or no address" } kv("unmasked", "yes"+muted.Render(why)) } @@ -1182,9 +1182,9 @@ func applyPairs(p *provider.Provider, pairs []string) error { return fmt.Errorf("compaction=native|magpie, not %q", v) } case "unmasked": - // yes: a model on this computer or the local network gets the - // requests as written, unmasked by Settings' redaction (lc on - // Discord); only while every address of it is local + // yes: the provider gets the requests as written, unmasked by + // Settings' redaction (lc, AcMilan on Discord): the user's word + // at any address, never for an account or another magpie // (provider.SkipsRedaction) if v != "yes" && v != "no" { return fmt.Errorf("unmasked=yes|no, not %q", v) diff --git a/internal/gateway/unredacted_test.go b/internal/gateway/unredacted_test.go index 72e4f67a8..df883b8ed 100644 --- a/internal/gateway/unredacted_test.go +++ b/internal/gateway/unredacted_test.go @@ -3,6 +3,7 @@ package gateway import ( "context" "io" + "net" "net/http" "net/http/httptest" "regexp" @@ -12,6 +13,7 @@ import ( "github.com/yetone/magpie/internal/gwmw" "github.com/yetone/magpie/internal/masking" + "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" ) @@ -334,3 +336,39 @@ func TestUnredactedAskedButSentElsewhereMasked(t *testing.T) { t.Fatalf("scanned %d times, want 1", n) } } + +// AcMilan on Discord: "Send requests unmasked" is the user's switch for +// each provider. A model at a name of the user's own DNS +// (http://llm.corp.lan:8000) gets the request whole with it on, and +// masked with it off; nothing is looked up to decide. The name is reached +// through a proxy set in Settings, the test's fake, so no lookup reaches +// the network. +func TestLANNameUnredactedProvider(t *testing.T) { + const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst" + chat := `{"model":"fake/m1","max_tokens":10,"messages":[{"role":"user","content":"my key is ` + key + `"}]}` + for _, on := range []bool{true, false} { + f := &fake{ctype: "application/json", reply: `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":1}}`} + up := setup(t, provider.Anthropic, f) + t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) { + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + })) + p, err := provider.Find("fake") + if err != nil { + t.Fatal(err) + } + p.Unredacted = on + p.Anthropic = "http://llm.corp.lan:8000" + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if err := settings.Save(settings.Settings{Redact: true, Proxy: up.URL}); err != nil { + t.Fatal(err) + } + if code, reply := post(t, "/v1/messages", chat); code != 200 || f.calls != 1 { + t.Fatalf("on %v: %d %s, the model asked %d times", on, code, reply, f.calls) + } + if whole := strings.Contains(string(f.got), key); whole != on { + t.Fatalf("switch on %v, sent whole %v: %s", on, whole, f.got) + } + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 0c5af5ba5..29aa31bf5 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3218,6 +3218,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .editor .bar .danger { margin-left: -7px; } .editor .editor-error { grid-column: 1 / -1; font-size: 12px; line-height: 1.45; color: var(--red); white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } .editor .editor-error.warn { color: var(--amber); } +.editor .hint.unmasked-away { color: var(--amber); } /* what a pasted curl command filled in (curlOf), said where an error is */ .editor .editor-error.note { color: var(--fg-2); } .busy { opacity: .55; pointer-events: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 182aae6ae..c456a7952 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -9754,10 +9754,7 @@ function drawEditor(p, presetID) { if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField()); - // a relay in front of Anthropic's or OpenAI's API searches the web as - // they do, which magpie can't tell from its host (#359): a client's web - // search goes to it as sent, rather than through magpie's own. Only its - // Anthropic or Responses API can be asked to: a Chat one has no such tool + // a relay that searches the web as its vendor does gets a client's search as sent (#359) if (custom) { const [stk, scb] = tick(t("Searches the web by itself"), !!draft.searches); scb.onchange = () => { draft.searches = scb.checked; }; @@ -9767,11 +9764,7 @@ function drawEditor(p, presetID) { advIn.append(...row); } - // which header the key goes in on a third-party Anthropic API: both by - // default, one alone for a service that refuses the two together (Aloha - // on Discord: "x-api-key 和 Authorization 不可以同时存在"), which magpie - // also learns from that refusal. Anthropic's, Bedrock's (its runtime and - // its Mantle endpoint) and Azure's own APIs take x-api-key alone already + // a third-party Anthropic API's key header: both, or one for a service refusing two (Aloha) const twoKeyHeaders = () => { if (p?.account || vertex) return false; if (p && !custom) return !!p.bothAuth; @@ -9802,25 +9795,27 @@ function drawEditor(p, presetID) { advIn.append(...field(t("User-Agent"), utk, t("For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins."))); } - // a model on this computer or the local network (Ollama, LM Studio, a - // vLLM box) may be sent requests unmasked by Settings' redaction (lc on - // Discord). Only the user can say it is local all the way: a relay run - // locally, or Ollama's cloud models, pass a request on to a vendor + // the user's switch at any address (AcMilan), with a caution while on const addressOf = (k) => (draft[k] ?? (isNew && pr ? pr[k] : "")) || ""; - const onLAN = () => !p?.account && (p?.preset || pr?.id) !== "remote-magpie" && localAddresses(["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf)); - if (!p?.account) { + const unmaskable = () => !p?.account && (p?.preset || pr?.id) !== "remote-magpie"; + if (unmaskable()) { const [ltk, lcb] = tick(t("Send requests unmasked"), !!draft.unredacted); - lcb.onchange = () => { draft.unredacted = lcb.checked; }; + lcb.onchange = () => { draft.unredacted = lcb.checked; showLocal(); }; const row = field(t("Redaction"), ltk, t("For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.")); - showLocal = () => { for (const e of row) e.style.display = onLAN() ? "" : "none"; }; + const away = el("div", "hint unmasked-away"); + row[1].append(away); + showLocal = () => { + const urls = ["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf); + const host = draft.unredacted ? awayHost(urls) : ""; + away.textContent = host ? t("{host} isn't on this computer or your local network: turned on, requests go to it unmasked.", { host }) : ""; + away.hidden = !host; + if (draft.unredacted) askLANNames(urls, showLocal); + }; showLocal(); advIn.append(...row); } - // a provider the user added whose server has a certificate nothing - // trusts (a vLLM on the LAN, Ollama behind a self-signed cert, a - // company CA, #2383) may be asked without checking it: only its own - // https:// hosts, never a preset's or a sign-in's (provider.TakesInsecureTLS) + // a user's provider whose certificate nothing trusts (#2383, provider.TakesInsecureTLS) const tlsTakes = () => custom && (!p || !!p.takesInsecureTLS); const onHTTPS = () => ["chat", "responses", "anthropic", "gemini", "decide"].map(addressOf).some((u) => /^\s*https:\/\//i.test(u)); if (tlsTakes()) { @@ -10186,7 +10181,7 @@ function drawEditor(p, presetID) { body.searches = !!draft.searches && searchable(); body.pinUpstream = !!draft.pinUpstream; if (twoKeyHeaders()) body.authHeader = draft.authHeader || ""; - body.unredacted = !!draft.unredacted && onLAN(); + body.unredacted = !!draft.unredacted && unmaskable(); if (tlsTakes()) body.insecureTLS = !!draft.insecureTLS && onHTTPS(); if (custom) body.limitRestOff = !!draft.limitRestOff; if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction(); @@ -20353,23 +20348,43 @@ function syncWhen(iso) { return new Date().toDateString() === d.toDateString() ? t("at {time}", { time }) : d.toLocaleDateString(intlLang()) + " " + time; } -// localAddresses: every address given is on this computer or the local -// network (localhost, *.local, a loopback or private IP), as -// provider.LocalAddresses says, and there is at least one -function localAddresses(urls) { - const given = urls.map((u) => (u || "").trim()).filter(Boolean); - return given.length > 0 && given.every((u) => { - let h; - try { h = new URL(u).hostname.toLowerCase(); } catch { return false; } - if (h.startsWith("[")) h = h.slice(1, -1); - if (h === "localhost" || h.endsWith(".local") || h === "::1") return true; - const v4 = h.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/); - if (v4) { - const a = +v4[1], b = +v4[2]; - return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168); - } - return /^f[cd][0-9a-f]{2}:/.test(h); - }); +// awayHost: the first host of urls not local +function awayHost(urls) { + for (const h of urls.map(urlHost)) if (h && (localIP(h) ?? lanNames.get(h)) === false) return h; + return ""; +} + +function urlHost(u) { + try { return new URL((u || "").trim()).hostname.toLowerCase().replace(/^\[|\]$|\.$/g, ""); } catch { return null; } +} + +// localIP: null for a name +function localIP(h) { + if (h === "localhost" || h.endsWith(".local") || h === "::1") return true; + const v4 = h.match(/^(\d+)\.(\d+)\.\d+\.\d+$/); + if (v4) { + const a = +v4[1], b = +v4[2]; + return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254); + } + return h.includes(":") ? /^(f[cd]|fe[89ab])[0-9a-f]{2}:/.test(h) : null; +} + +// lanNames: whether a name of the user's DNS resolves only locally (null: asking) +const lanNames = new Map(); +let lanAskTimer = 0; + +function askLANNames(urls, then) { + clearTimeout(lanAskTimer); + const hosts = [...new Set(urls.map(urlHost))].filter((h) => h && localIP(h) === null && !lanNames.has(h)); + if (!hosts.length) return; + lanAskTimer = setTimeout(async () => { + hosts.forEach((h) => lanNames.set(h, null)); + try { + const r = await api("local-hosts", { hosts }); + hosts.forEach((h) => lanNames.set(h, r?.local?.[h] === true)); + then(); + } catch { hosts.forEach((h) => lanNames.delete(h)); } + }, 300); } function tick(label, on) { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 1e102c767..715208553 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3670,6 +3670,7 @@ const I18N = { "Codex compacts on this provider": "Codex 在此服务商上原生压缩", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的压缩请求原样交给此服务商,它加密的摘要原样还给 Codex。关闭时由 magpie 写摘要。这样压缩过的对话只能在此服务商和账号上继续:换到别处会报错说明,绝不丢掉上下文发出。", "For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "给运行在这台电脑或局域网里的模型:密钥、个人信息和你设的脱敏词按原样发给它。如果它是本地的中转或代理、会把请求转给供应商,请保持关闭。", + "{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} 不在这台电脑或局域网里:打开后,请求会不脱敏地发给它。", "User-Agent": "User-Agent", "Send the agent's own User-Agent": "发送 Agent 自己的 User-Agent", "For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "给只允许指定编程 Agent 使用的套餐:每个请求带上 Agent 自己发来的 User-Agent(pi、OpenCode、Claude Code…),而不是 magpie 的。magpie 自己发出的请求,以及 Agent 没带 User-Agent 的请求,仍以 magpie 的身份发送。上面请求头里设置的 User-Agent 始终优先。", @@ -7853,6 +7854,7 @@ const I18N = { "Codex compacts on this provider": "Codex 在此服務商上原生壓縮", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的壓縮請求原樣交給此服務商,它加密的摘要原樣還給 Codex。關閉時由 magpie 寫摘要。這樣壓縮過的對話只能在此服務商和帳號上繼續:換到別處會報錯說明,絕不丟掉上下文送出。", "For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "給執行在這臺電腦或區域網裡的模型:金鑰、個人資訊和你設的脫敏詞按原樣發給它。如果它是本地的中轉或代理、會把請求轉給供應商,請保持關閉。", + "{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} 不在這臺電腦或區域網裡:開啟後,請求會不脫敏地發給它。", "User-Agent": "User-Agent", "Send the agent's own User-Agent": "傳送 Agent 自己的 User-Agent", "For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "給只允許指定程式設計 Agent 使用的方案:每個請求帶上 Agent 自己送來的 User-Agent(pi、OpenCode、Claude Code…),而不是 magpie 的。magpie 自己發出的請求,以及 Agent 沒帶 User-Agent 的請求,仍以 magpie 的身分傳送。上面請求頭裡設定的 User-Agent 永遠優先。", @@ -12053,6 +12055,7 @@ const I18N = { "Codex compacts on this provider": "Codex のコンパクションをこのプロバイダーで行う", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex のコンパクション要求をそのままこのプロバイダーに送り、暗号化された要約をそのまま Codex に返します。オフのときは magpie が要約を書きます。こうしてコンパクションした会話は、このプロバイダーとアカウントでのみ続けられます。他へはエラーで断り、コンテキストを落として送ることはしません。", "For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "このコンピューターかローカルネットワークで動くモデル用:シークレット、個人情報、マスクする語はそのまま送られます。リクエストをベンダーに転送するローカルのリレーやプロキシではオフのままにしてください。", + "{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} はこのコンピューターにもローカルネットワークにもありません:オンにすると、リクエストはマスクされずに送られます。", "User-Agent": "User-Agent", "Send the agent's own User-Agent": "エージェント自身の User-Agent を送る", "For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "指定したコーディングエージェントだけが使えるプラン向け:各リクエストは magpie のものではなく、エージェントが送ってきた User-Agent(pi、OpenCode、Claude Code…)で送られます。magpie 自身のリクエストと、エージェントが User-Agent を付けなかったリクエストは、引き続き magpie として送られます。上のヘッダーで設定した User-Agent が常に優先されます。", @@ -16267,6 +16270,7 @@ const I18N = { "Codex compacts on this provider": "Codex kompaktiert bei diesem Anbieter", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex’ Kompaktierung geht so an diesen Anbieter, wie Codex sie sendet, und die versiegelte Zusammenfassung kommt unverändert zu Codex zurück. Aus: magpie schreibt die Zusammenfassung. Ein so kompaktiertes Gespräch geht nur bei diesem Anbieter und Konto weiter: ein anderer wird mit einem Fehler abgelehnt, nie ohne den Kontext angefragt.", "For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "Für ein Modell auf diesem Computer oder in Ihrem lokalen Netzwerk: Geheimnisse, persönliche Daten und Ihre maskierten Wörter gehen unverändert an es. Lassen Sie es aus für ein lokales Relay oder einen Proxy, der Anfragen an einen Anbieter weiterreicht.", + "{host} isn't on this computer or your local network: turned on, requests go to it unmasked.": "{host} ist weder auf diesem Computer noch in Ihrem lokalen Netzwerk: Eingeschaltet gehen Anfragen unmaskiert an ihn.", "User-Agent": "User-Agent", "Send the agent's own User-Agent": "Den eigenen User-Agent des Agenten senden", "For a plan that serves only the coding agents it names: each request goes with the User-Agent the agent sent (pi, OpenCode, Claude Code…), not magpie's. Requests magpie makes itself, and ones the agent sent without one, still go as magpie. A User-Agent set in Headers above always wins.": "Für einen Tarif, der nur die genannten Coding-Agenten zulässt: Jede Anfrage geht mit dem User-Agent, den der Agent gesendet hat (pi, OpenCode, Claude Code…), nicht mit dem von magpie. Anfragen, die magpie selbst stellt, und solche, die der Agent ohne einen gesendet hat, gehen weiter als magpie. Ein oben unter Header gesetzter User-Agent hat immer Vorrang.", diff --git a/internal/gui/localhosts.go b/internal/gui/localhosts.go new file mode 100644 index 000000000..bd04f772c --- /dev/null +++ b/internal/gui/localhosts.go @@ -0,0 +1,49 @@ +package gui + +import ( + "encoding/json" + "net/http" + "strings" + "sync" + + "github.com/yetone/magpie/internal/provider" +) + +// localHostsRoutes: POST /api/local-hosts {"hosts":[...]} answers +// {"local":{host:bool}}, whether each host is on this computer or the +// local network (provider.LocalHost). The provider editor shows a caution +// under "Send requests unmasked" for a provider with an address that +// isn't; a page can't resolve a name of the user's own DNS +// (http://llm.corp.lan:8000, AcMilan on Discord), so it asks here. It +// only words the editor: the switch is the user's, and no request asks. +func localHostsRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/local-hosts", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Hosts []string `json:"hosts"` + } + if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 16<<10)).Decode(&in); err != nil { + http.Error(rw, err.Error(), http.StatusBadRequest) + return + } + if len(in.Hosts) > 8 { // a provider has five addresses + in.Hosts = in.Hosts[:8] + } + var mu sync.Mutex + var wg sync.WaitGroup + out := map[string]bool{} + for _, h := range in.Hosts { + h = strings.ToLower(strings.TrimSpace(h)) + if h == "" || len(h) > 253 { + continue + } + wg.Go(func() { + local := provider.LocalHost(strings.Trim(h, "[]")) + mu.Lock() + out[h] = local + mu.Unlock() + }) + } + wg.Wait() + writeJSON(rw, map[string]any{"local": out}) + }) +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 41490c637..f6c993264 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1066,6 +1066,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { contextRoutesAPI(mux) tuneRoutes(mux) groupRoutes(mux) + localHostsRoutes(mux) // how each key's or account's requests stand under its limit on // requests at once (#892), read every two seconds while a provider's // rows are shown; empty when the gateway runs elsewhere diff --git a/internal/gui/tests/provider-unmasked.test.cjs b/internal/gui/tests/provider-unmasked.test.cjs index 33a039b81..dd7eeb439 100644 --- a/internal/gui/tests/provider-unmasked.test.cjs +++ b/internal/gui/tests/provider-unmasked.test.cjs @@ -1,10 +1,13 @@ // Run with Node's test runner and Playwright on the module path; see README.md. -// A model on this computer or the local network (lc on Discord): the -// provider editor's Redaction row, "Send requests unmasked", is there while -// every address of the provider is local (localhost, a private IP), opens as -// it was saved, and Save posts it. A relay at a vendor's address has no such -// row, and one whose address is changed to a vendor's is saved masked. A -// signed-in account has none. In English and Chinese, wide and narrow. +// "Send requests unmasked" (lc on Discord) is the user's switch for each +// provider they added (AcMilan on Discord): the editor's Redaction row is +// there whatever the address, opens as it was saved, and Save posts it. +// Turned on, a caution under it names an address not on this computer or +// the local network (a relay, a vendor, a name magpie says resolves elsewhere: +// /api/local-hosts); a local one (localhost, a private IP, a name of the +// user's own DNS resolving only to the local network) has none. A +// name is asked about only once the switch is on, so an editor merely +// opened asks nothing. A signed-in account has no row. In English and Chinese, wide and narrow. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -27,6 +30,9 @@ const base = { const local = { ...base, id: "local", name: "Local Box", chat: "http://localhost:11434/v1" }; const lan = { ...base, id: "lan", name: "LAN Box", chat: "http://192.168.1.20:8000/v1", unredacted: true }; const relay = { ...base, id: "relay", name: "Relay", chat: "https://relay.example.com/v1" }; +const named = { ...base, id: "named", name: "Corp LLM", chat: "http://llm.corp.lan:8000/v1" }; +// what magpie says each name resolves to: only the local network, or not +const lanHosts = { "llm.corp.lan": true, "relay.example.com": false, "api.vendor.example": false }; const codex = { id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], @@ -34,8 +40,8 @@ const codex = { proxy: "", }; -function serve(lang, posts) { - const providers = { providers: [local, lan, relay, codex], presets: [], excluded: [], gateway: { running: true, window: true } }; +function serve(lang, posts, asked) { + const providers = { providers: [local, lan, relay, named, codex], presets: [], excluded: [], gateway: { running: true, window: true } }; const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; return async (route) => { const url = new URL(route.request().url()); @@ -45,6 +51,11 @@ function serve(lang, posts) { if (url.pathname === "/api/state") return json(state); if (url.pathname === "/api/providers") return json(providers); if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/local-hosts") { + const { hosts } = route.request().postDataJSON(); + asked.push(...hosts); + return json({ local: Object.fromEntries(hosts.map((h) => [h, lanHosts[h] === true])) }); + } if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); return json(providers); @@ -57,8 +68,8 @@ function serve(lang, posts) { } const words = { - en: { tick: "Send requests unmasked", save: "Save" }, - zh: { tick: "请求不脱敏", save: "保存" }, + en: { tick: "Send requests unmasked", save: "Save", away: (h) => `${h} isn't on this computer or your local network` }, + zh: { tick: "请求不脱敏", save: "保存", away: (h) => `${h} 不在这台电脑或局域网里` }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -79,15 +90,28 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const errors = []; page.on("pageerror", (e) => errors.push(e.message)); const posts = []; - await page.route("**/*", serve(lang, posts)); + const asked = []; + await page.route("**/*", serve(lang, posts, asked)); await page.goto("http://magpie.test/?view=providers"); await page.locator(".row.provider", { hasText: name }).click(); await unfold(page); await page.locator(".editor .bar").waitFor(); - return { page, errors, posts }; + return { page, errors, posts, asked }; }; const row = (page) => page.locator(".editor label.tick", { hasText: w.tick }); const box = (page) => row(page).locator("input"); + const caution = (page) => page.locator(".editor .hint.unmasked-away"); + // the caution once it has settled: a name is asked about a moment + // after it is typed + const cautionSays = async (page, text) => { + let shown = ""; + for (let i = 0; i < 100; i++) { + shown = (await caution(page).isVisible()) ? await caution(page).textContent() : ""; + if (text ? shown.includes(text) : shown === "") return; + await page.waitForTimeout(20); + } + assert.fail(`the caution says ${JSON.stringify(shown)}, want ${JSON.stringify(text)}`); + }; const save = async (page, posts) => { const n = posts.length; await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); @@ -98,6 +122,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", test(`${engine} ${lang} ${width}: a model on localhost is set to go unmasked, and saved so`, async (t) => { const { page, errors, posts } = await open(t, "Local Box"); assert.equal(await row(page).isVisible(), true); + await cautionSays(page, ""); assert.equal(await box(page).isChecked(), false, "opens masked"); const r = await row(page).boundingBox(); assert.ok(r.width > 60 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`); @@ -110,6 +135,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const missing = await page.evaluate(() => [ "Redaction", "Send requests unmasked", "For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.", + "{host} isn't on this computer or your local network: turned on, requests go to it unmasked.", ].filter((k) => !I18N.zh[k])); assert.deepEqual(missing, [], "every string has its Chinese"); assert.deepEqual(errors, []); @@ -126,19 +152,62 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); - test(`${engine} ${lang} ${width}: a relay has no row, and a local one moved to a vendor's address is saved masked`, async (t) => { - { - const { page, errors } = await open(t, "Relay"); - assert.equal(await row(page).isVisible(), false); - assert.deepEqual(errors, []); - } + test(`${engine} ${lang} ${width}: a relay has the row with a caution naming it, and turned on is saved so`, async (t) => { + const { page, errors, posts, asked } = await open(t, "Relay"); + assert.equal(await row(page).isVisible(), true); + await page.waitForTimeout(400); + assert.deepEqual(asked, [], "nothing is asked while the switch is off"); + await cautionSays(page, ""); + await box(page).scrollIntoViewIfNeeded(); + await box(page).check(); + await cautionSays(page, w.away("relay.example.com")); + await caution(page).scrollIntoViewIfNeeded(); + const c = await caution(page).boundingBox(); + assert.ok(c.x >= 0 && c.x + c.width <= width, `the caution fits: ${JSON.stringify(c)}`); + const saved = await save(page, posts); + assert.equal(saved.body.id, "relay"); + assert.equal(saved.body.unredacted, true, "the user's word, whatever the address"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: a local one moved to a vendor's address keeps the switch, now with a caution`, async (t) => { const { page, errors, posts } = await open(t, "Local Box"); await box(page).scrollIntoViewIfNeeded(); await box(page).check(); await page.locator(".editor input[type=url]").first().fill("https://api.vendor.example/v1"); - assert.equal(await row(page).isVisible(), false, "the row goes with the local address"); + await cautionSays(page, w.away("api.vendor.example")); + assert.equal(await box(page).isChecked(), true); const saved = await save(page, posts); - assert.equal(saved.body.unredacted, false); + assert.equal(saved.body.unredacted, true); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: one at a LAN name magpie finds local has no caution, and is saved unmasked`, async (t) => { + const { page, errors, posts, asked } = await open(t, "Corp LLM"); + await box(page).scrollIntoViewIfNeeded(); + await box(page).check(); + for (let i = 0; i < 100 && !asked.length; i++) await page.waitForTimeout(20); + assert.deepEqual(asked, ["llm.corp.lan"], "the name is asked about once"); + await page.waitForTimeout(100); + await cautionSays(page, ""); + const saved = await save(page, posts); + assert.equal(saved.body.id, "named"); + assert.equal(saved.body.unredacted, true); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: a name typed in loses the caution once magpie finds it local, and one it doesn't gets it`, async (t) => { + const { page, errors, asked } = await open(t, "Relay"); + await box(page).scrollIntoViewIfNeeded(); + await box(page).check(); + await cautionSays(page, w.away("relay.example.com")); + await page.locator(".editor input[type=url]").first().fill("http://llm.corp.lan:8000/v1"); + for (let i = 0; i < 100 && !asked.includes("llm.corp.lan"); i++) await page.waitForTimeout(20); + assert.ok(asked.includes("llm.corp.lan"), "the name typed is asked about"); + await page.waitForTimeout(100); + await cautionSays(page, ""); + await page.locator(".editor input[type=url]").first().fill("https://api.vendor.example/v1"); + await cautionSays(page, w.away("api.vendor.example")); assert.deepEqual(errors, []); }); diff --git a/internal/gui/unredacted_test.go b/internal/gui/unredacted_test.go index 21bca561a..800bb01d5 100644 --- a/internal/gui/unredacted_test.go +++ b/internal/gui/unredacted_test.go @@ -1,12 +1,17 @@ package gui import ( + "context" + "encoding/json" + "maps" + "net" "net/http" "net/http/httptest" "os" "strings" "testing" + "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/provider" ) @@ -42,3 +47,32 @@ func TestProviderSaveKeepsUnredacted(t *testing.T) { t.Fatalf("saved masked again: %+v %v", p, err) } } + +// AcMilan on Discord: the editor can't resolve a name of the user's own +// DNS, so it asks /api/local-hosts whether to caution under "Send +// requests unmasked": a name resolving only to private addresses is local, one +// resolving to a public address or not at all isn't, and an IP or +// localhost is judged by what it is. +func TestLocalHostsAPI(t *testing.T) { + t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) { + switch host { + case "llm.corp.lan": + return []net.IPAddr{{IP: net.ParseIP("192.168.1.20")}}, nil + case "api.vendor.example": + return []net.IPAddr{{IP: net.ParseIP("203.0.113.7")}}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + })) + mux := http.NewServeMux() + localHostsRoutes(mux) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/local-hosts", strings.NewReader(`{"hosts":["LLM.corp.lan","api.vendor.example","gone.lan","localhost","[::1]","8.8.8.8","10.1.2.3"]}`))) + var got struct{ Local map[string]bool } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 200 { + t.Fatalf("%d %s %v", w.Code, w.Body, err) + } + want := map[string]bool{"llm.corp.lan": true, "api.vendor.example": false, "gone.lan": false, "localhost": true, "[::1]": true, "8.8.8.8": false, "10.1.2.3": true} + if !maps.Equal(got.Local, want) { + t.Fatalf("%v, want %v", got.Local, want) + } +} diff --git a/internal/netproxy/localname.go b/internal/netproxy/localname.go new file mode 100644 index 000000000..7dca8d3fa --- /dev/null +++ b/internal/netproxy/localname.go @@ -0,0 +1,86 @@ +package netproxy + +import ( + "context" + "net" + "strings" + "sync" + "time" +) + +// LocalName says whether a name of the user's own DNS +// (http://llm.corp.lan:8000, AcMilan on Discord) resolves only to this +// computer or the local network. The provider editor asks it +// (/api/local-hosts) to tell whether "Send requests unmasked" needs its +// caution; no request is routed or dialled by it. + +// localKeep is how long what LocalName found for a name is kept. +const localKeep = time.Minute + +var localCache = struct { + sync.Mutex + m map[string]lanSeen +}{m: map[string]lanSeen{}} + +// LocalName reports whether host, a name, resolves (in lanWait) to at +// least one address and every address it resolves to is on this computer +// or the local network (LocalIP). A name that doesn't resolve, or doesn't +// in time, is not: what can't be read is unknown, and unknown is masked. +func LocalName(host string) bool { + host = strings.ToLower(strings.TrimSuffix(host, ".")) + if host == "" || net.ParseIP(host) != nil { + return false + } + localCache.Lock() + s, ok := localCache.m[host] + localCache.Unlock() + if ok && time.Since(s.at) < localKeep { + return s.lan + } + ctx, cancel := context.WithTimeout(context.Background(), lanWait) + addrs, err := lanLookup(ctx, host) + cancel() + local := err == nil && allLocal(addrs) + localCache.Lock() + if len(localCache.m) >= 256 { + clear(localCache.m) + } + localCache.m[host] = lanSeen{lan: local, at: time.Now()} + localCache.Unlock() + return local +} + +// LocalIP says ip is on this computer or the local network: a loopback, +// private (10/8, 172.16/12, 192.168/16, fc00::/7) or link-local address. +// Carrier-grade NAT (100.64/10) is not: it is a Tailscale address, but +// also an ISP's. +func LocalIP(ip net.IP) bool { + return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() +} + +func allLocal(addrs []net.IPAddr) bool { + for _, a := range addrs { + if !LocalIP(a.IP) { + return false + } + } + return len(addrs) > 0 +} + +// SetLookup has names resolved by f, for a test that must not reach the +// network, and forgets what earlier lookups found; restore puts the +// system's resolver back. +func SetLookup(f func(ctx context.Context, host string) ([]net.IPAddr, error)) (restore func()) { + old := lanLookup + lanLookup = f + forget := func() { + lanCache.Lock() + clear(lanCache.m) + lanCache.Unlock() + localCache.Lock() + clear(localCache.m) + localCache.Unlock() + } + forget() + return func() { lanLookup = old; forget() } +} diff --git a/internal/netproxy/localname_test.go b/internal/netproxy/localname_test.go new file mode 100644 index 000000000..27eea2c03 --- /dev/null +++ b/internal/netproxy/localname_test.go @@ -0,0 +1,65 @@ +package netproxy + +import ( + "context" + "net" + "sync/atomic" + "testing" +) + +// lookups answers names from m, several addresses each, and counts the +// lookups made. +func lookups(t *testing.T, m map[string][]string) *atomic.Int32 { + t.Helper() + n := new(atomic.Int32) + t.Cleanup(SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) { + n.Add(1) + ips, ok := m[host] + if !ok { + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + } + var out []net.IPAddr + for _, s := range ips { + out = append(out, net.IPAddr{IP: net.ParseIP(s)}) + } + return out, nil + })) + return n +} + +// AcMilan on Discord: a name of the user's own DNS counts as local when +// every address it resolves to is loopback, private or link-local; one +// resolving to a public address, to a public and a private one, or not at +// all, is not. +func TestLocalName(t *testing.T) { + lookups(t, map[string][]string{ + "llm.corp.lan": {"192.168.1.20"}, + "gpu.home.arpa": {"10.0.0.7", "fd00::7"}, + "loop.test": {"127.0.0.1"}, + "linklocal.lan": {"169.254.10.2"}, + "public.example": {"203.0.113.7"}, + "mixed.example": {"10.0.0.2", "203.0.113.7"}, + "cgnat.example": {"100.101.102.103"}, + "nothing.example": {}, + }) + for host, want := range map[string]bool{ + "llm.corp.lan": true, "LLM.corp.lan.": true, "gpu.home.arpa": true, "loop.test": true, "linklocal.lan": true, + "public.example": false, "mixed.example": false, "cgnat.example": false, "nothing.example": false, + "gone.lan": false, "192.168.1.20": false, "": false, + } { + if got := LocalName(host); got != want { + t.Errorf("%q: %v, want %v", host, got, want) + } + } +} + +// A lookup that doesn't answer in lanWait is unknown, so not local. +func TestLocalNameSlowLookupIsNot(t *testing.T) { + t.Cleanup(SetLookup(func(ctx context.Context, host string) ([]net.IPAddr, error) { + <-ctx.Done() + return nil, ctx.Err() + })) + if LocalName("slow.lan") { + t.Fatal("a lookup that timed out counted as local") + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 337acfba1..802a9e1e8 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -327,12 +327,13 @@ type Provider struct { // Azure's own APIs, which take x-api-key alone, ignore it. AuthHeader string `json:"authHeader,omitempty"` - // Unredacted has requests to a provider on this machine or the local - // network (Ollama, LM Studio, a vLLM box) go as the agent wrote them, - // unmasked by Settings' redaction, which keeps secrets from vendors - // (lc on Discord). It is the user's word, not the address's: a relay - // run locally, or Ollama's cloud models, pass a request on to a vendor. - // See SkipsRedaction. + // Unredacted has requests to a provider go as the agent wrote them, + // unmasked by Settings' redaction, which keeps secrets from vendors: + // for a model on this machine or the local network (Ollama, LM Studio, + // a vLLM box; lc on Discord). It is the user's word, not the + // address's (AcMilan on Discord): the editor cautions when an address + // isn't local, and a relay run locally, or Ollama's cloud models, pass + // a request on to a vendor whatever the address. See SkipsRedaction. Unredacted bool `json:"unredacted,omitempty"` // InsecureTLS has magpie take the certificate of the provider's own diff --git a/internal/provider/unredacted.go b/internal/provider/unredacted.go index da974a0d2..d6a12e217 100644 --- a/internal/provider/unredacted.go +++ b/internal/provider/unredacted.go @@ -1,33 +1,41 @@ package provider -import "net/url" +import ( + "net" -// SkipsRedaction says requests to p go unmasked: the user set Unredacted, -// and every address p has is on this machine or the local network. One -// edited to a vendor's afterwards is masked again. A signed-in account, a -// plugin's provider and another magpie are always masked: each reaches a -// vendor. + "github.com/yetone/magpie/internal/netproxy" +) + +// SkipsRedaction says requests to p go unmasked: the user set Unredacted +// ("Send requests unmasked") and p has an address. It is the user's word +// whatever the address (AcMilan on Discord: the user decides for each +// provider); the editor cautions when an address isn't on this machine or +// the local network (LocalHost), and nothing here looks one up. A +// signed-in account, a plugin's provider and another magpie are always +// masked: each reaches a vendor. func (p Provider) SkipsRedaction() bool { if !p.Unredacted || p.Account != nil || p.IsRemoteMagpie() { return false } - return LocalAddresses(p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Decide) + for _, b := range []string{p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Decide} { + if b != "" { + return true + } + } + return false } -// LocalAddresses says every non-empty base URL among bases is on this -// machine or the local network (localhost, *.local, a loopback or private -// IP), and there is at least one. -func LocalAddresses(bases ...string) bool { - n := 0 - for _, b := range bases { - if b == "" { - continue - } - u, err := url.Parse(b) - if err != nil || u.Host == "" || !local(u.Hostname()) { - return false - } - n++ +// LocalHost says host is on this machine or the local network: localhost, +// a .local name, a loopback, private or link-local IP, or a name every +// address of which is one (netproxy.LocalName, looked up now and kept a +// minute; one that doesn't resolve isn't). Only the editor's caution asks +// it (/api/local-hosts), never a request. +func LocalHost(host string) bool { + if local(host) { + return true } - return n > 0 + if ip := net.ParseIP(host); ip != nil { + return netproxy.LocalIP(ip) + } + return netproxy.LocalName(host) } diff --git a/internal/provider/unredacted_test.go b/internal/provider/unredacted_test.go index fbac792c0..4926d6b64 100644 --- a/internal/provider/unredacted_test.go +++ b/internal/provider/unredacted_test.go @@ -1,25 +1,36 @@ package provider -import "testing" +import ( + "context" + "net" + "testing" -// Only a provider the user set to go unmasked whose every address is on -// this machine or the local network skips redaction; one at a vendor's -// address, a signed-in account or another magpie never does. + "github.com/yetone/magpie/internal/netproxy" +) + +// "Send requests unmasked" is the user's switch for each provider +// (AcMilan on Discord): set, a provider goes unmasked at whatever address, +// a name of the user's own DNS or a vendor's; unset, it is masked. A +// signed-in account or another magpie never goes unmasked. Nothing is +// looked up to decide: the lookup fails the test if it is. func TestSkipsRedaction(t *testing.T) { + t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) { + t.Errorf("SkipsRedaction looked up %s", host) + return nil, &net.DNSError{Err: "no lookups here", Name: host} + })) cases := []struct { name string p Provider want bool }{ {"ollama", Provider{Unredacted: true, Chat: "http://localhost:11434/v1", Anthropic: "http://localhost:11434"}, true}, - {"loopback ip", Provider{Unredacted: true, Chat: "http://127.0.0.1:1234/v1"}, true}, - {"ipv6 loopback", Provider{Unredacted: true, Chat: "http://[::1]:8000/v1"}, true}, {"lan", Provider{Unredacted: true, Chat: "http://192.168.1.20:8000/v1"}, true}, - {"mdns", Provider{Unredacted: true, Responses: "http://gpu-box.local:8000/v1"}, true}, + {"a lan name", Provider{Unredacted: true, Chat: "http://llm.corp.lan:8000/v1"}, true}, + {"a lan name, off", Provider{Chat: "http://llm.corp.lan:8000/v1"}, false}, + {"a vendor, set by the user", Provider{Unredacted: true, Chat: "https://api.deepseek.com/v1"}, true}, + {"a public ip, set by the user", Provider{Unredacted: true, Chat: "http://8.8.8.8/v1"}, true}, + {"through its own proxy", Provider{Unredacted: true, Chat: "http://llm.corp.lan:8000/v1", Proxy: "socks5://127.0.0.1:1080"}, true}, {"not set", Provider{Chat: "http://localhost:11434/v1"}, false}, - {"a vendor", Provider{Unredacted: true, Chat: "https://api.deepseek.com/v1"}, false}, - {"one address a vendor's", Provider{Unredacted: true, Chat: "http://localhost:11434/v1", Anthropic: "https://ollama.com"}, false}, - {"a public ip", Provider{Unredacted: true, Chat: "http://8.8.8.8/v1"}, false}, {"no address", Provider{Unredacted: true}, false}, {"an account", Provider{Unredacted: true, Chat: "http://localhost:1/v1", Account: &Account{Agent: "codex"}}, false}, {"another magpie", Provider{Unredacted: true, Preset: RemoteMagpiePreset, Anthropic: "http://192.168.1.5:3425"}, false}, @@ -30,3 +41,42 @@ func TestSkipsRedaction(t *testing.T) { } } } + +// LocalHost, which decides only whether the editor cautions, takes +// localhost, .local, loopback, private and link-local IPs, and a name +// that resolves only to those; a public name or IP, one resolving to a +// public address among private ones, or one that doesn't resolve, isn't. +func TestLocalHost(t *testing.T) { + fakeDNS(t, map[string][]string{ + "llm.corp.lan": {"192.168.1.20"}, + "gpu.home.arpa": {"10.0.0.7", "fd00::7"}, + "public.example": {"203.0.113.7"}, + "mixed.example": {"10.0.0.2", "203.0.113.7"}, + }) + for host, want := range map[string]bool{ + "localhost": true, "gpu-box.local": true, "127.0.0.1": true, "::1": true, "192.168.1.20": true, "169.254.10.2": true, + "llm.corp.lan": true, "gpu.home.arpa": true, + "public.example": false, "mixed.example": false, "gone.lan": false, "8.8.8.8": false, + } { + if got := LocalHost(host); got != want { + t.Errorf("%s: %v, want %v", host, got, want) + } + } +} + +// fakeDNS has names resolve to m's addresses and no other name resolve, +// so no test looks a name up on the network. +func fakeDNS(t *testing.T, m map[string][]string) { + t.Helper() + t.Cleanup(netproxy.SetLookup(func(_ context.Context, host string) ([]net.IPAddr, error) { + ips, ok := m[host] + if !ok { + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + } + var out []net.IPAddr + for _, s := range ips { + out = append(out, net.IPAddr{IP: net.ParseIP(s)}) + } + return out, nil + })) +}