# How CoSec Handles IP-Based Regional Access Management: A Technical Deep Dive

> Discover how CoSec manages IP-based regional access. Learn how it enriches requests with geo data and enforces location-based access controls using the ipRegion attribute.

- Repository: [Ahoo Wang/cosec](https://github.com/ahoo-wang/cosec)
- Tags: technical-deep-dive
- Published: 2026-02-23

---

**CoSec enriches every incoming request with geographic region data derived from the client’s IP address using the embedded ip2region database, then evaluates policy conditions against the `ipRegion` attribute to enforce location-based access controls.**

CoSec (Context Security) is an open-source security framework designed for cloud-native applications. Understanding how it implements **IP-based regional access management** reveals a sophisticated, data-driven approach to geographic policy enforcement that requires no hard-coded location logic.

## IP-to-Region Lookup Architecture

The foundation of CoSec’s regional access control lies in the `Ip2RegionRequestAttributesAppender` class, which automatically enriches request metadata with geographic information before policy evaluation begins.

### Loading the ip2region Database

At startup, the appender initializes the `ip2region.xdb` database—a compact binary file containing IP-to-region mappings. This file resides in `cosec-ip2region/src/main/resources/ip2region.xdb` and is loaded into memory to ensure high-performance lookups without external API dependencies.

### Enriching Requests with Geographic Attributes

When a request arrives, the appender extracts the client IP from `request.remoteIp` and queries the database:

```kotlin
// From Ip2RegionRequestAttributesAppender.kt
val region = searcher.search(request.remoteIp)
request.setAttribute(REQUEST_ATTRIBUTES_IP_REGION_KEY, region)

```

The resulting region string (formatted as `国家|区域|省份|城市|ISP`, e.g., `CN|北京|北京|电信`) is stored in the request’s attribute map under the key **`ipRegion`**. This attribute becomes available to all downstream policy evaluation components.

## Policy-Based Regional Access Control

CoSec’s policy engine evaluates the enriched `ipRegion` attribute against declarative rules defined in JSON or YAML policy files.

### Defining Region Conditions in Policy Files

The policy condition schema ([`condition.schema.json`](https://github.com/ahoo-wang/cosec/blob/main/condition.schema.json)) supports **attribute-based conditions** that reference the `ipRegion` key. Administrators define geographic restrictions using standard condition syntax:

```json
{
  "name": "north-america-only",
  "description": "Restrict access to US and Canada",
  "conditions": [
    {
      "type": "attribute",
      "key": "ipRegion",
      "operator": "in",
      "values": ["US|*", "CA|*"]
    }
  ],
  "actions": ["ALLOW"]
}

```

### Supported Operators for IP Region Matching

The policy engine supports multiple comparison operators for geographic data:

- **`equals`** – Exact match on the full region string
- **`in`** – Membership in a list of allowed regions (supports wildcards)
- **`startsWith`** – Prefix matching for broad geographic blocks (e.g., `CN|` for all China regions)

Wildcards (`*`) in condition values enable flexible matching without specifying complete region strings, allowing policies like `US|California|*` to match any city in California.

## Integration with Web Frameworks

CoSec’s regional access management integrates seamlessly with popular Java web frameworks through filter chains and gateway components.

### Servlet Filter Integration (Web MVC)

In the Web MVC module (`cosec-webmvc`), the `AuthorizationFilter` orchestrates the request enrichment and policy evaluation pipeline:

```kotlin
// Simplified flow from AuthorizationFilter.kt
override fun doFilter(request, response, chain) {
    val cosecRequest = request.toCoSecRequest()
    
    // Ip2RegionRequestAttributesAppender runs here via ServiceLoader
    requestContext.appendAttributes(cosecRequest)
    
    val decision = authorizationEngine.authorize(cosecRequest)
    if (decision.isAllow()) {
        chain.doFilter(request, response)
    } else {
        response.sendError(403)
    }
}

```

The `Ip2RegionRequestAttributesAppender` is automatically discovered via Java’s **ServiceLoader** mechanism, requiring only a registration file in `META-INF/services/me.ahoo.cosec.context.request.RequestAttributesAppender`.

### Gateway Server Implementation

For microservice architectures, the Gateway module (`cosec-gateway-server`) applies the same regional access controls at the edge. The enriched `ipRegion` attribute flows through the gateway’s reactive pipeline, allowing centralized geographic policy enforcement before requests reach backend services.

## Configuration Examples

### Registering the IP Region Appender

Create the ServiceLoader registration file to enable automatic discovery:

```text

# File: src/main/resources/META-INF/services/me.ahoo.cosec.context.request.RequestAttributesAppender

me.ahoo.cosec.ip2region.Ip2RegionRequestAttributesAppender

```

### Blocking Specific Countries

Deny access from specific regions while allowing all others:

```json
{
  "name": "block-sanctioned-regions",
  "conditions": [
    {
      "type": "attribute",
      "key": "ipRegion",
      "operator": "in",
      "values": ["CN|*", "RU|*", "KP|*"]
    }
  ],
  "actions": ["DENY"]
}

```

## Summary

CoSec implements **IP-based regional access management** through a three-stage pipeline:

- **IP Resolution**: The `Ip2RegionRequestAttributesAppender` queries the embedded `ip2region.xdb` database to resolve client IPs into geographic region strings.
- **Attribute Enrichment**: Region data is injected into request attributes under the `ipRegion` key via the ServiceLoader-discovered appender mechanism.
- **Policy Enforcement**: The authorization engine evaluates region-aware conditions using operators like `in`, `equals`, and `startsWith` against the enriched request attributes.

This architecture decouples geographic logic from application code, enabling declarative, fine-grained regional access control through JSON/YAML policy configuration.

## Frequently Asked Questions

### How does CoSec determine the geographic region from an IP address?

CoSec uses the `Ip2RegionRequestAttributesAppender` class to query an embedded `ip2region.xdb` database file. This database maps IP addresses to region strings in the format `国家|区域|省份|城市|ISP` (e.g., `US|California|San Francisco|Telecom`). The lookup happens at request time and adds zero external API dependencies.

### Can I use wildcards in IP region policy conditions?

Yes. CoSec’s policy engine supports wildcard patterns (using `*`) in condition values for the `ipRegion` attribute. This allows broad geographic matching such as `US|*` (any location in the United States) or `CN|北京|*` (any district in Beijing) without specifying complete region strings.

### Where is the ip2region database file located in the CoSec repository?

The binary database file is located at `cosec-ip2region/src/main/resources/ip2region.xdb` in the repository. This file is loaded by the `Ip2RegionRequestAttributesAppender` at application startup to enable fast in-memory IP-to-region lookups.

### How do I block specific countries while allowing others?

Create a policy condition using the `attribute` type with the `ipRegion` key and the `in` operator. List the country codes you want to block (e.g., `CN|*`, `RU|*`) as values, and set the action to `DENY`. All requests from IPs resolving to those regions will be rejected, while traffic from other regions proceeds to subsequent policy evaluations.