San Marino's founding in the fourth century is dubious, at best. Although there certainly is no way of disproving that a semi-autonomous christian community was living atop Mt. Titano as early as 301, the oldest document we know of referring to the council that met in atop the mountain to rule the "Land of Saint Marinus" dates to 885.
The region where San Marino is found was traditionally a border area between the independent cities of Northern Italy and the lands under the influence of the Papacy. Since the late twelfth century, the lands ruled by the Pope in central Italy were hodgepodge of independent cities, multi-level feudal holdings, cities within feudal holdings, and cities run by citizens with feudal holdings (fun!). You could say the whole of the Papal States were hundreds of San Marinos of varying size and power.
In the thirteenth century, the local Abbot came to San Marino to claim the church's shares of taxes during a particularly active period of Papal consolidation. The council of elders conveniently produced an "ancient" document attesting to the town's independence. It helped that the town is virtually unassailable. To small to really bother anyone, San Marino continued governing itself until the modern era.