diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 5658e68..81abb01 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -26,12 +26,12 @@ jobs: cache: maven - name: Initialize CodeQL - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4 with: languages: java-kotlin build-mode: autobuild - name: Autobuild - uses: github/codeql-action/autobuild@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + uses: github/codeql-action/autobuild@915412ff23e8b7659517e607487dbeae018f2934 # v4 - name: Analyze - uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 \ No newline at end of file + uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4 \ No newline at end of file diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index b1fe8fc..b4617b9 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -40,7 +40,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Reject new high-severity dependencies - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5 + uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5 with: fail-on-severity: high comment-summary-in-pr: always diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 058db7b..df6d494 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,4 +1,4 @@ wrapperVersion=3.3.4 distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.10.1/apache-maven-3.10.1-bin.zip -distributionSha256Sum=9c1ef9174ef250a5009ed0dec97cbe8699acf7479add4e62bf7b0ea791c0adb5 +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.10.2/apache-maven-3.10.2-bin.zip +distributionSha256Sum=7d69999d218e025cf1c14691ba748a09706e47999bd505009403cef9d757c2df diff --git a/changelog/v0.2.15.md b/changelog/v0.2.15.md new file mode 100644 index 0000000..7dbf635 --- /dev/null +++ b/changelog/v0.2.15.md @@ -0,0 +1,31 @@ +# v0.2.15 + +Provider errors stay behind the gateway, the default system prompt grows to 100k, and +usage reporting filters and pages correctly. + +## Added + +- `/admin/usage` returns `page`, `limit`, `total` and `has_more`; `/admin/audit` + and `/admin/prompt-logs` accept `page`, so long histories are reachable. +- The admin console gains a **Usage** browser (key/end-user/window filters, paging, + CSV export of the filtered set) and an **Audit** log (actor, action, target, + expandable redacted details). + +## Changed + +- The gateway-wide default system prompt accepts up to 100,000 characters (was + 16,000), enough for a full upstream prompt. Migration `V24` widens the column; + the console reads the new limit from `max_chars` and can load a prompt from a file. + +## Fixed + +- `/admin/usage` now applies `keyId`, `endUser` and `window` in the query. A + key-scoped request used to ignore the window, and an end-user filter ran after + the row limit, so older matching rows disappeared. The CSV export had the same + post-limit filter and could omit a key's rows on a busy gateway. +- Upstream failures no longer leak the provider's own error text. An expired or + revoked provider key returns a gateway-owned `provider_auth_error`, and an + unreachable provider returns `upstream_network_error`, instead of echoing + provider credentials, hostnames or the per-route failure list. A 400/422 still + carries the provider's reason because it describes the caller's own body. + `GATEWAY_EXPOSE_UPSTREAM_DETAIL=true` restores the old passthrough. diff --git a/docs/ADMIN-UI.md b/docs/ADMIN-UI.md index 57520b2..b01b4de 100644 --- a/docs/ADMIN-UI.md +++ b/docs/ADMIN-UI.md @@ -7,11 +7,12 @@ The admin console lives in its own repository, [an1ndra/path-admin](https://gith ## What it covers Read and write against this API: dashboard (spend, cache, latency, provider circuits, top -models, recent failures), providers (create/edit with a provider API key, probe, delete), -routes (add a model, enable/disable, delete), client keys (create with budgets and -allowlists, top up, revoke), **configuration** (the gateway switches, the default system -prompt, alert email and the daily digest) and **settings** (the session: identity, scopes, -token, sign out). +models, recent failures), usage (filter by key/end user/window, page through rows, export +CSV), audit (every admin write, filterable by action), providers (create/edit with a +provider API key, probe, delete), routes (add a model, enable/disable, delete), client keys +(create with budgets and allowlists, top up, revoke), **configuration** (the gateway +switches, the default system prompt, alert email and the daily digest) and **settings** +(the session: identity, scopes, token, sign out). ## Auth diff --git a/docs/API.md b/docs/API.md index 9cb5b7a..de7446a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -42,9 +42,10 @@ Every failure uses the OpenAI envelope: | `insufficient_credits` | 402 | balance cannot cover the call | | `rate_limit_exceeded` | 429 | per-key RPM limit (has `Retry-After`) | | `provider_not_configured` | 502 | provider row has no credential | -| `provider_auth_error` | 502 | upstream rejected the gateway's key | +| `provider_auth_error` | 502 | upstream rejected the gateway's key (expired, revoked or wrong) | | `upstream_invalid_request` | 400 | upstream rejected the client's body | | `upstream_timeout` | 504 | connect/read/idle timeout | +| `upstream_network_error` | 502 | the provider could not be reached | | `upstream_error` | 502 | upstream 5xx or unmapped failure | | `all_providers_failed` | 502 | every route in the chain failed | | `circuit_open` | 503 | provider parked by the circuit breaker | @@ -58,6 +59,17 @@ Every failure uses the OpenAI envelope: | `unsupported_endpoint` | 501 | endpoint not available for this provider type | | `route_exists` / `provider_exists` | 409 | duplicate admin create | +Upstream failures are translated into the gateway's own message. The provider's raw +text is **not** returned by default for authentication, network, timeout and 5xx +failures: it can name the provider, echo part of a credential (some providers include +the key prefix in an auth error), or expose internal hostnames. A 400/422 is the +exception, because its text describes the caller's own body (`context length exceeded`, +`unsupported role`) and is useful; it is passed through unchanged. The full cause is +logged with the provider slug and remains visible through +`POST /admin/providers/{id}/probe`. Set `GATEWAY_EXPOSE_UPSTREAM_DETAIL=true` when +debugging an integration and you want the raw text plus the per-route failure list in +the response. + --- ## Public API @@ -97,8 +109,9 @@ curl -s -X PUT http://localhost:8080/admin/system-prompt \ -d '{"enabled":true,"text":"Always answer in British English."}' ``` -`text` accepts up to 16,000 characters. Enabling with blank text returns 400; disabling -keeps the stored text. The console edits this same endpoint. +`text` accepts up to 100,000 characters. Enabling with blank text returns 400; disabling +keeps the stored text. The console edits this same endpoint and reads the live limit from +`max_chars`. **Non-streaming** @@ -378,9 +391,11 @@ ids land at `0.00` and are flagged in `description`. |---|---|---| | GET | `/admin/stats?window=24h` | totals, percentiles, cache, providers/models | | GET | `/admin/stats?window=24h&bucket=1h` | the same, plus a bucketed time series | -| GET | `/admin/usage?window=24h&limit=100&keyId=` | raw usage rows | +| GET | `/admin/usage?window=24h&limit=100&page=0&keyId=&endUser=` | raw usage rows, paged; the response carries `total` and `has_more` | +| GET | `/admin/audit?limit=100&page=0&action=` | admin writes, newest first | +| GET | `/admin/prompt-logs?limit=50&page=0&keyId=` | stored prompts when logging is on | | POST | `/admin/digest/test?date=2026-11-19` | send yesterday's summary now and return its text | -| GET | `/admin/usage/export?from=2026-01-01&to=2026-02-01` | CSV for an explicit date slice (archive before a purge) | +| GET | `/admin/usage/export?from=2026-01-01&to=2026-02-01` | CSV for an explicit date slice (archive before a purge); `keyId`, `endUser` and `projectId` filter the query, not the result | ```json { diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index cdaff9c..d56899b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -38,6 +38,7 @@ except the provider credentials you actually use. | `GATEWAY_IDEMPOTENCY_MAX_BYTES` | `2097152` | larger responses are not stored for replay | | `GATEWAY_IDEMPOTENCY_PENDING` | `2m` | abandoned PENDING claims are reclaimed after this | | `GATEWAY_CACHE_MAX_BYTES` | `2097152` | larger responses are not cached | +| `GATEWAY_EXPOSE_UPSTREAM_DETAIL` | `false` | return the provider's raw error text and per-route details to callers; off keeps the gateway's own wording | Timeouts live in `application.yml` under `gateway.*`: `connect-timeout` (10s), `request-timeout` (180s), `stream-idle-timeout` (120s). A provider row can override the diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 03c80b3..58ed053 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -96,10 +96,11 @@ curl -s localhost:8080/admin/providers/health -H "$A" ```bash curl -s 'localhost:8080/admin/stats?window=24h' -H "$A" -curl -s 'localhost:8080/admin/usage?window=7d&limit=50' -H "$A" +curl -s 'localhost:8080/admin/usage?window=7d&limit=50&page=0' -H "$A" +curl -s 'localhost:8080/admin/usage?window=7d&keyId=3&endUser=alice' -H "$A" curl -s 'localhost:8080/admin/usage/export?window=30d&limit=5000' -H "$A" -o usage.csv -curl -s 'localhost:8080/admin/audit?action=route.update&limit=50' -H "$A" -curl -s 'localhost:8080/admin/prompt-logs?limit=20' -H "$A" +curl -s 'localhost:8080/admin/audit?action=route.update&limit=50&page=0' -H "$A" +curl -s 'localhost:8080/admin/prompt-logs?limit=20&page=0' -H "$A" ``` ## CI runners diff --git a/mvnw.cmd b/mvnw.cmd index 92450f9..5761d94 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,189 +1,189 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.4 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' - -$MAVEN_M2_PATH = "$HOME/.m2" -if ($env:MAVEN_USER_HOME) { - $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" -} - -if (-not (Test-Path -Path $MAVEN_M2_PATH)) { - New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null -} - -$MAVEN_WRAPPER_DISTS = $null -if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { - $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" -} else { - $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" -} - -$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" -$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -$actualDistributionDir = "" - -# First try the expected directory name (for regular distributions) -$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" -$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" -if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { - $actualDistributionDir = $distributionUrlNameMain -} - -# If not found, search for any directory with the Maven executable (for snapshots) -if (!$actualDistributionDir) { - Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { - $testPath = Join-Path $_.FullName "bin/$MVN_CMD" - if (Test-Path -Path $testPath -PathType Leaf) { - $actualDistributionDir = $_.Name - } - } -} - -if (!$actualDistributionDir) { - Write-Error "Could not find Maven distribution directory in extracted archive" -} - -Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/path-gateway/pom.xml b/path-gateway/pom.xml index 79682c5..361936d 100644 --- a/path-gateway/pom.xml +++ b/path-gateway/pom.xml @@ -7,7 +7,7 @@ io.github.an1ndra path-parent - 0.2.14 + 0.2.15 ../pom.xml diff --git a/path-gateway/src/main/java/com/anindra/path/admin/AdminController.java b/path-gateway/src/main/java/com/anindra/path/admin/AdminController.java index 6988c9b..fa34658 100644 --- a/path-gateway/src/main/java/com/anindra/path/admin/AdminController.java +++ b/path-gateway/src/main/java/com/anindra/path/admin/AdminController.java @@ -359,8 +359,9 @@ public Map usage(@RequestParam(required = false) Long keyId, @RequestParam(required = false) Long projectId, @RequestParam(required = false) String endUser, @RequestParam(defaultValue = "24h") String window, - @RequestParam(defaultValue = "100") int limit) { - return reporting.usage(keyId, projectId, endUser, window, limit); + @RequestParam(defaultValue = "100") int limit, + @RequestParam(defaultValue = "0") int page) { + return reporting.usage(keyId, projectId, endUser, window, limit, page); } @PostMapping("/providers/{id}/probe") @@ -418,14 +419,16 @@ private static java.time.Instant instant(String value, String param) { @GetMapping("/audit") public List> auditLog(@RequestParam(required = false) String action, - @RequestParam(defaultValue = "100") int limit) { - return audit.list(action, limit); + @RequestParam(defaultValue = "100") int limit, + @RequestParam(defaultValue = "0") int page) { + return audit.list(action, limit, page); } @GetMapping("/prompt-logs") public List> promptLogs(@RequestParam(required = false) Long keyId, - @RequestParam(defaultValue = "50") int limit) { - return promptLogs.list(keyId, limit); + @RequestParam(defaultValue = "50") int limit, + @RequestParam(defaultValue = "0") int page) { + return promptLogs.list(keyId, limit, page); } @PostMapping("/models/sync") diff --git a/path-gateway/src/main/java/com/anindra/path/admin/AdminReportingService.java b/path-gateway/src/main/java/com/anindra/path/admin/AdminReportingService.java index a94da93..ddad48d 100644 --- a/path-gateway/src/main/java/com/anindra/path/admin/AdminReportingService.java +++ b/path-gateway/src/main/java/com/anindra/path/admin/AdminReportingService.java @@ -26,27 +26,47 @@ public class AdminReportingService { private final com.anindra.path.repo.ClientKeyRepository keys; public Map usage(Long keyId, Long projectId, String endUser, String window, - int limit) { + int limit, int page) { Duration parsed = Durations.cap(Durations.parse(window, Duration.ofHours(24)), Duration.ofDays(365)); int capped = Math.max(1, Math.min(limit, 500)); + int safePage = Math.max(0, page); + PageRequest pageable = PageRequest.of(safePage, capped); java.time.Instant from = java.time.Instant.now().minus(parsed); + boolean hasEndUser = endUser != null && !endUser.isBlank(); List records; - if (endUser != null && !endUser.isBlank()) { - records = keyId != null - ? usage.findByClientKeyIdAndEndUserOrderByCreatedAtDesc( - keyId, endUser, PageRequest.of(0, capped)) - : usage.findAll(PageRequest.of(0, capped)).stream() - .filter(r -> endUser.equals(r.getEndUser())).toList(); - } else if (keyId != null) { - records = usage.findByClientKeyIdOrderByCreatedAtDesc(keyId, PageRequest.of(0, capped)); + long total; + if (keyId != null) { + if (hasEndUser) { + records = usage.findByClientKeyIdAndEndUserAndCreatedAtAfterOrderByCreatedAtDesc( + keyId, endUser, from, pageable); + total = usage.countByClientKeyIdAndEndUserAndCreatedAtAfter(keyId, endUser, from); + } else { + records = usage.findByClientKeyIdAndCreatedAtAfterOrderByCreatedAtDesc( + keyId, from, pageable); + total = usage.countByClientKeyIdAndCreatedAtAfter(keyId, from); + } } else if (projectId != null) { List keyIds = projectKeyIds(projectId); - records = keyIds.isEmpty() ? List.of() - : usage.findByClientKeyIdInAndCreatedAtAfterOrderByCreatedAtDesc( - keyIds, from, PageRequest.of(0, capped)); + if (keyIds.isEmpty()) { + records = List.of(); + total = 0; + } else if (hasEndUser) { + records = usage.findByClientKeyIdInAndEndUserAndCreatedAtAfterOrderByCreatedAtDesc( + keyIds, endUser, from, pageable); + total = usage.countByClientKeyIdInAndEndUserAndCreatedAtAfter(keyIds, endUser, from); + } else { + records = usage.findByClientKeyIdInAndCreatedAtAfterOrderByCreatedAtDesc( + keyIds, from, pageable); + total = usage.countByClientKeyIdInAndCreatedAtAfter(keyIds, from); + } + } else if (hasEndUser) { + records = usage.findByEndUserAndCreatedAtAfterOrderByCreatedAtDesc( + endUser, from, pageable); + total = usage.countByEndUserAndCreatedAtAfter(endUser, from); } else { - records = usage.findByCreatedAtAfterOrderByCreatedAtDesc(from, PageRequest.of(0, capped)); + records = usage.findByCreatedAtAfterOrderByCreatedAtDesc(from, pageable); + total = usage.countByCreatedAtAfter(from); } List> rows = new ArrayList<>(); @@ -56,7 +76,7 @@ public Map usage(Long keyId, Long projectId, String endUser, Str row.put("at", r.getCreatedAt().toString()); row.put("key_id", r.getClientKeyId()); row.put("key_name", r.getClientKeyName()); - row.put("end_user", r.getEndUser()); + row.put("end_user", r.getEndUser()); row.put("model", r.getPublicModelId()); row.put("provider", r.getProviderSlug()); row.put("upstream_model", r.getUpstreamModelId()); @@ -97,7 +117,11 @@ public Map usage(Long keyId, Long projectId, String endUser, Str out.put("window", parsed.toString()); out.put("project_id", projectId); out.put("end_user", endUser); + out.put("page", safePage); + out.put("limit", capped); out.put("count", rows.size()); + out.put("total", total); + out.put("has_more", ((long) safePage + 1) * capped < total); out.put("data", rows); return out; } @@ -106,17 +130,31 @@ public Map usage(Long keyId, Long projectId, String endUser, Str public String usageCsv(Long keyId, Long projectId, String endUser, java.time.Instant from, java.time.Instant to, int limit) { int capped = Math.max(1, Math.min(limit, 50_000)); + PageRequest pageable = PageRequest.of(0, capped); + boolean hasEndUser = endUser != null && !endUser.isBlank(); List rows; - if (projectId != null) { + if (keyId != null) { + rows = hasEndUser + ? usage.findByClientKeyIdAndEndUserAndCreatedAtBetweenOrderByCreatedAtAsc( + keyId, endUser, from, to, pageable) + : usage.findByClientKeyIdAndCreatedAtBetweenOrderByCreatedAtAsc( + keyId, from, to, pageable); + } else if (projectId != null) { List keyIds = projectKeyIds(projectId); - rows = keyIds.isEmpty() ? List.of() - : usage.findByClientKeyIdInAndCreatedAtBetweenOrderByCreatedAtAsc( - keyIds, from, to, PageRequest.of(0, capped)); - } else if (endUser != null && !endUser.isBlank()) { - rows = usage.findByCreatedAtBetweenOrderByCreatedAtAsc(from, to, PageRequest.of(0, capped)) - .stream().filter(r -> endUser.equals(r.getEndUser())).toList(); + if (keyIds.isEmpty()) { + rows = List.of(); + } else if (hasEndUser) { + rows = usage.findByClientKeyIdInAndEndUserAndCreatedAtBetweenOrderByCreatedAtAsc( + keyIds, endUser, from, to, pageable); + } else { + rows = usage.findByClientKeyIdInAndCreatedAtBetweenOrderByCreatedAtAsc( + keyIds, from, to, pageable); + } + } else if (hasEndUser) { + rows = usage.findByEndUserAndCreatedAtBetweenOrderByCreatedAtAsc( + endUser, from, to, pageable); } else { - rows = usage.findByCreatedAtBetweenOrderByCreatedAtAsc(from, to, PageRequest.of(0, capped)); + rows = usage.findByCreatedAtBetweenOrderByCreatedAtAsc(from, to, pageable); } StringBuilder csv = new StringBuilder(); @@ -126,9 +164,6 @@ public String usageCsv(Long keyId, Long projectId, String endUser, java.time.Ins .append("cost_usd,latency_ms,ttft_ms,streamed,status,error_code,end_user\n"); for (UsageRecord r : rows) { - if (keyId != null && !keyId.equals(r.getClientKeyId())) { - continue; - } csv.append(r.getCreatedAt()).append(',') .append(r.getClientKeyId() == null ? "" : r.getClientKeyId()).append(',') .append(escape(r.getClientKeyName())).append(',') diff --git a/path-gateway/src/main/java/com/anindra/path/admin/AuditService.java b/path-gateway/src/main/java/com/anindra/path/admin/AuditService.java index 8b1dc9f..ecdabcc 100644 --- a/path-gateway/src/main/java/com/anindra/path/admin/AuditService.java +++ b/path-gateway/src/main/java/com/anindra/path/admin/AuditService.java @@ -99,10 +99,15 @@ private static String currentActor() { } public List> list(String action, int limit) { + return list(action, limit, 0); + } + + public List> list(String action, int limit, int page) { int capped = Math.max(1, Math.min(limit, 500)); + int safePage = Math.max(0, page); List rows = action == null || action.isBlank() - ? audit.findAllByOrderByCreatedAtDesc(PageRequest.of(0, capped)) - : audit.findByActionOrderByCreatedAtDesc(action, PageRequest.of(0, capped)); + ? audit.findAllByOrderByCreatedAtDesc(PageRequest.of(safePage, capped)) + : audit.findByActionOrderByCreatedAtDesc(action, PageRequest.of(safePage, capped)); List> out = new ArrayList<>(); for (AdminAudit row : rows) { diff --git a/path-gateway/src/main/java/com/anindra/path/admin/PromptLogService.java b/path-gateway/src/main/java/com/anindra/path/admin/PromptLogService.java index 4aff85f..6ff4da7 100644 --- a/path-gateway/src/main/java/com/anindra/path/admin/PromptLogService.java +++ b/path-gateway/src/main/java/com/anindra/path/admin/PromptLogService.java @@ -57,10 +57,15 @@ public void record(Long clientKeyId, String requestId, String model, String requ } public List> list(Long clientKeyId, int limit) { + return list(clientKeyId, limit, 0); + } + + public List> list(Long clientKeyId, int limit, int page) { int capped = Math.max(1, Math.min(limit, 200)); + int safePage = Math.max(0, page); List rows = clientKeyId == null - ? logs.findAllByOrderByCreatedAtDesc(PageRequest.of(0, capped)) - : logs.findByClientKeyIdOrderByCreatedAtDesc(clientKeyId, PageRequest.of(0, capped)); + ? logs.findAllByOrderByCreatedAtDesc(PageRequest.of(safePage, capped)) + : logs.findByClientKeyIdOrderByCreatedAtDesc(clientKeyId, PageRequest.of(safePage, capped)); List> out = new ArrayList<>(); for (PromptLog row : rows) { diff --git a/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java b/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java index 161a62a..e24da72 100644 --- a/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java +++ b/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java @@ -34,7 +34,8 @@ @RequiredArgsConstructor public class SystemPromptService { - public static final int MAX_CHARS = 16000; + /** Large enough for a full upstream prompt; the Claude Code core prompt is ~18k. */ + public static final int MAX_CHARS = 100_000; private static final Duration CACHE_TTL = Duration.ofSeconds(5); private final SystemPromptSettingsRepository repository; diff --git a/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java b/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java index 4f9d60a..dd95a15 100644 --- a/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java +++ b/path-gateway/src/main/java/com/anindra/path/config/GatewayProperties.java @@ -84,6 +84,19 @@ public class GatewayProperties { private SharedState sharedState = new SharedState(); private Alert alert = new Alert(); private Digest digest = new Digest(); + private Errors errors = new Errors(); + + /** + * What an upstream failure looks like to the caller. Provider text can name the + * provider, echo part of a credential, or leak internal hostnames, so it is + * off by default; the full cause is always logged. + */ + @Getter + @Setter + public static class Errors { + /** Put the provider's raw error text and per-route details in the response. */ + private boolean exposeUpstreamDetail = false; + } /** Daily spend digest. Off when no email channel is configured, whatever this says. */ @Getter diff --git a/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptSettings.java b/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptSettings.java index 7be108b..9a991c4 100644 --- a/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptSettings.java +++ b/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptSettings.java @@ -25,7 +25,7 @@ public class SystemPromptSettings { private boolean enabled; - @Column(length = 16000) + @Column(length = 100000) private String text = ""; private Instant updatedAt; diff --git a/path-gateway/src/main/java/com/anindra/path/gateway/ChatService.java b/path-gateway/src/main/java/com/anindra/path/gateway/ChatService.java index ee63847..080f5ce 100644 --- a/path-gateway/src/main/java/com/anindra/path/gateway/ChatService.java +++ b/path-gateway/src/main/java/com/anindra/path/gateway/ChatService.java @@ -121,7 +121,9 @@ public Result complete(ChatRequestSpec spec, ClientKey key) { if (available > 0 && !breaker.isAvailable(providerId)) { lastError = new ApiException(503, "upstream_error", "circuit_open", - "Provider '" + rr.providerSlug() + "' is temporarily unavailable."); + exposeDetail() + ? "Provider '" + rr.providerSlug() + "' is temporarily unavailable." + : "The provider for this model is temporarily unavailable. Retry shortly."); failures.add(rr.providerSlug() + ": circuit open"); fallbackFrom = fallbackFrom == null ? rr.providerSlug() : fallbackFrom; continue; @@ -131,7 +133,9 @@ public Result complete(ChatRequestSpec spec, ClientKey key) { if (apiKey == null) { lastError = ApiException.upstream(502, - "Provider '" + rr.providerSlug() + "' has no API key configured.", + exposeDetail() + ? "Provider '" + rr.providerSlug() + "' has no API key configured." + : "The gateway is not configured for this model. Contact the gateway operator.", "provider_not_configured"); failures.add(rr.providerSlug() + ": not configured"); fallbackFrom = fallbackFrom == null ? rr.providerSlug() : fallbackFrom; @@ -156,11 +160,11 @@ public Result complete(ChatRequestSpec spec, ClientKey key) { } if (failure.retryable() && i < chain.size() - 1) { failures.add(rr.providerSlug() + ": " + failure.getMessage()); - lastError = toApiException(failure); + lastError = toApiException(failure, exposeDetail()); fallbackFrom = fallbackFrom == null ? rr.providerSlug() : fallbackFrom; continue; } - lastError = toApiException(failure); + lastError = toApiException(failure, exposeDetail()); long latency = elapsedMs(started); usage.recordError(key, spec, rr.providerSlug(), rr.route().getUpstreamModelId(), latency, false, attempts, lastError.status(), lastError.code(), lastError.getMessage()); @@ -199,12 +203,32 @@ public Result complete(ChatRequestSpec spec, ClientKey key) { return new Result(normalized, rr.providerSlug(), rr.route().getUpstreamModelId(), cost, latency, cacheKey == null ? "off" : "miss"); + } catch (UpstreamException e) { + // Raised by an adapter itself (for example a failed Vertex token exchange), + // not by the response check above. + if (e.retryable()) { + recordBreakerFailure(providerId, e); + } + metrics.recordFailure(rr.providerSlug(), spec.publicModel()); + log.warn("Upstream {} failed before a response: {} ({})", + rr.providerSlug(), e.getMessage(), e.providerCode()); + lastError = toApiException(e, exposeDetail()); + failures.add(rr.providerSlug() + ": " + e.getMessage()); + fallbackFrom = fallbackFrom == null ? rr.providerSlug() : fallbackFrom; + if (e.retryable() && i < chain.size() - 1) { + continue; + } + usage.recordError(key, spec, rr.providerSlug(), rr.route().getUpstreamModelId(), + elapsedMs(started), false, attempts, lastError.status(), lastError.code(), + lastError.getMessage()); + throw lastError; + } catch (IOException e) { breaker.onFailure(providerId); metrics.recordFailure(rr.providerSlug(), spec.publicModel()); String reason = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); - lastError = ApiException.upstream(502, - "Could not reach " + rr.providerSlug() + ": " + reason, "upstream_network_error"); + log.warn("Could not reach upstream {}: {}", rr.providerSlug(), reason); + lastError = networkError(rr.providerSlug(), reason, exposeDetail()); failures.add(rr.providerSlug() + ": " + reason); fallbackFrom = fallbackFrom == null ? rr.providerSlug() : fallbackFrom; if (i == chain.size() - 1) { @@ -216,9 +240,16 @@ public Result complete(ChatRequestSpec spec, ClientKey key) { } } + if (!failures.isEmpty()) { + log.warn("All routes failed for model {}: {}", spec.publicModel(), String.join("; ", failures)); + } if (lastError == null) { - lastError = ApiException.upstream(502, "All upstream routes failed.", "all_providers_failed"); - } else if (!failures.isEmpty()) { + lastError = ApiException.upstream(502, + exposeDetail() + ? "All upstream routes failed." + : "No provider could serve this request right now. Retry shortly.", + "all_providers_failed"); + } else if (exposeDetail() && !failures.isEmpty()) { lastError = new ApiException(lastError.status(), lastError.type(), lastError.code(), lastError.getMessage() + " (routes tried: " + String.join("; ", failures) + ")"); } @@ -256,12 +287,19 @@ private void recordBreakerFailure(Long providerId, UpstreamException failure) { private ProviderAdapter adapterFor(Provider provider) { ProviderAdapter adapter = adapters.get(provider.getType()); if (adapter == null) { - throw ApiException.upstream(500, "No adapter for provider type " + provider.getType(), + throw ApiException.upstream(500, + exposeDetail() + ? "No adapter for provider type " + provider.getType() + : "This model is not supported by the gateway.", "adapter_missing"); } return adapter; } + private boolean exposeDetail() { + return props.getErrors().isExposeUpstreamDetail(); + } + static String firstNonBlank(String... values) { for (String value : values) { if (value != null && !value.isBlank()) { @@ -271,7 +309,54 @@ static String firstNonBlank(String... values) { return null; } + /** A connect/read failure that never produced an HTTP status from the provider. */ + static ApiException networkError(String providerSlug, String reason, boolean exposeDetail) { + return ApiException.upstream(502, + exposeDetail + ? "Could not reach " + providerSlug + ": " + reason + : "The selected provider is currently unreachable. Retry shortly.", + "upstream_network_error"); + } + + /** Client-facing mapping: the gateway's own wording, never the provider's. */ public static ApiException toApiException(UpstreamException e) { + return toApiException(e, false); + } + + public static ApiException toApiException(UpstreamException e, boolean exposeDetail) { + if (exposeDetail) { + return toDetailedApiException(e); + } + int status = e.status(); + if (status == 400 || status == 422) { + // This one is about the caller's own body ("context length exceeded", + // "unsupported role"), so the detail is useful and safe to keep. + return new ApiException(400, "invalid_request_error", "upstream_invalid_request", e.getMessage()); + } + if (status == 401 || status == 403) { + return new ApiException(502, "upstream_error", "provider_auth_error", + "The gateway could not authenticate with the selected provider. " + + "This is a gateway configuration problem, not a problem with your request."); + } + if (status == 404) { + return ApiException.notFound( + "The requested model is not available on the selected provider.", "model_not_found"); + } + if (status == 429) { + int retryAfter = e.retryAfterSeconds() > 0 ? e.retryAfterSeconds() : 5; + return ApiException.rateLimited( + "The provider is rate limiting requests. Retry shortly.", retryAfter); + } + if (status == 408) { + return new ApiException(504, "upstream_error", "upstream_timeout", + "The provider did not respond in time. Retry shortly."); + } + return new ApiException(502, "upstream_error", "upstream_error", + "The provider returned an error. Retry shortly."); + } + + /** Opt-in passthrough for operators debugging an integration. */ + private static ApiException toDetailedApiException(UpstreamException e) { int status = e.status(); if (status == 400 || status == 422) { return new ApiException(400, "invalid_request_error", "upstream_invalid_request", e.getMessage()); diff --git a/path-gateway/src/main/java/com/anindra/path/gateway/EmbeddingsService.java b/path-gateway/src/main/java/com/anindra/path/gateway/EmbeddingsService.java index c5ea245..ae10e63 100644 --- a/path-gateway/src/main/java/com/anindra/path/gateway/EmbeddingsService.java +++ b/path-gateway/src/main/java/com/anindra/path/gateway/EmbeddingsService.java @@ -1,6 +1,7 @@ package com.anindra.path.gateway; import com.anindra.path.api.ApiException; +import com.anindra.path.config.GatewayProperties; import com.anindra.path.domain.ClientKey; import com.anindra.path.domain.Provider; import com.anindra.path.domain.ProviderType; @@ -34,6 +35,7 @@ public record Result(JsonNode body, String providerSlug, String upstreamModel, B private final ApiKeyService apiKeys; private final CreditGuard creditGuard; private final ObjectMapper mapper; + private final GatewayProperties props; public Result embed(ObjectNode request, ClientKey key) { JsonNode input = request.get("input"); @@ -59,7 +61,9 @@ public Result embed(ObjectNode request, ClientKey key) { String apiKey = credentials.apiKey(provider); if (apiKey == null) { throw ApiException.upstream(502, - "Provider '" + provider.getSlug() + "' has no API key configured.", + exposeDetail() + ? "Provider '" + provider.getSlug() + "' has no API key configured." + : "The gateway is not configured for this model. Contact the gateway operator.", "provider_not_configured"); } @@ -83,7 +87,7 @@ private Result doEmbed(ObjectNode request, ClientKey key, ChatRequestSpec spec, headers, body.toString()); if (!response.ok()) { throw ChatService.toApiException(UpstreamClient.mapError( - response.status(), response.body(), response.headers())); + response.status(), response.body(), response.headers()), exposeDetail()); } JsonNode parsed = mapper.readTree(response.body()); if (parsed instanceof ObjectNode object) { @@ -94,14 +98,17 @@ private Result doEmbed(ObjectNode request, ClientKey key, ChatRequestSpec spec, UsageService.CallMeta.nonStream(ChatService.elapsedMs(started), null, "stop", 1, null)); return new Result(parsed, provider.getSlug(), resolved.route().getUpstreamModelId(), cost); } catch (IOException e) { - throw ApiException.upstream(502, "Could not reach " + provider.getSlug() + ": " + e.getMessage(), - "upstream_network_error"); + throw ChatService.networkError(provider.getSlug(), e.getMessage(), exposeDetail()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw ApiException.upstream(502, "Request interrupted", "upstream_interrupted"); } } + private boolean exposeDetail() { + return props.getErrors().isExposeUpstreamDetail(); + } + /** RouteResolver speaks ChatRequestSpec; embeddings only need the model and fallbacks. */ private ChatRequestSpec routingSpec(String model) { ObjectNode synthetic = mapper.createObjectNode(); diff --git a/path-gateway/src/main/java/com/anindra/path/gateway/StreamService.java b/path-gateway/src/main/java/com/anindra/path/gateway/StreamService.java index bcd4fb5..9cf338c 100644 --- a/path-gateway/src/main/java/com/anindra/path/gateway/StreamService.java +++ b/path-gateway/src/main/java/com/anindra/path/gateway/StreamService.java @@ -129,7 +129,9 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client if (available > 0 && !breaker.isAvailable(providerId)) { lastError = new ApiException(503, "upstream_error", "circuit_open", - "Provider '" + provider.getSlug() + "' is temporarily unavailable."); + exposeDetail() + ? "Provider '" + provider.getSlug() + "' is temporarily unavailable." + : "The provider for this model is temporarily unavailable. Retry shortly."); failures.add(provider.getSlug() + ": circuit open"); fallbackFrom = fallbackFrom == null ? provider.getSlug() : fallbackFrom; continue; @@ -138,13 +140,19 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client attempts++; if (adapter == null) { - lastError = ApiException.upstream(500, "No adapter for " + provider.getType(), "adapter_missing"); + lastError = ApiException.upstream(500, + exposeDetail() + ? "No adapter for " + provider.getType() + : "This model is not supported by the gateway.", + "adapter_missing"); continue; } String apiKey = credentials.apiKey(provider); if (apiKey == null) { lastError = ApiException.upstream(502, - "Provider '" + provider.getSlug() + "' has no API key configured.", + exposeDetail() + ? "Provider '" + provider.getSlug() + "' has no API key configured." + : "The gateway is not configured for this model. Contact the gateway operator.", "provider_not_configured"); failures.add(provider.getSlug() + ": not configured"); fallbackFrom = fallbackFrom == null ? provider.getSlug() : fallbackFrom; @@ -226,6 +234,8 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client return true; } catch (UpstreamException e) { + log.warn("Stream route {} -> {} ({}): {}", provider.getSlug(), e.status(), + e.providerCode(), e.getMessage()); metrics.recordFailure(provider.getSlug(), spec.publicModel()); if (e.retryable()) { if (e.status() == 429 && e.retryAfterSeconds() > 0) { @@ -234,7 +244,7 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client breaker.onFailure(providerId); } } - lastError = ChatService.toApiException(e); + lastError = ChatService.toApiException(e, exposeDetail()); if (!committed && e.retryable() && i < chain.size() - 1) { log.warn("Stream route {} failed before first chunk ({}), trying next", provider.getSlug(), e.getMessage()); @@ -265,10 +275,9 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client } catch (IOException e) { breaker.onFailure(providerId); + log.warn("Stream to upstream {} broke: {}", provider.getSlug(), e.getMessage()); if (!committed) { - lastError = ApiException.upstream(502, - "Could not reach " + provider.getSlug() + ": " + e.getMessage(), - "upstream_network_error"); + lastError = ChatService.networkError(provider.getSlug(), e.getMessage(), exposeDetail()); if (i < chain.size() - 1) { failures.add(provider.getSlug() + ": " + e.getMessage()); fallbackFrom = fallbackFrom == null ? provider.getSlug() : fallbackFrom; @@ -276,7 +285,9 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client } } lastError = ApiException.upstream(502, - "Stream to " + provider.getSlug() + " broke: " + e.getMessage(), + exposeDetail() + ? "Stream to " + provider.getSlug() + " broke: " + e.getMessage() + : "The connection to the provider was interrupted. Retry shortly.", "upstream_stream_error"); usage.recordError(key, spec, provider.getSlug(), rr.route().getUpstreamModelId(), ChatService.elapsedMs(started), true, attempts, lastError.status(), lastError.code(), lastError.getMessage()); @@ -298,9 +309,16 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client } } + if (!failures.isEmpty()) { + log.warn("All stream routes failed for model {}: {}", spec.publicModel(), String.join("; ", failures)); + } if (lastError == null) { - lastError = ApiException.upstream(502, "All upstream routes failed.", "all_providers_failed"); - } else if (!failures.isEmpty()) { + lastError = ApiException.upstream(502, + exposeDetail() + ? "All upstream routes failed." + : "No provider could serve this request right now. Retry shortly.", + "all_providers_failed"); + } else if (exposeDetail() && !failures.isEmpty()) { lastError = new ApiException(lastError.status(), lastError.type(), lastError.code(), lastError.getMessage() + " (routes tried: " + String.join("; ", failures) + ")"); } @@ -310,6 +328,10 @@ public boolean stream(HttpServletResponse response, ChatRequestSpec spec, Client return false; } + private boolean exposeDetail() { + return props.getErrors().isExposeUpstreamDetail(); + } + /** Writes through while capturing the SSE payload for the response cache. */ private static final class Tee extends OutputStream { diff --git a/path-gateway/src/main/java/com/anindra/path/repo/UsageRecordRepository.java b/path-gateway/src/main/java/com/anindra/path/repo/UsageRecordRepository.java index 3c5b9c6..a0813bd 100644 --- a/path-gateway/src/main/java/com/anindra/path/repo/UsageRecordRepository.java +++ b/path-gateway/src/main/java/com/anindra/path/repo/UsageRecordRepository.java @@ -15,6 +15,35 @@ public interface UsageRecordRepository extends JpaRepository List findByCreatedAtAfterOrderByCreatedAtDesc(Instant from, Pageable pageable); + // Windowed variants. The bare findByClientKeyId... above ignores `window`, which made + // ?keyId=1&window=1h return all-time rows. + List findByClientKeyIdAndCreatedAtAfterOrderByCreatedAtDesc( + Long clientKeyId, Instant from, Pageable pageable); + + List findByEndUserAndCreatedAtAfterOrderByCreatedAtDesc( + String endUser, Instant from, Pageable pageable); + + List findByClientKeyIdAndEndUserAndCreatedAtAfterOrderByCreatedAtDesc( + Long clientKeyId, String endUser, Instant from, Pageable pageable); + + List findByClientKeyIdInAndEndUserAndCreatedAtAfterOrderByCreatedAtDesc( + java.util.Collection keyIds, String endUser, Instant from, Pageable pageable); + + // Exact slices for the CSV export, with the key and end-user filters in the query + // rather than applied after the row limit. + List findByClientKeyIdAndCreatedAtBetweenOrderByCreatedAtAsc( + Long clientKeyId, Instant from, Instant to, Pageable pageable); + + List findByEndUserAndCreatedAtBetweenOrderByCreatedAtAsc( + String endUser, Instant from, Instant to, Pageable pageable); + + List findByClientKeyIdAndEndUserAndCreatedAtBetweenOrderByCreatedAtAsc( + Long clientKeyId, String endUser, Instant from, Instant to, Pageable pageable); + + List findByClientKeyIdInAndEndUserAndCreatedAtBetweenOrderByCreatedAtAsc( + java.util.Collection keyIds, String endUser, Instant from, Instant to, + Pageable pageable); + List findByCreatedAtBetweenOrderByCreatedAtAsc(Instant from, Instant to, Pageable pageable); List findByClientKeyIdInAndCreatedAtAfterOrderByCreatedAtDesc( @@ -75,6 +104,16 @@ long countByClientKeyIdInAndCreatedAtAfterAndCacheTier( long countByClientKeyIdAndCreatedAtAfter(Long clientKeyId, Instant from); + long countByClientKeyIdInAndCreatedAtAfter( + java.util.Collection keyIds, Instant from); + + long countByEndUserAndCreatedAtAfter(String endUser, Instant from); + + long countByClientKeyIdAndEndUserAndCreatedAtAfter(Long clientKeyId, String endUser, Instant from); + + long countByClientKeyIdInAndEndUserAndCreatedAtAfter( + java.util.Collection keyIds, String endUser, Instant from); + @Query("select coalesce(sum(u.costUsd), 0) from UsageRecord u " + "where u.clientKeyId in (select k.id from ClientKey k where k.projectId = :projectId) " + "and u.createdAt >= :from") diff --git a/path-gateway/src/main/resources/application.yml b/path-gateway/src/main/resources/application.yml index 452baf6..f56fc03 100644 --- a/path-gateway/src/main/resources/application.yml +++ b/path-gateway/src/main/resources/application.yml @@ -120,6 +120,11 @@ gateway: enabled: ${GATEWAY_DIGEST:true} cron: "${GATEWAY_DIGEST_CRON:0 0 8 * * *}" usage-retention: ${GATEWAY_USAGE_RETENTION:180d} + # Provider error text can name the provider, echo part of a credential, or expose + # internal hostnames. Off means callers get the gateway's own message; the full + # cause is still logged and visible in the admin probe. + errors: + expose-upstream-detail: ${GATEWAY_EXPOSE_UPSTREAM_DETAIL:false} idempotency: ttl: ${GATEWAY_IDEMPOTENCY_TTL:24h} pending-timeout: ${GATEWAY_IDEMPOTENCY_PENDING:2m} diff --git a/path-gateway/src/main/resources/db/migration/V24__system_prompt_max_chars.sql b/path-gateway/src/main/resources/db/migration/V24__system_prompt_max_chars.sql new file mode 100644 index 0000000..f0da0dc --- /dev/null +++ b/path-gateway/src/main/resources/db/migration/V24__system_prompt_max_chars.sql @@ -0,0 +1,5 @@ +-- A full upstream prompt does not fit in 16k. The Claude Code core prompt is +-- ~18k characters; 100k leaves room for a longer system prompt without turning +-- the row into an unbounded document store. +alter table system_prompt_settings + alter column text set data type varchar(100000); diff --git a/path-gateway/src/test/java/com/anindra/path/admin/AdminUsageFilterTest.java b/path-gateway/src/test/java/com/anindra/path/admin/AdminUsageFilterTest.java new file mode 100644 index 0000000..5bb7ce6 --- /dev/null +++ b/path-gateway/src/test/java/com/anindra/path/admin/AdminUsageFilterTest.java @@ -0,0 +1,157 @@ +package com.anindra.path.admin; + +import com.anindra.path.domain.UsageRecord; +import com.anindra.path.gateway.ApiKeyService; +import com.anindra.path.repo.ClientKeyRepository; +import com.anindra.path.repo.UsageRecordRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.servlet.MockMvc; + +import java.math.BigDecimal; +import java.time.Duration; +import java.time.Instant; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * The usage browser must filter in the database. Applying a key or end-user filter after + * the row limit silently drops matching rows that are older than someone else's newest. + */ +@SpringBootTest(properties = { + "spring.datasource.url=jdbc:h2:mem:adminusage;MODE=PostgreSQL;DB_CLOSE_DELAY=-1", + "spring.jpa.hibernate.ddl-auto=validate", + "gateway.admin-token=test-admin", + "gateway.bootstrap-demo-key=false", + "gateway.master-key-path=./target/test-master.key" +}) +@AutoConfigureMockMvc +class AdminUsageFilterTest { + + private static final String ADMIN = "test-admin"; + + @Autowired + private MockMvc mvc; + + @Autowired + private UsageRecordRepository usage; + + @Autowired + private ClientKeyRepository keys; + + @Autowired + private ApiKeyService apiKeys; + + private Long keyOne; + private Long keyTwo; + + @BeforeEach + void seed() { + usage.deleteAll(); + keys.deleteAll(); + keyOne = apiKeys.create("one", BigDecimal.TEN, 100).key().getId(); + keyTwo = apiKeys.create("two", BigDecimal.TEN, 100).key().getId(); + + Instant now = Instant.now(); + usage.save(record(keyOne, "one", "alice", "key1-old", + now.minus(Duration.ofDays(2)))); + usage.save(record(keyOne, "one", "alice", "key1-recent", + now.minus(Duration.ofMinutes(30)))); + // Newer than Alice's rows, and not hers: a global LIMIT + Java filter would + // return these two and then discard them, reporting zero Alice rows. + usage.save(record(keyTwo, "two", "bob", "key2-bob", + now.minus(Duration.ofMinutes(10)))); + usage.save(record(keyTwo, "two", "carol", "key2-carol", + now.minus(Duration.ofMinutes(20)))); + } + + private static UsageRecord record(Long keyId, String keyName, String endUser, + String model, Instant at) { + UsageRecord record = new UsageRecord(); + record.setClientKeyId(keyId); + record.setClientKeyName(keyName); + record.setEndUser(endUser); + record.setPublicModelId(model); + record.setProviderSlug("openai"); + record.setCreatedAt(at); + record.setCostUsd(new BigDecimal("0.001")); + record.setTotalTokens(100); + record.setStatus(UsageRecord.Status.SUCCESS); + return record; + } + + @Test + void aKeyFilterAlsoAppliesTheWindow() throws Exception { + // key1-old is two days back; the 1h window must exclude it. + mvc.perform(get("/admin/usage") + .header("X-Admin-Token", ADMIN) + .param("keyId", String.valueOf(keyOne)) + .param("window", "1h")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.total").value(1)) + .andExpect(jsonPath("$.data.length()").value(1)) + .andExpect(jsonPath("$.data[0].model").value("key1-recent")); + } + + @Test + void anEndUserFilterRunsBeforeTheLimit() throws Exception { + // Two newer rows belong to other users; Alice's two rows must still be found. + mvc.perform(get("/admin/usage") + .header("X-Admin-Token", ADMIN) + .param("endUser", "alice") + .param("window", "30d") + .param("limit", "2")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.total").value(2)) + .andExpect(jsonPath("$.data.length()").value(2)); + } + + @Test + void thePageAndTotalDescribeTheWholeFilteredSet() throws Exception { + mvc.perform(get("/admin/usage") + .header("X-Admin-Token", ADMIN) + .param("endUser", "alice") + .param("window", "30d") + .param("limit", "1") + .param("page", "1")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.page").value(1)) + .andExpect(jsonPath("$.total").value(2)) + .andExpect(jsonPath("$.has_more").value(false)) + .andExpect(jsonPath("$.data[0].model").value("key1-old")); + } + + @Test + void aKeyScopedCsvDoesNotLoseRowsToTheGlobalLimit() throws Exception { + mvc.perform(get("/admin/usage/export") + .header("X-Admin-Token", ADMIN) + .param("keyId", String.valueOf(keyOne)) + .param("window", "30d") + .param("limit", "10")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("key1-old"))) + .andExpect(content().string(containsString("key1-recent"))) + .andExpect(content().string(not(containsString("key2-bob")))); + } + + @Test + void anEndUserScopedCsvFiltersInTheQuery() throws Exception { + mvc.perform(get("/admin/usage/export") + .header("X-Admin-Token", ADMIN) + .param("endUser", "alice") + .param("window", "30d") + .param("limit", "10")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("key1-recent"))) + .andExpect(content().string(containsString("key1-old"))) + .andExpect(content().string(not(containsString("key2-bob")))); + } +} diff --git a/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java b/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java index da3da7b..5c26fbb 100644 --- a/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java +++ b/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java @@ -83,6 +83,17 @@ void enablingAnEmptyPromptIsRejected() { .extracting(e -> ((ApiException) e).status()).isEqualTo(400); } + @Test + void aPromptBeyondTheOldLimitIsAccepted() { + // 16k was too small for a full upstream prompt; 20k must round-trip. + String longPrompt = "x".repeat(20_000); + + service.save(longPrompt, true); + + assertThat(service.activeText()).hasSize(20_000); + assertThat(service.view().get("max_chars")).isEqualTo(SystemPromptService.MAX_CHARS); + } + @Test void promptsLongerThanTheLimitAreRejected() { String tooLong = "x".repeat(SystemPromptService.MAX_CHARS + 1); diff --git a/path-gateway/src/test/java/com/anindra/path/gateway/UpstreamErrorMappingTest.java b/path-gateway/src/test/java/com/anindra/path/gateway/UpstreamErrorMappingTest.java new file mode 100644 index 0000000..ef88234 --- /dev/null +++ b/path-gateway/src/test/java/com/anindra/path/gateway/UpstreamErrorMappingTest.java @@ -0,0 +1,102 @@ +package com.anindra.path.gateway; + +import com.anindra.path.api.ApiException; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The caller must see the gateway's own error, not the provider's. Provider text can + * echo part of a credential or an internal hostname; the full cause goes to the log. + */ +class UpstreamErrorMappingTest { + + private static final String LEAKY_KEY_BODY = + "{\"error\":{\"message\":\"Incorrect API key provided: sk-proj-SECRET123. " + + "Check your key at https://platform.openai.com\",\"type\":\"invalid_request_error\"}}"; + + @Test + void anExpiredProviderKeyIsTheGatewaysProblemAndDoesNotEchoTheCredential() { + ApiException mapped = ChatService.toApiException( + UpstreamClient.mapError(401, LEAKY_KEY_BODY, Map.of())); + + assertThat(mapped.status()).isEqualTo(502); + assertThat(mapped.code()).isEqualTo("provider_auth_error"); + assertThat(mapped.getMessage()) + .contains("gateway configuration problem") + .doesNotContain("sk-proj-SECRET123") + .doesNotContain("Incorrect API key") + .doesNotContain("platform.openai.com"); + } + + @Test + void aProviderServerErrorKeepsItsCodeButNotItsText() { + ApiException mapped = ChatService.toApiException(UpstreamClient.mapError( + 500, "{\"error\":{\"message\":\"internal shard 7 exploded at 10.0.0.4\"}}")); + + assertThat(mapped.status()).isEqualTo(502); + assertThat(mapped.code()).isEqualTo("upstream_error"); + assertThat(mapped.getMessage()) + .isEqualTo("The provider returned an error. Retry shortly.") + .doesNotContain("10.0.0.4"); + } + + @Test + void anInvalidRequestBodyKeepsItsActionableDetail() { + // 400/422 is about the caller's own body, so the reason survives. + ApiException mapped = ChatService.toApiException(UpstreamClient.mapError( + 400, "{\"error\":{\"message\":\"context length exceeded\"}}")); + + assertThat(mapped.status()).isEqualTo(400); + assertThat(mapped.code()).isEqualTo("upstream_invalid_request"); + assertThat(mapped.getMessage()).isEqualTo("context length exceeded"); + } + + @Test + void aMissingModelAndATimeoutStayActionable() { + ApiException notFound = ChatService.toApiException( + UpstreamClient.mapError(404, "{\"error\":{\"message\":\"model 'x' does not exist\"}}")); + assertThat(notFound.status()).isEqualTo(404); + assertThat(notFound.code()).isEqualTo("model_not_found"); + + ApiException timeout = ChatService.toApiException( + UpstreamClient.mapError(408, "{\"error\":{\"message\":\"read timed out\"}}")); + assertThat(timeout.status()).isEqualTo(504); + assertThat(timeout.code()).isEqualTo("upstream_timeout"); + assertThat(timeout.getMessage()).doesNotContain("read timed out"); + } + + @Test + void aProviderRateLimitPreservesTheRetryHint() { + ApiException mapped = ChatService.toApiException(UpstreamClient.mapError( + 429, "{\"error\":{\"message\":\"mock rate limit\"}}", Map.of("retry-after", "7"))); + + assertThat(mapped.status()).isEqualTo(429); + assertThat(mapped.code()).isEqualTo("rate_limit_exceeded"); + assertThat(mapped.retryAfterSeconds()).isEqualTo(7); + assertThat(mapped.getMessage()).doesNotContain("mock rate limit"); + } + + @Test + void anUnreachableProviderDoesNotLeakItsHostname() { + ApiException mapped = ChatService.networkError( + "openai", "Connection refused: 10.0.0.4:443", false); + + assertThat(mapped.status()).isEqualTo(502); + assertThat(mapped.code()).isEqualTo("upstream_network_error"); + assertThat(mapped.getMessage()) + .contains("currently unreachable") + .doesNotContain("10.0.0.4") + .doesNotContain("Connection refused"); + } + + @Test + void operatorsCanOptIntoTheRawDetail() { + ApiException mapped = ChatService.toApiException( + UpstreamClient.mapError(401, LEAKY_KEY_BODY, Map.of()), true); + + assertThat(mapped.getMessage()).contains("sk-proj-SECRET123"); + } +} diff --git a/path-spring-ai/pom.xml b/path-spring-ai/pom.xml index 7368042..70e8f00 100644 --- a/path-spring-ai/pom.xml +++ b/path-spring-ai/pom.xml @@ -7,7 +7,7 @@ io.github.an1ndra path-parent - 0.2.14 + 0.2.15 ../pom.xml diff --git a/pom.xml b/pom.xml index f1ecd74..8d71803 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ io.github.an1ndra path-parent - 0.2.14 + 0.2.15 pom path-parent Build parent for Path, the provider-agnostic LLM gateway, and its Spring AI adapter diff --git a/tools/smoke_test.py b/tools/smoke_test.py index dac563e..2f80252 100644 --- a/tools/smoke_test.py +++ b/tools/smoke_test.py @@ -298,6 +298,28 @@ def main(): check("allow_fallbacks=false surfaces the 500", status == 502 and body.get("error", {}).get("code") == "upstream_error", str(status) + str(body)[:200]) + # Provider text must stay behind the gateway: an expired key is our fault, not the + # caller's, and the upstream body can echo part of the credential. + jreq("POST", "/admin/routes", { + "publicModelId": "auth-error-test", "providerId": providers["openai"]["id"], + "upstreamModelId": "unauthorized-model", "priority": 1, + "inputPricePerMillion": 1, "outputPricePerMillion": 1}, admin=True) + status, _, body = jreq("POST", "/v1/chat/completions", { + "model": "auth-error-test", "messages": [{"role": "user", "content": "hi"}]}, key=key) + err = body.get("error", {}) + check("expired provider key is reported as the gateway's error", + status == 502 and err.get("code") == "provider_auth_error" + and "bad key" not in err.get("message", "") + and "gateway configuration" in err.get("message", ""), + str(status) + str(err)[:200]) + + _, _, streamed = sse_post("/v1/chat/completions", { + "model": "auth-error-test", "stream": True, + "messages": [{"role": "user", "content": "hi"}]}, key) + stream_error = next((p for p in streamed if "provider_auth_error" in p), "") + check("streaming uses the same gateway-owned error", + bool(stream_error) and "bad key" not in stream_error, stream_error[:200]) + # --------------------------------------------------------------- limits, params status, _, body = jreq("POST", "/v1/chat/completions", {"model": "gpt-4o-mini",