- Notifications
You must be signed in to change notification settings - Fork 1
feat Chave API Bearer para endpoint e atualização de Dockerfile funcionando em 2025 #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
- Implementa middleware de autenticação usando Authorization header - Adiciona proteção de API com chave mestra configurável via .env - Cria documentação completa em português (API_USAGE.md) - Inclui exemplos práticos de uso para todas as linguagens suportadas - Documenta uso de params para múltiplos casos de teste - Atualiza README com referências à nova documentação
|
| Warning Rate limit exceeded@kalilfagundes has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 20 minutes and 55 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
WalkthroughAdds optional API key Bearer authentication and integrates it into the POST execution route; updates environment example with API_KEY comments; introduces a Portuguese API usage guide and README additions; and restructures the Dockerfile with consolidated package installs, PHP 8.3, FPC HTTPS install, and line-ending normalization steps. Changes
Sequence DiagramsequenceDiagram participant Client participant Server participant Auth as "Auth Middleware" participant Validate as "Validation" participant Handler Client->>Server: POST /execute (with or without Authorization) Server->>Auth: authenticate(req) alt API_KEY not set Auth-->>Server: allow (bypass) else API_KEY set Auth->>Auth: parse Authorization header alt header missing/format invalid Auth-->>Client: 401 Unauthorized (missing/invalid header) else token provided alt token == API_KEY Auth-->>Validate: proceed else token != API_KEY Auth-->>Client: 401 Unauthorized (invalid token) end end end Validate->>Handler: validated request Handler-->>Client: execution result (200 / error) Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (2)
src/middlewares/auth.ts (1)
7-44: Consider adding rate limiting and security logging.To improve security posture:
- Add rate limiting to prevent brute-force attacks on the API key
- Log failed authentication attempts for security monitoring
Consider using a library like
express-rate-limitfor rate limiting:import rateLimit from 'express-rate-limit' // Apply before authentication const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs message: 'Muitas tentativas de autenticação. Tente novamente mais tarde.' })For logging, add:
// On failed authentication console.warn(`[AUTH] Failed authentication attempt from ${request.ip}`)README.md (1)
42-45: Add language identifier to code block.The code block on line 42 should specify
envas the language for proper syntax highlighting.Apply this diff:
-``` +```env API_KEY="sua_api_key_secreta_aqui" ```
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
.env.example(1 hunks)API_USAGE.md(1 hunks)Dockerfile(2 hunks)README.md(3 hunks)src/middlewares/auth.ts(1 hunks)src/middlewares/index.ts(1 hunks)src/routes.ts(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/routes.ts (2)
src/middlewares/auth.ts (1)
authenticate(7-44)src/middlewares/validation.ts (1)
validate(33-45)
🪛 Gitleaks (8.29.0)
API_USAGE.md
[high] 617-619: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.
(curl-auth-header)
[high] 629-631: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.
(curl-auth-header)
[high] 642-644: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.
(curl-auth-header)
🪛 LanguageTool
API_USAGE.md
[uncategorized] ~175-~175: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: ...ro na compilação, a resposta não contém result. ```typescript interface CodeRun { ...
(ABREVIATIONS_PUNCTUATION)
[style] ~241-~241: Evite abreviações de internet. Considere escrever “não” por extenso. Se quis dizer “n”, coloque entre aspas.
Context: ...a"] } ### Entrada Multilinhas Use `\n` para separar linhas de entrada: js...
(INTERNET_ABBREVIATIONS)
[style] ~251-~251: Evite abreviações de internet. Considere escrever “não” por extenso. Se quis dizer “n”, coloque entre aspas.
Context: ...portante:** Sempre termine entradas com \n quando seu código espera ler múltiplas...
(INTERNET_ABBREVIATIONS)
[uncategorized] ~558-~558: Sinal de pontuação isolado.
Context: ...ções infinitas: - SANDBOX_TIMEOUT: Tempo máximo de execução em milissegund...
(UNLIKELY_OPENING_PUNCTUATION)
[locale-violation] ~591-~591: “performance” é um estrangeirismo. É preferível dizer “desempenho”, “atuação”, “apresentação”, “espetáculo” ou “interpretação”.
Context: ...exão**: Use keep-alive HTTP para melhor performance em múltiplas requisições 3. **Tratament...
(PT_BARBARISMS_REPLACE_PERFORMANCE)
README.md
[style] ~70-~70: Para conferir mais clareza ao seu texto, prefira mover o advérbio.
Context: ....yml -d ``` Nota: O Docker Compose automaticamente carrega as variáveis do arquivo .env, incluindo ...
(COLOCAÇÃO_ADVÉRBIO)
🪛 markdownlint-cli2 (0.18.1)
README.md
42-42: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (10)
API_USAGE.md (1)
1-728: Excellent comprehensive API documentation.This is a thorough and well-structured guide covering authentication, all supported languages with practical examples, error handling, and best practices. The Portuguese documentation will be valuable for users.
Note: The static analysis warnings about "curl-auth-header" are false positives—these are instructional examples with placeholder tokens, not actual secrets.
Dockerfile (4)
8-22: Excellent package consolidation.Consolidating package installation into a single
RUNlayer reduces image layers and improves build efficiency. The addition ofdos2unixandwgetsupports the subsequent build steps.
15-15: Good upgrade to PHP 8.3.Upgrading from PHP 7.x to PHP 8.3 brings security updates, performance improvements, and modern language features.
34-36: Improved FPC installation using HTTPS mirror.Switching from FTP to the SourceForge HTTPS mirror improves reliability and security. The comment clearly explains the rationale for the change.
61-62: Appropriate use of dos2unix for cross-platform compatibility.Running
dos2unixon shell scripts ensures correct line endings regardless of the development environment, preventing execution issues from CRLF line endings.Also applies to: 77-78
src/middlewares/index.ts (1)
1-2: LGTM!Clean barrel export following the existing pattern. This properly exposes the new authentication middleware alongside the validation middleware.
src/routes.ts (1)
4-4: Correct middleware integration.The authentication middleware is properly imported and applied before validation in the POST route. This ensures requests are authenticated before being validated and executed.
Also applies to: 18-18
.env.example (1)
6-6: Good placeholder for API key configuration.The placeholder value clearly indicates where users should insert their API key, and the comments above explain the optional nature of the configuration.
README.md (2)
11-29: Clear authentication documentation.The authentication section effectively explains the Bearer token scheme, configuration requirements, and the optional nature when API_KEY is not set. This aligns well with the implementation.
31-70: Well-structured setup and execution guidance.The updated configuration and execution sections clearly guide users through setting up the API key and running the application both locally and with Docker. The note about automatic environment variable loading is helpful.
| if (token !== apiKey) { | ||
| return response.status(401).json({ | ||
| error: 'API key inválida.' | ||
| }) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Timing attack vulnerability in token comparison.
The direct string comparison token !== apiKey is vulnerable to timing attacks. An attacker could measure response times to deduce the API key character by character.
Use a constant-time comparison function to prevent timing-based attacks:
+import crypto from 'crypto' + /** * Middleware de autenticação usando API Key * Valida o header Authorization: Bearer <token> */ export function authenticate(): RequestHandler { return (request, response, next) => { const apiKey = process.env.API_KEY // Se API_KEY não está configurada no ambiente, permite acesso if (!apiKey) { return next() } // Extrai o token do header Authorization const authHeader = request.headers.authorization if (!authHeader) { return response.status(401).json({ error: 'Autenticação necessária. Forneça o header Authorization.' }) } // Valida o formato "Bearer <token>" const [scheme, token] = authHeader.split(' ') if (scheme !== 'Bearer' || !token) { return response.status(401).json({ error: 'Formato de autenticação inválido. Use: Authorization: Bearer <api_key>' }) } // Valida se o token corresponde à API key configurada - if (token !== apiKey) { + const tokenBuffer = Buffer.from(token) + const apiKeyBuffer = Buffer.from(apiKey) + + if (tokenBuffer.length !== apiKeyBuffer.length || + !crypto.timingSafeEqual(tokenBuffer, apiKeyBuffer)) { return response.status(401).json({ error: 'API key inválida.' }) } // Token válido, permite continuar next() } }📝 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.
| if (token !== apiKey) { | |
| return response.status(401).json({ | |
| error: 'API key inválida.' | |
| }) | |
| } | |
| import crypto from 'crypto' | |
| /** | |
| * Middleware de autenticação usando API Key | |
| * Valida o header Authorization: Bearer <token> | |
| */ | |
| export function authenticate(): RequestHandler { | |
| return (request, response, next) => { | |
| const apiKey = process.env.API_KEY | |
| // Se API_KEY não está configurada no ambiente, permite acesso | |
| if (!apiKey) { | |
| return next() | |
| } | |
| // Extrai o token do header Authorization | |
| const authHeader = request.headers.authorization | |
| if (!authHeader) { | |
| return response.status(401).json({ | |
| error: 'Autenticação necessária. Forneça o header Authorization.' | |
| }) | |
| } | |
| // Valida o formato "Bearer <token>" | |
| const [scheme, token] = authHeader.split(' ') | |
| if (scheme !== 'Bearer' || !token) { | |
| return response.status(401).json({ | |
| error: 'Formato de autenticação inválido. Use: Authorization: Bearer <api_key>' | |
| }) | |
| } | |
| // Valida se o token corresponde à API key configurada | |
| const tokenBuffer = Buffer.from(token) | |
| const apiKeyBuffer = Buffer.from(apiKey) | |
| if (tokenBuffer.length !== apiKeyBuffer.length || | |
| !crypto.timingSafeEqual(tokenBuffer, apiKeyBuffer)) { | |
| return response.status(401).json({ | |
| error: 'API key inválida.' | |
| }) | |
| } | |
| // Token válido, permite continuar | |
| next() | |
| } | |
| } |
🤖 Prompt for AI Agents
In src/middlewares/auth.ts around lines 35 to 39, replace the direct string comparison (token !== apiKey) with a constant-time comparison: compute fixed-length digests (e.g., SHA-256) of both token and apiKey using crypto.createHash(...).digest() and then call crypto.timingSafeEqual on the two digests; also ensure token is a string (fall back to empty string) before hashing so the function always runs and returns 401 on mismatch. Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
.env.example(1 hunks)
🧰 Additional context used
🪛 dotenv-linter (4.0.0)
.env.example
[warning] 6-6: [QuoteCharacter] The value has quote characters (', ")
(QuoteCharacter)
[warning] 7-7: [DuplicatedKey] The API_KEY key is duplicated
(DuplicatedKey)
[warning] 7-7: [QuoteCharacter] The value has quote characters (', ")
(QuoteCharacter)
🔇 Additional comments (1)
.env.example (1)
4-5: Character encoding appears fixed.The Portuguese comments with diacritics (autenticação, não, aceitará, requisições) are now displaying correctly with proper UTF-8 encoding. This resolves the character encoding corruption issue flagged in the previous review. Ensure the file continues to be saved with UTF-8 encoding (without BOM) to maintain this.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Modifiquei a Dockerfile e agora ela está funcionando via Coolify. Adicionei também uma chave API Bearer no endpoint.
Summary by CodeRabbit
New Features
Documentation
Chores