Skip to content

Fix: Run container as non-root user to mitigate RCE vulnerability#19

Draft
Copilot wants to merge 4 commits intomainfrom
copilot/fix-dockerfile-root-user-security
Draft

Fix: Run container as non-root user to mitigate RCE vulnerability#19
Copilot wants to merge 4 commits intomainfrom
copilot/fix-dockerfile-root-user-security

Conversation

Copy link
Copy Markdown

Copilot AI commented Nov 7, 2025

Container defaulted to root user, enabling RCE exploits to gain full privileges for container escape, lateral movement, and host compromise.

Changes

  • User creation: Added dedicated appuser system user with isolated group
  • Ownership: Set /app directory ownership to appuser:appuser after file copy
  • Runtime context: Added USER appuser directive to drop privileges before entrypoint
# Create a non-root user with dedicated group
RUN addgroup --system appuser && \
    adduser --system --no-create-home --ingroup appuser appuser

COPY . .

# Change ownership of application files to non-root user
RUN chown -R appuser:appuser /app

USER appuser

Notes

Pre-existing issues remain unaddressed per minimal change scope:

  • Missing poetry.lock file will cause build failure (line 12)
  • Unnecessary poetry shell command in build context (line 17)
Original prompt

Please fix the following security issue:

Remote code execution (RCE) due to root user in Dockerfile

Remote code execution (RCE) inside the container could grant full root privileges, enabling lateral movement, container escape attempts, and host impact via mounted volumes or the Docker socket.

The Dockerfile lacks a non-root USER directive, so the container defaults to running as root, giving any process or exploited service unnecessary and dangerous privileges.

Dockerfile:1-17 Create a dedicated unprivileged user and switch to it. For example: adduser --system --home /app appuser; chown files to appuser; then set USER appuser in the Dockerfile. Grant only needed file and capability permissions.

<fix_impact>
Processes that require privileged ports (<1024), root-owned file access, or elevated capabilities may fail until permissions, ports, or capabilities are adjusted.
</fix_impact>

Keep the changes minimal - only make the necessary code changes to fix the security issue.


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Summary by CodeRabbit

  • Chores
    • Reforçada a segurança da aplicação através de melhorias na configuração do container de implantação.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 7, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

O Dockerfile foi modificado para implementar práticas de segurança com a criação de um usuário e grupo não-root (appuser), atribuição de propriedade adequada do diretório /app e execução do container sob esse usuário não-privilegiado.

Changes

Cohort / Cohort File(s) Resumo das Alterações
Configuração de Segurança com Usuário Não-Root
Dockerfile
Criação de grupo e usuário de sistema (appuser); atribuição de propriedade do diretório /app; definição do USER como appuser para execução do container

Estimated code review effort

🎯 2 (Simples) | ⏱️ ~8 minutos

  • Verificar se o usuário e grupo são criados corretamente antes de serem utilizados
  • Confirmar que a ordem das instruções RUN não causa problemas de permissão
  • Validar se há impacto em volumes montados ou arquivos gerados em tempo de execução

Poem

🐰 Um coelho sábio viu a necessidade,
De deixar o root na obscuridade,
Com appuser reinou com segurança,
E /app sob proteção confiança,
Chown fez, e a porta se abriu com leveza! 🔐

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 O título descreve com precisão a principal mudança: correção de um problema de execução remota de código através da alteração do Dockerfile para usar um usuário não-root.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

Copilot AI and others added 2 commits November 7, 2025 20:40
Co-authored-by: yuriishizawa <50813580+yuriishizawa@users.noreply.github.com>
… timing

Co-authored-by: yuriishizawa <50813580+yuriishizawa@users.noreply.github.com>
@yuriishizawa
Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 7, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@yuriishizawa
Copy link
Copy Markdown
Owner

@sourcery-ai review

Co-authored-by: yuriishizawa <50813580+yuriishizawa@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (2)
Dockerfile (2)

6-7: Considere usar groupadd e useradd (POSIX-compliant) para maior robustez e compatibilidade.

Os comandos addgroup e adduser com a sintaxe usada funcionam em Debian, mas a combinação de flags --home /app --no-create-home é confusa (especifica um home mas depois diz para não criá-lo). A alternativa com groupadd -r e useradd -r é mais clara e segue convenções POSIX.

-RUN addgroup --system appuser && \
-    adduser --system --home /app --no-create-home --ingroup appuser appuser
+RUN groupadd -r appuser && \
+    useradd -r -d /app -s /sbin/nologin -g appuser appuser

14-17: ⚠️ Nota: poetry shell em linha 17 (pré-existente) pode não ter o efeito esperado em contexto Dockerfile.

A diretiva poetry shell é interativa e não costuma funcionar em builds não-interativos. Como virtualenvs.create já está desabilitado em linha 15 (correto), o poetry shell é redundante. Considere remover em um future refactor, mas não é bloqueador para esta correção de segurança.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f465881 and 114fd98.

📒 Files selected for processing (1)
  • Dockerfile (2 hunks)
🔇 Additional comments (1)
Dockerfile (1)

21-24: Ótimo posicionamento de chown e USER — segurança implementada corretamente.

O comando chown -R appuser:appuser /app está corretamente posicionado após a cópia dos arquivos, e a diretiva USER appuser está corretamente colocada após todas as operações que exigem privilégios root. Nenhuma operação subsequente (incluindo ENTRYPOINT/CMD) requer permissões elevadas. A mitigação de RCE está bem implementada.

Copilot AI changed the title [WIP] Fix remote code execution issue in Dockerfile Fix: Run container as non-root user to mitigate RCE vulnerability Nov 7, 2025
Copilot AI requested a review from yuriishizawa November 7, 2025 20:44
@yuriishizawa
Copy link
Copy Markdown
Owner

@coderabbitai help

@yuriishizawa
Copy link
Copy Markdown
Owner

@sourcery-ai help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 7, 2025

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue comments.

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
    • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
    • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit configuration file (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@yuriishizawa
Copy link
Copy Markdown
Owner

@CodeRabbit atualize o poetry deste repositório para >= 2.0.0 e remova o comando poetry shell do dockerfile

@yuriishizawa
Copy link
Copy Markdown
Owner

@coderabbitai atualize o poetry deste repositório para >= 2.0.0 e remova o comando poetry shell do dockerfile

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 7, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the Dockerfile to understand current Poetry usage
cat Dockerfile

echo "---"

# Check for pyproject.toml which contains Poetry configuration
cat pyproject.toml 2>/dev/null || echo "pyproject.toml not found"

echo "---"

# Search for any Poetry version specifications in the repository
rg -n "poetry" --type-add 'docker:Dockerfile*' --type docker -i

echo "---"

# Look for poetry.lock file
ls -la poetry.lock 2>/dev/null || echo "poetry.lock not found"

Length of output: 1455


@yuriishizawa, entendido! Vou atualizar o Poetry para >= 2.0.0 e remover o comando poetry shell do Dockerfile.

Aqui está o Dockerfile atualizado:

FROM python:3.10
EXPOSE 8501
WORKDIR /app

# Create a non-root user with dedicated group
RUN addgroup --system appuser && \
    adduser --system --no-create-home --ingroup appuser appuser

# COPY requirements.txt ./requirements.txt
# RUN pip3 install -r requirements.txt

COPY pyproject.toml poetry.lock ./

RUN pip install 'poetry>=2.0.0' && \
    poetry config virtualenvs.create false && \
    poetry install --no-dev

COPY . .

# Change ownership of application files to non-root user
RUN chown -R appuser:appuser /app

USER appuser

ENTRYPOINT ["streamlit"]
CMD ["run", "myapp.py"]

Mudanças realizadas:

  1. ✅ Atualizado Poetry de 1.5.0 para >=2.0.0 (linha 14)
  2. ✅ Removido o comando poetry shell (linha 17 antiga) - este comando não é necessário no Dockerfile pois os ambientes virtuais já estão desabilitados com virtualenvs.create false

Nota: O arquivo poetry.lock referenciado na linha 12 não existe no repositório. Você pode querer:

  • Gerar o arquivo executando poetry lock localmente, ou
  • Remover a referência ao poetry.lock da linha COPY se preferir instalar sempre as versões mais recentes das dependências

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 7, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the Dockerfile to see current Poetry setup
cat Dockerfile

# Check for pyproject.toml
if [ -f pyproject.toml ]; then
  cat pyproject.toml
fi

# Search for any Poetry configuration or version specifications
fd -t f "poetry" --exec cat {}

# Check for any other Docker-related files
fd -t f -e yml -e yaml docker

Length of output: 1183


@yuriishizawa, entendido! Vou atualizar o Poetry para >= 2.0.0 e remover o comando poetry shell do Dockerfile.

O comando poetry shell realmente não faz sentido no contexto do Dockerfile, pois:

  1. É um comando interativo para ativar ambientes virtuais
  2. Os virtualenvs estão desabilitados (virtualenvs.create false)
  3. Não tem efeito em um build não-interativo do Docker

Aqui está a seção atualizada do Dockerfile:

FROM python:3.10
EXPOSE 8501
WORKDIR /app

# Create a non-root user with dedicated group
RUN addgroup --system appuser && \
    adduser --system --no-create-home --ingroup appuser appuser

# COPY requirements.txt ./requirements.txt
# RUN pip3 install -r requirements.txt

COPY pyproject.toml poetry.lock ./

RUN pip install "poetry>=2.0.0" && \
    poetry config virtualenvs.create false && \
    poetry install --no-dev

COPY . .

# Change ownership of application files to non-root user
RUN chown -R appuser:appuser /app

USER appuser

ENTRYPOINT ["streamlit"]
CMD ["run", "myapp.py"]

Mudanças realizadas:

  1. ✅ Atualizado Poetry de poetry==1.5.0 para poetry>=2.0.0
  2. ✅ Removido o comando poetry shell que era desnecessário

Estas alterações mantêm a segurança implementada neste PR (usuário não-root) e modernizam a versão do Poetry.

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.

2 participants