Copyright law specifically allows for libraries and archives to make copies of copyrighted material.
Without such laws, without libraries, knowledge could not be guaranteed to be shared freely among the public, resulting in ever growing knowledge and education gaps between those with means and those without.
Edit: Since you asked for the legal ground, here it is specifically:
https://www.law.cornell.edu/uscode/text/17/108
And here’s is further discussion by the copyright office itself:
https://www.copyright.gov/policy/section108/discussion-docum...
Congress and the copyright office have made it an important part of copyright law to protect archival, library and fair use doctrine.