# Story 2.1: Auth Service - JWT Authentication

## Metadata
- **Story ID**: 2.1
- **Title**: Auth Service - JWT Authentication
- **Epic**: 2 - Core Services (Authentication & Authorization)
- **Status**: Pending
- **Priority**: High
- **Estimated Time**: 8-10 hours
- **Dependencies**: 1.1, 1.2, 1.5, 1.7

## Goal
Implement Auth Service as an independent microservice with JWT token generation/validation. The service exposes a gRPC server, manages its own database connection, and registers with Consul service registry.

## Description
This story implements the Auth Service as a separate, independently deployable microservice. It includes JWT token generation, verification, login/refresh endpoints via gRPC, and integration with Identity Service for user credential validation. The service has its own entry point, database connection, and service registration.

## Deliverables

### 1. Service Entry Point (`cmd/auth-service/main.go`)
- Independent service entry point
- Bootstrap with core kernel services
- Register with Consul service registry
- Start gRPC server on configured port (default: 8081)
- Graceful shutdown with service deregistration

### 2. gRPC Service Definition (`api/proto/auth.proto`)
- `LoginRequest` / `LoginResponse` - User login
- `RefreshTokenRequest` / `RefreshTokenResponse` - Token refresh
- `ValidateTokenRequest` / `ValidateTokenResponse` - Token validation
- `AuthService` gRPC service definition

### 3. gRPC Server Implementation (`services/auth/internal/api/server.go`)
- gRPC server implementation
- Handler for Login, RefreshToken, ValidateToken
- Integration with Auth Service business logic

### 4. Auth Service Implementation (`services/auth/internal/service/auth_service.go`)
- JWT token generation (access tokens: 15 min, refresh tokens: 7 days)
- Token signature verification (HMAC or RSA)
- Token expiration validation
- Claims extraction and validation
- Uses `IdentityServiceClient` for credential validation

### 5. Database Connection and Schema (`services/auth/ent/schema/`)
- Auth Service database connection (schema: `auth`)
- Refresh token storage schema (if storing refresh tokens in DB)
- Migration support
- Per-service connection pool

### 6. Service Client Integration
- Uses `IdentityServiceClient` to validate user credentials
- Uses `AuditServiceClient` to log authentication events
- Service discovery via Consul

### 7. Service Registration
- Register with Consul on startup
- Health check endpoint for Consul
- Service metadata (name: `auth-service`, port: 8081)
- Deregister on shutdown

## Implementation Steps

1. **Create Service Entry Point**
   - Create `cmd/auth-service/main.go`
   - Bootstrap with core kernel (config, logger, DI, health, metrics)
   - Create database connection (auth schema)
   - Register with Consul service registry
   - Start gRPC server

2. **Define gRPC Service**
   - Create `api/proto/auth.proto`
   - Define Login, RefreshToken, ValidateToken RPCs
   - Generate Go code from proto

3. **Implement Auth Service**
   - Create `services/auth/internal/service/auth_service.go`
   - Implement JWT token generation/validation
   - Integrate with IdentityServiceClient for credential validation
   - Integrate with AuditServiceClient for logging

4. **Implement gRPC Server**
   - Create `services/auth/internal/api/server.go`
   - Implement gRPC handlers
   - Wire up service logic

5. **Database Setup**
   - Create `services/auth/ent/schema/` if storing refresh tokens
   - Set up migrations
   - Configure per-service connection pool

6. **Service Registration**
   - Register with Consul on startup
   - Set up health check endpoint
   - Handle graceful shutdown

## Acceptance Criteria
- [x] Auth Service is independently deployable
- [x] Service entry point exists at `cmd/auth-service/main.go`
- [x] Service registers with Consul on startup
- [x] gRPC server starts on configured port (8081)
- [x] Login RPC validates credentials via IdentityServiceClient
- [x] Login RPC returns access and refresh tokens
- [x] RefreshToken RPC issues new access tokens
- [x] ValidateToken RPC validates token signatures and expiration
- [x] Service has its own database connection (auth schema)
- [x] Service uses AuditServiceClient for logging
- [x] Service can be discovered by API Gateway via Consul
- [x] Health check endpoint works for Consul

## Related ADRs
- [ADR-0017: JWT Token Strategy](../../adr/0017-jwt-token-strategy.md)
- [ADR-0029: Microservices Architecture](../../adr/0029-microservices-architecture.md)
- [ADR-0030: Service Communication Strategy](../../adr/0030-service-communication-strategy.md)

## Implementation Notes
- Use JWT v5 library
- Support both HMAC and RSA signing
- Token secrets should be configurable
- Consider token blacklisting for logout (future enhancement)
- Refresh tokens should be stored securely (database or cache)

## Testing
```bash
# Test Auth Service
go test ./services/auth/...

# Test service startup
go run cmd/auth-service/main.go

# Test gRPC service (via grpcurl or client)
grpcurl -plaintext localhost:8081 list
grpcurl -plaintext -d '{"email":"user@example.com","password":"password"}' \
  localhost:8081 auth.AuthService/Login

# Test service discovery
# Verify service is registered in Consul
consul catalog services
consul catalog service auth-service
```

## Files to Create/Modify
- `cmd/auth-service/main.go` - Service entry point
- `api/proto/auth.proto` - gRPC service definition
- `services/auth/internal/api/server.go` - gRPC server implementation
- `services/auth/internal/service/auth_service.go` - Auth service logic
- `services/auth/ent/schema/` - Database schema (if storing refresh tokens)
- `config/default.yaml` - Add auth service configuration

