"bw unlock" fails when run at startup from .zsrhc beacuse it no longer prompts for my password?

Hi all.

For a long time, I’ve had a simple script in my .zshrc file on MacOS that will fetch some values from BitWarden (using the Bitwarden CLI) to set them as environment variables. For this, the script needs to login to my vault, which means it will prompt me for my BitWarden password when it’s run:

if [[ -z "${MY_USERNAME}" || -z "${MY_PASSWORD}" ]]
then
    BW_SESSION=$(bw unlock --raw)
    bw sync
    MY_USER=$(bw get username my-vault-item --session $BW_SESSION)
    MY_PASSWORD=$(bw get password my-vault-item --session $BW_SESSION)
    launchctl setenv MY_USER $MY_USER
    export MY_USER=$MY_USER
    launchctl setenv MY_PASSWORD $MY_PASSWORD
    export MY_PASSWORD=$MY_PASSWORD
    bw lock > /dev/null 2>&1
fi

However, a few months ago (perhaps after an OS or BitWarden update), it stopped working. After a reboot, when I open iTerm (or the default MacOS Terminal app), the script now runs without prompting me for my password after bw unlock, so it doesn’t get a session key and the subsequent commands fail as expected.

This is the output shown in the terminal:

You are not logged in.
You are not logged in.
error: option '--session <session>' argument missing
error: option '--session <session>' argument missing
Usage: launchctl setenv <<key> <value>, ...>
Usage: launchctl setenv <<key> <value>, ...>

The interesting thing is, if I manually do source .zshrc after that, everything works perfectly. It prompts for my password, my env variables are set, and they’re available for any future shell sessions until I reboot my PC again.

I’ve also tried adding a 5s delay before the bw unlock line, like this:

if [[ -z "${MY_USERNAME}" || -z "${MY_PASSWORD}" ]]
then
    sleep 5
    BW_SESSION=$(bw unlock --raw)
    bw sync
    MY_USER=$(bw get username my-vault-item --session $BW_SESSION)
    MY_PASSWORD=$(bw get password my-vault-item --session $BW_SESSION)
    launchctl setenv MY_USER $MY_USER
    export MY_USER=$MY_USER
    launchctl setenv MY_PASSWORD $MY_PASSWORD
    export MY_PASSWORD=$MY_PASSWORD
    bw lock > /dev/null 2>&1
fi

But it didn’t change anything. The terminal waits for 5 seconds, everything’s properly initialized, but then it pushes through without prompting me for my password anyway.

Any idea of why the script is no longer prompting me for my password when executed automatically at shell startup app, but it does when manually sourced?

1 Like