IC Improve Code Recipes

Recipe 6.5 · Python

Getting Connection Strings Out of Source Code

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Connection strings with SQL logins and passwords are compiled into classes, pasted into console tools and copied between projects. Some of them point at production. Removing them feels risky because nobody is sure which code still uses which string.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Hard-coded connection string with credentials in source (p134_r6_5_hardcoded_connection_string_before.py)
"""Hard-coded connection string with credentials in source

Source: ImproveCode, Chapter 6, Recipe 6.5 "Getting Connection Strings Out of Source Code"
Section: The way it's often written
Book page: 134  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The constant is the same ODBC-style string pyodbc would accept (plus a Driver).
"""

from __future__ import annotations

from typing import Final


# Not this: credentials in source control, forever.
class Db:
    CONN: Final = (
        "Server=PRODSQL01;Database=Billing;"
        "User Id=sa;Password=Summer2014!;")

The improved recipe

Find every connection string, move it to configuration under ConnectionStrings, prefer passwordless authentication, and add a startup guard that refuses to run in production with a password read from a JSON file. The guard uses Microsoft.Data.SqlClient.

PowerShell
# Find candidates in a working copy (review every hit by hand).
Get-ChildItem -Recurse -Include *.cs,*.config,*.json,*.ps1 |
    Select-String -Pattern 'Password\s*=|Pwd\s*=|User ID\s*=' |
    Select-Object Path, LineNumber, Line

The JSON file keeps only a passwordless default:

JSON
{
  "ConnectionStrings": {
    "AppDb": "Server=localhost;Database=AppDb;Integrated Security=true"
  }
}

Usage in Program.cs, with the factory from Chapter 1, Recipe 1.1:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Guard that validates connection strings and rejects passwords in JSON files (p134_r6_5_connection_string_guard.py)
"""Guard that validates connection strings and rejects passwords in JSON files

Source: ImproveCode, Chapter 6, Recipe 6.5 "Getting Connection Strings Out of Source Code"
Section: The improved recipe
Book page: 134-136  -- original C# listing
Converted from C# to Python.
A small key=value parser replaces SqlConnectionStringBuilder (with its common synonyms);
configuration is modelled as ordered named sources (as in Recipe 6.3) where "json"
sources play the role of JsonConfigurationProvider; APP_ENVIRONMENT replaces IsDevelopment().
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Mapping

_SYNONYMS = {
    "server": "Data Source", "data source": "Data Source", "address": "Data Source",
    "database": "Initial Catalog", "initial catalog": "Initial Catalog",
    "password": "Password", "pwd": "Password",
    "application name": "Application Name", "app": "Application Name",
}


class ConnectionStringBuilder:
    """Minimal stand-in for SqlConnectionStringBuilder."""

    def __init__(self, value: str) -> None:
        self._parts: dict[str, str] = {}
        for segment in value.split(";"):
            if not segment.strip():
                continue
            if "=" not in segment:
                raise ValueError(f"Format of the connection string is invalid near '{segment}'.")
            key, val = segment.split("=", 1)
            norm = key.strip().lower()
            self._parts[_SYNONYMS.get(norm, key.strip())] = val.strip()

    def _get(self, key: str) -> str:
        return self._parts.get(key, "")

    @property
    def password(self) -> str:
        return self._get("Password")

    @property
    def data_source(self) -> str:
        return self._get("Data Source")

    @property
    def initial_catalog(self) -> str:
        return self._get("Initial Catalog")

    @property
    def application_name(self) -> str:
        return self._get("Application Name")

    @application_name.setter
    def application_name(self, value: str) -> None:
        self._parts["Application Name"] = value

    @property
    def connection_string(self) -> str:
        return ";".join(f"{k}={v}" for k, v in self._parts.items())


@dataclass(frozen=True)
class ConfigSource:
    name: str
    kind: str  # "json", "env", "secrets", ...
    values: Mapping[str, str] = field(default_factory=dict)


@dataclass(frozen=True)
class HostEnvironment:
    application_name: str
    environment_name: str

    def is_development(self) -> bool:
        return self.environment_name == "Development"


def _get(providers: list[ConfigSource], key: str) -> str | None:
    for provider in reversed(providers):
        if key in provider.values:
            return provider.values[key]
    return None


class ConnectionStringGuard:
    @staticmethod
    def get_required(
        providers: list[ConfigSource], environment: HostEnvironment, name: str
    ) -> str:
        """Reads a connection string, checks that it parses,
        and refuses passwords stored in JSON files outside Development."""
        value = _get(providers, f"ConnectionStrings:{name}")
        if value is None or not value.strip():
            raise RuntimeError(
                f"Connection string '{name}' is missing. Set "
                f"ConnectionStrings__{name} or a user secret.")

        # Raises ValueError for a malformed string.
        builder = ConnectionStringBuilder(value)

        if (not environment.is_development()
                and builder.password
                and ConnectionStringGuard._comes_from_json_file(providers, name)):
            raise RuntimeError(
                f"Connection string '{name}' contains a password and "
                "is stored in a JSON file. Move it to a secret store.")

        if not builder.application_name or "SqlClient" in builder.application_name:
            builder.application_name = environment.application_name

        return builder.connection_string

    @staticmethod
    def describe(connection_string: str) -> str:
        """Server and database only, safe to log."""
        builder = ConnectionStringBuilder(connection_string)
        return f"{builder.data_source}/{builder.initial_catalog}"

    @staticmethod
    def _comes_from_json_file(providers: list[ConfigSource], name: str) -> bool:
        key = f"ConnectionStrings:{name}"
        source = next((p for p in reversed(providers) if key in p.values), None)
        return source is not None and source.kind == "json"

Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.

Python Registering a connection factory with a guarded connection string (p136_r6_5_register_guarded_connection_factory.py)
"""Registering a connection factory with a guarded connection string

Source: ImproveCode, Chapter 6, Recipe 6.5 "Getting Connection Strings Out of Source Code"
Section: The improved recipe
Book page: 136  -- original C# listing
Converted from C# to Python.
pyodbc replaces SqlConnection; a module-level singleton factory replaces the DI
registration; ConnectionStringGuard is from p134_r6_5_connection_string_guard.py.
"""

from __future__ import annotations

from typing import Any, Protocol

import pyodbc


class DbConnectionFactory(Protocol):
    def create(self) -> pyodbc.Connection: ...


class SqlConnectionFactory:
    def __init__(self, connection_string: str) -> None:
        self._connection_string = connection_string

    def create(self) -> pyodbc.Connection:
        return pyodbc.connect(self._connection_string)


def register(connection_string_guard: Any, providers: Any, environment: Any) -> DbConnectionFactory:
    cs = connection_string_guard.get_required(providers, environment, "AppDb")
    return SqlConnectionFactory(cs)  # singleton

How it works

The search script is deliberately crude. It finds Password=, Pwd= and User ID= in code, config and scripts, and you review each hit. In my experience the list is longer than anyone expects, and the oldest hits are in console tools and SSIS script tasks that nobody remembers.

GetConnectionString("AppDb") reads ConnectionStrings:AppDb from any source: JSON, user secrets, an environment variable named ConnectionStrings__AppDb, or a Key Vault secret named Billing--ConnectionStrings--AppDb with the Recipe 6.4 prefix manager. Code that consumes the string doesn't change when the value moves between those homes.

Parsing with SqlConnectionStringBuilder turns a typo (Sever=) into an exception at startup instead of at the first query. Setting ApplicationName makes the app visible by name in sys.dm_exec_sessions and in SQL Server traces, which your DBA will thank you for during the next blocking investigation.

The guard enforces the policy in code. A production deployment where someone pasted a password into appsettings.Production.json fails with a clear message. The same string supplied through an environment variable or Key Vault passes. Development is exempt so local setups stay simple.

Describe gives you a safe string for logs and health checks. Logging the full connection string is one of the most common ways passwords leak into log files.

Variations and pitfalls

  • The best password is no password. On a Windows domain, run the app pool or service under a domain or group managed service account and use Integrated Security=true. In Azure, use a managed identity with Authentication=Active Directory Managed Identity (or Active Directory Default). Check the Microsoft.Data.SqlClient release notes for your version to see whether Entra ID authentication needs an extra package.
  • Moving a password out of the code doesn't remove it from the repository history. Treat every password that was ever committed as leaked and rotate it.
  • Microsoft.Data.SqlClient 4.0 and later encrypt connections by default. For a local or test server without a trusted certificate, add TrustServerCertificate=true in the development connection string only. In production, install a proper certificate.
  • Give each application its own login with only the permissions it needs. A shared sa login is how one compromised intranet page becomes a compromised server.
  • Keep one connection string per database per application. If five projects need the same database, they each read ConnectionStrings:AppDb from their own configuration.