How do I let user Y write in folder A only when executing script X?
I believe that this will require program X having setuid permissions, and belonging to a user UA that has write privileges to folder A. Then when X is invoked it runs as UA, no matter what user it was invoked by.
Most shells (maybe all) won't let scripts have setuid permissions, they'll just ignore that permission bit unless X is a binary. of course x could be a binary wrapper that just executes some separate script X.sh.
You shouldn't setuid X as root if you don't have to. You could make folder A be writable by a user UA with less privileges.
Alternatively, you could make folder A be writable by a dedicated group, and assign X to that group, and use setgid on X instead of setuid.
This issue is commonly faced by games - nethack for example has "bones" files and a hiscore table that should be writable by the game but not by any of the individual non-administrator users. This is done by having the executable setgid.
http://nethack.wikia.com/wiki/Setgid has a rundown on this system. The advantage is that an exploit of nethack would only get you group games privileges, rather user root privileges.
How about having script x write to /usr/bin, but as user z which is a user account for this specific purpose?
Granted, this means using the sticky bit, which has its own security concerns, but you can lock down user z (no logins, very restricted permissions beyond /usr/bin, etc.)
I'm not the best on Linux security, but it was the only thing I could come up with on short notice.
A lot of applications execute privilege separation--they do everything they can as an unprivileged user and then the one or two operations that require root are actually done by a separate process. (Alternately: start as root, do the one-two things that require root, and drop privileges.)
Your other option, off the top of my head, is sudo.