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

docs: add direct asyncpg IAM authentication tests #121

Merged
merged 15 commits into from
Sep 22, 2023
Merged

Conversation

jackwotherspoon
Copy link
Collaborator

@jackwotherspoon jackwotherspoon commented Sep 18, 2023

Add direct TCP IAM authentication samples for asyncpg driver (SQLAlchemy + native asyncpg).

Should result in following sample in docs:

alloydb_sqlalchemy_asyncpg_connect_iam_authn_direct region tag:

import sqlalchemy
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import event

import google.auth
from google.auth.credentials import Credentials
from google.auth.transport.requests import Request

# initialize Google Auth credentials
credentials, _ = google.auth.default(
    scopes=["https://www.googleapis.com/auth/cloud-platform"]
)

def get_authentication_token(credentials: Credentials) -> str:
    """Get OAuth2 access token to be used for IAM database authentication"""
    # refresh credentials if expired
    if not credentials.valid:
        request = Request()
        credentials.refresh(request)
    return credentials.token

engine = create_async_engine(
    # Equivalent URL:
    # postgresql+asyncpg://<user>:empty@<host>:5432/<db_name>
    sqlalchemy.engine.url.URL.create(
        drivername="postgresql+asyncpg",
        username=user,  # IAM db user, e.g. service-account@project-id.iam
        password="",  # placeholder to be replaced with OAuth2 token
        host=ip_address,  # AlloyDB instance IP address
        port=5432,
        database=db_name,  # "my-database-name"
    ),
    connect_args={"ssl": "require"},
)

# set 'do_connect' event listener to replace password with OAuth2 token
# must use engine.sync_engine as async events are not implemented
@event.listens_for(engine.sync_engine, "do_connect")
def auto_iam_authentication(dialect, conn_rec, cargs, cparams) -> None:
    cparams["password"] = get_authentication_token(credentials)

# use connection from connection pool to query AlloyDB database
async with engine.connect() as conn:
    result = await conn.execute(sqlalchemy.text("SELECT NOW()"))
    time = result.fetchone()
    print("Current time is ", time[0])

alloydb_native_asyncpg_connect_iam_authn_direct region tag:

import asyncpg

import google.auth
from google.auth.transport.requests import Request

# initialize Google Auth credentials
credentials, _ = google.auth.default(
    scopes=["https://www.googleapis.com/auth/cloud-platform"]
)

def get_authentication_token() -> str:
    """Get OAuth2 access token to be used for IAM database authentication"""
    # refresh credentials if expired
    if not credentials.valid:
        request = Request()
        credentials.refresh(request)
    return credentials.token

# ... inside async context
async with asyncpg.create_pool(
    user=user,  # IAM db user, e.g. service-account@project-id.iam
    password=get_authentication_token,  # set OAuth2 token as password
    host=ip_address,  # AlloyDB instance IP address
    port=5432,
    database=db,  # my-database
    ssl="require",
) as pool:
    # acquire connection from native asyncpg connection pool
    async with pool.acquire() as conn:
        time = await conn.fetchrow("SELECT NOW()")
        print("Current time is ", time[0])

Closes #120

@jackwotherspoon jackwotherspoon self-assigned this Sep 18, 2023
@jackwotherspoon jackwotherspoon marked this pull request as ready for review September 19, 2023 00:32
@jackwotherspoon jackwotherspoon requested a review from a team as a code owner September 19, 2023 00:32
@jackwotherspoon jackwotherspoon changed the title docs: add direct asyncpg IAM authentication test docs: add direct asyncpg IAM authentication tests Sep 19, 2023
@jackwotherspoon jackwotherspoon merged commit 70701c6 into main Sep 22, 2023
15 checks passed
@jackwotherspoon jackwotherspoon deleted the asyncpg-sample branch September 22, 2023 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add test demonstating Auto IAM AuthN on direct path
2 participants