Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions changelog/v0.2.23.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# v0.2.23

Per-request attribution and per-key IP pinning.

## Added

- Usage rows record `client_ip` and `user_agent`, so every call can be tied to
the key and address that made it.
- Client keys accept `allowed_ips` (comma-separated IPs/CIDRs); any other address
fails with 403 `key_ip_not_allowed`.
- The console gains a **Security** page with recent calls, key, client IP, user
agent, model, status and request id, plus a filter.
- Usage CSV exports include `client_ip` and `user_agent`.
3 changes: 2 additions & 1 deletion docs/ADMIN-UI.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ The admin console lives in its own repository, [an1ndra/path-admin](https://gith
Read and write against this API: dashboard (spend, cache, latency, provider circuits, top
models, recent failures), usage (filter by key/end user/window, page through rows, export
CSV), audit (every admin write, filterable by action), IP access (allow/deny CIDR rules and
the addresses seen, with country and user agent), end users (aggregate spend and blocking),
the addresses seen, with country and user agent), security (recent calls with key, client
IP, user agent and request id), end users (aggregate spend and blocking),
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
Expand Down
7 changes: 7 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Every failure uses the OpenAI envelope:
| `payload_too_large` | 413 | request body above `GATEWAY_MAX_REQUEST_BYTES` |
| `unsupported_parameter` | 422 | parameter has no equivalent for this provider |
| `model_not_allowed` | 403 | key's `allowed_models` does not cover the model |
| `key_ip_not_allowed` | 403 | key's `allowed_ips` does not cover the caller's address |
| `idempotency_conflict` | 409 | same `Idempotency-Key`, different body |
| `idempotency_in_progress` | 409 | duplicate while the first attempt is running |
| `shutting_down` | 503 | instance is draining; retry elsewhere |
Expand Down Expand Up @@ -428,6 +429,12 @@ ids land at `0.00` and are flagged in `description`.
| 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); `keyId`, `endUser` and `projectId` filter the query, not the result |

Usage rows now carry `client_ip` and `user_agent`, so a key can be tied to the
addresses that used it. A client key may also set `allowed_ips` (comma-separated
IPs/CIDRs); requests from any other address fail with 403 `key_ip_not_allowed`.
The console's Security page lists recent calls with key, IP, user agent and
request id.

```json
{
"requests": 21, "total_tokens": 384, "cost_usd": 0.000393,
Expand Down
2 changes: 1 addition & 1 deletion path-gateway/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.22</version>
<version>0.2.23</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ public Map<String, Object> usage(Long keyId, Long projectId, String endUser, Str
row.put("tokens_per_second", r.getTokensPerSecond());
row.put("upstream_request_id", r.getUpstreamRequestId());
row.put("request_id", r.getRequestId());
row.put("client_ip", r.getClientIp());
row.put("user_agent", r.getUserAgent());
row.put("finish_reason", r.getFinishReason());
row.put("attempts", r.getAttempts());
row.put("fallback_from", r.getFallbackFrom());
Expand Down Expand Up @@ -161,7 +163,7 @@ public String usageCsv(Long keyId, Long projectId, String endUser, java.time.Ins
csv.append("created_at,key_id,key_name,model,provider,upstream_model,prompt_tokens,")
.append("completion_tokens,cached_input_tokens,cache_write_tokens,reasoning_tokens,")
.append("input_cost_usd,cached_input_cost_usd,cache_write_cost_usd,output_cost_usd,")
.append("cost_usd,latency_ms,ttft_ms,streamed,status,error_code,end_user\n");
.append("cost_usd,latency_ms,ttft_ms,streamed,status,error_code,end_user,client_ip,user_agent\n");

for (UsageRecord r : rows) {
csv.append(r.getCreatedAt()).append(',')
Expand All @@ -185,7 +187,9 @@ public String usageCsv(Long keyId, Long projectId, String endUser, java.time.Ins
.append(r.isStreamed()).append(',')
.append(r.getStatus().name().toLowerCase()).append(',')
.append(escape(r.getErrorCode())).append(',')
.append(escape(r.getEndUser()))
.append(escape(r.getEndUser())).append(',')
.append(escape(r.getClientIp())).append(',')
.append(escape(r.getUserAgent()))
.append('\n');
}
return csv.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public record KeyInput(String name, @JsonAlias("creditLimitUsd") BigDecimal cred
@JsonAlias("rpmLimit") Integer rpmLimit,
@JsonAlias("maxConcurrentRequests") Integer maxConcurrentRequests,
@JsonAlias("allowedModels") String allowedModels,
@JsonAlias("allowedIps") String allowedIps,
@JsonAlias("projectId") Long projectId,
Boolean enabled) {
}
Expand Down Expand Up @@ -476,6 +477,7 @@ public Map<String, Object> createKey(KeyInput in) {
created.key().setMonthlyLimitUsd(in.monthlyLimitUsd());
created.key().setMaxOutputTokens(in.maxOutputTokens());
created.key().setAllowedModels(in.allowedModels());
created.key().setAllowedIps(in.allowedIps());
created.key().setEndUserDailyLimitUsd(in.endUserDailyLimitUsd());
created.key().setProjectId(in.projectId());
clientKeys.save(created.key());
Expand Down Expand Up @@ -522,6 +524,9 @@ public Map<String, Object> updateKey(Long id, KeyInput in) {
if (in.allowedModels() != null) {
key.setAllowedModels(in.allowedModels());
}
if (in.allowedIps() != null) {
key.setAllowedIps(in.allowedIps());
}
if (in.projectId() != null) {
key.setProjectId(in.projectId());
}
Expand Down Expand Up @@ -570,6 +575,7 @@ private Map<String, Object> keyView(ClientKey k) {
view.put("end_user_daily_limit_usd", k.getEndUserDailyLimitUsd());
view.put("max_output_tokens", k.getMaxOutputTokens());
view.put("allowed_models", k.getAllowedModels());
view.put("allowed_ips", k.getAllowedIps());
view.put("project_id", k.getProjectId());
view.put("credit_limit_usd", k.getCreditLimitUsd());
view.put("used_usd", k.getUsedUsd());
Expand Down
24 changes: 22 additions & 2 deletions path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public class AuthFilter extends OncePerRequestFilter {
public static final String ADMIN_PRINCIPAL_ATTR = "gateway.adminPrincipal";
public static final String ADMIN_SESSION_HEADER = "X-Admin-Session";
public static final String ADMIN_USER_ID_ATTR = "gateway.adminUserId";
public static final String CLIENT_IP_ATTR = "gateway.clientIp";
public static final String CLIENT_UA_ATTR = "gateway.userAgent";

private final ApiKeyService apiKeys;
private final RateLimitStore rateLimiter;
Expand Down Expand Up @@ -75,6 +77,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
: path.startsWith("/v1") ? "api" : null;
if (ruleScope != null) {
String address = clientAddress(request);
request.setAttribute(CLIENT_IP_ATTR, address);
request.setAttribute(CLIENT_UA_ATTR, request.getHeader("User-Agent"));
com.anindra.path.gateway.IpAccessService.Decision decision = ipAccess.check(address, ruleScope);
if (!decision.allowed()) {
throw new ApiException(403, "permission_error", decision.code(), decision.message());
Expand All @@ -93,6 +97,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
requireActuatorAccess(request, path);
} else if (!isPublicModelsRequest(request)) {
ClientKey key = authenticateClientKey(request);
enforceKeyIp(key, (String) request.getAttribute(CLIENT_IP_ATTR));
int retryAfter = rateLimiter.acquire(key.getId(), key.getRpmLimit());
if (retryAfter > 0) {
throw ApiException.rateLimited(
Expand Down Expand Up @@ -228,8 +233,23 @@ private ClientKey authenticateClientKey(HttpServletRequest request) {
}
}

private ClientKey resolveClientKey(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
/** A key can be pinned to one or more IPs/CIDRs; blank means any address. */
private static void enforceKeyIp(ClientKey key, String address) {
String allowed = key.getAllowedIps();
if (allowed == null || allowed.isBlank() || address == null || address.isBlank()) {
return;
}
for (String rule : allowed.split(",")) {
String candidate = rule.trim();
if (!candidate.isEmpty() && com.anindra.path.gateway.IpAccessService.matches(candidate, address)) {
return;
}
}
throw ApiException.forbidden(
"This API key is not allowed from address " + address + ".", "key_ip_not_allowed");
}

private ClientKey resolveClientKey(HttpServletRequest request) { String header = request.getHeader(HttpHeaders.AUTHORIZATION);
String token = null;
if (header != null && header.regionMatches(true, 0, "Bearer ", 0, 7)) {
token = header.substring(7).trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ public class ClientKey {
@Column(length = 1024)
private String allowedModels;

/** Comma-separated IPs/CIDRs; blank means any address. */
@Column(length = 1024)
private String allowedIps;

/** Per-end-user daily cap applied to any request carrying an end_user. */
@Column(precision = 18, scale = 6)
private BigDecimal endUserDailyLimitUsd;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,13 @@ public enum Status {SUCCESS, ERROR}
@Column(length = 128)
private String requestId;

/** Resolved client address (CF-Connecting-IP when configured, else the socket address). */
@Column(length = 64)
private String clientIp;

@Column(length = 255)
private String userAgent;

@Column(length = 32)
private String finishReason;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,17 @@ private static boolean validLiteral(String value) {
return value.matches("[0-9a-fA-F:.]+");
}

/** True when {@code ip} is inside {@code cidr}; used by per-key allowlists. */
public static boolean matches(String cidr, String ip) {
try {
return Cidr.parse(cidr).contains(InetAddress.getByName(ip));
} catch (Exception e) {
return false;
}
}

/** A parsed IPv4/IPv6 network. Prefix 0 is rejected so a rule cannot silently block everything. */
static final class Cidr {

private final String text;
private final byte[] network;
private final int prefix;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,20 @@ private static BigDecimal nz(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}

private static String requestAttr(String name) {
var attributes = org.springframework.web.context.request.RequestContextHolder
.getRequestAttributes();
if (attributes instanceof org.springframework.web.context.request.ServletRequestAttributes servlet) {
Object value = servlet.getRequest().getAttribute(name);
return value == null ? null : String.valueOf(value);
}
return null;
}

private static String truncate(String value, int max) {
return value == null || value.length() <= max ? value : value.substring(0, max);
}

@Transactional
public BigDecimal recordSuccess(ClientKey key, ChatRequestSpec spec, RouteResolver.ResolvedRoute resolved,
TokenUsage tokens, CallMeta meta) {
Expand Down Expand Up @@ -123,6 +137,8 @@ public BigDecimal recordSuccess(ClientKey key, ChatRequestSpec spec, RouteResolv
record.setStreamed(meta.streamed());
record.setUpstreamRequestId(meta.requestId());
record.setRequestId(currentRequestId());
record.setClientIp(requestAttr(com.anindra.path.config.AuthFilter.CLIENT_IP_ATTR));
record.setUserAgent(truncate(requestAttr(com.anindra.path.config.AuthFilter.CLIENT_UA_ATTR), 255));
record.setFinishReason(meta.finishReason());
record.setAttempts(meta.attempts());
record.setFallbackFrom(meta.fallbackFrom());
Expand Down Expand Up @@ -182,6 +198,8 @@ public void recordError(ClientKey key, ChatRequestSpec spec, String providerSlug
record.setErrorCode(code);
record.setErrorMessage(message != null && message.length() > 500 ? message.substring(0, 500) : message);
record.setRequestId(currentRequestId());
record.setClientIp(requestAttr(com.anindra.path.config.AuthFilter.CLIENT_IP_ATTR));
record.setUserAgent(truncate(requestAttr(com.anindra.path.config.AuthFilter.CLIENT_UA_ATTR), 255));
usage.save(record);
// Kept separate from path_requests_total so an alert can tell a 4xx from a 5xx
// without a high-cardinality label on the request counter.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Per-request attribution and per-key IP allowlists.

alter table usage_records add column client_ip varchar(64);
alter table usage_records add column user_agent varchar(255);

alter table client_keys add column allowed_ips varchar(1024);
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.anindra.path;

import com.anindra.path.gateway.ApiKeyService;
import com.anindra.path.repo.ClientKeyRepository;
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 org.springframework.test.web.servlet.request.RequestPostProcessor;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:keyiptest;MODE=PostgreSQL;DB_CLOSE_DELAY=-1",
"spring.jpa.hibernate.ddl-auto=validate",
"gateway.bootstrap-demo-key=false",
"gateway.master-key-path=./target/test-master.key"
})
@AutoConfigureMockMvc
class KeyIpAllowlistTest {

@Autowired
private MockMvc mvc;

@Autowired
private ApiKeyService apiKeys;

@Autowired
private ClientKeyRepository keys;

private String plaintext;

@BeforeEach
void setUp() {
keys.deleteAll();
var created = apiKeys.create("ip-pinned", null, 100);
plaintext = created.plaintext();
var key = created.key();
key.setAllowedIps("203.0.113.0/24");
keys.save(key);
}

private static RequestPostProcessor address(String ip) {
return request -> { request.setRemoteAddr(ip); return request; };
}

@Test
void anAllowlistedAddressReachesTheApi() throws Exception {
mvc.perform(get("/v1/models").with(address("203.0.113.9"))
.header("Authorization", "Bearer " + plaintext))
.andExpect(status().isOk());
}

@Test
void anyOtherAddressIsRejectedAfterAuthentication() throws Exception {
mvc.perform(get("/v1/models").with(address("198.51.100.9"))
.header("Authorization", "Bearer " + plaintext))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.error.code").value("key_ip_not_allowed"));
}
}
2 changes: 1 addition & 1 deletion path-spring-ai/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.22</version>
<version>0.2.23</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.22</version>
<version>0.2.23</version>
<packaging>pom</packaging>
<name>path-parent</name>
<description>Build parent for Path, the provider-agnostic LLM gateway, and its Spring AI adapter</description>
Expand Down
3 changes: 3 additions & 0 deletions tools/smoke_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,9 @@ def main():
any(r["provider"] == "anthropic" and r["cache_write_tokens"] == 2 for r in rows),
str([(r["provider"], r["cache_write_tokens"]) for r in rows]))
check("usage rows itemise cost", all("cost_breakdown" in r for r in rows))
check("usage rows carry the client address and user agent",
any(r.get("client_ip") and r.get("user_agent") for r in rows),
str([(r.get("client_ip"), r.get("user_agent")) for r in rows[:3]]))
check("streamed rows record ttft", any(r["streamed"] and r.get("ttft_ms") for r in rows))
check("streamed rows record throughput", any(r["streamed"] and r.get("tokens_per_second") for r in rows))
check("rows carry an upstream request id", any(r.get("upstream_request_id") for r in rows),
Expand Down