diff --git a/changelog/v0.2.23.md b/changelog/v0.2.23.md
new file mode 100644
index 0000000..36f5d15
--- /dev/null
+++ b/changelog/v0.2.23.md
@@ -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`.
diff --git a/docs/ADMIN-UI.md b/docs/ADMIN-UI.md
index cc3e7ff..3d0f8cf 100644
--- a/docs/ADMIN-UI.md
+++ b/docs/ADMIN-UI.md
@@ -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
diff --git a/docs/API.md b/docs/API.md
index 0c158d8..9d9551d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -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 |
@@ -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,
diff --git a/path-gateway/pom.xml b/path-gateway/pom.xml
index 489c111..58553e0 100644
--- a/path-gateway/pom.xml
+++ b/path-gateway/pom.xml
@@ -7,7 +7,7 @@
io.github.an1ndra
path-parent
- 0.2.22
+ 0.2.23
../pom.xml
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 ddad48d..76c2c7a 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
@@ -99,6 +99,8 @@ public Map 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());
@@ -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(',')
@@ -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();
diff --git a/path-gateway/src/main/java/com/anindra/path/admin/AdminService.java b/path-gateway/src/main/java/com/anindra/path/admin/AdminService.java
index 248e025..5e013de 100644
--- a/path-gateway/src/main/java/com/anindra/path/admin/AdminService.java
+++ b/path-gateway/src/main/java/com/anindra/path/admin/AdminService.java
@@ -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) {
}
@@ -476,6 +477,7 @@ public Map 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());
@@ -522,6 +524,9 @@ public Map 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());
}
@@ -570,6 +575,7 @@ private Map 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());
diff --git a/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java b/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java
index 67ecefa..064f30f 100644
--- a/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java
+++ b/path-gateway/src/main/java/com/anindra/path/config/AuthFilter.java
@@ -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;
@@ -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());
@@ -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(
@@ -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();
diff --git a/path-gateway/src/main/java/com/anindra/path/domain/ClientKey.java b/path-gateway/src/main/java/com/anindra/path/domain/ClientKey.java
index 23b2205..eda0618 100644
--- a/path-gateway/src/main/java/com/anindra/path/domain/ClientKey.java
+++ b/path-gateway/src/main/java/com/anindra/path/domain/ClientKey.java
@@ -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;
diff --git a/path-gateway/src/main/java/com/anindra/path/domain/UsageRecord.java b/path-gateway/src/main/java/com/anindra/path/domain/UsageRecord.java
index 0daf92e..0ef8036 100644
--- a/path-gateway/src/main/java/com/anindra/path/domain/UsageRecord.java
+++ b/path-gateway/src/main/java/com/anindra/path/domain/UsageRecord.java
@@ -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;
diff --git a/path-gateway/src/main/java/com/anindra/path/gateway/IpAccessService.java b/path-gateway/src/main/java/com/anindra/path/gateway/IpAccessService.java
index 1d7ac65..643f3c0 100644
--- a/path-gateway/src/main/java/com/anindra/path/gateway/IpAccessService.java
+++ b/path-gateway/src/main/java/com/anindra/path/gateway/IpAccessService.java
@@ -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;
diff --git a/path-gateway/src/main/java/com/anindra/path/gateway/UsageService.java b/path-gateway/src/main/java/com/anindra/path/gateway/UsageService.java
index e8feccb..83bc617 100644
--- a/path-gateway/src/main/java/com/anindra/path/gateway/UsageService.java
+++ b/path-gateway/src/main/java/com/anindra/path/gateway/UsageService.java
@@ -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) {
@@ -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());
@@ -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.
diff --git a/path-gateway/src/main/resources/db/migration/V29__usage_client_ip_key_allowlist.sql b/path-gateway/src/main/resources/db/migration/V29__usage_client_ip_key_allowlist.sql
new file mode 100644
index 0000000..953713b
--- /dev/null
+++ b/path-gateway/src/main/resources/db/migration/V29__usage_client_ip_key_allowlist.sql
@@ -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);
diff --git a/path-gateway/src/test/java/com/anindra/path/KeyIpAllowlistTest.java b/path-gateway/src/test/java/com/anindra/path/KeyIpAllowlistTest.java
new file mode 100644
index 0000000..3f44c27
--- /dev/null
+++ b/path-gateway/src/test/java/com/anindra/path/KeyIpAllowlistTest.java
@@ -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"));
+ }
+}
diff --git a/path-spring-ai/pom.xml b/path-spring-ai/pom.xml
index de659cb..8b79273 100644
--- a/path-spring-ai/pom.xml
+++ b/path-spring-ai/pom.xml
@@ -7,7 +7,7 @@
io.github.an1ndra
path-parent
- 0.2.22
+ 0.2.23
../pom.xml
diff --git a/pom.xml b/pom.xml
index bb52ee6..a3e4656 100644
--- a/pom.xml
+++ b/pom.xml
@@ -13,7 +13,7 @@
io.github.an1ndra
path-parent
- 0.2.22
+ 0.2.23
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 2f80252..f0acc61 100644
--- a/tools/smoke_test.py
+++ b/tools/smoke_test.py
@@ -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),