# Story 1.8: API Gateway Implementation

## Metadata
- **Story ID**: 1.8
- **Title**: API Gateway Implementation
- **Epic**: 1 - Core Kernel & Infrastructure
- **Status**: In Progress
- **Priority**: High
- **Estimated Time**: 8-10 hours
- **Dependencies**: 1.1, 1.5, 1.7

## Goal
Implement API Gateway as core infrastructure component that routes all external traffic to backend services via service discovery (Consul). Gateway handles authentication, rate limiting, CORS, and request transformation.

## Description
This story implements the API Gateway service that serves as the single entry point for all external traffic. The gateway routes requests to backend services via Consul service discovery, validates JWT tokens via Auth Service, checks permissions via Authz Service, and handles rate limiting and CORS.

## Deliverables

### 1. API Gateway Service Entry Point (`cmd/api-gateway/main.go`)
- Service entry point for API Gateway
- Bootstrap with core kernel services
- Register with Consul service registry
- Start HTTP server

### 2. Gateway Implementation (`services/gateway/internal/`)
- **Routing Engine** (`router.go`):
  - Route configuration from YAML
  - Path matching and service routing
  - Service discovery integration (Consul)
  - Load balancing across service instances
  
- **Authentication Middleware** (`auth.go`):
  - JWT token extraction from headers
  - Token validation via Auth Service client
  - User context injection
  
- **Authorization Middleware** (`authz.go`):
  - Permission checking via Authz Service client (optional, for route-level auth)
  - Route-based permission configuration
  
- **Rate Limiting** (`ratelimit.go`):
  - Per-user rate limiting (via user ID from JWT)
  - Per-IP rate limiting
  - Redis-backed rate limiting state
  - Configurable limits per route
  
- **CORS Support** (`cors.go`):
  - Configurable CORS headers
  - Preflight request handling
  
- **Request/Response Transformation** (`transform.go`):
  - Request modification before forwarding
  - Response modification before returning
  - Header manipulation

### 3. Gateway Configuration (`config/default.yaml`)
```yaml
gateway:
  port: 8080
  routes:
    - path: /api/v1/auth/**
      service: auth-service
      auth_required: false
      rate_limit:
        per_user: 100/minute
        per_ip: 1000/minute
    - path: /api/v1/users/**
      service: identity-service
      auth_required: true
      permission: user.read
      rate_limit:
        per_user: 50/minute
    - path: /api/v1/blog/**
      service: blog-service
      auth_required: true
      permission: blog.post.read
  cors:
    allowed_origins: ["*"]
    allowed_methods: ["GET", "POST", "PUT", "DELETE"]
    allowed_headers: ["Authorization", "Content-Type"]
  service_discovery:
    type: consul
    consul:
      address: "localhost:8500"
```

### 4. Service Discovery Integration
- Consul integration for service discovery
- Dynamic service endpoint resolution
- Health check filtering (only route to healthy services)
- Load balancing across service instances

### 5. Health Check Endpoint
- `GET /healthz` - Gateway health check
- `GET /ready` - Gateway readiness (checks service registry connectivity)

## Implementation Steps

1. **Create Service Entry Point**
   - Create `cmd/api-gateway/main.go`
   - Bootstrap with core kernel
   - Register with Consul

2. **Implement Routing Engine**
   - Create `services/gateway/internal/router.go`
   - Implement route matching
   - Integrate with Consul service discovery
   - Implement load balancing

3. **Implement Authentication**
   - Create `services/gateway/internal/auth.go`
   - JWT token extraction
   - Token validation via Auth Service client
   - User context injection

4. **Implement Rate Limiting**
   - Create `services/gateway/internal/ratelimit.go`
   - Redis integration
   - Per-user and per-IP limiting

5. **Implement CORS**
   - Create `services/gateway/internal/cors.go`
   - Configurable CORS support

6. **Add Configuration**
   - Update `config/default.yaml`
   - Add gateway configuration

7. **Test Gateway**
   - Test routing to backend services
   - Test authentication
   - Test rate limiting
   - Test service discovery

## Acceptance Criteria
- [x] API Gateway service is independently deployable
- [x] Gateway routes requests to backend services correctly
- [x] JWT validation works via Auth Service client
- [x] Rate limiting works correctly (per-user and per-IP)
- [x] CORS is configurable and works
- [x] Service discovery integration works (Consul)
- [x] Gateway has health check endpoint
- [x] All external traffic goes through gateway
- [x] Gateway registers with Consul
- [x] Load balancing works across service instances

## Related ADRs
- [ADR-0032: API Gateway Strategy](../../adr/0032-api-gateway-strategy.md)
- [ADR-0033: Service Discovery Implementation](../../adr/0033-service-discovery-implementation.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)

## Implementation Notes
- Gateway is a core infrastructure component, not optional
- All external traffic must go through gateway
- Gateway uses service clients for backend communication
- Service discovery via Consul is required
- Rate limiting state is stored in Redis
- Gateway should be horizontally scalable

## Testing
```bash
# Test gateway startup
go run cmd/api-gateway/main.go

# Test routing
curl http://localhost:8080/api/v1/auth/login

# Test with Consul
docker-compose up consul
go test ./services/gateway/... -tags=integration
```

## Files to Create/Modify
- `cmd/api-gateway/main.go` - Gateway service entry point
- `services/gateway/internal/router.go` - Routing engine
- `services/gateway/internal/auth.go` - Authentication middleware
- `services/gateway/internal/authz.go` - Authorization middleware
- `services/gateway/internal/ratelimit.go` - Rate limiting
- `services/gateway/internal/cors.go` - CORS support
- `services/gateway/internal/transform.go` - Request/response transformation
- `config/default.yaml` - Add gateway configuration

