"How long can beer sit in a keg?"
A couple hundred years, I would imagine, until either the keg rusts through or the seals deteriorate enough that the beer is able to evaporate.
Your real question is more likely "How long can beer sit in a keg and stay good and fresh-tasting?"
As others have said, it is dependent on the degree to which you can reduce oxygen exposure.
If it is already fully fermented out, you can add the priming sugar, wait for yeast activity, then closed loop transfer to a purged keg (via purged lines).
Alternately (and preferably), you time it so you have about 4 gravity points left to full attenuation and transfer the beer (via purged lines to a purged keg) and let it naturally condition with its own residual sugar (called spunding - do some searches, there's lots of info on this). By the way, you don't use an airlock here - you can use a spunding valve or just leave it sealed. This will also create the pressure you want to help keep air out. This is preferable because you are naturally carbonating the beer without opening it up or adding additional sugar. You'll also get better foam and head retention on a spunded beer.
Give it a try.
Then storing it as cold as your logistics allow will help (once you have given it a week or so to finish fermenting and carbonate). In a fridge (lagering) is ideal, but a cool basement or some such will do. The cooler the better.