Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(dbc-ui): encode characters before building sqlalchemy uri #17969

Closed
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pylintrc
Expand Up @@ -364,7 +364,7 @@ max-args=5
ignored-argument-names=_.*

# Maximum number of locals for function / method body
max-locals=15
max-locals=16

# Maximum number of return / yield for function / method body
max-returns=10
Expand Down
6 changes: 5 additions & 1 deletion superset/databases/commands/validate.py
Expand Up @@ -30,6 +30,7 @@
InvalidParametersError,
)
from superset.databases.dao import DatabaseDAO
from superset.databases.utils import encode_parameters
from superset.db_engine_specs import get_engine_specs
from superset.db_engine_specs.base import BasicParametersMixin
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
Expand Down Expand Up @@ -99,9 +100,12 @@ def run(self) -> None:
except json.decoder.JSONDecodeError:
encrypted_extra = {}

# encode parameters
params = encode_parameters(self._properties.get("parameters", {}))
Copy link
Member

@eschutho eschutho Jan 7, 2022

Choose a reason for hiding this comment

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

does this value get saved somewhere or is this just for validation?

Copy link
Member Author

Choose a reason for hiding this comment

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

encode paramaters returns the encode keys in a new dictionary (params) which is used to build the sqlalchemy url a few lines below

Copy link
Member

Choose a reason for hiding this comment

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

Hugh, I think the problem is that the validation command doesn't save the database, so the encoding will only apply during validation but not later. You also need to update DatabaseParametersSchemaMixin.

It might be simpler to implement the encoding logic inside build_sqlalchemy_uri. This way it will work with both the validator command and the APIs, and we can have DB-specific encoding logic, which could be needed in the future.

Copy link
Member

Choose a reason for hiding this comment

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

We need to remove this line now, otherwise we'll end up double encoding the parameters when we call build_sqlalchemy_uri below.


# try to connect
sqlalchemy_uri = engine_spec.build_sqlalchemy_uri( # type: ignore
self._properties.get("parameters"), encrypted_extra,
params, encrypted_extra,
)
if self._model and sqlalchemy_uri == self._model.safe_sqlalchemy_uri():
sqlalchemy_uri = self._model.sqlalchemy_uri_decrypted
Expand Down
5 changes: 5 additions & 0 deletions superset/databases/schemas.py
Expand Up @@ -28,6 +28,7 @@
from sqlalchemy.exc import ArgumentError

from superset import db
from superset.databases.utils import encode_parameters
from superset.db_engine_specs import BaseEngineSpec, get_engine_specs
from superset.exceptions import CertificateException, SupersetSecurityException
from superset.models.core import ConfigurationMethod, Database, PASSWORD_MASK
Expand Down Expand Up @@ -254,6 +255,10 @@ def build_sqlalchemy_uri(
the constructed SQLAlchemy URI to be passed.
"""
parameters = data.pop("parameters", {})

# encode parameters
parameters = encode_parameters(parameters)
Copy link
Member

Choose a reason for hiding this comment

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

We also need to add this to DB engine specs that implement their own build_sqlalchemy_uri.

Copy link
Member Author

Choose a reason for hiding this comment

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

i added the encode_params to snowflake but, for gsheets and bigquery we don't leverage parameters to build the uri.
gsheets we always just return "gsheets:// and for biguery we just leverage encrypted_extra


# TODO(AAfghahi) standardize engine.
engine = (
data.pop("engine", None)
Expand Down
11 changes: 11 additions & 0 deletions superset/databases/utils.py
Expand Up @@ -14,6 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import urllib
from typing import Any, Dict, List, Optional

from superset import app
Expand Down Expand Up @@ -101,3 +102,13 @@ def get_table_metadata(
"indexes": keys,
"comment": table_comment,
}


def encode_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
encoded_params = {}
for k, v in parameters.items():
if isinstance(v, str):
encoded_params[k] = urllib.parse.quote_plus(v)
else:
encoded_params[k] = v
return encoded_params
46 changes: 46 additions & 0 deletions tests/integration_tests/databases/utils_tests.py
@@ -0,0 +1,46 @@
# 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.
import pytest

from superset.databases.utils import encode_parameters


@pytest.mark.parametrize(
"test_input, expected",
[
(
{
"host": "local%host",
"port": "5432",
"database": "postgres",
"username": "postgres",
"password": "hugh@miles4",
"query": {},
},
{
"host": "local%25host",
"port": "5432",
"database": "postgres",
"username": "postgres",
"password": "hugh%40miles4",
"query": {},
},
)
],
)
def test_escape_parameters(test_input, expected):
assert encode_parameters(test_input) == expected