Skip to content

Support rotating db credentials without restart (e.g. Aurora DSQL IAM auth) #1195

Open

Description

@Cyberider

Summary/Intro:

SQLPage has no built-in way to mint/refresh the needed AWS IAM token to authenticate with the DSQL database (because that requires AWS SigV4 signing via AWS SDK/CLI).

I’m trying to run SQLPage against Amazon Aurora DSQL (PostgreSQL-compatible, IAM-authenticated) from an AWS Lightsail Ubuntu 22.04 instance (but the same problem would also happen from the SQLPage Lambda runtime).

DSQL uses short-lived IAM auth tokens (SigV4-style) as the PostgreSQL password. Manual psql works only when I provide an IAM token and use the correct username mapping.

SQLPage cannot connect and repeatedly logs:

  • Failed to connect to the database: error returned from database: invalid password packet size
  • Then exits / restarts under systemd, causing upstream 502s in my setup.

Environment

  • SQLPage version: 0.40.0
  • OS: Ubuntu 22.04 (Lightsail)
  • Target DB: Aurora DSQL in us-west-2
  • Connection style: TLS required (sslmode=require)
  • SQLPage launched via systemd as a non-login user (e.g., sqlpage)

What works (manual)

Using the DSQL console “Connect with token”, I can connect from the same machine:

export PGPASSWORD='<DSQL token (presigned URL format, expires ~15m)>'
psql "host=<cluster>.dsql.us-west-2.on.aws port=5432 dbname=postgres user=admin sslmode=require" -c "select now();"

This succeeds. If I omit user=admin, DSQL returns:

  • Wrong user to action mapping. user: ubuntu, action: DbConnectAdmin

So DSQL requires both:

  1. an IAM token password
  2. a correct username/action mapping (e.g. admin for DbConnectAdmin)

What fails (SQLPage)

SQLPage has no visible options/help for AWS/IAM/DSQL token generation and appears to attempt a normal Postgres password auth. With database_url like:

{
  "database_url": "postgresql://@<cluster>.dsql.us-west-2.on.aws:5432/postgres?sslmode=require",
  "database_driver": "postgres"
}

SQLPage repeatedly fails with:

  • invalid password packet size

Even when AWS credentials are available in the environment, SQLPage does not appear to generate/use a DSQL IAM token.

Expected behavior

It would be great if SQLPage could support Aurora DSQL IAM authentication, e.g.:

  • ability to generate the required IAM auth token automatically (SigV4) when connecting
  • ability to set/override the PostgreSQL username explicitly (DSQL requires a specific mapping, e.g. admin)
  • docs/examples for Aurora DSQL

Workaround (in the meantime)

Because DSQL requires a rotating IAM token (~15 minutes), and SQLPage doesn’t generate tokens, you need a local component that does.

Practical workaround

Run a local PostgreSQL pooler/proxy on the server (PgBouncer or similar):

  • SQLPage connects to the local proxy on 127.0.0.1 with a static password
  • The proxy connects to DSQL using the IAM token as its upstream password
  • A small timer/job refreshes the token periodically (e.g., every 10 minutes) and reloads/restarts the proxy

This keeps SQLPage stable without restarting it every 15 minutes.

Notes:

  • Manual psql confirms DSQL connectivity is fine when using token + correct username (e.g. admin).
  • On Lightsail there’s no instance role, so the token refresh process uses a dedicated IAM “machine user” (access keys) stored securely and restricted to DSQL permissions.

Reproduction steps

1. Create an Aurora DSQL cluster

  • Region: any (tested in us-west-2)
  • No special configuration required

2. Obtain a DSQL IAM auth token from the AWS Console

  1. Open the DSQL cluster in the AWS Console

  2. Click “Connect” → “Connect with token”

  3. Choose:

    • User / Action: Admin (DbConnectAdmin)
  4. Copy the generated token (a long presigned URL–style string)

This token expires after ~15 minutes.


3. Verify connectivity using psql (works)

On a Linux machine with network access to the cluster:

export PGPASSWORD='<PASTE TOKEN FROM CONSOLE HERE>'

psql "host=<cluster-id>.dsql.<region>.on.aws \
      port=5432 \
      dbname=postgres \
      user=admin \
      sslmode=require" \
     -c "select now();"

Result:
Connection succeeds and returns the current timestamp.

Notes:

  • Omitting user=admin causes DSQL to fail with
    Wrong user to action mapping
  • Using any non-token password fails

4. Attempt the same connection using SQLPage (fails)

Using SQLPage 0.40.0, configure sqlpage.json:

{
  "database_url": "postgresql://admin@<cluster-id>.dsql.<region>.on.aws:5432/postgres?sslmode=require",
  "database_driver": "postgres"
}

Start SQLPage (e.g. via systemd).

Observed behavior:

  • SQLPage repeatedly logs:
Failed to connect to the database: error returned from database: invalid password packet size
  • SQLPage exits or restarts
  • The server never binds to its HTTP port

Providing valid AWS credentials in the environment does not change the outcome.


5. Expected behavior

Since:

  • psql succeeds with the same endpoint using an IAM auth token
  • SQLPage targets PostgreSQL-compatible databases

SQLPage would need to either:

  • Generate and use an IAM auth token for Aurora DSQL, or
  • Provide a documented/first-class way to integrate with token-based PostgreSQL authentication (e.g., via hooks or helpers)

Activity

  1. added
    enhancement
    on Jan 20, 2026
  2. lovasoa commented on Jan 21, 2026

    @lovasoa
    Collaborator

    Hello ? Does everything work in SQLPage when you use the TOKEN FROM CONSOLE as a password in SQLPage too?

    I'm not sure SQLPage should support aws-specific things, but it should make it easy to use your database anyway if it allows standard pg connections (just like psql).

    You should handle the token generation on your side, and then just pass it to SQLPage

  3. lovasoa commented on Jan 21, 2026

    @lovasoa
    Collaborator

    If with psql, you are using

    export PGPASSWORD='xxx'

    Then with sqlpage you should use

    export DATABASE_PASSWORD='xxx'

    See https://github.com/sqlpage/SQLPage/blob/main/configuration.md

  4. lovasoa commented on Jan 21, 2026

    @lovasoa
    Collaborator

    You can write a small script like

    #!/usr/bin/env bash
    set -euo pipefail
    
    DSQL_HOST="${DSQL_HOST:?set DSQL_HOST to your cluster endpoint, e.g. foo.dsql.us-east-1.on.aws}"
    DSQL_PORT="${DSQL_PORT:-5432}"
    DSQL_DB="${DSQL_DB:-postgres}"
    DSQL_USER="${DSQL_USER:-admin}"
    
    # Derive region from "<id>.dsql.<region>.on.aws"
    REGION="$(echo "$DSQL_HOST" | cut -d "." -f 3)"
    
    TOKEN="$(aws dsql generate-db-connect-admin-auth-token \
      --region "$REGION" \
      --hostname "$DSQL_HOST" \
      --expires-in "$TOKEN_TTL_SECONDS")"
    
    export DATABASE_URL="postgres://${DSQL_USER}@${DSQL_HOST}:${DSQL_PORT}/${DSQL_DB}?sslmode=require"
    export DATABASE_PASSWORD="$TOKEN"
    
    # Do not open new DB connections after startup
    export SQLPAGE_MAX_DATABASE_POOL_CONNECTIONS="${SQLPAGE_MAX_DATABASE_POOL_CONNECTIONS:-1}"
    
    # Stop SQLPage from closing/reopening connections
    export SQLPAGE_DATABASE_CONNECTION_IDLE_TIMEOUT_SECONDS="${SQLPAGE_DATABASE_CONNECTION_IDLE_TIMEOUT_SECONDS:-1e9}"
    export SQLPAGE_DATABASE_CONNECTION_MAX_LIFETIME_SECONDS="${SQLPAGE_DATABASE_CONNECTION_MAX_LIFETIME_SECONDS:-1e9}"
    
    exec sqlpage
  5. lovasoa commented on Jan 21, 2026

    @lovasoa
    Collaborator

    And I haven't tested it, but I suppose you can use https://github.com/aws/aws-advanced-odbc-wrapper/blob/main/docs/getting-started.md if you want to keep client-side connection pooling with automatic token generation when a new connection is opened.

  6. Cyberider commented on Jan 23, 2026

    @Cyberider
    Author

    Hello ? Does everything work in SQLPage when you use the TOKEN FROM CONSOLE as a password in SQLPage too?

    I'm not sure SQLPage should support aws-specific things, but it should make it easy to use your database anyway if it allows standard pg connections (just like psql).

    You should handle the token generation on your side, and then just pass it to SQLPage

    Thanks — after reworking my setup and testing this end-to-end, I can confirm the following (with the help of ChatGPT):

    Yes: SQLPage works correctly with Aurora DSQL when the DSQL IAM token is passed as the database password. Once I passed the token correctly, SQLPage connected immediately and behaves exactly like psql using IAM auth.

    The earlier error I reported:

    invalid password packet size
    

    turned out not to be a SQLPage or protocol issue. It was caused by me not passing the DSQL token correctly as the password. Once that was fixed, the error disappeared.


    What works today

    • SQLPage can connect directly to Aurora DSQL
    • No PgBouncer, no proxy, no driver changes
    • Uses a standard PostgreSQL URL
    • The DSQL IAM token is provided as the database password
    • Behavior matches psql with IAM authentication

    Nothing AWS-specific is required inside SQLPage for basic connectivity.


    Token lifetime is the real limitation

    • DSQL tokens generated via AWS Console expire after 15 minutes
    • DSQL tokens generated via AWS CLI expire after 60 minutes

    SQLPage works perfectly while the token is valid. When the token expires, new connections fail, which is expected.


    How I’m handling token generation

    Following your suggestion, I kept AWS-specific logic entirely outside SQLPage.

    I start SQLPage via a small wrapper that:

    1. Generates a fresh DSQL auth token using the AWS CLI
    2. Exports it as DATABASE_PASSWORD
    3. Starts SQLPage normally

    Example wrapper:

    #!/usr/bin/env bash
    set -euo pipefail
    
    INSTANCE="${1:?usage: sqlpage-wrapper <ENV-APP>}"
    ENV_FILE="/etc/sqlpage/apps/${INSTANCE}.env"
    
    source "${ENV_FILE}"
    
    if [[ -n "${DSQL_HOST:-}" ]]; then
      : "${AWS_REGION:?AWS_REGION must be set}"
    
      export DATABASE_PASSWORD="$(
        aws dsql generate-db-connect-admin-auth-token \
          --hostname "${DSQL_HOST}" \
          --region "${AWS_REGION}" \
          --expires-in 3600
      )"
    fi
    
    cd "${APP_ROOT}/app"
    exec /usr/local/bin/sqlpage

    This works reliably.


    Where seamless token refresh becomes a design question

    If SQLPage reads the database password only at startup and keeps a connection pool alive, then an externally refreshed token cannot be used by a running SQLPage process without a restart, unless a proxy layer is introduced.

    For direct SQLPage → DSQL connections, seamless token refresh would require SQLPage (or its pool layer) to support rotating database credentials.

    Conceptually, that could look like a generalized (non-AWS-specific) feature such as:

    • A password provider hook

      • re-read an env var or file
      • or execute a command to obtain credentials
    • Connection pool rotation

      • allow existing connections to complete
      • expire connections created with old credentials
      • open new connections using refreshed credentials
    • Careful handling of retries and long-running requests

      • avoid killing in-flight requests
      • retry connection acquisition cleanly during rotation

    This would be broadly useful for any environment with short-lived or rotating DB credentials, not just DSQL.


    Summary

    • SQLPage already works with Aurora DSQL using standard PostgreSQL semantics
    • The earlier failure was due to incorrect token injection, not a SQLPage limitation
    • Token expiration is the only remaining operational issue
    • Seamless refresh for direct connections would require generalized credential-rotation support

    Thanks for pushing me toward “generate the token externally and pass it as the password” — once I aligned with that model, everything worked as expected.

  7. Cyberider commented on Jan 23, 2026

    @Cyberider
    Author
    # Do not open new DB connections after startup
    export SQLPAGE_MAX_DATABASE_POOL_CONNECTIONS="${SQLPAGE_MAX_DATABASE_POOL_CONNECTIONS:-1}"
    
    # Stop SQLPage from closing/reopening connections
    export SQLPAGE_DATABASE_CONNECTION_IDLE_TIMEOUT_SECONDS="${SQLPAGE_DATABASE_CONNECTION_IDLE_TIMEOUT_SECONDS:-1e9}"
    export SQLPAGE_DATABASE_CONNECTION_MAX_LIFETIME_SECONDS="${SQLPAGE_DATABASE_CONNECTION_MAX_LIFETIME_SECONDS:-1e9}"
    

    Thanks for the concrete script suggestion — it helped clarify exactly where the boundary is today between SQLPage’s behavior and what Aurora DSQL expects from clients.

    Aurora DSQL behaves differently from traditional PostgreSQL backends in a way that makes this workaround fragile and, in practice, misaligned with its design goals.

    DSQL is explicitly built for massive concurrency with many short-lived client connections and does not require or benefit from client-side connection pooling in the classic Postgres sense. Its scaling model favors opening new authenticated connections freely rather than holding onto a small number of long-lived ones.

    Because of that, forcing SQLPage into:

    • a single connection (SQLPAGE_MAX_DATABASE_POOL_CONNECTIONS=1), and
    • effectively infinite connection lifetimes

    works against DSQL’s intended usage model rather than with it.

    More importantly, this approach is fragile:

    • It assumes the single connection will never be dropped (network blips, backend maintenance, idle reaping, etc.).
    • If that connection is dropped after the token expires, SQLPage cannot recover without a restart.
    • It serializes all database access through one connection, limiting throughput even though DSQL itself is designed for extremely high concurrency.

    This can work for a short-lived demo or low-traffic experiment, but it is not a viable foundation for production usage with DSQL.

    What does work reliably today is:

    • generating a DSQL auth token externally (CLI / SDK),
    • passing it to SQLPage as DATABASE_PASSWORD, and
    • letting SQLPage open standard Postgres connections.

    That confirms SQLPage already speaks the correct protocol and does not need any AWS-specific database logic.

    The remaining gap is credential rotation without restart. Because the DSQL token is the password, refreshing it necessarily requires:

    • a way to supply a new password to SQLPage at runtime, and
    • controlled retirement of connections created with the old token.

    This is not AWS-specific — it’s a general “short-lived / rotating database credentials” problem (similar to RDS IAM auth, Vault-issued credentials, etc.).

    The reason this matters for me specifically is that the end goal I’m working toward is SQLPage running in AWS Lambda, connecting directly to DSQL. That combination offers effectively infinite, seamless scalability — but it only works if SQLPage can natively handle short-lived, rotating database credentials without requiring restarts.

    In a Lambda environment, restarts are not a reliable or meaningful control mechanism, and connection pinning is actively harmful. The natural model there is:

    • short-lived processes,
    • frequent connection creation,
    • and credentials that rotate transparently.

    If SQLPage were to support this natively in a cloud-agnostic way, it would likely look like a generalized mechanism such as:

    • a pluggable “password provider” (env reload, file reload, or command execution),
    • pool-aware credential rotation (new connections use new credentials, old ones drain),
    • and careful retry handling for in-flight or long-running requests.

    That would keep SQLPage fully portable while enabling first-class support for modern databases that rely on short-lived authentication.

    I really appreciate the discussion — getting this working confirmed that SQLPage itself is already compatible with DSQL, and that the remaining challenge is entirely about credential lifecycle rather than protocol support.

  8. Cyberider commented on Jan 23, 2026

    @Cyberider
    Author

    And I haven't tested it, but I suppose you can use https://github.com/aws/aws-advanced-odbc-wrapper/blob/main/docs/getting-started.md if you want to keep client-side connection pooling with automatic token generation when a new connection is opened.

    Thanks for the suggestion — I’m aware SQLPage now has ODBC support, and the AWS advanced ODBC wrapper is an interesting project.

    Even with ODBC available, I don’t think the ODBC wrapper is a good fit for Postgres + Aurora DSQL in this case.

    Using it would require routing SQLPage’s Postgres traffic through an ODBC Postgres driver, replacing SQLPage’s native async Postgres path. That adds significant complexity and feels like a regression, especially since SQLPage already speaks the Postgres protocol correctly and works fine with DSQL once a valid token is provided.

    More importantly, the ODBC wrapper only handles token generation when a new connection is opened. It doesn’t address the core issue here: rotating short-lived database credentials while the application is running, and safely retiring connections created with an old token.

    Given that SQLPage does not support credential rotation today (and likely won’t for some time), a small local proxy like PgBouncer is actually a more practical workaround:

    • SQLPage continues using its native Postgres driver.
    • Token generation and rotation can be handled entirely outside SQLPage.
    • SQLPage sees a stable local Postgres endpoint with no AWS-specific logic.

    Even PgBouncer is only a stop-gap. Aurora DSQL is designed for massive concurrency and many short-lived connections, so restricting pools or forcing long-lived connections works against its intended usage model.

    Many thanks for the amazing SQLPage you are building!

  9. lovasoa commented on Jan 23, 2026

    @lovasoa
    Collaborator

    Please! Do not paste huge walls of unverified verbose generated text to me! that's not fair. If you cannot be bothered to write it, I cannot be bothered to read it 😞

  10. changed the title [-]AWS Aurora DSQL (IAM auth) not supported: SQLPage fails with invalid password packet size / cannot generate IAM token[/-] [+]Support rotating db credentials without restart (e.g. Aurora DSQL IAM auth)[/+] on Jan 23, 2026
  11. Cyberider commented on Jan 23, 2026

    @Cyberider
    Author

    Sorry! I was trying to be helpful and for others later reading it with the same issue.

    TL;DR

    I got SQLPage working directly with Aurora DSQL using IAM auth tokens. The earlier invalid password packet size error was my mistake (token not passed correctly).

    The remaining limitation is simply this: SQLPage cannot rotate short-lived DB credentials at runtime, so when the DSQL token expires the process must restart.

    ODBC doesn’t really help here (even with SQLPage’s ODBC support), and restricting connections is fragile. A proxy like PgBouncer is the only workable stop-gap today.

    I changed this repo issue title from
    "AWS Aurora DSQL (IAM auth) not supported: SQLPage fails with invalid password packet size / cannot generate IAM token"

    Many thanks for the amazing SQLPage you are building!

  12. lovasoa commented on Jan 23, 2026

    @lovasoa
    Collaborator

    Hi ! No problem !

    when the DSQL token expires the process must restart.

    I don't think that's true. Once the connection is established, it's not cut when the token expires.

    ODBC doesn’t really help

    I think with the aws odbc driver it would just work out of the box (not tried though)

    A proxy like PgBouncer is the only workable stop-gap today.

    It may be a good idea but I'm not sure; I suppose it degrades performance.


    I would keep one connection per sqlpage instance, and eventually multiple sqlpage instances if very strict performance/reliability constraints apply.

  13. Cyberider commented on Jan 23, 2026

    @Cyberider
    Author

    Thanks but DSQL is explicitly built for massive concurrency with many short-lived client connections and does not require or benefit from client-side connection pooling in the classic Postgres sense. DSQL advises against using pooling. Its scaling model favors opening many new authenticated connections freely rather than holding onto a small number of long-lived ones.

    This is not AWS-specific, it’s a general “short-lived / rotating database credentials” problem with modern dbs (similar to RDS IAM auth, Vault-issued credentials, etc.).

    The reason this matters for me specifically is that the end goal I’m working toward is SQLPage running in AWS Lambda, connecting directly to DSQL. That combination offers effectively infinite, seamless scalability — but it only works if SQLPage can natively handle short-lived, rotating database credentials without requiring restarts.

    Thanks

  14. lovasoa commented on Jan 24, 2026

    @lovasoa
    Collaborator

    Hi! Disabling connection pooling is exactly what I am suggesting! If you put SQLPage without connection pooling in a lambda with a simple retrieval script for the initial identification, you will get exactly what you want: many shortlived connections with massive concurrency.

    Out of curiosity, what scale are you envisioning? How many users do you have?

  15. Cyberider commented on Jan 31, 2026

    @Cyberider
    Author

    Since your last post 6 days ago DSQL changed the max expiry time for tokens generated from the CLI from 60 minutes to 1 week! That changes things a lot!

    I can now run SQLPage with a weekly restart (Lightsail or Lambda) to pick up a fresh token, which is good enough for now given the project is still in early dev and has no users.

    It’s not as clean as native credential rotation, but it’s a workable interim solution without proxies or ODBC, and it aligns well with the “short-lived connections / no pooling” model you described.

    The project is in the dev stage, zero users, but I think it does not take anymore dev time to develop a SQLPage Lambda + DSQL app when starting from scratch vs other stacks and then migrating to that stack and with that stack you get seamless scalability and a relatively easier to maintain db.

    Thank you for your time and help with the amazing SQLPage!

  16. lovasoa commented on Jan 31, 2026

    @lovasoa
    Collaborator

    You do not need to restart sqlpage when the token expires. Once the connection is established it is valid even if the token is expired. You only need to ensure the instance is properly restarted when the connection is lost (when it crashes). But you need that anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions