The tax-exempt status is granted for Exempt Purposes, but not as a matter of altruistic intention: https://www.irs.gov/charities-non-profits/charitable-organiz...
For example, ask your favorite LLM search engine: Can you list non-profits/501(c)(3) that are US defense contractors?
Draper Laboratory and Energetics Technology Center are registered 501(c)(3) corporations. Their primary output is weapons research. RAND Corp, whose name you'd likely recognize, is also a DoD contractor and 501(c)(3).
The NRA Foundation and the Heritage Foundation are also registered as 501(c)(3).