While restarting, click Command + R. When you are at Recovery Utilities, choose Reinstall the OS X.
If reinstallation is not permitted then you would like to erase the existing OS X from Disk Utility. Do it only if the data is not important. If data is important, you may first put you Mac in target disk mode, connect it to another Mac (if available) and save all the data important.
If reinstallation or fresh installation of OS X mitigates this issue, you are fine. If not, your top-case with keyboard seems failing. (In some cases like this I have seen Logic Board failing).
How to figure out if the topcase with keyboard is failing when you do not have replacement parts in hand? Well, you can open the back-pane. Turn on your Mac and quickly, lift up the keyboard latch and pull the keyboard flex out. Let your Mac run without the keyboard and see if it turns off on its own. Do not let it sleep. Keep waking it up using the trackpad. Upon keyboard disconnected, if your Mac still turns off, it's not a keyboard issue. It's most probably logic board issue. Inspect if your logic board shows any sign of corrosion. You may like to take apart completely so that you can see it. Better use magnifying glass to stop it. Sometimes, trapped moisture turns into water with a condensation method internally and impairs the logic board. We do not notice it because we believe that we never spilled water over our Mac.
Hope this helps.