jwt_auth_cognito 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: dd002e4c7b2a20d24633f29af47544d8fe6b15eeba7e35fbe52b8152a09228ad
4
+ data.tar.gz: 38f681ce7fe3d9d9d7b6a7c95384ec2637f88f56b0cb9d794b6e945705b75dbb
5
+ SHA512:
6
+ metadata.gz: 226064e684251b7e740d1c016ddd6f751d53bc3a99b6c4ae28d12faae19e91a53042cf6d4e8413d5fc79f3c3783bd83078e8eda7d8236755227379e276b1b8dc
7
+ data.tar.gz: b94a68ee2b52cbffb93e95d73a56c46743954edb006de458366d0bc826e9e82b5dc684deab7b26567781992f3054287cbfa5c972cbc928511f1e6fa9d1c44862
data/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2024-06-16
11
+
12
+ ### Added
13
+ - Initial release of jwt_auth_cognito gem
14
+ - JWT token validation with AWS Cognito JWKS support
15
+ - Redis-based token blacklisting functionality
16
+ - Support for both secure (JWKS) and basic (development) validation modes
17
+ - Access token and ID token specific validation
18
+ - Batch token validation
19
+ - User token management and invalidation
20
+ - Comprehensive error handling with specific error types
21
+ - Configurable JWKS caching
22
+ - Graceful degradation when Redis is unavailable
23
+ - Full test suite with RSpec
24
+ - Comprehensive documentation and usage examples
25
+
26
+ ### Features
27
+ - Offline JWT validation without AWS API calls
28
+ - Automatic public key retrieval and caching
29
+ - Token revocation and blacklist management
30
+ - Multi-token validation support
31
+ - Custom claim validation options
32
+ - Rails integration examples
33
+ - Production-ready with security best practices
data/CLAUDE.md ADDED
@@ -0,0 +1,135 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Common Commands
6
+
7
+ ### Development and Testing
8
+ ```bash
9
+ # Install dependencies
10
+ bundle install
11
+
12
+ # Run tests
13
+ bundle exec rspec
14
+
15
+ # Run linting
16
+ bundle exec rubocop
17
+
18
+ # Run both tests and linting (default)
19
+ bundle exec rake
20
+
21
+ # Run a specific test file
22
+ bundle exec rspec spec/jwt_auth_cognito/configuration_spec.rb
23
+
24
+ # Test basic functionality
25
+ ruby examples/simple_test.rb
26
+ ```
27
+
28
+ ### Gem Management
29
+ ```bash
30
+ # Build the gem
31
+ gem build jwt_auth_cognito.gemspec
32
+
33
+ # Install locally for testing
34
+ bundle exec rake install
35
+
36
+ # Test gem packaging
37
+ gem contents jwt_auth_cognito-0.1.0.gem
38
+ ```
39
+
40
+ ### Configuration Generation
41
+ ```bash
42
+ # Rails generator (creates initializer and .env.example)
43
+ rails generate jwt_auth_cognito:install
44
+
45
+ # Rake tasks for configuration management
46
+ rake jwt_auth_cognito:install # Install configuration
47
+ rake jwt_auth_cognito:config # View current config
48
+ rake jwt_auth_cognito:test_redis # Test Redis connection
49
+ rake jwt_auth_cognito:test_cognito # Test Cognito connection
50
+ ```
51
+
52
+ ## Architecture Overview
53
+
54
+ ### Core Components
55
+ - **JwtValidator**: Main validation orchestrator that coordinates JWKS validation and blacklist checking
56
+ - **JwksService**: Handles AWS Cognito JWKS fetching, caching, and signature validation
57
+ - **RedisService**: Low-level Redis operations with comprehensive TLS support and retry logic
58
+ - **TokenBlacklistService**: High-level token revocation and blacklist management
59
+ - **Configuration**: Centralized configuration with environment variable fallbacks
60
+
61
+ ### Key Design Patterns
62
+
63
+ **Service Layer Architecture**: Each major functionality (JWT validation, JWKS handling, Redis operations, blacklisting) is isolated into dedicated service classes that can be used independently or orchestrated through JwtValidator.
64
+
65
+ **Configuration Management**: Dual configuration approach supporting both programmatic configuration and environment variables, with automatic fallback chain for maximum flexibility.
66
+
67
+ **Error Hierarchy**: Comprehensive error types that mirror the Node.js implementation for consistency across implementations.
68
+
69
+ **Compatibility Layer**: Designed to match the API and behavior of the Node.js auth package, ensuring consistent functionality across language implementations.
70
+
71
+ ### Redis Architecture
72
+ - **Connection Management**: Single connection with comprehensive TLS support including certificate validation
73
+ - **Retry Logic**: Exponential backoff for failed operations
74
+ - **Blacklist Strategy**: Uses Redis sets with automatic TTL management for token revocation
75
+ - **User Token Tracking**: Maintains user-to-tokens mapping for bulk revocation capabilities
76
+
77
+ ### JWT Validation Flow
78
+ 1. **Structure Validation**: Basic JWT format and claims validation
79
+ 2. **Blacklist Check**: Fast Redis lookup for revoked tokens
80
+ 3. **JWKS Validation**: Signature verification against Cognito public keys (secure mode only)
81
+ 4. **Claims Validation**: Audience, issuer, expiration, and custom claims validation
82
+
83
+ ### Client Secret Support
84
+ - **Optional Enhancement**: HMAC-SHA256 secret hash calculation matching AWS Cognito requirements
85
+ - **Backward Compatibility**: All functionality works without client secret configuration
86
+ - **Security Integration**: Secret hash automatically included in blacklist operations when configured
87
+
88
+ ## Environment Configuration
89
+
90
+ The gem supports extensive environment variable configuration for deployment flexibility:
91
+
92
+ - `COGNITO_*` variables for AWS Cognito settings
93
+ - `REDIS_*` variables for Redis connection and TLS configuration
94
+ - `JWKS_CACHE_TTL` for caching behavior
95
+ - Automatic Rails environment detection for validation mode selection
96
+
97
+ ## Rails Integration
98
+
99
+ ### Generator System
100
+ - **Install Generator**: Creates optimized initializer and environment templates
101
+ - **Configuration Detection**: Automatically detects existing Redis configuration
102
+ - **Environment Setup**: Generates appropriate .env.example with all required variables
103
+
104
+ ### Service Integration
105
+ - **Railtie Integration**: Automatic Rails integration with proper loading order
106
+ - **Middleware Ready**: Designed for easy integration into authentication middleware
107
+ - **Error Handling**: Rails-compatible error types and responses
108
+
109
+ ## Testing Strategy
110
+
111
+ ### Test Structure
112
+ - **Unit Tests**: Individual service testing with mocked dependencies
113
+ - **Integration Tests**: Full validation flow testing with WebMock for external calls
114
+ - **Configuration Tests**: Environment variable handling and validation
115
+ - **Error Handling Tests**: Comprehensive error scenario coverage
116
+
117
+ ### Test Helpers
118
+ - **Configuration Reset**: Automatic test isolation with `reset_configuration!`
119
+ - **WebMock Integration**: Disabled external calls with localhost exceptions
120
+ - **Redis Mocking**: Isolated Redis testing without external dependencies
121
+
122
+ ## Version Compatibility
123
+
124
+ Designed for compatibility with legacy Rails applications:
125
+ - **Ruby**: >= 2.7.0 (compatible with llegando-neo Ruby 2.7.5)
126
+ - **Rails**: >= 5.0 (compatible with llegando-neo Rails 5.2.6)
127
+ - **Redis**: >= 4.2.5 (matches llegando-neo Redis version constraints)
128
+
129
+ ## Publishing and Distribution
130
+
131
+ The gem is prepared for RubyGems.org publication with:
132
+ - Complete gemspec with metadata
133
+ - Proper file inclusion patterns
134
+ - Version compatibility constraints
135
+ - MIT license and documentation
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
6
+
7
+ gem "rake", "~> 13.0"
8
+ gem "rspec", "~> 3.0"
9
+ gem "rubocop", "~> 1.21"
10
+ gem "webmock", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 The Optimal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/PUBLISH_GUIDE.md ADDED
@@ -0,0 +1,187 @@
1
+ # 📦 Guía para Publicar jwt_auth_cognito en RubyGems
2
+
3
+ Esta guía te llevará paso a paso para publicar tu gema en RubyGems.org y poder usarla de forma remota.
4
+
5
+ ## 🛠️ **Prerequisitos**
6
+
7
+ ### 1. Cuenta en RubyGems.org
8
+ - Ve a [rubygems.org](https://rubygems.org) y crea una cuenta
9
+ - Confirma tu email
10
+
11
+ ### 2. Configurar credenciales locales
12
+ ```bash
13
+ # Configurar tu API key (se te pedirá email y password)
14
+ gem signin
15
+ ```
16
+
17
+ ## 🚀 **Proceso de Publicación**
18
+
19
+ ### **Paso 1: Verificar la gema**
20
+
21
+ ```bash
22
+ # Asegúrate de estar en el directorio de la gema
23
+ cd /jwt-auth-cognito-gem
24
+
25
+ # Verificar que todos los tests pasen
26
+ bundle exec rspec
27
+
28
+ # Verificar que no haya problemas de código
29
+ bundle exec rubocop
30
+
31
+ # Verificar la estructura de la gema
32
+ gem build jwt_auth_cognito.gemspec
33
+ ```
34
+
35
+ ### **Paso 2: Construir la gema**
36
+
37
+ ```bash
38
+ # Limpiar gemas anteriores
39
+ rm -f *.gem
40
+
41
+ # Construir la gema final
42
+ gem build jwt_auth_cognito.gemspec
43
+ ```
44
+
45
+ ### **Paso 3: Verificar antes de publicar**
46
+
47
+ ```bash
48
+ # Verificar el contenido de la gema
49
+ gem contents jwt_auth_cognito-0.1.0.gem
50
+
51
+ # Verificar metadatos
52
+ gem specification jwt_auth_cognito-0.1.0.gem
53
+ ```
54
+
55
+ ### **Paso 4: Publicar en RubyGems**
56
+
57
+ ```bash
58
+ # Publicar la gema (¡CUIDADO! Esto es irreversible)
59
+ gem push jwt_auth_cognito-0.1.0.gem
60
+ ```
61
+
62
+ ## ✅ **Verificación de Publicación**
63
+
64
+ ### 1. Verificar en la web
65
+ - Ve a: https://rubygems.org/gems/jwt_auth_cognito
66
+ - Debería aparecer tu gema con toda la información
67
+
68
+ ### 2. Probar instalación
69
+ ```bash
70
+ # En otro directorio, probar instalar
71
+ gem install jwt_auth_cognito
72
+
73
+ # O en un proyecto Rails
74
+ echo 'gem "jwt_auth_cognito", "~> 0.1.0"' >> Gemfile
75
+ bundle install
76
+ ```
77
+
78
+ ## 🔄 **Para Actualizaciones Futuras**
79
+
80
+ ### **Paso 1: Actualizar versión**
81
+ ```ruby
82
+ # En lib/jwt_auth_cognito/version.rb
83
+ module JwtAuthCognito
84
+ VERSION = "0.1.1" # Incrementar versión
85
+ end
86
+ ```
87
+
88
+ ### **Paso 2: Actualizar CHANGELOG**
89
+ ```markdown
90
+ # En CHANGELOG.md
91
+ ## [0.1.1] - 2024-06-17
92
+ ### Added
93
+ - Nueva funcionalidad X
94
+ ### Fixed
95
+ - Bug corregido Y
96
+ ```
97
+
98
+ ### **Paso 3: Publicar nueva versión**
99
+ ```bash
100
+ gem build jwt_auth_cognito.gemspec
101
+ gem push jwt_auth_cognito-0.1.1.gem
102
+ ```
103
+
104
+ ## 🏷️ **Versionado Semántico**
105
+
106
+ Sigue estas reglas para versiones:
107
+
108
+ - **MAJOR** (1.0.0): Cambios incompatibles
109
+ - **MINOR** (0.1.0): Nuevas funcionalidades compatibles
110
+ - **PATCH** (0.1.1): Correcciones de bugs
111
+
112
+ ## 🛡️ **Consideraciones de Seguridad**
113
+
114
+ ### ⚠️ **IMPORTANTE: Una vez publicado, NO se puede borrar**
115
+ - Las versiones de gemas son permanentes en RubyGems
116
+ - Solo se puede "yankar" (ocultar) pero sigue existiendo
117
+ - Revisa muy bien antes de publicar
118
+
119
+ ### 🔐 **Proteger tu cuenta**
120
+ ```bash
121
+ # Habilitar MFA (Multi-Factor Authentication)
122
+ gem owner --add your_email@domain.com --otp YOUR_OTP_CODE jwt_auth_cognito
123
+
124
+ # Ver owners de tu gema
125
+ gem owner jwt_auth_cognito
126
+ ```
127
+
128
+ ## 📋 **Checklist de Pre-publicación**
129
+
130
+ - [ ] ✅ Tests pasando (`bundle exec rspec`)
131
+ - [ ] ✅ Código limpio (`bundle exec rubocop`)
132
+ - [ ] ✅ Versión actualizada
133
+ - [ ] ✅ CHANGELOG actualizado
134
+ - [ ] ✅ README.md completo
135
+ - [ ] ✅ Licencia correcta
136
+ - [ ] ✅ Metadatos del gemspec correctos
137
+ - [ ] ✅ Archivos innecesarios excluidos (.gitignore)
138
+ - [ ] ✅ Gema construida exitosamente
139
+ - [ ] ✅ Contenido de la gema verificado
140
+
141
+ ## 🎯 **Después de Publicar**
142
+
143
+ ### 1. Actualizar documentación
144
+ - Actualiza el README con instrucciones de instalación desde RubyGems
145
+ - Actualiza ejemplos para usar la versión publicada
146
+
147
+ ### 2. Comunicar el lanzamiento
148
+ - Anuncia en tu equipo/empresa
149
+ - Actualiza documentación interna
150
+ - Considera crear un release en GitHub
151
+
152
+ ### 3. Monitorear uso
153
+ - Revisa estadísticas en rubygems.org
154
+ - Monitorea issues/feedback de usuarios
155
+
156
+ ## 🆘 **Si algo sale mal**
157
+
158
+ ### Yankar una versión (ocultar)
159
+ ```bash
160
+ gem yank jwt_auth_cognito -v 0.1.0
161
+ ```
162
+
163
+ ### Restaurar una versión yankeada
164
+ ```bash
165
+ gem unyank jwt_auth_cognito -v 0.1.0
166
+ ```
167
+
168
+ ## 📞 **Soporte**
169
+
170
+ - **RubyGems Help**: https://guides.rubygems.org/
171
+ - **Documentación oficial**: https://guides.rubygems.org/publishing/
172
+ - **Soporte RubyGems**: https://help.rubygems.org/
173
+
174
+ ---
175
+
176
+ ## 🚀 **Comandos Rápidos de Publicación**
177
+
178
+ ```bash
179
+ # Flujo completo de publicación
180
+ bundle exec rspec # Tests
181
+ bundle exec rubocop # Linting
182
+ rm -f *.gem # Limpiar
183
+ gem build jwt_auth_cognito.gemspec # Construir
184
+ gem push jwt_auth_cognito-0.1.0.gem # Publicar
185
+ ```
186
+
187
+ ¡Ya tienes todo listo para publicar tu gema en RubyGems! 🎉