Skip to content

Conversation

@kalilfagundes
Copy link

@kalilfagundes kalilfagundes commented Nov 10, 2025

Modifiquei a Dockerfile e agora ela está funcionando via Coolify. Adicionei também uma chave API Bearer no endpoint.

Summary by CodeRabbit

  • New Features

    • Optional API key authentication applied to API endpoints
  • Documentation

    • Added a comprehensive Portuguese API usage guide with examples and best practices
    • Updated README with authentication and setup instructions
    • Added example environment entries and explanatory comments for API key usage
  • Chores

    • Updated Docker build and runtime steps and dependencies for improved build reliability

kalilfagundes and others added 10 commits November 10, 2025 15:40
- 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
@changeset-bot
Copy link

changeset-bot bot commented Nov 10, 2025

⚠️ No Changeset found

Latest commit: 61a4a99

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 36ed75c and 61a4a99.

📒 Files selected for processing (2)
  • .env.example (1 hunks)
  • Dockerfile (2 hunks)

Walkthrough

Adds 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

Cohort / File(s) Summary
Environment example
\.env.example
Added Portuguese comments and API_KEY="sua_api_key_secreta_aqui" (duplicated entry) to document optional API-key authentication.
Documentation
API_USAGE.md, README.md
Added comprehensive Portuguese API usage guide and extended README sections covering authentication, examples, env setup, local/Docker run, and request/response formats.
Authentication middleware
src/middlewares/auth.ts, src/middlewares/index.ts
New authenticate() middleware reading API_KEY (bypass if unset); validates Authorization: Bearer <token> and returns 401 on missing/invalid token; re-exported from middleware index.
Route integration
src/routes.ts
Inserted authenticate() into the POST /execute middleware chain before validation.
Docker build & scripts
Dockerfile
Consolidated package installation into single RUN, upgraded PHP to php83, added packages (binutils, wget, dos2unix), switched FPC install to HTTPS SourceForge mirror, ensured dos2unix + chmod normalization for scripts across stages, and adjusted copy/entrypoint ordering.

Sequence Diagram

sequenceDiagram
    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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay special attention to:
    • Dockerfile changes (PHP version bump, FPC HTTPS install, package consolidation, and script normalization).
    • src/middlewares/auth.ts for correct header parsing, clear error messages, and security (bypass logic when API_KEY unset).
    • src/routes.ts to confirm middleware ordering and compatibility with existing validation logic.
    • .env.example duplicate API_KEY entry (intentional vs. accidental).

Poem

🐰 A tiny key I tuck away,
I guard the sandbox day by day,
Scripts line-ended, PHP reborn,
FPC fetched from HTTPS morn,
Hop — the code runs safe and gay!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: adding Bearer API key authentication and updating the Dockerfile for Coolify compatibility.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a 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:

  1. Add rate limiting to prevent brute-force attacks on the API key
  2. Log failed authentication attempts for security monitoring

Consider using a library like express-rate-limit for 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 env as 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

📥 Commits

Reviewing files that changed from the base of the PR and between 991e546 and 4e70d63.

📒 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 RUN layer reduces image layers and improves build efficiency. The addition of dos2unix and wget supports 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 dos2unix on 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.

Comment on lines +35 to +39
if (token !== apiKey) {
return response.status(401).json({
error: 'API key inválida.'
})
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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>
Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e70d63 and 36ed75c.

📒 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.

kalilfagundes and others added 2 commits November 10, 2025 17:48
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant