Repository: celery/celery

Issue:
Celery Worker Redis Sentinel Password Exposed in STDOUT
# Checklist
- [X] I have verified that the issue exists against the `master` branch of Celery.
- [ ] This has already been asked to the [discussion group](https://groups.google.com/forum/#!forum/celery-users) first.
- [X] I have read the relevant section in the
  [contribution guide](http://docs.celeryproject.org/en/latest/contributing.html#other-bugs)
  on reporting bugs.
- [X] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22)
  for similar or identical bug reports.
- [X] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22)
  for existing proposed fixes.
- [X] I have checked the [commit log](https://github.com/celery/celery/commits/master)
  to find out if the bug was already fixed in the master branch.
- [X ] I have included all related issues and possible duplicate issues
  in this issue (If there are none, check this box anyway).

## Mandatory Debugging Information

- [ ] I have included the output of ``celery -A proj report`` in the issue.
    (if you are not able to do this, then at least specify the Celery
     version affected).
- [X] I have verified that the issue exists against the `master` branch of Celery.
- [] I have included the contents of ``pip freeze`` in the issue.
- [ ] I have included all the versions of all the external dependencies required
  to reproduce this bug.

## Optional Debugging Information
- [ ] I have tried reproducing the issue on more than one Python version
  and/or implementation.
- [ ] I have tried reproducing the issue on more than one message broker and/or
  result backend.
- [ ] I have tried reproducing the issue on more than one version of the message
  broker and/or result backend.
- [ ] I have tried reproducing the issue on more than one operating system.
- [ ] I have tried reproducing the issue on more than one workers pool.
- [ ] I have tried reproducing the issue with autoscaling, retries,
  ETA/Countdown & rate limits disabled.
- [ ] I have tried reproducing the issue after downgrading
  and/or upgrading Celery and its dependencies.

#### Related Issues

- None

#### Possible Duplicates

- None

## Environment & Settings
<!-- Include the contents of celery --version below -->
**Celery version**: v5.0.5
<!-- Include the output of celery -A proj report below -->
<details>
<summary><b><code>celery report</code> Output:</b></summary>
<p>

```
```

</p>
</details>

# Steps to Reproduce

## Required Dependencies
<!-- Please fill the required dependencies to reproduce this issue -->
* **Minimal Python Version**: N/A or Unknown
* **Minimal Celery Version**: N/A or Unknown
* **Minimal Kombu Version**: N/A or Unknown
* **Minimal Broker Version**: N/A or Unknown
* **Minimal Result Backend Version**: N/A or Unknown
* **Minimal OS and/or Kernel Version**: N/A or Unknown
* **Minimal Broker Client Version**: N/A or Unknown
* **Minimal Result Backend Client Version**: N/A or Unknown

### Python Packages
<!-- Please fill the contents of pip freeze below -->
<details>
<summary><b><code>pip freeze</code> Output:</b></summary>
<p>

```
```

</p>
</details>

### Other Dependencies
<!--
Please provide system dependencies, configuration files
and other dependency information if applicable
-->
<details>
<p>
N/A
</p>
</details>

## Minimally Reproducible Test Case
<!--
Please provide a reproducible test case.
Refer to the Reporting Bugs section in our contribution guide.

We prefer submitting test cases in the form of a PR to our integration test suite.
If you can provide one, please mention the PR number below.
If not, please attach the most minimal code example required to reproduce the issue below.
If the test case is too large, please include a link to a gist or a repository below.
-->

<details>
<p>

```
CELERY_BROKER_URL = 'sentinel://:my_redis_password@server1.com:26379/0;sentinel://:my_redis_password@server2.com:26379/0;sentinel://:my_redis_password@server3.com:26379/0' 

CELERY_RESULT_BACKEND = 'sentinel://:my_redis_password@server1.com:26379/0;sentinel://:my_redis_password@server2.com:26379/0;sentinel://:my_redis_password@server3.com:26379/0' 
```

</p>
</details>

# Expected Behavior
<!-- Describe in detail what you expect to happen -->
```
- ** ---------- .> transport:   sentinel://:**@server1.com:26379/0
- ** ---------- .> results:     sentinel://:**@server1.com:26379/0;sentinel://:**@server2.com:26379/0;sentinel://:**@server3.com:26379/0
- *** --- * --- .> concurrency: 8 (prefork)
```
# Actual Behavior
```
- ** ---------- .> transport:   sentinel://:**@server1.com:26379/0
- ** ---------- .> results:     sentinel://:**@server1.com:26379/0;sentinel://:my_redis_password@server2.com:26379/0;sentinel://:my_redis_password@server3.com:26379/0
- *** --- * --- .> concurrency: 8 (prefork)
```

The results output in celery (at launch) shows the redis sentinel password when using results.



Discussion:
Hey @K-MTG :wave:,
Thank you for opening an issue. We will get back to you as soon as we can.
Also, check out our [Open Collective](https://opencollective.com/celery) and consider backing us - every little helps!

We also offer priority support for our sponsors.
If you require immediate assistance please consider sponsoring us.


Resolving patch:
diff --git a/celery/backends/redis.py b/celery/backends/redis.py
--- a/celery/backends/redis.py
+++ b/celery/backends/redis.py
@@ -7,7 +7,7 @@
 
 from kombu.utils.functional import retry_over_time
 from kombu.utils.objects import cached_property
-from kombu.utils.url import _parse_url
+from kombu.utils.url import _parse_url, maybe_sanitize_url
 
 from celery import states
 from celery._state import task_join_will_block
@@ -585,6 +585,8 @@ class SentinelManagedSSLConnection(
 
 class SentinelBackend(RedisBackend):
     """Redis sentinel task result store."""
+    # URL looks like `sentinel://0.0.0.0:26347/3;sentinel://0.0.0.0:26348/3`
+    _SERVER_URI_SEPARATOR = ";"
 
     sentinel = getattr(redis, "sentinel", None)
     connection_class_ssl = SentinelManagedSSLConnection if sentinel else None
@@ -595,9 +597,30 @@ def __init__(self, *args, **kwargs):
 
         super().__init__(*args, **kwargs)
 
+    def as_uri(self, include_password=False):
+        """
+        Return the server addresses as URIs, sanitizing the password or not.
+        """
+        # Allow superclass to do work if we don't need to force sanitization
+        if include_password:
+            return super(SentinelBackend, self).as_uri(
+                include_password=include_password,
+            )
+        # Otherwise we need to ensure that all components get sanitized rather
+        # by passing them one by one to the `kombu` helper
+        uri_chunks = (
+            maybe_sanitize_url(chunk)
+            for chunk in (self.url or "").split(self._SERVER_URI_SEPARATOR)
+        )
+        # Similar to the superclass, strip the trailing slash from URIs with
+        # all components empty other than the scheme
+        return self._SERVER_URI_SEPARATOR.join(
+            uri[:-1] if uri.endswith(":///") else uri
+            for uri in uri_chunks
+        )
+
     def _params_from_url(self, url, defaults):
-        # URL looks like sentinel://0.0.0.0:26347/3;sentinel://0.0.0.0:26348/3.
-        chunks = url.split(";")
+        chunks = url.split(self._SERVER_URI_SEPARATOR)
         connparams = dict(defaults, hosts=[])
         for chunk in chunks:
             data = super()._params_from_url(


Test patch:
diff --git a/t/unit/backends/test_redis.py b/t/unit/backends/test_redis.py
--- a/t/unit/backends/test_redis.py
+++ b/t/unit/backends/test_redis.py
@@ -1203,6 +1203,16 @@ def test_url(self):
         found_dbs = [cp['db'] for cp in x.connparams['hosts']]
         assert found_dbs == expected_dbs
 
+        # By default passwords should be sanitized
+        display_url = x.as_uri()
+        assert "test" not in display_url
+        # We can choose not to sanitize with the `include_password` argument
+        unsanitized_display_url = x.as_uri(include_password=True)
+        assert unsanitized_display_url == x.url
+        # or to explicitly sanitize
+        forcibly_sanitized_display_url = x.as_uri(include_password=False)
+        assert forcibly_sanitized_display_url == display_url
+
     def test_get_sentinel_instance(self):
         x = self.Backend(
             'sentinel://:test@github.com:123/1;'