# Issue #86: [FED-003] Authentik OIDC Integration - Security Fixes

## Code Review Findings

The initial implementation (commit 6878d57) was high quality but included placeholder implementations for security-critical functions. This document tracks the completion of those implementations.

## Security-Critical Issues

### 1. JWT Token Validation (CRITICAL)
**Problem**: `validateToken()` always returns `valid: false`
**Risk**: Cannot verify authenticity of federated tokens
**Solution**: Implement proper JWT validation with signature verification

### 2. OIDC Discovery (CRITICAL)
**Problem**: `generateAuthUrl()` returns hardcoded placeholder URL
**Risk**: Cannot initiate real federated authentication flows
**Solution**: Implement OIDC discovery and proper authorization URL generation

## Implementation Plan

### 1. Add Dependencies
- [x] Add `jose` library for JWT handling (industry-standard, secure)

### 2. Implement JWT Validation
- [ ] Fetch OIDC discovery metadata from issuer
- [ ] Cache JWKS (JSON Web Key Set) for performance
- [ ] Verify JWT signature using remote public key
- [ ] Validate standard claims (iss, aud, exp, iat)
- [ ] Extract user identity from token
- [ ] Handle expired tokens gracefully
- [ ] Return proper validation results

### 3. Implement OIDC Discovery
- [ ] Fetch `.well-known/openid-configuration` from remote instance
- [ ] Cache discovery metadata
- [ ] Generate proper OAuth2 authorization URL
- [ ] Add PKCE (code_challenge, code_verifier) for security
- [ ] Include proper state parameter for CSRF protection
- [ ] Support standard OIDC scopes (openid, profile, email)

### 4. Update Tests
- [ ] Replace mock-based tests with real behavior tests
- [ ] Test valid JWT validation
- [ ] Test expired/invalid token rejection
- [ ] Test OIDC discovery and URL generation
- [ ] Test PKCE parameter generation
- [ ] Maintain 85%+ test coverage

### 5. Security Considerations
- Cache JWKS to avoid excessive network calls
- Validate token expiration strictly
- Use PKCE to prevent authorization code interception
- Validate issuer matches expected remote instance
- Validate audience matches our instance ID
- Handle network failures gracefully

## Implementation Notes

**PKCE Flow**:
1. Generate random code_verifier (base64url-encoded random bytes)
2. Generate code_challenge = base64url(SHA256(code_verifier))
3. Store code_verifier in session/database
4. Include code_challenge in authorization URL
5. Send code_verifier in token exchange

**JWT Validation Flow**:
1. Parse JWT without verification to get header
2. Fetch JWKS from issuer (cache for 1 hour)
3. Find matching key by kid (key ID)
4. Verify signature using public key
5. Validate claims (iss, aud, exp, iat, nbf)
6. Extract user identity (sub, email, etc.)

## Progress

- [x] Add jose library
- [ ] Implement validateToken()
- [ ] Implement generateAuthUrl()
- [ ] Add PKCE support
- [ ] Update tests
- [ ] Verify all tests pass
- [ ] Commit security fixes
