It seems to be a common fantasy trope, that a dungeon or hidden treasure can be accessed by solving a puzzle or riddle (occasionally featuring helpful hints in the form of a poem). They can be mechanical, magical, or the combination of both.
Of course, the purpose of a real security system is to differentiate between authorized and unauthorized personnel, based on a combination of the following:
- something you posses. For example, a key you keep on your person or distribute only to trusted underlings, and not a key which is hidden among a few other keys at the location, with a poem containing a riddle how to choose the correct one, if the intruder even cares to solve it instead of just brute forcing all of them.
- something you know. For example, a password or a number sequence you memorize and only tell to trusted underlings, and not the solution of a riddle inscribed next to the locked door.
- something you are. In modern times it can be biometric data, in fantasy it can be your race or bloodline. Still, the latter one could include a large number of people you wouldn't want accessing your hidden base.
Instead of the above, in fantasy it's common to use riddles, which anyone lucky or smart enough can solve, this defeats the whole purpose of having a locked entryway.
Please note, that this question is about riddles or puzzles being used where the intention was to keep unauthorized access away from something the creator of the riddle wants to keep away from trespassers. Therefore, the following types of riddles or puzzles are not answers to the question:
- the makers of the puzzle do it out of sheer curiosity or boredom, or just to have fun or screw with the people (like the myth of the Sphinx)
- the makers of the puzzle do it as a way to test people, or to gift eligible people with their treasure.
To fulfill the criteria of the question, the riddle or puzzle must be an honest (but misguided) effort to protect something, and prevent access from anyone who doesn't already know the solution. Of course, inevitably, someone will solve the puzzle and gain access who the creator of the puzzle didn't intend to do so.
If the earliest example is mythological, it would be nice to include the earliest work of fiction additionally to it.