Skip to content

Instantly share code, notes, and snippets.

@bohanyang
Created July 5, 2023 13:57
Show Gist options
  • Save bohanyang/aabb562ad12906ff13420a907c87d2ca to your computer and use it in GitHub Desktop.
Save bohanyang/aabb562ad12906ff13420a907c87d2ca to your computer and use it in GitHub Desktop.
PostgREST JWKS
services:
jwks-updater:
image: jwks-updater
build:
context: .
dockerfile: ./jwks-updater.Dockerfile
depends_on:
postgres: # Disable this if you are using an external Postgres database
condition: service_healthy
postgrest:
condition: service_started
restart: unless-stopped
environment:
PGHOST: ${POSTGRES_HOST}
PGPORT: ${POSTGRES_PORT}
PGDATABASE: ${POSTGRES_DB}
PGUSER: ${POSTGRES_USER}
PGPASSWORD: ${POSTGRES_PASSWORD}
JWKS_URI: ${JWKS_URI}
FROM alpine:latest
RUN apk --no-cache add curl jq postgresql-client ca-certificates
COPY jwks-updater.sh /usr/local/bin/
CMD ["sh", "-c", "while true; do jwks-updater.sh; sleep 5s; done"]
#!/usr/bin/env sh
set -eu
postgrest_role='authenticator'
kid_cache_path='/tmp/postgrest-jwks-kids.txt'
cached_kids=''
if [ -f "$kid_cache_path" ]; then
cached_kids=$(cat "$kid_cache_path")
fi
jwks_response=$(curl -fsSL "$JWKS_URI")
fetched_kids=$(echo "$jwks_response" | jq -r '.keys[].kid')
execute_sql() {
psql -v ON_ERROR_STOP=1 --no-psqlrc "$@"
}
set_pgrst_in_db() {
echo "ALTER ROLE ${postgrest_role} IN DATABASE ${PGDATABASE} SET ${1} = :'v';" | execute_sql -v v="$2"
}
reload_pgrst() {
execute_sql -c "NOTIFY pgrst, 'reload config';"
}
if [ "$cached_kids" != "$fetched_kids" ]; then
date
set_pgrst_in_db pgrst.jwt_secret "$jwks_response"
set_pgrst_in_db pgrst.jwt_secret_is_base64 false
reload_pgrst
echo "$fetched_kids" | tee "$kid_cache_path"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment