Making upstart job redirect output as unprivileged user

1

1

I am currently making an upstart job run as an unprivileged user like so:

start on started mongodb
stop on runlevel [06]

respawn
respawn limit 10 100

env NODE_ENV=production

pre-start script
    ulimit -n 2048
end script

exec sudo -u mainuser /usr/bin/make -C /home/mainuser/app start-prod >> /home/mainuser/data/logs/app.log 2>> /home/mainuser/data/logs/app.err.log

This works good, with one exception: the log files app.log and app.err.log are being written as root (root becomes the owner of these files).

How do I ensure that the log files are written by the unprivileged mainuser?

Tom

Posted 2012-05-20T14:15:57.317

Reputation: 259

Answers

1

Some thoughts from the top of my head: you could use | sudo -u mainuser tee to write the file (but if you want to split STDOUT and STDERR it can become a bit messy), or you could in the script check if the log files exist and are owned by mainuser, if not create and chown mainuser. Then appending output as you do would keep ownership.

Quick snippet:

#!/bin/sh
user="mainuser"
group="mainuser"
for i in /home/mainuser/data/logs/app.log /home/mainuser/data/logs/app.err.log; do
    if [ ! -f "${i}" ] || [ "$(stat -c%U -- "${i}")" != "${user}" ]; then
        touch -- "${i}"
        chown ${user}:${group} -- "${i}"
    fi
done

This is quick and doesn't handle cases such as the log files existing as directories/links and so on very nicely, but in practice it might be fine.

I haven't worked with Upstart though, so maybe there are simpler ways.

Daniel Andersson

Posted 2012-05-20T14:15:57.317

Reputation: 20 465

I don't think an unprivileged user can "steal" or chown a file owned by root. The tee hint is more interesting, but before I try to implement it I will wait and see if there are any better options available, if you don't mind. Maybe I should just modify my make script so that it will do the logging. – Tom – 2012-05-20T15:43:23.760

@Tom: You run the above test as root in the upstart script, in the pre-start script section I would guess, before dropping privilege to mainuser. Only root can chown as well. – Daniel Andersson – 2012-05-20T15:50:05.590