Repository navigation
chore: created OAUTH_SUCCESS_REDIRECT_URL for the FrontEnd URL - #38
cleberjamaral wants to merge 1 commit into
Conversation
WalkthroughThis PR introduces environment-driven OAuth redirect configuration by adding a new Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/routes/auth.js (1)
32-46: Add validation for the OAuth redirect URL.The
OAUTH_SUCCESS_REDIRECT_URLenvironment variable is used directly as a redirect target without validation. This creates a potential open redirect vulnerability if the environment variable is misconfigured to point to an external malicious site.Consider validating that the URL is either a relative path or matches an allowed domain:
router.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => { // Recupera o redirectTo do state parameter const state = req.query.state; - let finalUrl = process.env.OAUTH_SUCCESS_REDIRECT_URL || '/default'; + let finalUrl = validateRedirectUrl(process.env.OAUTH_SUCCESS_REDIRECT_URL) || '/default'; if (state) { try { const decoded = Buffer.from(state, 'base64').toString('utf-8'); - // Valida se o resultado é um path relativo seguro (não permite URLs externas) - if (decoded) { + const validatedDecoded = validateRedirectUrl(decoded); + if (validatedDecoded) { - finalUrl = decoded; + finalUrl = validatedDecoded; } } catch (err) { console.error('Error decoding state:', err); } } res.redirect(finalUrl); } );Add a validation helper at the top of the file:
/** * Validates redirect URL to prevent open redirect vulnerabilities * @param {string} url - URL to validate * @returns {string|null} - Validated URL or null if invalid */ function validateRedirectUrl(url) { if (!url || typeof url !== 'string') return null; // Allow relative paths if (url.startsWith('/')) { return url; } // Allow specific whitelisted domains (configure via environment) const allowedDomains = (process.env.ALLOWED_REDIRECT_DOMAINS || 'localhost:3001').split(','); try { const urlObj = new URL(url); const hostWithPort = urlObj.port ? `${urlObj.hostname}:${urlObj.port}` : urlObj.hostname; if (allowedDomains.some(domain => hostWithPort === domain.trim())) { return url; } } catch (err) { // Invalid URL format return null; } return null; }Note: The existing validation at line 38 also needs improvement—it currently only checks if
decodedis truthy rather than validating it's a safe redirect target. The suggestion above addresses both issues.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
.env.example(1 hunks)src/routes/auth.js(1 hunks)
🧰 Additional context used
🪛 dotenv-linter (4.0.0)
.env.example
[warning] 14-14: [UnorderedKey] The GOOGLE_CALLBACK_URL key should go before the GOOGLE_CLIENT_ID key
(UnorderedKey)
[warning] 15-15: [EndingBlankLine] No blank line at the end of the file
(EndingBlankLine)
| GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback | ||
| OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/ No newline at end of file |
There was a problem hiding this comment.
Environment variable added correctly.
The new OAUTH_SUCCESS_REDIRECT_URL variable is properly added to the OAuth configuration section. The localhost URL is appropriate for development.
Note: Static analysis indicates a missing blank line at the end of the file. Consider adding one for consistency:
GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback
OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/
+📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback | |
| OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/ | |
| GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback | |
| OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/ | |
🧰 Tools
🪛 dotenv-linter (4.0.0)
[warning] 14-14: [UnorderedKey] The GOOGLE_CALLBACK_URL key should go before the GOOGLE_CLIENT_ID key
(UnorderedKey)
[warning] 15-15: [EndingBlankLine] No blank line at the end of the file
(EndingBlankLine)
🤖 Prompt for AI Agents
In .env.example around lines 14 to 15, the file is missing a trailing blank line
at EOF; fix by adding a single newline (blank line) at the end of the file so
the file ends with a newline character for consistency with POSIX conventions.
There was a problem hiding this comment.
O PR melhora o código, embora não resolva todos os problemas de autenticação. Deve-se usar o parâmetro redirect_uri (ref.: Google) para atender plenamente à demanda do sistema.
Descrição
Cria variavel de ambiente para indicar a URL (geralmente do FrontEnd) a qual o google/callback deve redirecionar após a autenticação bem sucedida.
Creio que manter o endpoint google/callback é uma boa prática, pois facilita indicar uma URL que fallback e deixa o endereço de retorno fixo para agentes externos, sendo que o redirecionamento a um endereço variável fica no caso em uma varenv.
Tipos de Mudanças
Como o teste foi realizado?
Checklist:
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.