binwiederhier / ntfy

Send push notifications to your phone or desktop using PUT/POST
https://ntfy.sh
Apache License 2.0
18.54k stars 729 forks source link

Bootstrap user when starting docker container #1190

Open Cheezzhead opened 1 month ago

Cheezzhead commented 1 month ago

I would like to bootstrap my ntfy users, to avoid having to make a backup of the auth.db file. This involves creating each user with the CLI before starting the main ntfy process. Unfortunately, doing this on a fresh server throws the error auth-file does not exist; please start the server at least once to create it. As far as I can see, the only way to create this auth-file is to run ntfy serve at least once, kill the server and then restart. This seems... not ideal.

When it comes to the ephemerality (if that's a word) of docker containers, it is common practice to bootstrap users in this way; for example, official docker database images such as postgres allow you to define a user with environment variables to be created on startup.

Following those standards, the best way to solve this would be to add similar environment variable functionality (e.g. NTFY_USER and NTFY_PASSWORD), creating this user if it is supplied. Alternatively, providing a CLI (sub)command to create the auth.db file (other than running ntfy serve and then forcefully killing it once) would also be beneficial. I don't know which of these is easier, I guess it depends on where/how the auth file is created in the internal code.

Also it's entirely possible that there is already such a method and I haven't looked closely enough.

compose.yml

ntfy:
    image: binwiederhier/ntfy:latest
    container_name: ntfy
    #command: [serve]
    entrypoint: /bootstrap_users.sh
    secrets: [ntfy-admin-pass, other-pass]
    environment:
      NTFY_BASE_URL: https://ntfy.${DOMAIN}
      NTFY_BEHIND_PROXY: true
      NTFY_UPSTREAM_BASE_URL: https://ntfy.sh
      # Access control
      NTFY_ENABLE_LOGIN: true
      NTFY_ENABLE_SIGNUP: false
      NTFY_AUTH_DEFAULT_ACCESS: deny-all
      NTFY_AUTH_FILE: /var/lib/ntfy/auth.db
      # Caching
      NTFY_CACHE_FILE: /var/lib/ntfy/cache.db
      NTFY_ATTACHMENT_CACHE_DIR: /var/lib/ntfy/attachments
    volumes:
      - ./ntfy/bootstrap_users.sh:/bootstrap_users.sh:ro
      - ntfy_data:/var/lib/ntfy

bootstrap_users.sh

# Admin
NTFY_PASSWORD="$(cat /run/secrets/ntfy-admin-pass)" ntfy user add --role=admin admin

# Readers
if NTFY_PASSWORD="$(cat /run/secrets/...)" ntfy user add some-reader; then
    ntfy access reader "*" read
fi

// etc..

# Run
cd /usr/bin || exit 1
ntfy serve