Generating a login cookie for Nextcloud

When running a Nextcloud (or ownCloud 10 for that matter) you usually have a key-value database like redis, valkey, keydb or memcache for session handling. This introduces some complications for monitoring, because it does not suffice to simply check if the host is up.

Indeed, just the file storage failing would still lead to the login page rendering fine, but file access being disturbed, so at least we do need a check like

NC_URL="https://example.org"
WEBDAV_URL="${NC_URL}/remote.php/dav/files/"
USER=atestuser
PASSWORD=somepassword

curl -u ${USER}:${PASSWORD} -s -G ${WEBDAV_URL}/${USER}/Readme.md

Still, session handling can be broken independently, and it would not show up in this test, because we do not use a session, but a user using the web interface would not be able to use the Nextcloud instance. Sadly it also does not suffice to check if your key-value db is up, networking can be a bitch sometimes.

One can "simply" run selenium tests mimicking the login flow and this is definitely recommended, but they tend to be too expensive to be run at the frequencies appropriate for liveness checks.

So we need a test which tries to get a cookie.

With ownCloud 10, you can repurpose the cookie generated from the request above:

OC_URL="https://example.org"
WEBDAV_URL="${OC_URL}/remote.php/dav/files/"
USER=atestuser
PASSWORD=somepassword

curl -c cookies.txt -u ${USER}:${PASSWORD} -s -G ${WEBDAV_URL}/${USER}/Readme.md
curl -b cookies.txt -s -G ${WEBDAV_URL}/${USER}/Readme.md

But Nextcloud does some primitive brute force protection by presenting a token string on the login page, as well as encoding a session passphrase in the cookie, so we actually need to use this cookie and craft the actual login POST request:

NC_URL="https://example.org"
WEBDAV_URL="${NC_URL}/remote.php/dav/files/"
USER=atestuser
PASSWORD=somepassword

requesttoken=$(curl -c cookies.txt ${NC_URL}/login | \
  grep data-requesttoken | \
  sed -e 's/^ data-requesttoken="//g' -e 's/">$//g')
curl -b cookies.txt -c cookies.txt \
  --data-urlencode "user=${USER}" \
  --data-urlencode "password=${PASSWORD}" \
  --data-urlencode "requesttoken=${requesttoken}" \
  -X POST "${NC_URL}/login" 
curl -b cookies.txt -m 7 -s -G \
        "${WEBDAV_URL}/Readme.md"

Now this is can be integrated into one's general CI pipeline or even ancient monitoring tools like check_mk.

blogroll

social