Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion pkg/mac/build-functions.sh
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,9 @@ _complete_bundle() {
yarn run webpacker 2>&1
unset NODE_ENV NODE_OPTIONS

curl https://curl.se/ca/cacert.pem -o cacert.pem -s
# --fail: an HTTP error page saved as cacert.pem would break every
# outbound HTTPS request, where a missing file falls back to certifi.
curl --fail -sS https://curl.se/ca/cacert.pem -o cacert.pem || exit 1
popd > /dev/null || exit

# copy the web directory to the bundle as it is required by runtime
Expand Down
7 changes: 5 additions & 2 deletions web/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,8 +478,11 @@
# What key should we look at in the upgrade data file?
UPGRADE_CHECK_KEY = 'pgadmin4'

# Which CA file should we use?
# Default to cacert.pem in the same directory as config.py et al.
# Which CA file should pgAdmin's own outbound HTTPS requests (upgrade check,
# AI assistant, cloud deployment, OAuth2) verify against?
# Default to cacert.pem in the same directory as config.py et al. If that file
# does not exist, certifi's bundle is used instead. Set to None to use
# Python's default CA store (normally the system store).
CA_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"cacert.pem")

Expand Down
7 changes: 5 additions & 2 deletions web/pgacloud/utils/starfleet_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,17 @@ def __init__(self, message, status=None):
class StarfleetClient:
def __init__(self, api_url=DEFAULT_API_URL, client_id=None,
client_secret=None, token=None, expires_at=None,
http=None):
http=None, ca_certs=None):
self.api_url = (api_url or DEFAULT_API_URL).rstrip('/')
self.client_id = client_id
self.client_secret = client_secret
self.token = token
self.expires_at = expires_at
# ca_certs=None leaves OpenSSL's default verify paths in place, which
# honour SSL_CERT_FILE; pgAdmin sets that for its background jobs.
self._http = http or urllib3.PoolManager(
timeout=urllib3.Timeout(connect=10, read=60), retries=False)
timeout=urllib3.Timeout(connect=10, read=60), retries=False,
cert_reqs='CERT_REQUIRED', ca_certs=ca_certs)

def _can_mint(self):
return bool(self.client_id and self.client_secret)
Expand Down
9 changes: 7 additions & 2 deletions web/pgadmin/authenticate/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from pgadmin.utils import PgAdminModule, get_safe_post_login_redirect, \
get_safe_post_logout_redirect
from pgadmin.utils.csrf import pgCSRFProtect
from pgadmin.utils.tls import get_ca_file
from pgadmin.model import db

OAUTH2_LOGOUT = 'oauth2.logout'
Expand Down Expand Up @@ -265,11 +266,15 @@ def __init__(self):
oauth2_config['OAUTH2_NAME']] = oauth2_config

# Build client_kwargs with defaults
verify = oauth2_config.get('OAUTH2_SSL_CERT_VERIFICATION', True)
if verify is True:
# Verify against the same CA bundle as pgAdmin's other
# outbound HTTPS requests.
verify = get_ca_file() or True
client_kwargs = {
'scope': oauth2_config.get(
'OAUTH2_SCOPE', 'email profile'),
'verify': oauth2_config.get(
'OAUTH2_SSL_CERT_VERIFICATION', True)
'verify': verify
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

pkce_method = oauth2_config.get('OAUTH2_CHALLENGE_METHOD')
Expand Down
13 changes: 3 additions & 10 deletions web/pgadmin/llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

import json
import logging
import ssl
from flask import request
from flask_babel import gettext
from flask_security import permissions_required
Expand All @@ -25,16 +24,10 @@
from pgadmin.llm.utils import LLMApiError, urlopen_no_redirect
from pgadmin.tools.user_management.PgAdminPermissions import \
AllPermissionTypes
from pgadmin.utils.tls import create_ssl_context

# Try to use certifi for proper SSL certificate handling
try:
import certifi
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
except ImportError:
SSL_CONTEXT = ssl.create_default_context()

# Enforce minimum TLS 1.2 to satisfy security requirements
SSL_CONTEXT.minimum_version = ssl.TLSVersion.TLSv1_2
# Verifies against config.CA_FILE or certifi, with TLS 1.2 minimum.
SSL_CONTEXT = create_ssl_context()


MODULE_NAME = 'llm'
Expand Down
15 changes: 4 additions & 11 deletions web/pgadmin/llm/providers/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,22 @@

import json
import socket
import ssl
import urllib.request
import urllib.error
from collections.abc import Generator
from typing import Optional, Union
import uuid

# Try to use certifi for proper SSL certificate handling
try:
import certifi
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
except ImportError:
SSL_CONTEXT = ssl.create_default_context()

# Enforce minimum TLS 1.2 to satisfy security requirements
SSL_CONTEXT.minimum_version = ssl.TLSVersion.TLSv1_2

from pgadmin.llm.client import LLMClient, LLMClientError
from pgadmin.llm.models import (
Message, Tool, ToolCall, LLMResponse, LLMError,
Role, StopReason, Usage
)
from pgadmin.llm.utils import urlopen_no_redirect
from pgadmin.utils.tls import create_ssl_context

# Verifies against config.CA_FILE or certifi, with TLS 1.2 minimum.
SSL_CONTEXT = create_ssl_context()


# Default model if none specified
Expand Down
15 changes: 4 additions & 11 deletions web/pgadmin/llm/providers/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,23 @@

import json
import socket
import ssl
import urllib.parse
import urllib.request
import urllib.error
from collections.abc import Generator
from typing import Optional, Union
import uuid

# Try to use certifi for proper SSL certificate handling
try:
import certifi
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
except ImportError:
SSL_CONTEXT = ssl.create_default_context()

# Enforce minimum TLS 1.2 to satisfy security requirements
SSL_CONTEXT.minimum_version = ssl.TLSVersion.TLSv1_2

from pgadmin.llm.client import LLMClient, LLMClientError
from pgadmin.llm.models import (
Message, Tool, ToolCall, LLMResponse, LLMError,
Role, StopReason, Usage
)
from pgadmin.llm.utils import urlopen_no_redirect
from pgadmin.utils.tls import create_ssl_context

# Verifies against config.CA_FILE or certifi, with TLS 1.2 minimum.
SSL_CONTEXT = create_ssl_context()


# Default configuration
Expand Down
14 changes: 11 additions & 3 deletions web/pgadmin/llm/providers/ollama.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
Role, StopReason, Usage
)
from pgadmin.llm.utils import urlopen_no_redirect
from pgadmin.utils.tls import create_ssl_context

# Verifies against config.CA_FILE or certifi, with TLS 1.2 minimum, for an
# Ollama server behind HTTPS.
SSL_CONTEXT = create_ssl_context()


# Default configuration
Expand Down Expand Up @@ -73,7 +78,8 @@ def is_available(self) -> bool:
try:
# Check if Ollama is running
req = urllib.request.Request(f'{self._api_url}/api/tags')
with urlopen_no_redirect(req, timeout=5) as response:
with urlopen_no_redirect(req, timeout=5,
context=SSL_CONTEXT) as response:
data = json.loads(response.read().decode('utf-8'))
# Check if our model is available
models = [m.get('name', '') for m in data.get('models', [])]
Expand Down Expand Up @@ -216,7 +222,8 @@ def _make_request(self, payload: dict) -> dict:
)

try:
with urlopen_no_redirect(request, timeout=300) as response:
with urlopen_no_redirect(request, timeout=300,
context=SSL_CONTEXT) as response:
return json.loads(response.read().decode('utf-8'))
except urllib.error.HTTPError as e:
error_body = e.read().decode('utf-8')
Expand Down Expand Up @@ -349,7 +356,8 @@ def _process_stream(
)

try:
response = urlopen_no_redirect(request, timeout=300)
response = urlopen_no_redirect(request, timeout=300,
context=SSL_CONTEXT)
except urllib.error.HTTPError as e:
error_body = e.read().decode('utf-8')
try:
Expand Down
15 changes: 4 additions & 11 deletions web/pgadmin/llm/providers/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,22 @@

import json
import socket
import ssl
import urllib.request
import urllib.error
from collections.abc import Generator
from typing import Optional, Union
import uuid

# Try to use certifi for proper SSL certificate handling
try:
import certifi
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
except ImportError:
SSL_CONTEXT = ssl.create_default_context()

# Enforce minimum TLS 1.2 to satisfy security requirements
SSL_CONTEXT.minimum_version = ssl.TLSVersion.TLSv1_2

from pgadmin.llm.client import LLMClient, LLMClientError
from pgadmin.llm.models import (
Message, Tool, ToolCall, LLMResponse, LLMError,
Role, StopReason, Usage
)
from pgadmin.llm.utils import urlopen_no_redirect
from pgadmin.utils.tls import create_ssl_context

# Verifies against config.CA_FILE or certifi, with TLS 1.2 minimum.
SSL_CONTEXT = create_ssl_context()


# Default model if none specified
Expand Down
23 changes: 3 additions & 20 deletions web/pgadmin/misc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

"""A blueprint module providing utility functions for the application."""

import certifi
from pgadmin.utils import driver
from flask import request, current_app
from flask_babel import gettext
Expand All @@ -31,8 +30,8 @@
import json
import os
import sys
import ssl
from urllib.request import urlopen
from pgadmin.utils.tls import create_ssl_context
from urllib.parse import unquote
from pgadmin.settings import get_setting, store_setting
import html
Expand Down Expand Up @@ -380,24 +379,8 @@ def upgrade_check():
# Do not wait for more than 5 seconds.
# It stuck on rendering the browser.html, while working in the
# broken network.
if sys.version_info >= (
3, 13):
# Use SSL context for Python 3.13+
if os.path.exists(config.CA_FILE):
context = ssl.create_default_context(cafile=config.CA_FILE)
else:
context = ssl.create_default_context(
cafile=certifi.where()
)

response = urlopen(url, data=data, timeout=5,
context=context)
elif os.path.exists(config.CA_FILE):
# Use cafile parameter for older versions
response = urlopen(url, data=data, timeout=5,
cafile=config.CA_FILE)
else:
response = urlopen(url, data, 5, cafile=certifi.where())
response = urlopen(url, data=data, timeout=5,
context=create_ssl_context())
current_app.logger.debug(
'Version check HTTP response code: %d' % response.getcode()
)
Expand Down
4 changes: 4 additions & 0 deletions web/pgadmin/misc/cloud/azure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from pgadmin.utils import PgAdminModule
from pgadmin.utils.text_sanitize import sanitize_external_text
from pgadmin.user_login_check import pga_login_required
from pgadmin.utils.tls import ca_file_env
import json
from flask import session, current_app, request
from flask_login import current_user
Expand Down Expand Up @@ -842,6 +843,9 @@ def deploy_on_azure(data):
env['AZURE_DATABASE_PASSWORD'] = data[
'db_details']['db_password']

# pgacloud's own HTTPS requests (such as the public IP lookup)
# verify against the same CA bundle as pgAdmin.
env.update(ca_file_env())
p.set_env_variables(None, env=env)
p.update_server_id(p.id, sid)
p.start()
Expand Down
4 changes: 4 additions & 0 deletions web/pgadmin/misc/cloud/google/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from pgadmin.utils import PgAdminModule, filename_with_file_manager_path
from pgadmin.utils.text_sanitize import sanitize_external_text
from pgadmin.user_login_check import pga_login_required
from pgadmin.utils.tls import ca_file_env
from flask import session, current_app, request
from flask_babel import gettext as _

Expand Down Expand Up @@ -355,6 +356,9 @@ def deploy_on_google(data):
if 'db_password' in data['db_details']:
env['GOOGLE_DATABASE_PASSWORD'] = data['db_details']['db_password']

# pgacloud's own HTTPS requests (such as the public IP lookup)
# verify against the same CA bundle as pgAdmin.
env.update(ca_file_env())
p.set_env_variables(None, env=env)
p.update_server_id(p.id, sid)
p.start()
Expand Down
10 changes: 8 additions & 2 deletions web/pgadmin/misc/cloud/rds/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from pgadmin.misc.bgprocess.processes import BatchProcess
from pgadmin.utils.ajax import make_json_response, \
internal_server_error, bad_request, success_return
from pgadmin.utils.tls import ca_file_env
from .regions import AWS_REGIONS
import json

Expand Down Expand Up @@ -100,8 +101,10 @@ def get_db_instances():
errormsg=gettext('Session has not created yet.')
)

if not eng_version or eng_version == '' or eng_version == 'undefined':
eng_version = '11.16'
# No version chosen yet: there is nothing to look up, and AWS rejects
# any hardcoded fallback once that version is retired.
if not eng_version or eng_version == 'undefined':
return make_json_response(data=[])

res = rds_obj.get_available_db_instance_class(
engine_version=eng_version)
Expand Down Expand Up @@ -365,6 +368,9 @@ def deploy_on_rds(data):
env['AWS_DATABASE_PASSWORD'] = data[
'db_details']['db_password']

# pgacloud's own HTTPS requests (such as the public IP lookup)
# verify against the same CA bundle as pgAdmin.
env.update(ca_file_env())
p.set_env_variables(None, env=env)
p.update_server_id(p.id, sid)
p.start()
Expand Down
22 changes: 21 additions & 1 deletion web/pgadmin/misc/cloud/rds/tests/test_rds_session_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,26 @@ def runTest(self):
body = json.loads(route_resp.data)
self.assertEqual(body.get('data'), [])

with app.test_request_context('/rds/db_instances/'):
with app.test_request_context(
'/rds/db_instances/?eng_version=18.6'):
session['aws'] = {
'secret': {
'access_key': 'AKIA_TEST',
'secret_access_key': 'SECRET_TEST',
'region': 'us-east-1',
}
}
route_resp = rds_mod.get_db_instances.__wrapped__()
self.assertEqual(route_resp.status_code, 200)
body = json.loads(route_resp.data)
self.assertEqual(body.get('data'), [])

# With no version chosen yet, AWS must not be asked at all:
# a hardcoded fallback version fails once AWS retires it.
with app.test_request_context('/rds/db_instances/'), \
patch.object(rds_mod.RDS,
'get_available_db_instance_class') \
as mock_lookup:
session['aws'] = {
'secret': {
'access_key': 'AKIA_TEST',
Expand All @@ -248,3 +267,4 @@ def runTest(self):
self.assertEqual(route_resp.status_code, 200)
body = json.loads(route_resp.data)
self.assertEqual(body.get('data'), [])
mock_lookup.assert_not_called()
Loading
Loading