Skip to content

fix(security): replace Math.random with crypto.randomUUID and fix URL hostname check#2461

Merged
diegosouzapw merged 1 commit into
release/v3.8.1from
fix/security-codeql-randomness-url-check
May 21, 2026
Merged

fix(security): replace Math.random with crypto.randomUUID and fix URL hostname check#2461
diegosouzapw merged 1 commit into
release/v3.8.1from
fix/security-codeql-randomness-url-check

Conversation

@diegosouzapw
Copy link
Copy Markdown
Owner

Fixes

Corrige os 2 alertas de code scanning CodeQL em aberto.

Alert #251 — Insecure randomness (js/insecure-randomness)

File: src/lib/cloudAgent/baseAgent.ts (linhas 88–93)

Math.random() era usado para gerar os sufixos aleatórios de taskId e activityId. O CodeQL sinalizou o uso como inseguro para um contexto de segurança (os IDs são usados como identificadores externos para tarefas do Jules).

Fix: substituído por crypto.randomUUID() (disponível globalmente no Node.js ≥20, alinhado ao runtime alvo do projeto):

// Antes
return `task_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;

// Depois
return `task_${Date.now()}_${crypto.randomUUID().replace(/-/g, "").substring(0, 9)}`;

Alert #252 — Incomplete URL substring sanitization (js/incomplete-url-substring-sanitization)

File: tests/unit/antigravity-discovery-bootstrap.test.ts (linha 155)

url.includes("daily-cloudcode-pa.googleapis.com") pode ser satisfeito por uma URL do tipo http://evil.com/daily-cloudcode-pa.googleapis.com, pois a string pode aparecer em qualquer posição.

Fix: substituído por verificação explícita do hostname via new URL():

// Antes
if (url.includes("daily-cloudcode-pa.googleapis.com")) {

// Depois
if (new URL(url).hostname === "daily-cloudcode-pa.googleapis.com") {

Test plan

…TaskId/ActivityId and fix URL hostname check in test
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request replaces Math.random() with crypto.randomUUID() for task and activity ID generation in the base agent and refines URL matching in unit tests to check hostnames specifically. The reviewer identified that truncating the UUIDs to nine characters significantly reduces entropy, which could lead to security vulnerabilities, and recommended using the full UUID. Additionally, the reviewer noted that changes to production code must be accompanied by unit tests to comply with the repository's style guide.


protected generateTaskId(): string {
return `task_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
return `task_${Date.now()}_${crypto.randomUUID().replace(/-/g, "").substring(0, 9)}`;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

security-medium medium

Ao truncar o UUID para apenas 9 caracteres hexadecimais, a entropia resultante é de aproximadamente 36 bits ($16^9$). Embora o uso de crypto.randomUUID() resolva o problema da previsibilidade do Math.random(), a baixa entropia do sufixo pode ainda permitir ataques de adivinhação por força bruta se esses IDs forem expostos externamente em um contexto de segurança (como mencionado na descrição do PR). Se não houver uma restrição rígida de comprimento no sistema que consome esses IDs, considere utilizar o UUID completo para aumentar a segurança e garantir a unicidade.

Além disso, de acordo com a regra 9 do guia de estilo do repositório, alterações em código de produção (src/) devem ser acompanhadas de testes. Como a lógica de geração de IDs foi alterada, seria ideal incluir ou atualizar testes unitários para validar o novo formato.

Suggested change
return `task_${Date.now()}_${crypto.randomUUID().replace(/-/g, "").substring(0, 9)}`;
return `task_${Date.now()}_${crypto.randomUUID()}`;
References
  1. Sempre inclua testes ao alterar código de produção (src/, open-sse/, electron/, bin/). (link)


protected generateActivityId(): string {
return `act_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
return `act_${Date.now()}_${crypto.randomUUID().replace(/-/g, "").substring(0, 9)}`;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

security-medium medium

Assim como no generateTaskId, o truncamento para 9 caracteres reduz significativamente a unicidade garantida pelo UUID. Para um identificador externo em um contexto de segurança, recomenda-se manter o UUID completo para minimizar riscos de colisão e previsibilidade.

Suggested change
return `act_${Date.now()}_${crypto.randomUUID().replace(/-/g, "").substring(0, 9)}`;
return `act_${Date.now()}_${crypto.randomUUID()}`;

@kilo-code-bot
Copy link
Copy Markdown

kilo-code-bot Bot commented May 21, 2026

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Overview

Both changes correctly address CodeQL security alerts without introducing new issues.

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 0

Files Reviewed

  • src/lib/cloudAgent/baseAgent.ts - Replaces Math.random() with crypto.randomUUID() for task/activity ID generation. Cryptographically secure, maintains same suffix length (9 chars), compatible with Node.js ≥20 target runtime.

  • tests/unit/antigravity-discovery-bootstrap.test.ts - Replaces url.includes() with new URL(url).hostname === for hostname verification. Eliminates path-based bypass vulnerability. Safe in test context where URLs are well-formed.

Verification Performed

  • Confirmed substring(0, 9) matches original substring(2, 11) length
  • Confirmed crypto.randomUUID() strip-dashes-then-substring produces valid random suffix
  • Confirmed test mock URLs are always well-formed (no URL constructor risk)
  • No edge cases or security regressions identified

Reviewed by qwen3.6-plus · 118,366 tokens

@diegosouzapw diegosouzapw merged commit d7001dc into release/v3.8.1 May 21, 2026
9 of 14 checks passed
@diegosouzapw diegosouzapw deleted the fix/security-codeql-randomness-url-check branch May 21, 2026 12:59
diegosouzapw added a commit that referenced this pull request May 21, 2026
…TaskId/ActivityId and fix URL hostname check in test (#2461) (#2489)

Co-authored-by: diegosouzapw <diego.souza.pw@gmail.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