diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 9fa8f73..3a654be 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -22,7 +22,11 @@ jobs: echo "::error::DOKPLOY_API_KEY is not set; cannot trigger the deployment." exit 1 fi - curl -fsS -X POST "https://dokploy.hacksubset.com/api/compose.deploy" \ + status=$(curl -sS -o /tmp/dokploy-response.json -w '%{http_code}' \ + -X POST "https://dokploy.hacksubset.com/api/compose.deploy" \ -H "x-api-key: $DOKPLOY_API_KEY" \ -H "Content-Type: application/json" \ - -d '{"composeId":"qFd9GlvcRtYr8iYIYNwhl","title":"GitHub tag ${{ github.ref_name }}"}' + -d '{"composeId":"qFd9GlvcRtYr8iYIYNwhl","title":"GitHub tag ${{ github.ref_name }}"}') + echo "Dokploy answered HTTP $status" + head -c 500 /tmp/dokploy-response.json; echo + test "$status" -ge 200 && test "$status" -lt 300 diff --git a/changelog/v0.2.16.md b/changelog/v0.2.16.md new file mode 100644 index 0000000..9aac2e6 --- /dev/null +++ b/changelog/v0.2.16.md @@ -0,0 +1,17 @@ +# v0.2.16 + +IP access control for the console and the public API. + +## Added + +- IP allow/deny rules enforced before authentication. Rules are CIDR-based, + scoped to `admin`, `api` or `all`, can expire, and deny wins. An allow rule + turns its scope into an allowlist; prefix `/0` is rejected so a rule cannot + lock every address out. +- Address observations for `/admin` and `/v1`: IP, country from `CF-IPCountry`, + user agent, first/last seen and request count, recorded at most once a minute + per address. +- `/admin/ip-rules` (list, create, enable/disable, delete) and + `/admin/ip-observations`. +- The console gains an **IP access** page with CIDR rules, expiry, observed + addresses and a one-click **Block IP** action. diff --git a/docs/ADMIN-UI.md b/docs/ADMIN-UI.md index b01b4de..32bffb4 100644 --- a/docs/ADMIN-UI.md +++ b/docs/ADMIN-UI.md @@ -8,7 +8,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), providers (create/edit with a +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 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** diff --git a/docs/API.md b/docs/API.md index de7446a..249c970 100644 --- a/docs/API.md +++ b/docs/API.md @@ -392,6 +392,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&page=0&keyId=&endUser=` | raw usage rows, paged; the response carries `total` and `has_more` | +| GET | `/admin/ip-rules` | IP allow/deny rules | +| POST | `/admin/ip-rules` | add a rule (`cidr`, `scope`, `action`, `note`, `expires_at`) | +| 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/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 | diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 58ed053..ce61a17 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -99,6 +99,10 @@ curl -s 'localhost:8080/admin/stats?window=24h' -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/ip-rules' -H "$A" +curl -s -X POST 'localhost:8080/admin/ip-rules' -H "$A" -H 'Content-Type: application/json' \ + -d '{"cidr":"203.0.113.0/24","scope":"all","action":"deny","note":"abuse report"}' +curl -s 'localhost:8080/admin/ip-observations?limit=50' -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" ``` diff --git a/path-gateway/pom.xml b/path-gateway/pom.xml index 361936d..6326bc1 100644 --- a/path-gateway/pom.xml +++ b/path-gateway/pom.xml @@ -7,7 +7,7 @@ io.github.an1ndra path-parent - 0.2.15 + 0.2.16 ../pom.xml diff --git a/path-gateway/src/main/java/com/anindra/path/admin/IpAccessController.java b/path-gateway/src/main/java/com/anindra/path/admin/IpAccessController.java new file mode 100644 index 0000000..4e4dd35 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/admin/IpAccessController.java @@ -0,0 +1,84 @@ +package com.anindra.path.admin; + +import com.anindra.path.api.ApiException; +import com.anindra.path.config.AuthFilter; +import com.anindra.path.gateway.IpAccessService; +import com.fasterxml.jackson.annotation.JsonAlias; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +/** + * IP allow/deny rules and the last-seen addresses that reached the gateway. Rules are + * enforced in {@link AuthFilter} before authentication, so a blocked address cannot even + * use a valid key. + */ +@RestController +@RequestMapping("/admin") +@RequiredArgsConstructor +public class IpAccessController { + + private final IpAccessService ipAccess; + + public record RuleInput(String cidr, String scope, String action, String note, + @JsonAlias("expiresAt") String expires_at) { + } + + public record EnabledInput(Boolean enabled) { + } + + @GetMapping("/ip-rules") + public List> rules() { + return ipAccess.listRules(); + } + + @PostMapping("/ip-rules") + public Map create(@RequestBody RuleInput input, HttpServletRequest request) { + return ipAccess.createRule(input.cidr(), input.scope(), input.action(), input.note(), + instant(input.expires_at()), actor(request)); + } + + @PatchMapping("/ip-rules/{id}") + public Map enable(@PathVariable Long id, @RequestBody EnabledInput input) { + if (input.enabled() == null) { + throw ApiException.badRequest("'enabled' is required.", "enabled"); + } + return ipAccess.setEnabled(id, input.enabled()); + } + + @DeleteMapping("/ip-rules/{id}") + public Map delete(@PathVariable Long id) { + ipAccess.deleteRule(id); + return Map.of("deleted", true); + } + + @GetMapping("/ip-observations") + public List> observations( + @RequestParam(defaultValue = "100") int limit) { + return ipAccess.listObservations(limit); + } + + private static Instant instant(String value) { + if (value == null || value.isBlank()) { + return null; + } + try { + return Instant.parse(value.trim()); + } catch (java.time.format.DateTimeParseException e) { + throw ApiException.badRequest( + "'expires_at' must be an ISO-8601 instant.", "expires_at"); + } + } + + 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"; + } +} 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 414c43a..8d33d97 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 @@ -39,6 +39,7 @@ public class AuthFilter extends OncePerRequestFilter { private final ApiKeyService apiKeys; private final RateLimitStore rateLimiter; + private final com.anindra.path.gateway.IpAccessService ipAccess; private final com.anindra.path.admin.TenancyService tenancy; private final AdminAuthLimiter adminAuthLimiter; private final ClientAuthLimiter clientAuthLimiter; @@ -64,6 +65,21 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } try { + // IP rules are enforced before authentication, so a blocked address cannot + // spend valid credentials. The actuator stays out of this: blocking it would + // break the orchestrator's health probe. + String ruleScope = path.startsWith("/admin") ? "admin" + : path.startsWith("/v1") ? "api" : null; + if (ruleScope != null) { + String address = clientAddress(request); + com.anindra.path.gateway.IpAccessService.Decision decision = ipAccess.check(address, ruleScope); + if (!decision.allowed()) { + throw new ApiException(403, "permission_error", decision.code(), decision.message()); + } + ipAccess.observe(address, ruleScope, request.getHeader("CF-IPCountry"), + request.getHeader("User-Agent")); + } + if (path.startsWith("/admin")) { requireAdmin(request); } else if (path.startsWith("/actuator")) { diff --git a/path-gateway/src/main/java/com/anindra/path/domain/IpObservation.java b/path-gateway/src/main/java/com/anindra/path/domain/IpObservation.java new file mode 100644 index 0000000..f2d8510 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/domain/IpObservation.java @@ -0,0 +1,39 @@ +package com.anindra.path.domain; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; + +/** Last-seen metadata for an address that reached the console or the API. */ +@Entity +@Table(name = "ip_observations") +@Getter +@Setter +@NoArgsConstructor +public class IpObservation { + + @Id + @Column(length = 64) + private String ip; + + @Column(nullable = false, length = 16) + private String scope; + + @Column(length = 16) + private String country; + + @Column(length = 255) + private String userAgent; + + @Column(nullable = false) + private Instant firstSeen = Instant.now(); + + @Column(nullable = false) + private Instant lastSeen = Instant.now(); + + @Column(nullable = false) + private long requests; +} diff --git a/path-gateway/src/main/java/com/anindra/path/domain/IpRule.java b/path-gateway/src/main/java/com/anindra/path/domain/IpRule.java new file mode 100644 index 0000000..4554bcb --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/domain/IpRule.java @@ -0,0 +1,47 @@ +package com.anindra.path.domain; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.Instant; + +/** An allow or deny rule for a CIDR, scoped to the console, the API, or both. */ +@Entity +@Table(name = "ip_rules") +@Getter +@Setter +@NoArgsConstructor +public class IpRule { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** IPv4/IPv6 address or CIDR. */ + @Column(nullable = false, length = 64) + private String cidr; + + /** admin, api or all. */ + @Column(nullable = false, length = 16) + private String scope; + + /** allow or deny. Deny wins when both match. */ + @Column(nullable = false, length = 8) + private String action; + + @Column(length = 255) + private String note; + + @Column(nullable = false) + private boolean enabled = true; + + private Instant expiresAt; + + @Column(length = 128) + private String createdBy; + + @Column(nullable = false) + private Instant createdAt = Instant.now(); +} 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 new file mode 100644 index 0000000..ec5980a --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/gateway/IpAccessService.java @@ -0,0 +1,370 @@ +package com.anindra.path.gateway; + +import com.anindra.path.admin.AuditService; +import com.anindra.path.api.ApiException; +import com.anindra.path.domain.IpObservation; +import com.anindra.path.domain.IpRule; +import com.anindra.path.repo.IpObservationRepository; +import com.anindra.path.repo.IpRuleRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.net.InetAddress; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; + +/** + * IP allow/deny rules for the console and the public API. + * + *

Deny wins over allow. Allow rules are optional: a scope only becomes an allowlist + * when at least one active allow rule exists, so an empty rule table never locks the + * operator out. Rules are cached for a few seconds; a create/delete invalidates this + * node immediately and other replicas pick it up within the TTL. + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class IpAccessService { + + public record Decision(boolean allowed, String code, String message) { + static Decision allow() { + return new Decision(true, null, null); + } + } + + private record CompiledRule(IpRule rule, Cidr cidr) { + } + + private record CachedRules(List rules, Instant loadedAt) { + } + + private static final Duration CACHE_TTL = Duration.ofSeconds(5); + private static final Duration OBSERVE_INTERVAL = Duration.ofMinutes(1); + private static final int MAX_NOTE = 255; + + private final IpRuleRepository rules; + private final IpObservationRepository observations; + private final AuditService audit; + private final AtomicReference cache = new AtomicReference<>(); + private final ConcurrentHashMap lastObserved = new ConcurrentHashMap<>(); + + // ------------------------------------------------------------------ request path + + public Decision check(String ip, String scope) { + if (ip == null || ip.isBlank() || !validLiteral(ip)) { + return Decision.allow(); + } + List active = activeRules(); + if (active.isEmpty()) { + return Decision.allow(); + } + InetAddress address; + try { + address = InetAddress.getByName(ip); + } catch (Exception e) { + return Decision.allow(); + } + + boolean hasAllow = false; + boolean matchedAllow = false; + for (CompiledRule compiled : active) { + String ruleScope = compiled.rule().getScope(); + if (!"all".equals(ruleScope) && !scope.equals(ruleScope)) { + continue; + } + if ("allow".equals(compiled.rule().getAction())) { + hasAllow = true; + } + if (!compiled.cidr().contains(address)) { + continue; + } + if ("deny".equals(compiled.rule().getAction())) { + return new Decision(false, "ip_blocked", + "This address is blocked by an administrator."); + } + matchedAllow = true; + } + if (hasAllow && !matchedAllow) { + return new Decision(false, "ip_not_allowed", + "This address is not on the console/API allowlist."); + } + return Decision.allow(); + } + + /** + * Records at most one observation per address per minute. A failure here must never + * turn a working request into a 500, so everything is swallowed after logging. + */ + public void observe(String ip, String scope, String country, String userAgent) { + if (ip == null || ip.isBlank()) { + return; + } + long now = System.currentTimeMillis(); + Long previous = lastObserved.put(ip, now); + if (previous != null && now - previous < OBSERVE_INTERVAL.toMillis()) { + return; + } + try { + IpObservation observation = observations.findById(ip).orElseGet(() -> { + IpObservation created = new IpObservation(); + created.setIp(ip); + created.setFirstSeen(Instant.ofEpochMilli(now)); + return created; + }); + observation.setScope(scope); + if (country != null && !country.isBlank()) { + observation.setCountry(truncate(country, 16)); + } + if (userAgent != null && !userAgent.isBlank()) { + observation.setUserAgent(truncate(userAgent, 255)); + } + observation.setLastSeen(Instant.ofEpochMilli(now)); + observation.setRequests(observation.getRequests() + 1); + observations.save(observation); + } catch (Exception e) { + log.debug("Could not record IP observation for {}: {}", ip, e.getMessage()); + } + } + + // ------------------------------------------------------------------ admin + + public List> listRules() { + List> out = new ArrayList<>(); + for (IpRule rule : rules.findAllByOrderByCreatedAtDesc()) { + Map row = new LinkedHashMap<>(); + row.put("id", rule.getId()); + row.put("cidr", rule.getCidr()); + row.put("scope", rule.getScope()); + row.put("action", rule.getAction()); + row.put("note", rule.getNote()); + row.put("enabled", rule.isEnabled()); + row.put("expires_at", rule.getExpiresAt() == null ? null : rule.getExpiresAt().toString()); + row.put("expired", rule.getExpiresAt() != null && rule.getExpiresAt().isBefore(Instant.now())); + row.put("created_by", rule.getCreatedBy()); + row.put("created_at", rule.getCreatedAt() == null ? null : rule.getCreatedAt().toString()); + out.add(row); + } + return out; + } + + @Transactional + public Map createRule(String cidr, String scope, String action, String note, + Instant expiresAt, String createdBy) { + Cidr parsed = Cidr.parse(cidr); + String normalizedScope = normalizeScope(scope); + String normalizedAction = normalizeAction(action); + if (expiresAt != null && expiresAt.isBefore(Instant.now())) { + throw ApiException.badRequest("'expires_at' must be in the future.", "expires_at"); + } + IpRule rule = new IpRule(); + rule.setCidr(parsed.text()); + rule.setScope(normalizedScope); + rule.setAction(normalizedAction); + rule.setNote(note == null ? null : truncate(note.trim(), MAX_NOTE)); + rule.setEnabled(true); + rule.setExpiresAt(expiresAt); + rule.setCreatedBy(createdBy == null ? "admin" : createdBy); + rule.setCreatedAt(Instant.now()); + rules.save(rule); + invalidate(); + audit.record("ip-rule.create", rule.getCidr(), Map.of( + "cidr", rule.getCidr(), "scope", rule.getScope(), "action", rule.getAction())); + return listRules().stream() + .filter(row -> rule.getId().equals(row.get("id"))) + .findFirst().orElseThrow(); + } + + @Transactional + public Map setEnabled(Long id, boolean enabled) { + IpRule rule = rules.findById(id) + .orElseThrow(() -> ApiException.notFound("No IP rule with id " + id, "ip_rule_not_found")); + rule.setEnabled(enabled); + rules.save(rule); + invalidate(); + audit.record(enabled ? "ip-rule.enable" : "ip-rule.disable", rule.getCidr(), + Map.of("cidr", rule.getCidr(), "enabled", enabled)); + return listRules().stream() + .filter(row -> rule.getId().equals(row.get("id"))) + .findFirst().orElseThrow(); + } + + @Transactional + public void deleteRule(Long id) { + IpRule rule = rules.findById(id) + .orElseThrow(() -> ApiException.notFound("No IP rule with id " + id, "ip_rule_not_found")); + rules.delete(rule); + invalidate(); + audit.record("ip-rule.delete", rule.getCidr(), Map.of("cidr", rule.getCidr())); + } + + public List> listObservations(int limit) { + int capped = Math.max(1, Math.min(limit, 500)); + List> out = new ArrayList<>(); + for (IpObservation observation : observations.findAllByOrderByLastSeenDesc(PageRequest.of(0, capped))) { + Decision decision = check(observation.getIp(), + "admin".equals(observation.getScope()) ? "admin" : "api"); + Map row = new LinkedHashMap<>(); + row.put("ip", observation.getIp()); + row.put("scope", observation.getScope()); + row.put("country", observation.getCountry()); + row.put("user_agent", observation.getUserAgent()); + row.put("first_seen", observation.getFirstSeen() == null ? null : observation.getFirstSeen().toString()); + row.put("last_seen", observation.getLastSeen() == null ? null : observation.getLastSeen().toString()); + row.put("requests", observation.getRequests()); + row.put("blocked", !decision.allowed()); + row.put("block_reason", decision.code()); + out.add(row); + } + return out; + } + + // ------------------------------------------------------------------ internals + + private List activeRules() { + CachedRules cached = cache.get(); + if (cached != null && cached.loadedAt().plus(CACHE_TTL).isAfter(Instant.now())) { + return cached.rules(); + } + synchronized (this) { + cached = cache.get(); + if (cached != null && cached.loadedAt().plus(CACHE_TTL).isAfter(Instant.now())) { + return cached.rules(); + } + List compiled = new ArrayList<>(); + Instant now = Instant.now(); + for (IpRule rule : rules.findByEnabledTrue()) { + if (rule.getExpiresAt() != null && rule.getExpiresAt().isBefore(now)) { + continue; + } + try { + compiled.add(new CompiledRule(rule, Cidr.parse(rule.getCidr()))); + } catch (RuntimeException e) { + log.warn("Ignoring invalid IP rule {} '{}': {}", rule.getId(), rule.getCidr(), e.getMessage()); + } + } + cache.set(new CachedRules(List.copyOf(compiled), now)); + return compiled; + } + } + + /** Drop the cache after a rule change; also used by tests. */ + public void invalidate() { + cache.set(null); + lastObserved.clear(); + } + + private static String normalizeScope(String scope) { + String value = scope == null ? "" : scope.trim().toLowerCase(); + if (!value.equals("admin") && !value.equals("api") && !value.equals("all")) { + throw ApiException.badRequest("'scope' must be admin, api or all.", "scope"); + } + return value; + } + + private static String normalizeAction(String action) { + String value = action == null ? "" : action.trim().toLowerCase(); + if (!value.equals("allow") && !value.equals("deny")) { + throw ApiException.badRequest("'action' must be allow or deny.", "action"); + } + return value; + } + + private static String truncate(String value, int max) { + return value.length() <= max ? value : value.substring(0, max); + } + + private static boolean validLiteral(String value) { + return value.matches("[0-9a-fA-F:.]+"); + } + + /** 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; + + private Cidr(String text, byte[] network, int prefix) { + this.text = text; + this.network = network; + this.prefix = prefix; + } + + static Cidr parse(String value) { + if (value == null || value.isBlank()) { + throw ApiException.badRequest("'cidr' is required.", "cidr"); + } + String raw = value.trim(); + String[] parts = raw.split("/", -1); + if (parts.length > 2 || parts[0].isBlank() || !validLiteral(parts[0])) { + throw ApiException.badRequest( + "'cidr' must be an IPv4/IPv6 address or CIDR, e.g. 203.0.113.0/24.", "cidr"); + } + InetAddress address; + try { + address = InetAddress.getByName(parts[0]); + } catch (Exception e) { + throw ApiException.badRequest("'cidr' is not a valid IP address.", "cidr"); + } + byte[] bytes = address.getAddress(); + int max = bytes.length * 8; + int prefix = max; + if (parts.length == 2) { + try { + prefix = Integer.parseInt(parts[1]); + } catch (NumberFormatException e) { + throw ApiException.badRequest("'cidr' prefix must be a number.", "cidr"); + } + } + if (prefix < 1 || prefix > max) { + throw ApiException.badRequest( + "'cidr' prefix must be between 1 and " + max + ".", "cidr"); + } + byte[] network = bytes.clone(); + for (int i = 0; i < network.length; i++) { + int bits = prefix - i * 8; + if (bits <= 0) { + network[i] = 0; + } else if (bits < 8) { + network[i] = (byte) (network[i] & (0xFF << (8 - bits))); + } + } + return new Cidr(raw, network, prefix); + } + + String text() { + return text; + } + + boolean contains(InetAddress address) { + byte[] candidate = address.getAddress(); + if (candidate.length != network.length) { + return false; + } + int full = prefix / 8; + int remainder = prefix % 8; + for (int i = 0; i < full; i++) { + if (candidate[i] != network[i]) { + return false; + } + } + if (remainder > 0) { + int mask = 0xFF << (8 - remainder); + if ((candidate[full] & mask) != (network[full] & mask)) { + return false; + } + } + return true; + } + } +} diff --git a/path-gateway/src/main/java/com/anindra/path/repo/IpObservationRepository.java b/path-gateway/src/main/java/com/anindra/path/repo/IpObservationRepository.java new file mode 100644 index 0000000..0c47f00 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/repo/IpObservationRepository.java @@ -0,0 +1,12 @@ +package com.anindra.path.repo; + +import com.anindra.path.domain.IpObservation; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface IpObservationRepository extends JpaRepository { + + List findAllByOrderByLastSeenDesc(Pageable pageable); +} diff --git a/path-gateway/src/main/java/com/anindra/path/repo/IpRuleRepository.java b/path-gateway/src/main/java/com/anindra/path/repo/IpRuleRepository.java new file mode 100644 index 0000000..fdbace5 --- /dev/null +++ b/path-gateway/src/main/java/com/anindra/path/repo/IpRuleRepository.java @@ -0,0 +1,13 @@ +package com.anindra.path.repo; + +import com.anindra.path.domain.IpRule; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface IpRuleRepository extends JpaRepository { + + List findAllByOrderByCreatedAtDesc(); + + List findByEnabledTrue(); +} diff --git a/path-gateway/src/main/resources/db/migration/V25__ip_access.sql b/path-gateway/src/main/resources/db/migration/V25__ip_access.sql new file mode 100644 index 0000000..407ffab --- /dev/null +++ b/path-gateway/src/main/resources/db/migration/V25__ip_access.sql @@ -0,0 +1,30 @@ +-- IP access rules and observations for the console and the public API. +-- Deny wins; allow rules form an optional allowlist per scope. + +create table ip_rules ( + id bigint generated by default as identity, + cidr varchar(64) not null, + scope varchar(16) not null, + action varchar(8) not null, + note varchar(255), + enabled boolean not null default true, + expires_at timestamp(6) with time zone, + created_by varchar(128), + created_at timestamp(6) with time zone not null, + primary key (id) +); + +create index ix_ip_rules_scope on ip_rules (scope, enabled); + +create table ip_observations ( + ip varchar(64) not null, + scope varchar(16) not null, + country varchar(16), + user_agent varchar(255), + first_seen timestamp(6) with time zone not null, + last_seen timestamp(6) with time zone not null, + requests bigint not null default 0, + primary key (ip) +); + +create index ix_ip_observations_last_seen on ip_observations (last_seen); diff --git a/path-gateway/src/test/java/com/anindra/path/IpAccessFilterTest.java b/path-gateway/src/test/java/com/anindra/path/IpAccessFilterTest.java new file mode 100644 index 0000000..fa230d3 --- /dev/null +++ b/path-gateway/src/test/java/com/anindra/path/IpAccessFilterTest.java @@ -0,0 +1,90 @@ +package com.anindra.path; + +import com.anindra.path.gateway.IpAccessService; +import com.anindra.path.repo.IpObservationRepository; +import com.anindra.path.repo.IpRuleRepository; +import org.junit.jupiter.api.AfterEach; +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.assertj.core.api.Assertions.assertThat; +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; + +/** Rules are checked before authentication, so a blocked address never reaches a credential. */ +@SpringBootTest(properties = { + "spring.datasource.url=jdbc:h2:mem:ipaccesstest;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 IpAccessFilterTest { + + private static final String ADMIN = "test-admin"; + private static final RequestPostProcessor ADDRESS = + request -> { request.setRemoteAddr("203.0.113.9"); return request; }; + + @Autowired + private MockMvc mvc; + + @Autowired + private IpAccessService ipAccess; + + @Autowired + private IpRuleRepository rules; + + @Autowired + private IpObservationRepository observations; + + @BeforeEach + @AfterEach + void clean() { + rules.deleteAll(); + observations.deleteAll(); + ipAccess.invalidate(); + } + + @Test + void aDenyRuleBlocksTheConsoleBeforeTheTokenIsChecked() throws Exception { + ipAccess.createRule("203.0.113.0/24", "admin", "deny", "test", null, "test"); + + mvc.perform(get("/admin/settings").with(ADDRESS).header("X-Admin-Token", ADMIN)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error.code").value("ip_blocked")); + } + + @Test + void anAllowlistBlocksEveryOtherAddress() throws Exception { + ipAccess.createRule("10.0.0.0/8", "admin", "allow", "office", null, "test"); + + mvc.perform(get("/admin/settings").with(ADDRESS).header("X-Admin-Token", ADMIN)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.error.code").value("ip_not_allowed")); + } + + @Test + void anAllowedAddressReachesTheApiAndStillNeedsAKey() throws Exception { + ipAccess.createRule("203.0.113.0/24", "api", "allow", "test", null, "test"); + + mvc.perform(get("/v1/models").with(ADDRESS).header("Authorization", "Bearer nope")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.error.code").value("invalid_api_key")); + } + + @Test + void everyRequestRecordsTheAddressOnce() throws Exception { + mvc.perform(get("/admin/settings").with(ADDRESS).header("X-Admin-Token", ADMIN)) + .andExpect(status().isOk()); + + assertThat(observations.findById("203.0.113.9")).isPresent(); + assertThat(observations.findById("203.0.113.9").orElseThrow().getRequests()).isEqualTo(1); + } +} diff --git a/path-gateway/src/test/java/com/anindra/path/gateway/IpAccessServiceTest.java b/path-gateway/src/test/java/com/anindra/path/gateway/IpAccessServiceTest.java new file mode 100644 index 0000000..7339253 --- /dev/null +++ b/path-gateway/src/test/java/com/anindra/path/gateway/IpAccessServiceTest.java @@ -0,0 +1,108 @@ +package com.anindra.path.gateway; + +import com.anindra.path.admin.AuditService; +import com.anindra.path.api.ApiException; +import com.anindra.path.domain.IpRule; +import com.anindra.path.repo.IpObservationRepository; +import com.anindra.path.repo.IpRuleRepository; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.net.InetAddress; +import java.time.Instant; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +class IpAccessServiceTest { + + private final IpRuleRepository rules = Mockito.mock(IpRuleRepository.class); + private final IpObservationRepository observations = Mockito.mock(IpObservationRepository.class); + private final IpAccessService service = new IpAccessService( + rules, observations, Mockito.mock(AuditService.class)); + + private static IpRule rule(String cidr, String scope, String action, Instant expires) { + IpRule rule = new IpRule(); + rule.setCidr(cidr); + rule.setScope(scope); + rule.setAction(action); + rule.setEnabled(true); + rule.setExpiresAt(expires); + return rule; + } + + @Test + void aDenyRuleBlocksAMatchingAddress() { + when(rules.findByEnabledTrue()).thenReturn(List.of(rule("203.0.113.0/24", "all", "deny", null))); + + IpAccessService.Decision decision = service.check("203.0.113.9", "api"); + + assertThat(decision.allowed()).isFalse(); + assertThat(decision.code()).isEqualTo("ip_blocked"); + } + + @Test + void anAllowRuleTurnsItsScopeIntoAnAllowlist() { + when(rules.findByEnabledTrue()).thenReturn(List.of(rule("10.0.0.0/8", "api", "allow", null))); + + assertThat(service.check("10.2.3.4", "api").allowed()).isTrue(); + IpAccessService.Decision outside = service.check("203.0.113.9", "api"); + assertThat(outside.allowed()).isFalse(); + assertThat(outside.code()).isEqualTo("ip_not_allowed"); + } + + @Test + void theAllowlistDoesNotLeakAcrossScopes() { + when(rules.findByEnabledTrue()).thenReturn(List.of(rule("10.0.0.0/8", "admin", "allow", null))); + + assertThat(service.check("203.0.113.9", "api").allowed()).isTrue(); + assertThat(service.check("203.0.113.9", "admin").allowed()).isFalse(); + } + + @Test + void denyWinsWhenAllowAndDenyBothMatch() { + when(rules.findByEnabledTrue()).thenReturn(List.of( + rule("10.0.0.0/8", "all", "allow", null), + rule("10.1.0.0/16", "all", "deny", null))); + + assertThat(service.check("10.1.2.3", "api").allowed()).isFalse(); + assertThat(service.check("10.2.3.4", "api").allowed()).isTrue(); + } + + @Test + void anExpiredRuleIsIgnored() { + when(rules.findByEnabledTrue()).thenReturn(List.of( + rule("203.0.113.0/24", "api", "deny", Instant.now().minusSeconds(60)))); + + assertThat(service.check("203.0.113.9", "api").allowed()).isTrue(); + } + + @Test + void cidrMatchingHandlesV4AndV6() throws Exception { + IpAccessService.Cidr v4 = IpAccessService.Cidr.parse("203.0.113.0/24"); + assertThat(v4.contains(InetAddress.getByName("203.0.113.9"))).isTrue(); + assertThat(v4.contains(InetAddress.getByName("203.0.114.9"))).isFalse(); + + IpAccessService.Cidr v6 = IpAccessService.Cidr.parse("2001:db8::/32"); + assertThat(v6.contains(InetAddress.getByName("2001:db8::1"))).isTrue(); + assertThat(v6.contains(InetAddress.getByName("2001:db9::1"))).isFalse(); + } + + @Test + void aPrefixOfZeroIsRejected() { + assertThatThrownBy(() -> IpAccessService.Cidr.parse("0.0.0.0/0")) + .isInstanceOf(ApiException.class); + assertThatThrownBy(() -> IpAccessService.Cidr.parse("::/0")) + .isInstanceOf(ApiException.class); + } + + @Test + void createRejectsAnUnknownScopeOrAction() { + assertThatThrownBy(() -> service.createRule("10.0.0.0/8", "nope", "deny", null, null, "test")) + .isInstanceOf(ApiException.class); + assertThatThrownBy(() -> service.createRule("10.0.0.0/8", "api", "nope", null, null, "test")) + .isInstanceOf(ApiException.class); + } +} diff --git a/path-spring-ai/pom.xml b/path-spring-ai/pom.xml index 70e8f00..bcfe0c9 100644 --- a/path-spring-ai/pom.xml +++ b/path-spring-ai/pom.xml @@ -7,7 +7,7 @@ io.github.an1ndra path-parent - 0.2.15 + 0.2.16 ../pom.xml diff --git a/pom.xml b/pom.xml index 8d71803..a4bbc3e 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ io.github.an1ndra path-parent - 0.2.15 + 0.2.16 pom path-parent Build parent for Path, the provider-agnostic LLM gateway, and its Spring AI adapter