This is an automated email from the ASF dual-hosted git repository.
gabotorresruiz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new e46b5e58182 feat(databases): expose safe hints for masked
encrypted_extra fields (#45996)
e46b5e58182 is described below
commit e46b5e581825ac4132da4cc7c813d619710e7539
Author: Gabriel Torres Ruiz <[email protected]>
AuthorDate: Tue Nov 17 22:07:19 2026 -0300
feat(databases): expose safe hints for masked encrypted_extra fields
(#45996)
---
UPDATING.md | 10 +
.../configuration/configuring-superset.mdx | 24 ++
docs/static/resources/openapi.json | 99 +++++
.../commands/database/encrypted_extra_hints.py | 50 +++
superset/config.py | 6 +
superset/constants.py | 1 +
superset/databases/api.py | 79 ++++
superset/databases/schemas.py | 34 ++
superset/db_engine_specs/README.md | 2 +
superset/db_engine_specs/base.py | 70 +++-
superset/models/core.py | 22 +
superset/utils/json.py | 114 ++++++
superset/views/base.py | 1 +
tests/integration_tests/databases/api_tests.py | 60 +++
tests/unit_tests/databases/api_test.py | 443 +++++++++++++++++++++
tests/unit_tests/databases/test_schemas.py | 18 +
tests/unit_tests/db_engine_specs/test_base.py | 167 ++++++++
tests/unit_tests/db_engine_specs/test_druid.py | 54 +++
tests/unit_tests/db_engine_specs/test_presto.py | 77 ++++
tests/unit_tests/db_engine_specs/test_trino.py | 74 ++++
tests/unit_tests/models/core_test.py | 77 ++++
tests/unit_tests/utils/json_tests.py | 429 ++++++++++++++++++++
22 files changed, 1910 insertions(+), 1 deletion(-)
diff --git a/UPDATING.md b/UPDATING.md
index cfc7dd329b6..5a32fa169f6 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -49,6 +49,16 @@ assists people when migrating to a new version.
dropdown cache settings. Resolved defaults and other unambiguous selections
do not require this additional listing.
+- New config `ENCRYPTED_EXTRA_HINT_CHARS` (default `0`, off): when set above
+ zero, users who can edit a database can reveal the last characters of each
+ stored secret in its Secure extra, at most 25% of a value, through
+ `GET /api/v1/database/<pk>/encrypted_extra_hints/`. See
+ [Configuring
Superset](docs/admin_docs/configuration/configuring-superset.mdx).
+ Whatever the setting, `engine_information` on the database endpoints gains
+ `encrypted_extra_sensitive_fields`, the engine's declared sensitive paths
+ and labels, and `GET /api/v1/database/<pk>/connection` lists the fields
+ stored in that database instead.
+
- With `ENABLE_VIEWERS` and `VIEWER_PROMISCUOUS_MODE` on, the dashboard grant
follows the legacy `DASHBOARD_RBAC` model: only the listed viewers of a
published dashboard read its charts and datasets without dataset permissions,
diff --git a/docs/admin_docs/configuration/configuring-superset.mdx
b/docs/admin_docs/configuration/configuring-superset.mdx
index 06854743ddc..8b2c9511de4 100644
--- a/docs/admin_docs/configuration/configuring-superset.mdx
+++ b/docs/admin_docs/configuration/configuring-superset.mdx
@@ -267,6 +267,30 @@ from flask import current_app;
print(current_app.config["SECRET_KEY"])
Save your `superset_config.py` with these values and then run `superset
re-encrypt-secrets`.
+## Revealing the ending of stored database secrets
+
+The Secure extra field of a database connection is masked once saved, so an
+editor cannot tell which token or key is stored, for example after a rotation.
+Set `ENCRYPTED_EXTRA_HINT_CHARS` to let editors reveal the last characters of
+each stored secret:
+
+```python
+ENCRYPTED_EXTRA_HINT_CHARS = 5
+```
+
+The default, `0`, turns the feature off. When it is above zero, the ending of
+each secret stored at a sensitive path of the engine can be requested from the
+endpoint below.
+
+- At most 25% of a value is ever revealed: a value shorter than four times the
+ configured number of characters reveals nothing, and its length is not
+ reported either.
+- For a PEM private key, the ending comes from its base64 body, without the
+ fixed footer, the line breaks or the padding.
+- The endings come from
+ `GET /api/v1/database/<pk>/encrypted_extra_hints/`, which requires the same
+ permission as editing the database. Each call is recorded in the event log.
+
## Setting up a production metadata database
Superset needs a database to store the information it manages, like the
definitions of
diff --git a/docs/static/resources/openapi.json
b/docs/static/resources/openapi.json
index 63fe277121b..f34f6eaa2a1 100644
--- a/docs/static/resources/openapi.json
+++ b/docs/static/resources/openapi.json
@@ -7854,12 +7854,52 @@
},
"type": "object"
},
+ "EncryptedExtraHintSchema": {
+ "properties": {
+ "label": {
+ "description": "Human readable name of the masked field",
+ "type": "string"
+ },
+ "path": {
+ "description": "JSONPath of the masked field",
+ "type": "string"
+ },
+ "suffix": {
+ "description": "Last characters of the stored value (of the base64
body for a PEM key), null when the value is too short to reveal any",
+ "nullable": true,
+ "type": "string"
+ }
+ },
+ "required": [
+ "label",
+ "path"
+ ],
+ "type": "object"
+ },
+ "EncryptedExtraHintsResponseSchema": {
+ "properties": {
+ "result": {
+ "items": {
+ "$ref": "#/components/schemas/EncryptedExtraHintSchema"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
"EngineInformation": {
"properties": {
"disable_ssh_tunneling": {
"description": "SSH tunnel is not available to the database",
"type": "boolean"
},
+ "encrypted_extra_sensitive_fields": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "JSONPath of each sensitive encrypted_extra field
and its label. On the database GET and on `available`: the engine's declared
patterns. On `/connection`: the fields present in the stored encrypted_extra.",
+ "type": "object"
+ },
"identifier_quote": {
"allOf": [
{
@@ -22659,6 +22699,13 @@
"description": "Whether the engine supports SSH
Tunnels",
"type": "boolean"
},
+ "encrypted_extra_sensitive_fields": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "JSONPath of each sensitive
encrypted_extra field and its label",
+ "type": "object"
+ },
"supports_file_upload": {
"description": "Whether the engine supports file
uploads",
"type": "boolean"
@@ -23450,6 +23497,58 @@
]
}
},
+ "/api/v1/database/{pk}/encrypted_extra_hints/": {
+ "get": {
+ "description": "Returns the label and last characters of each
sensitive field in the database's encrypted extra, so that a stored secret can
be told apart from another one without revealing it. The number of characters
is set by `ENCRYPTED_EXTRA_HINT_CHARS`; the list is empty when it is 0 or
less.",
+ "parameters": [
+ {
+ "description": "The database id",
+ "in": "path",
+ "name": "pk",
+ "required": true,
+ "schema": {
+ "type": "integer"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref":
"#/components/schemas/EncryptedExtraHintsResponseSchema"
+ }
+ }
+ },
+ "description": "Hints for the masked fields"
+ },
+ "401": {
+ "$ref": "#/components/responses/401"
+ },
+ "403": {
+ "$ref": "#/components/responses/403"
+ },
+ "404": {
+ "$ref": "#/components/responses/404"
+ },
+ "500": {
+ "$ref": "#/components/responses/500"
+ }
+ },
+ "security": [
+ {
+ "jwt": []
+ },
+ {
+ "api_key": []
+ }
+ ],
+ "summary": "Get hints for the masked fields of a database's encrypted
extra",
+ "tags": [
+ "Database"
+ ]
+ }
+ },
"/api/v1/database/{pk}/function_names/": {
"get": {
"parameters": [
diff --git a/superset/commands/database/encrypted_extra_hints.py
b/superset/commands/database/encrypted_extra_hints.py
new file mode 100644
index 00000000000..222d958563b
--- /dev/null
+++ b/superset/commands/database/encrypted_extra_hints.py
@@ -0,0 +1,50 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+from typing import Any
+
+from flask import current_app as app
+
+from superset.commands.base import BaseCommand
+from superset.commands.database.exceptions import DatabaseNotFoundError
+from superset.daos.database import DatabaseDAO
+from superset.models.core import Database
+
+
+class GetEncryptedExtraHintsCommand(BaseCommand):
+ """
+ Return hints (label and short suffix) for the string secrets stored in a
+ database's `encrypted_extra`, sized by `ENCRYPTED_EXTRA_HINT_CHARS`.
+ """
+
+ def __init__(self, model_id: int):
+ self._model_id = model_id
+ self._model: Database | None = None
+
+ def run(self) -> list[dict[str, Any]]:
+ self.validate()
+ assert self._model
+ return self._model.db_engine_spec.encrypted_extra_hints(
+ self._model.encrypted_extra,
+ int(app.config["ENCRYPTED_EXTRA_HINT_CHARS"]),
+ )
+
+ def validate(self) -> None:
+ self._model = DatabaseDAO.find_by_id(self._model_id)
+ if not self._model:
+ raise DatabaseNotFoundError()
diff --git a/superset/config.py b/superset/config.py
index 0e5166b0c36..d2190b72c7d 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -3281,6 +3281,12 @@ STATIC_ASSETS_PREFIX = ""
# Typically these should not be allowed.
PREVENT_UNSAFE_DB_CONNECTIONS = True
+# Number of trailing characters of each masked `encrypted_extra` field that
users
+# who can edit a database may reveal as a hint. Never more than 25% of a value
is
+# revealed: a value shorter than four times this number reveals nothing. 0
disables
+# the hints.
+ENCRYPTED_EXTRA_HINT_CHARS = 0
+
# If true all default urls on datasets will be handled as relative URLs by the
frontend
PREVENT_UNSAFE_DEFAULT_URLS_ON_DATASET = True
diff --git a/superset/constants.py b/superset/constants.py
index 98a5785c9cd..5c894e6957d 100644
--- a/superset/constants.py
+++ b/superset/constants.py
@@ -202,6 +202,7 @@ MODEL_API_RW_METHOD_PERMISSION_MAP = {
"delete_object": "write",
"copy_dash": "write",
"get_connection": "write",
+ "encrypted_extra_hints": "write",
"upload_metadata": "upload",
"slack_channels": "write",
"put_filters": "write",
diff --git a/superset/databases/api.py b/superset/databases/api.py
index c0406b1c01c..efea9d9690c 100644
--- a/superset/databases/api.py
+++ b/superset/databases/api.py
@@ -19,6 +19,7 @@
from __future__ import annotations
import logging
+from collections.abc import Callable
from datetime import datetime
from io import BytesIO
from typing import Any, cast
@@ -41,6 +42,9 @@ from sqlalchemy.exc import NoSuchTableError,
OperationalError, SQLAlchemyError
from superset import event_logger
from superset.commands.database.create import CreateDatabaseCommand
from superset.commands.database.delete import DeleteDatabaseCommand
+from superset.commands.database.encrypted_extra_hints import (
+ GetEncryptedExtraHintsCommand,
+)
from superset.commands.database.exceptions import (
DatabaseConnectionFailedError,
DatabaseCreateFailedError,
@@ -109,6 +113,8 @@ from superset.databases.schemas import (
DatabaseTablesResponse,
DatabaseTestConnectionSchema,
DatabaseValidateParametersSchema,
+ EncryptedExtraHintSchema,
+ EncryptedExtraHintsResponseSchema,
get_export_ids_schema,
OAuth2ProviderResponseSchema,
openapi_spec_methods_override,
@@ -191,6 +197,7 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
"delete_ssh_tunnel",
"schemas_access_for_file_upload",
"get_connection",
+ "encrypted_extra_hints",
"upload_metadata",
"upload",
"oauth2",
@@ -321,6 +328,8 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
DatabaseTablesResponse,
DatabaseTestConnectionSchema,
DatabaseValidateParametersSchema,
+ EncryptedExtraHintSchema,
+ EncryptedExtraHintsResponseSchema,
TableExtraMetadataResponseSchema,
TableMetadataResponseSchema,
SelectStarResponseSchema,
@@ -378,6 +387,12 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
"id": pk,
"result": database_connection_schema.dump(database, many=False),
}
+ # editors get the sensitive fields stored for this database, not the
+ # engine's declared patterns
+ if database and (information :=
response["result"].get("engine_information")):
+ information["encrypted_extra_sensitive_fields"] = (
+ database.stored_sensitive_fields()
+ )
try:
if database and database.ssh_tunnel:
# Mask credential fields explicitly at the API boundary so read
@@ -390,6 +405,63 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
except SupersetException as ex:
return self.response(ex.status, message=ex.message)
+ @expose("/<int:pk>/encrypted_extra_hints/", methods=("GET",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.encrypted_extra_hints"
+ ),
+ log_to_statsd=False,
+ include_request_data=False,
+ allow_extra_payload=True,
+ )
+ def encrypted_extra_hints(
+ self, pk: int, add_extra_log_payload: Callable[..., None]
+ ) -> Response:
+ """Get hints for the masked fields of a database's encrypted extra.
+ ---
+ get:
+ summary: Get hints for the masked fields of a database's encrypted
extra
+ description: >-
+ Returns the label and last characters of each sensitive field in
+ the database's encrypted extra, so that a stored secret can be told
+ apart from another one without revealing it. The number of
+ characters is set by `ENCRYPTED_EXTRA_HINT_CHARS`; the list is
empty
+ when it is 0 or less.
+ parameters:
+ - in: path
+ schema:
+ type: integer
+ description: The database id
+ name: pk
+ responses:
+ 200:
+ description: Hints for the masked fields
+ content:
+ application/json:
+ schema:
+ $ref:
"#/components/schemas/EncryptedExtraHintsResponseSchema"
+ 401:
+ $ref: '#/components/responses/401'
+ 403:
+ $ref: '#/components/responses/403'
+ 404:
+ $ref: '#/components/responses/404'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ hints = GetEncryptedExtraHintsCommand(pk).run()
+ except DatabaseNotFoundError:
+ return self.response_404()
+ # the event names the database even though it carries no request data
+ add_extra_log_payload(database_id=pk)
+ return self.response(
+ 200, result=EncryptedExtraHintSchema(many=True).dump(hints)
+ )
+
@expose("/<int:pk>", methods=("GET",))
@protect()
@safe
@@ -1994,6 +2066,13 @@ class DatabaseRestApi(BaseSupersetModelRestApi):
disable_ssh_tunneling:
description: Whether the engine supports SSH
Tunnels
type: boolean
+ encrypted_extra_sensitive_fields:
+ description: >-
+ JSONPath of each sensitive encrypted_extra
field
+ and its label
+ type: object
+ additionalProperties:
+ type: string
400:
$ref: '#/components/responses/400'
500:
diff --git a/superset/databases/schemas.py b/superset/databases/schemas.py
index 67f4e4d32d4..458d7f7f075 100644
--- a/superset/databases/schemas.py
+++ b/superset/databases/schemas.py
@@ -1135,6 +1135,28 @@ class CatalogsResponseSchema(Schema):
)
+class EncryptedExtraHintSchema(Schema):
+ path = fields.String(
+ required=True,
+ metadata={"description": "JSONPath of the masked field"},
+ )
+ label = fields.String(
+ required=True,
+ metadata={"description": "Human readable name of the masked field"},
+ )
+ suffix = fields.String(
+ allow_none=True,
+ metadata={
+ "description": "Last characters of the stored value (of the base64
"
+ "body for a PEM key), null when the value is too short to reveal
any"
+ },
+ )
+
+
+class EncryptedExtraHintsResponseSchema(Schema):
+ result = fields.List(fields.Nested(EncryptedExtraHintSchema))
+
+
class DatabaseTablesResponse(Schema):
extra = fields.Dict(
metadata={"description": "Extra data used to specify column metadata"}
@@ -1560,6 +1582,18 @@ class EngineInformationSchema(Schema):
"description": "Characters used to quote identifiers for this
dialect"
},
)
+ encrypted_extra_sensitive_fields = fields.Dict(
+ keys=fields.String(),
+ values=fields.String(),
+ metadata={
+ "description": (
+ "JSONPath of each sensitive encrypted_extra field and its
label. "
+ "On the database GET and on `available`: the engine's declared
"
+ "patterns. On `/connection`: the fields present in the stored "
+ "encrypted_extra."
+ )
+ },
+ )
class DatabaseConnectionSchema(Schema):
diff --git a/superset/db_engine_specs/README.md
b/superset/db_engine_specs/README.md
index 9b20995403e..de86c1fc6d4 100644
--- a/superset/db_engine_specs/README.md
+++ b/superset/db_engine_specs/README.md
@@ -1108,6 +1108,8 @@ This way, when a user edits an existing BigQuery
connection, the `private_key` i
Note that while this is a basic feature that should be implemented for
security reasons, it only makes sense in DB engine specs that use
`encrypted_extra` to store connection information.
+Masked fields can also come with a hint that helps tell stored secrets apart,
for example after a token rotation. When `ENCRYPTED_EXTRA_HINT_CHARS` is
greater than zero, `encrypted_extra_hints` returns, for each string found at a
path from `encrypted_extra_sensitive_field_paths`, its label, path and last
characters. The suffix is `None` when the value is shorter than four times the
configured length, so at most 25% of a value is ever revealed, and the length
of the value is never returne [...]
+
## Nice to have features
The next set of features are nice to have. They don't apply to all databases,
and are not strictly needed for security or usability.
diff --git a/superset/db_engine_specs/base.py b/superset/db_engine_specs/base.py
index 74397060feb..303e6b1e48e 100644
--- a/superset/db_engine_specs/base.py
+++ b/superset/db_engine_specs/base.py
@@ -108,7 +108,11 @@ from superset.superset_typing import (
from superset.utils import core as utils, json
from superset.utils.core import ColumnSpec, GenericDataType, QuerySource
from superset.utils.hashing import hash_from_str
-from superset.utils.json import redact_sensitive, reveal_sensitive
+from superset.utils.json import (
+ get_sensitive_field_hints,
+ redact_sensitive,
+ reveal_sensitive,
+)
from superset.utils.network import (
get_ssrf_safe_requester,
is_hostname_valid,
@@ -3482,6 +3486,67 @@ class BaseEngineSpec: # pylint:
disable=too-many-public-methods
return json.dumps(new_config)
+ @classmethod
+ def encrypted_extra_sensitive_field_labels(cls) -> dict[str, str]:
+ """
+ Map each sensitive `encrypted_extra` JSONPath to its human label,
sorted
+ by path. Paths without a declared label use their last segment, except
+ the secrets every engine adds (the OAuth2 client secret and the
embedded
+ guest credential), which get readable defaults.
+ """
+ declared = {
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ f"$.{EMBEDDED_CREDENTIALS_KEY}.password": "Embedded guest
password",
+ f"$.{EMBEDDED_CREDENTIALS_KEY}.privatekey_body": (
+ "Embedded guest private key (PEM)"
+ ),
+ f"$.{EMBEDDED_CREDENTIALS_KEY}.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ **(
+ cls.encrypted_extra_sensitive_fields
+ if isinstance(cls.encrypted_extra_sensitive_fields, dict)
+ else {}
+ ),
+ }
+ return {
+ path: declared.get(path, path.rsplit(".", 1)[-1])
+ for path in sorted(cls.encrypted_extra_sensitive_field_paths())
+ }
+
+ @classmethod
+ def encrypted_extra_hints(
+ cls, encrypted_extra: str | None, length: int
+ ) -> list[dict[str, Any]]:
+ """
+ Hints for the sensitive fields of `encrypted_extra`.
+
+ Each hint has the field `path`, a human `label` and the last `length`
+ characters of the stored value as `suffix` (``None`` when the value is
too
+ short to reveal any). Returns an empty list when `encrypted_extra` is
+ missing or malformed, or when `length` is not positive.
+ """
+ if encrypted_extra is None or length <= 0:
+ return []
+
+ try:
+ config = json.loads(encrypted_extra)
+ except (TypeError, json.JSONDecodeError):
+ return []
+
+ if not isinstance(config, dict):
+ return []
+
+ labels = cls.encrypted_extra_sensitive_field_labels()
+ return [
+ {**hint, "label": labels.get(hint["path"],
hint["path"].rsplit(".", 1)[-1])}
+ for hint in get_sensitive_field_hints(
+ config,
+ cls.encrypted_extra_sensitive_field_paths(),
+ length,
+ )
+ ]
+
@classmethod
def get_connection_identity(cls, uri: URL, connect_args: dict[str, Any])
-> URL:
"""
@@ -3523,6 +3588,9 @@ class BaseEngineSpec: # pylint:
disable=too-many-public-methods
"supports_oauth2": cls.supports_oauth2,
"supports_schemas": cls.supports_schemas,
"supports_offset": cls.supports_offset,
+ "encrypted_extra_sensitive_fields": (
+ cls.encrypted_extra_sensitive_field_labels()
+ ),
"identifier_quote": {
"start": cls.identifier_quote_start,
"end": cls.identifier_quote_end,
diff --git a/superset/models/core.py b/superset/models/core.py
index a1a64fe1200..ac84124f351 100755
--- a/superset/models/core.py
+++ b/superset/models/core.py
@@ -577,6 +577,28 @@ class Database(CoreDatabase, AuditMixinNullable,
ImportExportMixin): # pylint:
engine_information["oauth2_enabled"] = False
return engine_information
+ def stored_sensitive_fields(self) -> dict[str, str]:
+ """
+ Label of each sensitive field stored in `encrypted_extra`, by concrete
path.
+
+ Only string values count, sorted by path. Paths declared exactly use
their
+ declared label, any other path its last segment. A missing or malformed
+ `encrypted_extra` gives an empty dict.
+ """
+ try:
+ config = json.loads(self.encrypted_extra or "{}")
+ except (TypeError, json.JSONDecodeError):
+ return {}
+
+ spec = self.db_engine_spec
+ labels = spec.encrypted_extra_sensitive_field_labels()
+ return {
+ path: labels.get(path, path.rsplit(".", 1)[-1])
+ for path in json.get_sensitive_field_paths(
+ config, spec.encrypted_extra_sensitive_field_paths()
+ )
+ }
+
@classmethod
def get_password_masked_url_from_uri( # pylint: disable=invalid-name
cls, uri: str
diff --git a/superset/utils/json.py b/superset/utils/json.py
index cb946c7319c..6bf5bafc25c 100644
--- a/superset/utils/json.py
+++ b/superset/utils/json.py
@@ -17,6 +17,7 @@
import copy
import decimal
import logging
+import re
import uuid
from datetime import date, datetime, time, timedelta
from typing import Any, Callable, Dict, Optional, Union
@@ -400,6 +401,119 @@ def unrevealable_masked_fields(
]
+# A PEM block with an RFC 7468 label (`PRIVATE KEY`, `PKCS7`, `X509 CRL`, ...).
+# The label holds no dash, so it cannot run on into the closing dashes.
+_PEM_BLOCK = re.compile(r"-----BEGIN ([^-\r\n]+)-----(.+?)-----END \1-----",
re.DOTALL)
+_PEM_LINE_BREAKS = re.compile(r"\s|\\[rn]")
+
+
+def _pem_body(value: str) -> str | None:
+ """
+ Return the base64 body of the last PEM block without line breaks or
padding,
+ or ``None`` when the value does not end with a complete block.
+
+ Every PEM value ends with the same ``-----END <label>-----`` footer, so
only
+ the body tells two keys apart. The trailing ``=`` padding carries nothing
either.
+ A key followed by its certificate takes the certificate's body, the block
the
+ value ends with. Only the last header is tried, so the scan stays linear.
+ """
+ start = value.rfind("-----BEGIN ")
+ if start != -1 and (match := _PEM_BLOCK.match(value, start)):
+ return _PEM_LINE_BREAKS.sub("", match.group(2)).rstrip("=")
+ return None
+
+
+def _dotted_path_holds(node: Any) -> bool:
+ """
+ Whether every key on a matched path reads back the same from a dotted path:
+ a key with a dot would read as a nested path, and a key named ``*`` as a
+ wildcard.
+ """
+ if isinstance(node, Child):
+ return _dotted_path_holds(node.left) and _dotted_path_holds(node.right)
+ if isinstance(node, Fields):
+ return all("." not in field and field != "*" for field in node.fields)
+ return True
+
+
+def _sensitive_string_values(
+ payload: dict[str, Any],
+ sensitive_fields: set[str],
+) -> dict[str, str]:
+ """
+ Map each concrete path whose value is a string to that value, sorted by
path.
+ Keys a dotted path cannot tell apart (a dot, or ``*``) are left out.
+ """
+ if not isinstance(payload, dict):
+ return {}
+
+ values: dict[str, str] = {}
+ for json_path in sensitive_fields:
+ for match in parse(json_path).find(payload):
+ if isinstance(match.value, str) and
_dotted_path_holds(match.full_path):
+ values[f"$.{_render_jsonpath(match.full_path)}"] = match.value
+ return dict(sorted(values.items()))
+
+
+def get_sensitive_field_paths(
+ payload: dict[str, Any],
+ sensitive_fields: set[str],
+) -> list[str]:
+ """
+ Returns the concrete paths of the string values found at sensitive paths.
+
+ Wildcards expand per match and non-string values are skipped, so the result
+ lists exactly the fields :func:`get_sensitive_field_hints` would hint.
+
+ :param payload: The payload to inspect; anything but a dict yields no paths
+ :param sensitive_fields: The set of fields to look for, as JSONPath
expressions
+ :returns: JSONPath expressions sorted by path
+ """
+ return list(_sensitive_string_values(payload, sensitive_fields))
+
+
+def get_sensitive_field_hints(
+ payload: dict[str, Any],
+ sensitive_fields: set[str],
+ length: int,
+) -> list[dict[str, Any]]:
+ """
+ Returns a hint for each string value found at a sensitive path.
+
+ A hint holds the path and, when the trimmed value is at least ``4 *
length``
+ characters long, its last ``length`` characters. That caps what is
revealed at
+ 25% of the value; a shorter value gets no suffix and its length is not
reported
+ either, since a length alone can identify a short secret. For a PEM block,
the
+ suffix and the cap apply to its base64 body without padding. A stored mask,
+ which older imports saved, gets no suffix either: its ending would read as
+ still masked.
+
+ :param payload: The payload to inspect
+ :param sensitive_fields: The set of fields to hint, as JSONPath expressions
+ :param length: The number of trailing characters to reveal; ``<= 0``
disables hints
+ :returns: Hints sorted by path, as ``{"path", "suffix"}`` dicts
+ """
+ if length <= 0:
+ return []
+
+ hints: list[dict[str, Any]] = []
+ for path, stored in _sensitive_string_values(payload,
sensitive_fields).items():
+ value = stored.strip()
+ body = _pem_body(value)
+ revealable = value if body is None else body
+ hints.append(
+ {
+ "path": path,
+ "suffix": (
+ revealable[-length:]
+ if len(revealable) >= 4 * length and value != PASSWORD_MASK
+ else None
+ ),
+ }
+ )
+ return hints
+
+
def set_masked_fields(
payload: dict[str, Any],
path_values: dict[str, Any],
diff --git a/superset/views/base.py b/superset/views/base.py
index d4a4732bd81..82887455b5c 100644
--- a/superset/views/base.py
+++ b/superset/views/base.py
@@ -145,6 +145,7 @@ FRONTEND_CONF_KEYS = (
"CSV_STREAMING_ROW_THRESHOLD",
"EMBEDDED_DISABLE_PERMALINK_ORIGIN_REWRITE",
"SCARF_ANALYTICS",
+ "ENCRYPTED_EXTRA_HINT_CHARS",
)
logger = logging.getLogger(__name__)
diff --git a/tests/integration_tests/databases/api_tests.py
b/tests/integration_tests/databases/api_tests.py
index 7edb992217a..66f430ec827 100644
--- a/tests/integration_tests/databases/api_tests.py
+++ b/tests/integration_tests/databases/api_tests.py
@@ -3962,6 +3962,14 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": True,
"sqlalchemy_uri_placeholder":
"postgresql://user:password@host:port/dbname[?key=value&key=value...]",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.aws_iam.external_id": "AWS IAM External ID",
+ "$.aws_iam.role_arn": "AWS IAM Role ARN",
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": True,
"disable_ssh_tunneling": False,
@@ -3997,6 +4005,13 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": True,
"sqlalchemy_uri_placeholder": "bigquery://{project_id}",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.credentials_info.private_key": "Service Account
Private Key", # noqa: E501
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": True,
"disable_ssh_tunneling": True,
@@ -4062,6 +4077,14 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": False,
"sqlalchemy_uri_placeholder":
"redshift+psycopg2://user:password@host:port/dbname[?key=value&key=value...]",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.aws_iam.external_id": "AWS IAM External ID",
+ "$.aws_iam.role_arn": "AWS IAM Role ARN",
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": False,
"disable_ssh_tunneling": False,
@@ -4114,6 +4137,13 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": False,
"sqlalchemy_uri_placeholder": "gsheets://",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 Client
Secret",
+ "$.service_account_info.private_key": "Service
Account Private Key", # noqa: E501
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": False,
"disable_ssh_tunneling": True,
@@ -4179,6 +4209,14 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": False,
"sqlalchemy_uri_placeholder":
"mysql://user:password@host:port/dbname[?key=value&key=value...]",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.aws_iam.external_id": "AWS IAM External ID",
+ "$.aws_iam.role_arn": "AWS IAM Role ARN",
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": False,
"disable_ssh_tunneling": False,
@@ -4200,6 +4238,13 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": False,
"sqlalchemy_uri_placeholder":
"engine+driver://user:password@host:port/dbname[?key=value&key=value...]",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.*": "Encrypted Extra",
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": False,
"disable_ssh_tunneling": False,
@@ -4241,6 +4286,14 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": True,
"sqlalchemy_uri_placeholder":
"mysql://user:password@host:port/dbname[?key=value&key=value...]",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.aws_iam.external_id": "AWS IAM External ID",
+ "$.aws_iam.role_arn": "AWS IAM Role ARN",
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": False,
"disable_ssh_tunneling": False,
@@ -4262,6 +4315,13 @@ class TestDatabaseApi(SupersetTestCase):
"preferred": False,
"sqlalchemy_uri_placeholder":
"engine+driver://user:password@host:port/dbname[?key=value&key=value...]",
"engine_information": {
+ "encrypted_extra_sensitive_fields": {
+ "$.*": "Encrypted Extra",
+ "$.embedded_credentials.password": "Embedded guest
password", # noqa: E501
+ "$.embedded_credentials.privatekey_body":
"Embedded guest private key (PEM)", # noqa: E501
+ "$.embedded_credentials.privatekey_pass":
"Embedded guest private key passphrase", # noqa: E501
+ "$.oauth2_client_info.secret": "OAuth2 client
secret",
+ },
"supports_file_upload": True,
"supports_dynamic_catalog": False,
"disable_ssh_tunneling": False,
diff --git a/tests/unit_tests/databases/api_test.py
b/tests/unit_tests/databases/api_test.py
index fc844e4f3e8..45e2061d502 100644
--- a/tests/unit_tests/databases/api_test.py
+++ b/tests/unit_tests/databases/api_test.py
@@ -338,6 +338,11 @@ def test_database_connection(
"engine_information": {
"oauth2_enabled": False,
"disable_ssh_tunneling": True,
+ "encrypted_extra_sensitive_fields": {
+ "$.service_account_info.private_key": (
+ "Service Account Private Key"
+ ),
+ },
"supports_dynamic_catalog": False,
"supports_file_upload": True,
"supports_oauth2": True,
@@ -435,6 +440,19 @@ def test_database_connection(
"engine_information": {
"oauth2_enabled": False,
"disable_ssh_tunneling": True,
+ "encrypted_extra_sensitive_fields": {
+ "$.embedded_credentials.password": "Embedded guest
password",
+ "$.embedded_credentials.privatekey_body": (
+ "Embedded guest private key (PEM)"
+ ),
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 Client Secret",
+ "$.service_account_info.private_key": (
+ "Service Account Private Key"
+ ),
+ },
"supports_dynamic_catalog": False,
"supports_file_upload": True,
"supports_oauth2": True,
@@ -456,6 +474,339 @@ def test_database_connection(
}
+JWT_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZXJ2aWNlIn0.c2lnbmF0dXJlabcde"
# noqa: S105
+
+
+def add_druid_database(session: Session, encrypted_extra: str) -> None:
+ """
+ Store a Druid database with the given ``encrypted_extra``.
+ """
+ from superset.databases.api import DatabaseRestApi
+ from superset.models.core import Database
+
+ DatabaseRestApi.datamodel._session = session
+ Database.metadata.create_all(session.get_bind()) # pylint:
disable=no-member
+ db.session.add(
+ Database(
+ database_name="my_druid",
+ sqlalchemy_uri="druid://localhost:8082/druid/v2/sql/",
+ encrypted_extra=encrypted_extra,
+ )
+ )
+ db.session.commit()
+
+
+def test_encrypted_extra_hints(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """
+ The endpoint returns a hint per sensitive field and never the value itself.
+ """
+ add_druid_database(
+ session,
+ json.dumps(
+ {
+ "connect_args": {
+ "scheme": "https",
+ "jwt": JWT_TOKEN,
+ "password": "hunter2",
+ }
+ }
+ ),
+ )
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ event_log = mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 200
+ assert response.json == {
+ "result": [
+ {
+ "path": "$.connect_args.jwt",
+ "label": "JWT Token",
+ "suffix": "abcde",
+ },
+ {
+ "path": "$.connect_args.password",
+ "label": "Password",
+ "suffix": None,
+ },
+ ]
+ }
+ assert all(
+ set(hint) == {"path", "label", "suffix"} for hint in
response.json["result"]
+ )
+ assert JWT_TOKEN.encode() not in response.data
+ assert b"hunter2" not in response.data
+
+ event_log.assert_called_once()
+ assert event_log.call_args.args[1] ==
"DatabaseRestApi.encrypted_extra_hints"
+ assert event_log.call_args.kwargs["records"][0]["pk"] == 1
+ assert JWT_TOKEN not in str(event_log.call_args)
+ assert "hunter2" not in str(event_log.call_args)
+
+
+def test_encrypted_extra_hints_only_declared_keys(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """
+ Keys outside path, label and suffix never reach the response, not even a
+ length.
+ """
+ from superset.db_engine_specs.druid import DruidEngineSpec
+
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ mocker.patch("superset.utils.log.DBEventLogger.log")
+ mocker.patch.object(
+ DruidEngineSpec,
+ "encrypted_extra_hints",
+ return_value=[
+ {
+ "path": "$.connect_args.jwt",
+ "label": "JWT Token",
+ "suffix": "abcde",
+ "length": len(JWT_TOKEN),
+ "value": JWT_TOKEN,
+ }
+ ],
+ )
+
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 200
+ assert response.json == {
+ "result": [
+ {
+ "path": "$.connect_args.jwt",
+ "label": "JWT Token",
+ "suffix": "abcde",
+ }
+ ]
+ }
+
+
[email protected]("hint_chars", [0, -3])
+def test_encrypted_extra_hints_disabled(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+ hint_chars: int,
+) -> None:
+ """
+ No hints are returned when ``ENCRYPTED_EXTRA_HINT_CHARS`` is 0 or negative.
+ """
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS":
hint_chars})
+ mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 200
+ assert response.json == {"result": []}
+
+
[email protected](
+ "encrypted_extra",
+ ["null", "[]", "{}", '{"connect_args": {"jwt": '],
+)
+def test_encrypted_extra_hints_malformed(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+ encrypted_extra: str,
+) -> None:
+ """
+ An unusable ``encrypted_extra`` yields no hints instead of an error.
+ """
+ add_druid_database(session, encrypted_extra)
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 200
+ assert response.json == {"result": []}
+
+
[email protected]("database_id", [0, 2])
+def test_encrypted_extra_hints_not_found(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+ database_id: int,
+) -> None:
+ """
+ An unknown database id returns a JSON 404 and logs only the id.
+ """
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ event_log = mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response =
client.get(f"/api/v1/database/{database_id}/encrypted_extra_hints/")
+
+ assert response.status_code == 404
+ assert response.json == {"message": "Not found"}
+ event_log.assert_called_once()
+ assert event_log.call_args.kwargs["records"][0]["pk"] == database_id
+ assert JWT_TOKEN not in str(event_log.call_args)
+ assert "abcde" not in str(event_log.call_args)
+
+
[email protected]("database_id", ["-1", "abc"])
+def test_encrypted_extra_hints_invalid_id(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+ database_id: str,
+) -> None:
+ """
+ A negative or non-integer id does not match the route.
+ """
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ event_log = mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response =
client.get(f"/api/v1/database/{database_id}/encrypted_extra_hints/")
+
+ assert response.status_code == 404
+ assert JWT_TOKEN.encode() not in response.data
+ event_log.assert_not_called()
+
+
+def test_encrypted_extra_hints_requires_write(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """
+ A user who can read databases but not write them gets a 403.
+ """
+ from superset import security_manager
+
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ def can_read_only(permission_name: str, view_name: str) -> bool:
+ return permission_name != "can_write"
+
+ mocker.patch.object(security_manager, "is_item_public",
side_effect=can_read_only)
+ has_access = mocker.patch.object(
+ security_manager, "has_access", side_effect=can_read_only
+ )
+
+ event_log = mocker.patch("superset.utils.log.DBEventLogger.log")
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 403
+ assert JWT_TOKEN.encode() not in response.data
+ has_access.assert_any_call("can_write", "Database")
+ event_log.assert_not_called()
+
+
+def test_encrypted_extra_hints_requires_login(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+) -> None:
+ """
+ An anonymous request gets a 401 and leaves no event log row.
+ """
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ event_log = mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 401
+ assert JWT_TOKEN.encode() not in response.data
+ assert b"abcde" not in response.data
+ event_log.assert_not_called()
+
+
+def test_encrypted_extra_hints_ignores_query_params(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """
+ The hint length comes only from the server config, never from the request,
+ and the audit row records the database id without the request parameters.
+ """
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": 5})
+ event_log = mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response = client.get(
+ "/api/v1/database/1/encrypted_extra_hints/",
+ query_string={"length": "500", "path": "$.connect_args.jwt"},
+ )
+
+ assert response.status_code == 200
+ assert response.json == {
+ "result": [
+ {
+ "path": "$.connect_args.jwt",
+ "label": "JWT Token",
+ "suffix": "abcde",
+ }
+ ]
+ }
+ assert JWT_TOKEN.encode() not in response.data
+ assert event_log.call_args.kwargs["records"] == [
+ {
+ "path": "/api/v1/database/1/encrypted_extra_hints/",
+ "url_rule": "/api/v1/database/<int:pk>/encrypted_extra_hints/",
+ "object_ref": "DatabaseRestApi.encrypted_extra_hints",
+ "pk": 1,
+ "database_id": 1,
+ }
+ ]
+ assert event_log.call_args.kwargs["curated_payload"] == {}
+ assert event_log.call_args.kwargs["database_id"] == 1
+
+
+def test_encrypted_extra_hints_accepts_string_config(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+) -> None:
+ """
+ A length configured as a string, as from an environment variable, still
works.
+ """
+ add_druid_database(session, json.dumps({"connect_args": {"jwt":
JWT_TOKEN}}))
+ mocker.patch("sqlalchemy.engine.URL.get_driver_name", return_value="rest")
+ mocker.patch.dict(current_app.config, {"ENCRYPTED_EXTRA_HINT_CHARS": "5"})
+ mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ response = client.get("/api/v1/database/1/encrypted_extra_hints/")
+
+ assert response.status_code == 200
+ assert response.json["result"][0]["suffix"] == "abcde"
+
+
@pytest.mark.parametrize("full_payload", [False, True])
@pytest.mark.parametrize("change", [None, "password", "database_name"])
@pytest.mark.parametrize("with_tunnel", [False, True])
@@ -3610,3 +3961,95 @@ def test_available_keeps_azure_synapse_on_uri_form(
databases = {db["name"]: db for db in response.json["databases"]}
assert "parameters" not in databases["Azure Synapse"]
assert ("parameters" in databases["Microsoft SQL Server"]) is ("pymssql"
in drivers)
+
+
+def test_available_includes_sensitive_field_labels(
+ mocker: MockerFixture,
+ client: FlaskClient,
+ full_api_access: None,
+) -> None:
+ """The engine information lists the stored-secret fields of each engine."""
+ from superset.db_engine_specs.druid import DruidEngineSpec
+
+ mocker.patch(
+ "superset.databases.api.get_available_engine_specs",
+ return_value={DruidEngineSpec: {"pydruid"}},
+ )
+ response = client.get("/api/v1/database/available/")
+ assert response.status_code == 200
+ information = response.json["databases"][0]["engine_information"]
+ assert information["encrypted_extra_sensitive_fields"] == {
+ "$.connect_args.jwt": "JWT Token",
+ "$.connect_args.password": "Password",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+
+
+def test_connection_lists_stored_sensitive_fields(
+ mocker: MockerFixture,
+ session: Session,
+ client: FlaskClient,
+ full_api_access: None,
+) -> None:
+ """
+ The connection endpoint lists the sensitive fields stored for the database,
+ while the plain GET and the list keep the engine's declared patterns.
+ """
+ from superset.databases.api import DatabaseRestApi
+ from superset.models.core import Database
+
+ DatabaseRestApi.datamodel._session = session
+ Database.metadata.create_all(session.get_bind()) # pylint:
disable=no-member
+ db.session.add(
+ Database(
+ database_name="my_database",
+ sqlalchemy_uri="sqlite://",
+ encrypted_extra=json.dumps(
+ {
+ "api_key": "x",
+ "connect_args": {"timeout": 5},
+ "oauth2_client_info": {"secret": "s"},
+ }
+ ),
+ )
+ )
+ db.session.commit()
+ mocker.patch("superset.utils.log.DBEventLogger.log")
+
+ declared = {
+ "$.*": "Encrypted Extra",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+
+ response = client.get("/api/v1/database/1/connection")
+ assert response.status_code == 200
+ information = response.json["result"]["engine_information"]
+ assert information["encrypted_extra_sensitive_fields"] == {
+ "$.api_key": "api_key",
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+
+ response = client.get("/api/v1/database/1")
+ assert response.status_code == 200
+ fields = response.json["result"]["engine_information"][
+ "encrypted_extra_sensitive_fields"
+ ]
+ assert fields == declared
+ assert "$.api_key" not in fields
+
+ response = client.get("/api/v1/database/")
+ assert response.status_code == 200
+ fields = response.json["result"][0]["engine_information"][
+ "encrypted_extra_sensitive_fields"
+ ]
+ assert fields == declared
diff --git a/tests/unit_tests/databases/test_schemas.py
b/tests/unit_tests/databases/test_schemas.py
index 323807148a5..c26ce7af137 100644
--- a/tests/unit_tests/databases/test_schemas.py
+++ b/tests/unit_tests/databases/test_schemas.py
@@ -89,3 +89,21 @@ def
test_engine_information_schema_includes_identifier_quote_escape_by_doubling(
"end": "`",
"escape_by_doubling": False,
}
+
+
+def test_engine_information_schema_includes_encrypted_extra_sensitive_fields()
-> None:
+ """
+ The sensitive field labels must pass through so the modal can render a
+ field per stored secret.
+ """
+ from superset.databases.schemas import EngineInformationSchema
+
+ labels = {
+ "$.connect_args.jwt": "JWT Token",
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+ result = EngineInformationSchema().dump(
+ {"encrypted_extra_sensitive_fields": labels}
+ )
+
+ assert result["encrypted_extra_sensitive_fields"] == labels
diff --git a/tests/unit_tests/db_engine_specs/test_base.py
b/tests/unit_tests/db_engine_specs/test_base.py
index 45577601b81..57200400b26 100644
--- a/tests/unit_tests/db_engine_specs/test_base.py
+++ b/tests/unit_tests/db_engine_specs/test_base.py
@@ -589,6 +589,99 @@ def
test_secrets_are_masked_for_an_engine_that_declares_no_sensitive_fields() ->
}
+def test_encrypted_extra_sensitive_field_labels_default() -> None:
+ """
+ The base spec labels the catch-all path generically, and the secrets every
+ engine adds get readable defaults.
+ """
+ assert BaseEngineSpec.encrypted_extra_sensitive_field_labels() == {
+ "$.*": "Encrypted Extra",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+
+
+def test_encrypted_extra_sensitive_field_labels_from_set() -> None:
+ """
+ A spec declaring a set of paths gets the last path segment as the label.
+ """
+
+ class SetFieldsSpec(BaseEngineSpec):
+ encrypted_extra_sensitive_fields = {"$.a.b"}
+
+ labels = SetFieldsSpec.encrypted_extra_sensitive_field_labels()
+ assert labels == {
+ "$.a.b": "b",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+ assert list(labels) == sorted(labels)
+
+
+def test_encrypted_extra_sensitive_field_labels_from_dict() -> None:
+ """
+ A spec declaring a dict keeps its labels, and the keys are sorted by path.
+ """
+
+ class DictFieldsSpec(BaseEngineSpec):
+ encrypted_extra_sensitive_fields = {"$.z": "Zed", "$.a.b": "Bee"}
+
+ labels = DictFieldsSpec.encrypted_extra_sensitive_field_labels()
+ assert labels == {
+ "$.a.b": "Bee",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ "$.z": "Zed",
+ }
+ assert list(labels) == sorted(labels)
+
+
+def test_encrypted_extra_sensitive_field_labels_declared_label_wins() -> None:
+ """
+ A label the engine declares for a path that every engine adds overrides the
+ default one.
+ """
+
+ class DeclaredSpec(BaseEngineSpec):
+ encrypted_extra_sensitive_fields = {
+ "$.oauth2_client_info.secret": "Client Secret",
+ "$.embedded_credentials.password": "Guest Password",
+ }
+
+ assert DeclaredSpec.encrypted_extra_sensitive_field_labels() == {
+ "$.embedded_credentials.password": "Guest Password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "Client Secret",
+ }
+
+
+def test_get_public_information_includes_sensitive_field_labels() -> None:
+ """
+ The engine information carries the sensitive fields so a client can render
+ one input per stored secret before any value is revealed.
+ """
+ information = BaseEngineSpec.get_public_information()
+ assert (
+ information["encrypted_extra_sensitive_fields"]
+ == BaseEngineSpec.encrypted_extra_sensitive_field_labels()
+ )
+
+
def test_impersonate_user_backwards_compatible(mocker: MockerFixture) -> None:
"""
Test that the `impersonate_user` method calls the original methods it
replaced.
@@ -2361,6 +2454,80 @@ def test_expand_nested_columns_default_returns_input()
-> None:
assert BaseEngineSpec.expand_nested_columns(object(), columns) is columns
+def test_encrypted_extra_hints_disabled_or_unusable_input() -> None:
+ """
+ No hints are produced for a missing or malformed value, or a length of
zero.
+ """
+ secret = json.dumps({"connect_args": {"jwt": "j" * 40}})
+
+ assert DruidEngineSpec.encrypted_extra_hints(None, 4) == []
+ assert DruidEngineSpec.encrypted_extra_hints("{not json", 4) == []
+ assert DruidEngineSpec.encrypted_extra_hints(secret, 0) == []
+ assert DruidEngineSpec.encrypted_extra_hints(secret, -1) == []
+
+
+def test_encrypted_extra_hints_bigquery_private_key() -> None:
+ """
+ A service account key in PEM format is hinted by the end of its base64
body.
+ """
+ body = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASC" * 50 + "Ab3dE"
+ lines = [body[i : i + 64] for i in range(0, len(body), 64)]
+ private_key = "\n".join(
+ ["-----BEGIN PRIVATE KEY-----", *lines, "-----END PRIVATE KEY-----",
""]
+ )
+ config = json.dumps(
+ {"credentials_info": {"type": "service_account", "private_key":
private_key}}
+ )
+
+ assert BigQueryEngineSpec.encrypted_extra_hints(config, 5) == [
+ {
+ "path": "$.credentials_info.private_key",
+ "label": "Service Account Private Key",
+ "suffix": "Ab3dE",
+ }
+ ]
+
+
+def test_encrypted_extra_hints_non_object_json() -> None:
+ """
+ Valid JSON that is not an object yields no hints.
+ """
+ assert DruidEngineSpec.encrypted_extra_hints("[1, 2]", 4) == []
+ assert DruidEngineSpec.encrypted_extra_hints('"text"', 4) == []
+
+
+def test_encrypted_extra_hints_label_falls_back_to_last_path_segment(
+ mocker: MockerFixture,
+) -> None:
+ """
+ Specs that declare their sensitive fields as a set get the field name as
label.
+ """
+ mocker.patch.object(
+ BaseEngineSpec,
+ "encrypted_extra_sensitive_fields",
+ {"$.credentials.token"},
+ )
+ config = json.dumps({"credentials": {"token": "t" * 20 + "ab3d"}})
+
+ assert BaseEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.credentials.token",
+ "label": "token",
+ "suffix": "ab3d",
+ }
+ ]
+
+
[email protected](
+ "encrypted_extra", ["null", "[]", "42", '"str"', "{}", "{oops"]
+)
+def test_encrypted_extra_hints_unexpected_json(encrypted_extra: str) -> None:
+ """
+ JSON that is not an object with sensitive fields yields no hints and no
error.
+ """
+ assert DruidEngineSpec.encrypted_extra_hints(encrypted_extra, 5) == []
+
+
def test_get_catalog_reference_schema() -> None:
"""
An engine that doesn't say which schema a catalog gives a table named
without
diff --git a/tests/unit_tests/db_engine_specs/test_druid.py
b/tests/unit_tests/db_engine_specs/test_druid.py
index 85c5fa28638..f8e7e5aabba 100644
--- a/tests/unit_tests/db_engine_specs/test_druid.py
+++ b/tests/unit_tests/db_engine_specs/test_druid.py
@@ -258,3 +258,57 @@ def test_unmask_encrypted_extra() -> None:
assert DruidEngineSpec.unmask_encrypted_extra(old, new) == json.dumps(
{"connect_args": {"scheme": "http", "jwt": "old-token", "password":
"new"}}
)
+
+
+def test_encrypted_extra_hints() -> None:
+ """
+ The JWT and the password get labeled hints; `scheme` is never hinted.
+ """
+ from superset.db_engine_specs.druid import DruidEngineSpec
+ from superset.utils import json
+
+ config = json.dumps(
+ {
+ "connect_args": {
+ "scheme": "https" * 10,
+ "jwt": "j" * 20 + "ab3d",
+ "password": "p" * 20 + "9z8y",
+ },
+ }
+ )
+
+ assert DruidEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.connect_args.jwt",
+ "label": "JWT Token",
+ "suffix": "ab3d",
+ },
+ {
+ "path": "$.connect_args.password",
+ "label": "Password",
+ "suffix": "9z8y",
+ },
+ ]
+
+
+def test_encrypted_extra_sensitive_field_labels() -> None:
+ """
+ Druid publishes its JWT and password fields, plus the secrets every engine
+ adds.
+ """
+ from superset.db_engine_specs.druid import DruidEngineSpec
+
+ assert DruidEngineSpec.encrypted_extra_sensitive_field_labels() == {
+ "$.connect_args.jwt": "JWT Token",
+ "$.connect_args.password": "Password",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+ assert (
+
DruidEngineSpec.get_public_information()["encrypted_extra_sensitive_fields"]
+ == DruidEngineSpec.encrypted_extra_sensitive_field_labels()
+ )
diff --git a/tests/unit_tests/db_engine_specs/test_presto.py
b/tests/unit_tests/db_engine_specs/test_presto.py
index 0fb7e207e7f..34106035dfc 100644
--- a/tests/unit_tests/db_engine_specs/test_presto.py
+++ b/tests/unit_tests/db_engine_specs/test_presto.py
@@ -1474,3 +1474,80 @@ def test_unmask_encrypted_extra() -> None:
assert PrestoEngineSpec.unmask_encrypted_extra(old, new) == json.dumps(
{"auth_method": "jwt", "auth_params": {"token": "old-token"}}
)
+
+
+def test_encrypted_extra_hints_jwt_in_connect_args() -> None:
+ """
+ A JWT in `connect_args.requests_kwargs` is hinted; its siblings are not.
+ """
+ from superset.db_engine_specs.presto import PrestoEngineSpec
+ from superset.utils import json
+
+ config = json.dumps(
+ {
+ "connect_args": {
+ "protocol": "https" * 10,
+ "requests_kwargs": {"jwt": "j" * 20 + "ab3d"},
+ },
+ }
+ )
+
+ assert PrestoEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.connect_args.requests_kwargs.jwt",
+ "label": "JWT Token",
+ "suffix": "ab3d",
+ }
+ ]
+
+
+def test_encrypted_extra_hints_auth_params_token() -> None:
+ """
+ The `auth_params` token and password are hinted; `username` is not.
+ """
+ from superset.db_engine_specs.presto import PrestoEngineSpec
+ from superset.utils import json
+
+ config = json.dumps(
+ {
+ "auth_method": "jwt",
+ "auth_params": {
+ "username": "u" * 40,
+ "token": "t" * 20 + "ab3d",
+ "password": "short",
+ },
+ }
+ )
+
+ assert PrestoEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.auth_params.password",
+ "label": "Password",
+ "suffix": None,
+ },
+ {
+ "path": "$.auth_params.token",
+ "label": "JWT Token",
+ "suffix": "ab3d",
+ },
+ ]
+
+
+def test_encrypted_extra_hints_oauth2_client_secret() -> None:
+ """
+ The OAuth2 client secret is always hinted, even without a declared label.
+ """
+ from superset.db_engine_specs.presto import PrestoEngineSpec
+ from superset.utils import json
+
+ config = json.dumps(
+ {"oauth2_client_info": {"id": "i" * 40, "secret": "s" * 20 + "ab3d"}}
+ )
+
+ assert PrestoEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.oauth2_client_info.secret",
+ "label": "OAuth2 client secret",
+ "suffix": "ab3d",
+ }
+ ]
diff --git a/tests/unit_tests/db_engine_specs/test_trino.py
b/tests/unit_tests/db_engine_specs/test_trino.py
index d3f8d01ff7b..d0e419ed613 100644
--- a/tests/unit_tests/db_engine_specs/test_trino.py
+++ b/tests/unit_tests/db_engine_specs/test_trino.py
@@ -3062,6 +3062,80 @@ def test_handle_cursor_stops_polling_after_time_limit(
mock_cancel_query.assert_not_called()
+def test_encrypted_extra_hints_jwt_in_connect_args() -> None:
+ """
+ A JWT in `connect_args.requests_kwargs` is hinted; its siblings are not.
+ """
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ config = json.dumps(
+ {
+ "connect_args": {
+ "protocol": "https" * 10,
+ "requests_kwargs": {"jwt": "j" * 20 + "ab3d"},
+ },
+ }
+ )
+
+ assert TrinoEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.connect_args.requests_kwargs.jwt",
+ "label": "JWT Token",
+ "suffix": "ab3d",
+ }
+ ]
+
+
+def test_encrypted_extra_hints_auth_params_token() -> None:
+ """
+ The `auth_params` token and password are hinted; `username` is not.
+ """
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ config = json.dumps(
+ {
+ "auth_method": "jwt",
+ "auth_params": {
+ "username": "u" * 40,
+ "token": "t" * 20 + "ab3d",
+ "password": "short",
+ },
+ }
+ )
+
+ assert TrinoEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.auth_params.password",
+ "label": "Password",
+ "suffix": None,
+ },
+ {
+ "path": "$.auth_params.token",
+ "label": "JWT Token",
+ "suffix": "ab3d",
+ },
+ ]
+
+
+def test_encrypted_extra_hints_oauth2_client_secret() -> None:
+ """
+ The OAuth2 client secret is hinted with its declared label; the id is not.
+ """
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ config = json.dumps(
+ {"oauth2_client_info": {"id": "i" * 40, "secret": "s" * 20 + "ab3d"}}
+ )
+
+ assert TrinoEngineSpec.encrypted_extra_hints(config, 4) == [
+ {
+ "path": "$.oauth2_client_info.secret",
+ "label": "OAuth2 client secret",
+ "suffix": "ab3d",
+ }
+ ]
+
+
def test_apply_offset_before_limit_reorders_ansi_ordering() -> None:
"""
Trino requires OFFSET before LIMIT. Some SQLAlchemy drivers (e.g. PyHive)
diff --git a/tests/unit_tests/models/core_test.py
b/tests/unit_tests/models/core_test.py
index dce266d4efb..eaf1c9c9066 100644
--- a/tests/unit_tests/models/core_test.py
+++ b/tests/unit_tests/models/core_test.py
@@ -3311,6 +3311,83 @@ def
test_connection_does_not_re_exchange_a_refused_refresh_token(
engine.raw_connection.assert_not_called()
+def _catch_all_database() -> Database:
+ """A database on an engine with the catch-all rule and a mixed payload."""
+ return Database(
+ database_name="db",
+ sqlalchemy_uri="sqlite://",
+ encrypted_extra=json.dumps(
+ {
+ "api_key": "x",
+ "connect_args": {"timeout": 5},
+ "oauth2_client_info": {"secret": "s"},
+ }
+ ),
+ )
+
+
+def test_stored_sensitive_fields_catch_all_rule() -> None:
+ """
+ On an engine with the catch-all rule, only the stored string fields are
listed,
+ labeled by key name unless the path has a declared label.
+ """
+ assert _catch_all_database().stored_sensitive_fields() == {
+ "$.api_key": "api_key",
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+
+
+def test_stored_sensitive_fields_only_stored_declared_fields() -> None:
+ """
+ A declared field is listed with its label only when it is stored.
+ """
+ database = Database(
+ database_name="druid",
+ sqlalchemy_uri="druid://localhost:8082/druid/v2/sql/",
+ encrypted_extra=json.dumps({"connect_args": {"scheme": "https"}}),
+ )
+ assert database.stored_sensitive_fields() == {}
+
+ database.encrypted_extra = json.dumps(
+ {"connect_args": {"scheme": "https", "jwt": "token"}}
+ )
+ assert database.stored_sensitive_fields() == {"$.connect_args.jwt": "JWT
Token"}
+
+
[email protected]("encrypted_extra", [None, "", "{oops", "[1, 2]",
'"x"', "{}"])
+def test_stored_sensitive_fields_missing_or_malformed(
+ encrypted_extra: str | None,
+) -> None:
+ """
+ A missing, empty or malformed `encrypted_extra` lists no sensitive fields.
+ """
+ database = Database(
+ database_name="db",
+ sqlalchemy_uri="sqlite://",
+ encrypted_extra=encrypted_extra,
+ )
+
+ assert database.stored_sensitive_fields() == {}
+
+
+def test_engine_information_keeps_declared_patterns() -> None:
+ """
+ The engine information of a database lists the engine's declared patterns,
+ whatever is stored.
+ """
+ assert _catch_all_database().engine_information[
+ "encrypted_extra_sensitive_fields"
+ ] == {
+ "$.*": "Encrypted Extra",
+ "$.embedded_credentials.password": "Embedded guest password",
+ "$.embedded_credentials.privatekey_body": "Embedded guest private key
(PEM)",
+ "$.embedded_credentials.privatekey_pass": (
+ "Embedded guest private key passphrase"
+ ),
+ "$.oauth2_client_info.secret": "OAuth2 client secret",
+ }
+
+
def _embedded_snowflake_database(
*,
username: str = "embedded_svc",
diff --git a/tests/unit_tests/utils/json_tests.py
b/tests/unit_tests/utils/json_tests.py
index 5358f204180..ee03e17e12c 100644
--- a/tests/unit_tests/utils/json_tests.py
+++ b/tests/unit_tests/utils/json_tests.py
@@ -403,6 +403,398 @@ def test_get_masked_fields(
assert sorted(masked) == sorted(expected_result)
+def test_get_sensitive_field_hints_nested_path() -> None:
+ """
+ The trailing characters are returned for a nested path.
+ """
+ payload = {"connect_args": {"scheme": "https", "jwt": "a" * 40 + "ab3d"}}
+
+ assert json.get_sensitive_field_hints(payload, {"$.connect_args.jwt"}, 4)
== [
+ {"path": "$.connect_args.jwt", "suffix": "ab3d"}
+ ]
+
+
+def test_get_sensitive_field_hints_ignores_non_sensitive_fields() -> None:
+ """
+ Only the declared sensitive paths are hinted, however long other values
are.
+ """
+ payload = {"connect_args": {"scheme": "https" * 50, "jwt": "x" * 40 +
"wxyz"}}
+
+ hints = json.get_sensitive_field_hints(payload, {"$.connect_args.jwt"}, 4)
+
+ assert [hint["path"] for hint in hints] == ["$.connect_args.jwt"]
+
+
+def test_get_sensitive_field_hints_absent_path() -> None:
+ """
+ A declared path missing from the payload is not listed.
+ """
+ assert json.get_sensitive_field_hints({"a": "b"}, {"$.connect_args.jwt"},
4) == []
+
+
[email protected](
+ "value,suffix",
+ [
+ ("a" * 19, None),
+ ("a" * 15 + "vwxyz", "vwxyz"),
+ ("a" * 16 + "vwxyz", "vwxyz"),
+ ("short", None),
+ ("", None),
+ ],
+)
+def test_get_sensitive_field_hints_never_reveals_more_than_a_quarter(
+ value: str, suffix: str | None
+) -> None:
+ """
+ Values shorter than four times the hint length get no suffix.
+ """
+ hints = json.get_sensitive_field_hints({"secret": value}, {"$.secret"}, 5)
+
+ assert hints == [{"path": "$.secret", "suffix": suffix}]
+
+
+def test_get_sensitive_field_hints_withholds_the_length_of_a_short_value() ->
None:
+ """
+ A value too short to reveal gives nothing away, not even its length.
+ """
+ hints = json.get_sensitive_field_hints({"secret": "short"}, {"$.secret"},
5)
+
+ assert hints == [{"path": "$.secret", "suffix": None}]
+ assert "length" not in hints[0]
+
+
+def test_get_sensitive_field_hints_boundary_is_four_times_length() -> None:
+ """
+ Exactly four times the hint length is the shortest value that gets a
suffix.
+ """
+ below = json.get_sensitive_field_hints({"s": "a" * 7}, {"$.s"}, 2)
+ exact = json.get_sensitive_field_hints({"s": "a" * 6 + "zy"}, {"$.s"}, 2)
+
+ assert below[0]["suffix"] is None
+ assert exact[0]["suffix"] == "zy"
+
+
[email protected]("value", [None, 12345, True, 1.5, {"nested": "v" *
40}])
+def test_get_sensitive_field_hints_skips_non_string_values(value: Any) -> None:
+ """
+ Only strings are hinted; any other type is skipped without raising.
+ """
+ assert json.get_sensitive_field_hints({"secret": value}, {"$.secret"}, 4)
== []
+
+
+def test_get_sensitive_field_hints_wildcard_expands_per_match() -> None:
+ """
+ A wildcard path yields one hint per match, with the concrete path rendered.
+ """
+ payload = {
+ "primary": {"secret": "p" * 20 + "1111"},
+ "replica": {"secret": "r" * 20 + "2222"},
+ "other": {"secret": 7},
+ }
+
+ assert json.get_sensitive_field_hints(payload, {"$.*.secret"}, 4) == [
+ {"path": "$.primary.secret", "suffix": "1111"},
+ {"path": "$.replica.secret", "suffix": "2222"},
+ ]
+
+
+def test_get_sensitive_field_hints_trims_whitespace() -> None:
+ """
+ Whitespace is stripped before the suffix is computed.
+ """
+ value = "\n " + "a" * 20 + "ab3d" + " \r\n"
+
+ assert json.get_sensitive_field_hints({"secret": value}, {"$.secret"}, 4)
== [
+ {"path": "$.secret", "suffix": "ab3d"}
+ ]
+
+
+def test_get_sensitive_field_hints_whitespace_only_value() -> None:
+ """
+ A blank value never gets a suffix.
+ """
+ assert json.get_sensitive_field_hints({"secret": " "}, {"$.secret"}, 4)
== [
+ {"path": "$.secret", "suffix": None}
+ ]
+
+
+def test_get_sensitive_field_hints_empty_sensitive_fields() -> None:
+ """
+ No sensitive paths means no hints.
+ """
+ assert json.get_sensitive_field_hints({"secret": "a" * 40}, set(), 4) == []
+
+
[email protected]("length", [0, -1])
+def test_get_sensitive_field_hints_non_positive_length(length: int) -> None:
+ """
+ A non-positive hint length yields nothing instead of leaking the whole
value.
+ """
+ assert json.get_sensitive_field_hints({"s": "a" * 40}, {"$.s"}, length) ==
[]
+
+
+def test_get_sensitive_field_hints_sorted_and_deduplicated() -> None:
+ """
+ Hints are ordered by path, and overlapping expressions list a path once.
+ """
+ payload = {"b": "b" * 20, "a": "a" * 20}
+
+ hints = json.get_sensitive_field_hints(payload, {"$.b", "$.*", "$.a"}, 4)
+
+ assert [hint["path"] for hint in hints] == ["$.a", "$.b"]
+
+
+def _pem(
+ ending: str, newline: str = "\n", size: int = 1_523, label: str = "PRIVATE
KEY"
+) -> str:
+ """
+ A PEM block whose base64 body has ``size`` characters and ends with
+ ``ending``, split into 64-character lines joined by ``newline``.
+ """
+ filler = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7"
+ body = (filler * (size // len(filler) + 1))[: size - len(ending)] + ending
+ lines = [body[i : i + 64] for i in range(0, len(body), 64)]
+ return newline.join(
+ [f"-----BEGIN {label}-----", *lines, f"-----END {label}-----", ""]
+ )
+
+
+def test_get_sensitive_field_hints_pem_suffix_comes_from_the_body() -> None:
+ """
+ A PEM key reveals the end of its base64 body, not the fixed footer dashes.
+ """
+ pem = _pem("Ab3dE")
+
+ hints = json.get_sensitive_field_hints({"key": pem}, {"$.key"}, 5)
+
+ assert len(pem.strip()) == 1_600
+ assert hints == [{"path": "$.key", "suffix": "Ab3dE"}]
+
+
[email protected]("newline", ["\\n", "\r\n", "\\r\\n"])
+def test_get_sensitive_field_hints_pem_with_newline_escapes(newline: str) ->
None:
+ """
+ Escaped or CRLF line breaks give the same suffix as real newlines.
+ """
+ pem = _pem("Ab3dE", newline=newline)
+
+ assert json.get_sensitive_field_hints({"key": pem}, {"$.key"}, 5) == [
+ {"path": "$.key", "suffix": "Ab3dE"}
+ ]
+
+
[email protected]("ending", ["Ab3dE=", "Ab3dE=="])
+def test_get_sensitive_field_hints_pem_padding_is_not_revealed(ending: str) ->
None:
+ """
+ The base64 padding at the end of a PEM body is not revealed; the suffix
ends
+ with the last real base64 characters.
+ """
+ pem = _pem(ending)
+
+ assert json.get_sensitive_field_hints({"key": pem}, {"$.key"}, 5) == [
+ {"path": "$.key", "suffix": "Ab3dE"}
+ ]
+
+
+def test_get_sensitive_field_hints_pem_threshold_ignores_padding() -> None:
+ """
+ The four-times threshold applies to the PEM body without its padding.
+ """
+ pem = _pem("Ab3dE==", size=21)
+
+ assert json.get_sensitive_field_hints({"key": pem}, {"$.key"}, 5) == [
+ {"path": "$.key", "suffix": None}
+ ]
+
+
+def test_get_sensitive_field_hints_pem_rotation_changes_suffix() -> None:
+ """
+ Two keys that differ only in their body get different suffixes.
+ """
+ payload = {"old": _pem("Ab3dE"), "new": _pem("Zy9xW")}
+
+ hints = json.get_sensitive_field_hints(payload, {"$.old", "$.new"}, 5)
+
+ assert [hint["suffix"] for hint in hints] == ["Zy9xW", "Ab3dE"]
+
+
+def test_get_sensitive_field_hints_short_pem_body() -> None:
+ """
+ A PEM body shorter than four times the hint length reveals nothing, even
though
+ the whole value with its header and footer is long enough.
+ """
+ pem = _pem("Ab3dE", size=19)
+
+ assert json.get_sensitive_field_hints({"key": pem}, {"$.key"}, 5) == [
+ {"path": "$.key", "suffix": None}
+ ]
+
+
[email protected](
+ "label", ["RSA PRIVATE KEY", "PKCS7", "X509 CRL", "encrypted private key"]
+)
+def test_get_sensitive_field_hints_pem_any_label(label: str) -> None:
+ """
+ Any RFC 7468 label, with digits, spaces or lowercase, is a PEM block.
+ """
+ hints = json.get_sensitive_field_hints(
+ {"key": _pem("Ab3dE", label=label)}, {"$.key"}, 5
+ )
+
+ assert [hint["suffix"] for hint in hints] == ["Ab3dE"]
+
+
[email protected](
+ "value",
+ [
+ _pem("Ab3dE") + _pem("Zy9xW", label="CERTIFICATE"),
+ "prefix " + _pem("Zy9xW"),
+ ],
+)
+def test_get_sensitive_field_hints_pem_takes_the_last_block(value: str) ->
None:
+ """
+ A key followed by its certificate, or a block after other text, reveals the
+ body of the block the value ends with, never the footer dashes.
+ """
+ hints = json.get_sensitive_field_hints({"key": value}, {"$.key"}, 5)
+
+ assert [hint["suffix"] for hint in hints] == ["Zy9xW"]
+
+
+def test_get_sensitive_field_hints_pem_tries_only_the_last_header(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """
+ Headers repeated with no footer are matched once, from the last header, so
a
+ stored value cannot make the scan superlinear.
+ """
+ block = MagicMock(wraps=json._PEM_BLOCK)
+ monkeypatch.setattr(json, "_PEM_BLOCK", block)
+ value = ("-----BEGIN " + "x" * 180 + "-----") * 150
+
+ hints = json.get_sensitive_field_hints({"key": value}, {"$.key"}, 5)
+
+ assert [hint["suffix"] for hint in hints] == ["-----"]
+ block.match.assert_called_once()
+ block.findall.assert_not_called()
+
+
[email protected](
+ "value",
+ [
+ "token-----" + "a" * 20 + "-----",
+ "-----BEGIN PRIVATE KEY-----" + "a" * 20 + "-----END PUBLIC KEY-----",
+ ],
+)
+def test_get_sensitive_field_hints_dashes_are_not_a_pem(value: str) -> None:
+ """
+ Dashes alone, or a block whose footer does not match its header, are plain
text.
+ """
+ assert json.get_sensitive_field_hints({"key": value}, {"$.key"}, 5) == [
+ {"path": "$.key", "suffix": value[-5:]}
+ ]
+
+
+def test_get_sensitive_field_paths_dotted_path() -> None:
+ """
+ A declared nested path is listed when it holds a string.
+ """
+ payload = {"connect_args": {"scheme": "https", "jwt": "token"}}
+
+ assert json.get_sensitive_field_paths(payload, {"$.connect_args.jwt"}) == [
+ "$.connect_args.jwt"
+ ]
+
+
+def test_get_sensitive_field_paths_wildcard_keeps_only_strings() -> None:
+ """
+ A top-level wildcard lists the string keys only, sorted by path.
+ """
+ payload = {
+ "b_token": "x",
+ "connect_args": {"timeout": 5},
+ "a_key": "y",
+ "port": 3,
+ "flag": True,
+ "nothing": None,
+ "items": ["z"],
+ }
+
+ assert json.get_sensitive_field_paths(payload, {"$.*"}) == ["$.a_key",
"$.b_token"]
+
+
+def test_get_sensitive_field_paths_nested_wildcard() -> None:
+ """
+ A wildcard in the middle of a path yields one concrete path per string
match.
+ """
+ payload = {
+ "replica": {"secret": "r"},
+ "primary": {"secret": "p"},
+ "other": {"secret": 7},
+ }
+
+ assert json.get_sensitive_field_paths(payload, {"$.*.secret"}) == [
+ "$.primary.secret",
+ "$.replica.secret",
+ ]
+
+
+def test_get_sensitive_field_hints_stored_mask_has_no_suffix() -> None:
+ """
+ A stored mask, as older imports saved, gets no suffix that would read as
+ still masked, even when the hint length would reveal part of it.
+ """
+ hints = json.get_sensitive_field_hints({"key": PASSWORD_MASK}, {"$.key"},
2)
+
+ assert [hint["suffix"] for hint in hints] == [None]
+
+
+def test_get_sensitive_field_paths_skips_keys_a_dotted_path_cannot_hold() ->
None:
+ """
+ A key with a dot would collide with the nested path of the same name, and a
+ key named ``*`` would read as a wildcard, so neither is listed or hinted.
+ """
+ payload = {"a.b": "top-level", "a": {"b": "nested"}, "*": "star-key"}
+ fields = {"$.*", "$.a.b"}
+
+ assert json.get_sensitive_field_paths(payload, fields) == ["$.a.b"]
+ hints = json.get_sensitive_field_hints(payload, fields, 1)
+ assert [(hint["path"], hint["suffix"]) for hint in hints] == [("$.a.b",
"d")]
+
+
+def test_get_sensitive_field_paths_declared_leaf_under_an_object() -> None:
+ """
+ The wildcard skips an object, while a declared leaf inside it is listed.
+ """
+ payload = {"api_key": "x", "oauth2_client_info": {"id": "i", "secret":
"s"}}
+
+ assert json.get_sensitive_field_paths(
+ payload, {"$.*", "$.oauth2_client_info.secret"}
+ ) == ["$.api_key", "$.oauth2_client_info.secret"]
+
+
[email protected]("payload", [None, [], ["a", "b"], "text", 42, {}])
+def test_get_sensitive_field_paths_malformed_payload(payload: Any) -> None:
+ """
+ Anything but a non-empty object yields no paths and no error.
+ """
+ assert json.get_sensitive_field_paths(payload, {"$.*", "$.a.b"}) == []
+
+
+def test_get_sensitive_field_hints_agree_with_paths() -> None:
+ """
+ Hints are produced for exactly the paths the path helper lists.
+ """
+ payload = {"api_key": "k" * 24, "connect_args": {"timeout": 5}, "n": 1}
+ fields = {"$.*", "$.connect_args.jwt"}
+
+ hints = json.get_sensitive_field_hints(payload, fields, 4)
+
+ assert [hint["path"] for hint in hints] == json.get_sensitive_field_paths(
+ payload, fields
+ )
+
+
def test_reveal_sensitive_missing_in_old_payload() -> None:
"""
Test that a masked value with no counterpart in the old payload is passed
@@ -452,6 +844,43 @@ def test_dumps_preserves_unicode_when_ensure_ascii_false()
-> None:
assert json.dumps("你好,世界!", ensure_ascii=False) == '"你好,世界!"'
[email protected]("trailer", ["", "\n", " \r\n"])
+def test_get_sensitive_field_hints_unicode_uses_code_points(trailer: str) ->
None:
+ """
+ The suffix is the last code points of the trimmed value, emoji included.
+ """
+ value = "x" * 15 + "日本語🙂!" + trailer
+
+ assert json.get_sensitive_field_hints({"secret": value}, {"$.secret"}, 5)
== [
+ {"path": "$.secret", "suffix": "日本語🙂!"}
+ ]
+
+
+def test_get_sensitive_field_hints_mask_literal_is_an_ordinary_string() ->
None:
+ """
+ A stored value equal to the mask literal gets no special treatment.
+ """
+ value = PASSWORD_MASK * 2
+
+ assert json.get_sensitive_field_hints({"secret": value}, {"$.secret"}, 5)
== [
+ {"path": "$.secret", "suffix": "XXXXX"}
+ ]
+
+
+def test_get_sensitive_field_hints_large_payload() -> None:
+ """
+ A 1 MB secret next to thousands of other keys yields one correct hint.
+ """
+ payload = {
+ "connect_args": {"jwt": "j" * (1_000_000 - 4) + "ab3d"},
+ "other": {f"key_{i}": f"value_{i}" for i in range(10_000)},
+ }
+
+ hints = json.get_sensitive_field_hints(payload, {"$.connect_args.jwt"}, 5)
+
+ assert hints == [{"path": "$.connect_args.jwt", "suffix": "jab3d"}]
+
+
def test_redact_sensitive_leaves_empty_values_unmasked() -> None:
"""An empty secret has nothing to hide, and must not read as a stored
one."""
payload = {"credential": {"username": "", "password": "", "token": None}}