# DOCKER-BP-011: Prefer COPY Over ADD

> **Severity:** LOW | **CWE:** CWE-710

- **Language:** Docker
- **Category:** Best Practice
- **URL:** https://codepathfinder.dev/registry/docker/best-practice/DOCKER-BP-011
- **Detection:** `pathfinder scan --ruleset docker/DOCKER-BP-011 --project .`

## Description

Detects use of ADD instruction when COPY would suffice. ADD has implicit behavior
(auto-extraction of tar archives, URL downloading) that can be surprising and
create security risks.

## Vulnerable Code

```python
FROM ubuntu:22.04
ADD app.tar.gz /app/
ADD https://example.com/file /tmp/
```

## Secure Code

```python
COPY app.tar.gz /app/  # ✅ Just copies the file
RUN tar xzf /app/app.tar.gz  # ✅ Explicit extraction
```

## Detection Rule (Python SDK)

```python
from rules.container_decorators import dockerfile_rule
from rules.container_matchers import instruction


@dockerfile_rule(
    id="DOCKER-BP-011",
    name="Prefer COPY Over ADD",
    severity="LOW",
    cwe="CWE-710",
    category="best-practice",
    tags="docker,dockerfile,copy,add,file-operations,best-practice,transparency,predictability,anti-pattern",
    message="Use COPY instead of ADD for simple file operations. ADD has implicit behavior that can be surprising."
)
def prefer_copy_over_add():
    return instruction(type="ADD")
```

## How to Fix

- Use COPY for copying local files into the image
- Only use ADD when you specifically need tar auto-extraction or URL downloading
- For downloading files, prefer RUN with curl or wget for better control

## FAQ

**Q: What is the difference between ADD and COPY?**

COPY simply copies files from the build context. ADD has extra features: it auto-extracts tar archives and can download from URLs. These implicit behaviors can be surprising and introduce security risks.

**Q: When should I use ADD?**

Use ADD only when you need automatic tar extraction (e.g., ADD rootfs.tar.xz /). For all other cases, COPY is clearer and safer.

## References

- [Docker Best Practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [Dockerfile Best Practice: Use COPY instead of ADD for files](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy)

---

Source: https://codepathfinder.dev/registry/docker/best-practice/DOCKER-BP-011
Code Pathfinder — Open source, type-aware SAST with cross-file dataflow analysis
