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
15 changes: 15 additions & 0 deletions changelog/v0.2.17.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# v0.2.17

Admin roles and end-user blocking.

## Added

- Admin tokens carry a role (`owner`, `admin`, `viewer`) and an optional expiry.
Existing tokens keep their scopes; a viewer never gets write, and an expired
token stops authenticating.
- End-user management: `GET /admin/end-users` aggregates spend, requests, tokens
and last seen by `end_user`. `POST/DELETE /admin/end-users/block` blocks or
unblocks an id; blocked ids fail every chat request with 403
`end_user_blocked`, whichever key sends it.
- The console's Access page exposes roles, expiry and expiry state, and a new
End users page lists attributed ids with spend and block/unblock.
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), providers (create/edit with a
the addresses seen, with country and user agent), 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
switches, the default system prompt, alert email and the daily digest) and **settings**
Expand Down
3 changes: 3 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,9 @@ ids land at `0.00` and are flagged in `description`.
| PATCH | `/admin/ip-rules/{id}` | enable or disable a rule |
| DELETE | `/admin/ip-rules/{id}` | delete a rule |
| GET | `/admin/ip-observations?limit=100` | addresses seen at `/admin` and `/v1`, with country and user agent |
| GET | `/admin/end-users?limit=200` | end-user spend, requests, tokens and last seen |
| POST | `/admin/end-users/block` | block an `end_user` (`end_user`, `reason`) |
| DELETE | `/admin/end-users/block?endUser=` | unblock an end user |
| 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 |
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.16</version>
<version>0.2.17</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,9 @@ public record ProjectInput(String slug, String name,
Integer maxConcurrentRequests) {
}

public record TokenInput(String name, String scopes) {
public record TokenInput(String name, String scopes, String role,
@com.fasterxml.jackson.annotation.JsonAlias("expiresAt")
String expires_at) {
}

@GetMapping("/projects")
Expand Down Expand Up @@ -327,12 +329,15 @@ public List<Map<String, Object>> tokens() {

@PostMapping("/tokens")
public Map<String, Object> createToken(@RequestBody TokenInput input) {
var created = tenancy.createToken(input.name(), input.scopes());
var created = tenancy.createToken(input.name(), input.scopes(), input.role(),
input.expires_at() == null || input.expires_at().isBlank()
? null : instant(input.expires_at(), "expires_at"));
audit.record("token.create", "token:" + created.token().getId(), input);
Map<String, Object> view = new java.util.LinkedHashMap<>();
view.put("id", created.token().getId());
view.put("name", created.token().getName());
view.put("scopes", created.token().getScopes());
view.put("role", created.token().getRole());
view.put("token", created.plaintext());
view.put("warning", "Store this token now. It is not shown again.");
return view;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.anindra.path.admin;

import com.anindra.path.api.ApiException;
import com.anindra.path.config.AuthFilter;
import com.anindra.path.gateway.EndUserService;
import com.fasterxml.jackson.annotation.JsonAlias;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/** End-user attribution, spend and blocking. */
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class EndUserController {

private final EndUserService endUsers;

public record BlockInput(@JsonAlias("endUser") String end_user, String reason) {
}

@GetMapping("/end-users")
public List<Map<String, Object>> list(@RequestParam(defaultValue = "200") int limit) {
return endUsers.list(limit);
}

@PostMapping("/end-users/block")
public Map<String, Object> block(@RequestBody BlockInput input, HttpServletRequest request) {
return endUsers.block(input.end_user(), input.reason(), actor(request));
}

@DeleteMapping("/end-users/block")
public Map<String, Object> unblock(@RequestParam String endUser, HttpServletRequest request) {
return endUsers.unblock(endUser, actor(request));
}

private static String actor(HttpServletRequest request) {
Object principal = request.getAttribute(AuthFilter.ADMIN_PRINCIPAL_ATTR);
if (principal instanceof TenancyService.Principal p && p.name() != null) {
return p.name();
}
return "admin";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,11 @@ public List<Map<String, Object>> listTokens() {
row.put("name", token.getName());
row.put("masked_token", token.getTokenPrefix() + "..." + token.getTokenSuffix());
row.put("scopes", token.getScopes());
row.put("role", roleOf(token));
row.put("enabled", token.isEnabled());
row.put("expires_at", token.getExpiresAt() == null ? null : token.getExpiresAt().toString());
row.put("expired", token.getExpiresAt() != null
&& token.getExpiresAt().isBefore(java.time.Instant.now()));
row.put("created_at", token.getCreatedAt().toString());
out.add(row);
}
Expand All @@ -179,17 +183,29 @@ public List<Map<String, Object>> listTokens() {

@Transactional
public CreatedToken createToken(String name, String scopes) {
return createToken(name, scopes, null, null);
}

@Transactional
public CreatedToken createToken(String name, String scopes, String role,
java.time.Instant expiresAt) {
if (name == null || name.isBlank()) {
throw ApiException.badRequest("name is required", "name");
}
String normalized = normalizeScopes(scopes);
String normalizedRole = normalizeRole(role);
String normalized = normalizedRole == null ? normalizeScopes(scopes) : scopesForRole(normalizedRole);
if (expiresAt != null && !expiresAt.isAfter(java.time.Instant.now())) {
throw ApiException.badRequest("'expires_at' must be in the future.", "expires_at");
}
String secret = "adm_" + random(40);
AdminToken token = new AdminToken();
token.setName(name.trim());
token.setTokenHash(ApiKeyService.hash(secret));
token.setTokenPrefix(secret.substring(0, 12));
token.setTokenSuffix(secret.substring(secret.length() - 4));
token.setScopes(normalized);
token.setRole(normalizedRole);
token.setExpiresAt(expiresAt);
tokens.save(token);
return new CreatedToken(token, secret);
}
Expand All @@ -206,7 +222,31 @@ public Map<String, Object> revokeToken(Long id) {
public Optional<Principal> authenticate(String rawToken) {
return tokens.findByTokenHash(ApiKeyService.hash(rawToken))
.filter(AdminToken::isEnabled)
.map(token -> new Principal(token.getName(), scopesOf(token.getScopes())));
.filter(token -> token.getExpiresAt() == null
|| token.getExpiresAt().isAfter(java.time.Instant.now()))
.map(token -> new Principal(token.getName(),
token.getRole() == null ? scopesOf(token.getScopes())
: scopesOf(scopesForRole(token.getRole()))));
}

private static String normalizeRole(String role) {
if (role == null || role.isBlank()) {
return null;
}
String value = role.trim().toLowerCase();
if (!value.equals("owner") && !value.equals("admin") && !value.equals("viewer")) {
throw ApiException.badRequest("'role' must be owner, admin or viewer.", "role");
}
return value;
}

private static String roleOf(AdminToken token) {
return token.getRole() != null ? token.getRole()
: scopesOf(token.getScopes()).contains("write") ? "admin" : "viewer";
}

private static String scopesForRole(String role) {
return "viewer".equals(role) ? "read" : "read,write";
}

private static String normalizeScopes(String scopes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public class AdminToken {
@Column(nullable = false, length = 32)
private String scopes = "read";

/** owner, admin or viewer. Null keeps the legacy scopes-only behaviour. */
@Column(length = 16)
private String role;

private Instant expiresAt;

@Column(nullable = false)
private boolean enabled = true;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.anindra.path.domain;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.Instant;

/** An end_user id that may no longer call the API, regardless of its key. */
@Entity
@Table(name = "blocked_end_users")
@Getter
@Setter
@NoArgsConstructor
public class BlockedEndUser {

@Id
@Column(name = "end_user", length = 128)
private String endUser;

@Column(length = 255)
private String reason;

@Column(length = 128)
private String blockedBy;

@Column(nullable = false)
private Instant createdAt = Instant.now();
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public record Result(JsonNode body, String providerSlug, String upstreamModel,
private final UpstreamClient upstream;
private final UsageService usage;
private final ApiKeyService apiKeys;
private final EndUserService endUserService;
private final CreditGuard creditGuard;
private final ProviderCircuitBreaker breaker;
private final RoutingMetrics metrics;
Expand All @@ -42,7 +43,8 @@ public record Result(JsonNode body, String providerSlug, String upstreamModel,
private final Map<ProviderType, ProviderAdapter> adapters = new EnumMap<>(ProviderType.class);

public ChatService(RouteResolver resolver, ProviderCredentials credentials, UpstreamClient upstream,
UsageService usage, ApiKeyService apiKeys, CreditGuard creditGuard,
UsageService usage, ApiKeyService apiKeys, EndUserService endUserService,
CreditGuard creditGuard,
ProviderCircuitBreaker breaker, RoutingMetrics metrics,
ResponseCacheService cache, SemanticCacheService semantic,
GatewayProperties props, ObjectMapper mapper,
Expand All @@ -52,6 +54,7 @@ public ChatService(RouteResolver resolver, ProviderCredentials credentials, Upst
this.upstream = upstream;
this.usage = usage;
this.apiKeys = apiKeys;
this.endUserService = endUserService;
this.creditGuard = creditGuard;
this.breaker = breaker;
this.metrics = metrics;
Expand All @@ -63,6 +66,7 @@ public ChatService(RouteResolver resolver, ProviderCredentials credentials, Upst
}

public Result complete(ChatRequestSpec spec, ClientKey key) {
endUserService.assertAllowed(spec.endUser());
List<RouteResolver.ResolvedRoute> chain = resolver.resolve(spec, key.getId());
CreditGuard.Reservation reserved = creditGuard.check(key, spec, chain.get(0));
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.anindra.path.gateway;

import com.anindra.path.admin.AuditService;
import com.anindra.path.api.ApiException;
import com.anindra.path.domain.BlockedEndUser;
import com.anindra.path.repo.BlockedEndUserRepository;
import com.anindra.path.repo.UsageRecordRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* End users are the caller's own customer ids (the {@code end_user} field). This service
* lists their aggregate spend and can block an id before a request reaches a provider.
*/
@Service
@RequiredArgsConstructor
public class EndUserService {

private final BlockedEndUserRepository blocked;
private final UsageRecordRepository usage;
private final AuditService audit;

public void assertAllowed(String endUser) {
if (endUser != null && !endUser.isBlank() && blocked.existsById(endUser)) {
throw new ApiException(403, "permission_error", "end_user_blocked",
"This end user is blocked by an administrator.");
}
}

public List<Map<String, Object>> list(int limit) {
int capped = Math.max(1, Math.min(limit, 500));
Set<String> blockedIds = blocked.findAll().stream()
.map(BlockedEndUser::getEndUser)
.collect(Collectors.toSet());
List<Map<String, Object>> out = new ArrayList<>();
for (Object[] row : usage.groupByEndUser(PageRequest.of(0, capped))) {
Map<String, Object> item = new LinkedHashMap<>();
String endUser = (String) row[0];
item.put("end_user", endUser);
item.put("requests", row[1]);
item.put("total_tokens", row[2]);
item.put("cost_usd", row[3] == null ? BigDecimal.ZERO : row[3]);
item.put("last_seen", row[4] == null ? null : ((Instant) row[4]).toString());
item.put("blocked", blockedIds.contains(endUser));
out.add(item);
}
return out;
}

@Transactional
public Map<String, Object> block(String endUser, String reason, String actor) {
if (endUser == null || endUser.isBlank()) {
throw ApiException.badRequest("'end_user' is required.", "end_user");
}
if (endUser.length() > 128) {
throw ApiException.badRequest("'end_user' must be at most 128 characters.", "end_user");
}
BlockedEndUser entry = blocked.findById(endUser).orElseGet(() -> {
BlockedEndUser created = new BlockedEndUser();
created.setEndUser(endUser);
return created;
});
entry.setReason(reason == null || reason.isBlank() ? null
: reason.trim().substring(0, Math.min(reason.trim().length(), 255)));
entry.setBlockedBy(actor == null ? "admin" : actor);
entry.setCreatedAt(Instant.now());
blocked.save(entry);
audit.record("end-user.block", endUser, Map.of("end_user", endUser, "reason", entry.getReason()));
return Map.of("end_user", endUser, "blocked", true, "reason", entry.getReason());
}

@Transactional
public Map<String, Object> unblock(String endUser, String actor) {
if (endUser == null || endUser.isBlank()) {
throw ApiException.badRequest("'end_user' is required.", "end_user");
}
blocked.findById(endUser).ifPresent(blocked::delete);
audit.record("end-user.unblock", endUser, Map.of("end_user", endUser));
return Map.of("end_user", endUser, "blocked", false);
}
}
Loading