auth_middleware.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #ifndef AUTH_MIDDLEWARE_H
  2. #define AUTH_MIDDLEWARE_H
  3. #include <string>
  4. #include <vector>
  5. #include <functional>
  6. #include <memory>
  7. #include "jwt_auth.h"
  8. #include "user_manager.h"
  9. #include "server_config.h"
  10. #ifdef ENABLE_PAM_AUTH
  11. #include "pam_auth.h"
  12. #endif
  13. namespace httplib {
  14. class Request;
  15. class Response;
  16. }
  17. /**
  18. * @brief Authentication context structure
  19. */
  20. struct AuthContext {
  21. bool authenticated; ///< Authentication status
  22. std::string userId; ///< User ID
  23. std::string username; ///< Username
  24. std::string role; ///< User role
  25. std::vector<std::string> permissions; ///< User permissions
  26. std::string authMethod; ///< Authentication method used
  27. std::string errorMessage; ///< Error message if authentication failed
  28. std::string errorCode; ///< Error code for API responses
  29. };
  30. /**
  31. * @brief Authentication middleware class
  32. *
  33. * This class provides authentication and authorization middleware for HTTP requests.
  34. * It supports PAM and shared key authentication methods and
  35. * role-based access control.
  36. */
  37. class AuthMiddleware {
  38. public:
  39. /**
  40. * @brief Authentication handler function type
  41. *
  42. * @param req HTTP request
  43. * @param res HTTP response
  44. * @param context Authentication context
  45. */
  46. using AuthHandler = std::function<void(const httplib::Request& req,
  47. httplib::Response& res,
  48. const AuthContext& context)>;
  49. /**
  50. * @brief Construct a new Auth Middleware object
  51. *
  52. * @param config Authentication configuration
  53. * @param userManager User manager instance
  54. */
  55. explicit AuthMiddleware(AuthConfig config,
  56. std::shared_ptr<UserManager> userManager);
  57. /**
  58. * @brief Destroy the Auth Middleware object
  59. */
  60. ~AuthMiddleware();
  61. /**
  62. * @brief Initialize the authentication middleware
  63. *
  64. * @return true if initialization successful, false otherwise
  65. */
  66. bool initialize();
  67. /**
  68. * @brief Authenticate HTTP request
  69. *
  70. * @param req HTTP request
  71. * @param res HTTP response
  72. * @return AuthContext Authentication context
  73. */
  74. AuthContext authenticate(const httplib::Request& req, httplib::Response& res);
  75. /**
  76. * @brief Check if path requires authentication
  77. *
  78. * @param path Request path
  79. * @return true if authentication required, false otherwise
  80. */
  81. bool requiresAuthentication(const std::string& path) const;
  82. /**
  83. * @brief Check if path requires admin access
  84. *
  85. * @param path Request path
  86. * @return true if admin access required, false otherwise
  87. */
  88. bool requiresAdminAccess(const std::string& path) const;
  89. /**
  90. * @brief Check if path requires user access (any authenticated user)
  91. *
  92. * @param path Request path
  93. * @return true if user access required, false otherwise
  94. */
  95. bool requiresUserAccess(const std::string& path) const;
  96. /**
  97. * @brief Check if user has permission for path
  98. *
  99. * @param path Request path
  100. * @param permissions User permissions
  101. * @return true if user has access, false otherwise
  102. */
  103. bool hasPathAccess(const std::string& path,
  104. const std::vector<std::string>& permissions) const;
  105. /**
  106. * @brief Create authentication middleware handler
  107. *
  108. * @param handler Next handler in chain
  109. * @return AuthHandler Middleware handler function
  110. */
  111. AuthHandler createMiddleware(AuthHandler handler);
  112. /**
  113. * @brief Send authentication error response
  114. *
  115. * @param res HTTP response
  116. * @param message Error message
  117. * @param errorCode Error code
  118. * @param statusCode HTTP status code
  119. */
  120. void sendAuthError(httplib::Response& res,
  121. const std::string& message,
  122. const std::string& errorCode = "AUTH_ERROR",
  123. int statusCode = 401);
  124. /**
  125. * @brief Send authorization error response
  126. *
  127. * @param res HTTP response
  128. * @param message Error message
  129. * @param errorCode Error code
  130. */
  131. void sendAuthzError(httplib::Response& res,
  132. const std::string& message,
  133. const std::string& errorCode = "ACCESS_DENIED");
  134. /**
  135. * @brief Add public path (no authentication required)
  136. *
  137. * @param path Path to add
  138. */
  139. void addPublicPath(const std::string& path);
  140. /**
  141. * @brief Add admin-only path
  142. *
  143. * @param path Path to add
  144. */
  145. void addAdminPath(const std::string& path);
  146. /**
  147. * @brief Add user-only path
  148. *
  149. * @param path Path to add
  150. */
  151. void addUserPath(const std::string& path);
  152. /**
  153. * @brief Set JWT secret
  154. *
  155. * @param secret JWT secret key
  156. */
  157. void setJwtSecret(const std::string& secret);
  158. /**
  159. * @brief Get JWT secret
  160. *
  161. * @return std::string JWT secret key
  162. */
  163. std::string getJwtSecret() const;
  164. /**
  165. * @brief Set authentication method
  166. *
  167. * @param method Authentication method
  168. */
  169. void setAuthMethod(UserManager::AuthMethod method);
  170. /**
  171. * @brief Get authentication method
  172. *
  173. * @return UserManager::AuthMethod Current authentication method
  174. */
  175. UserManager::AuthMethod getAuthMethod() const;
  176. /**
  177. * @brief Enable or disable guest access
  178. *
  179. * @param enable Enable guest access
  180. */
  181. void setGuestAccessEnabled(bool enable);
  182. /**
  183. * @brief Check if guest access is enabled
  184. *
  185. * @return true if guest access enabled, false otherwise
  186. */
  187. bool isGuestAccessEnabled() const;
  188. /**
  189. * @brief Get authentication configuration
  190. *
  191. * @return AuthConfig Current configuration
  192. */
  193. AuthConfig getConfig() const;
  194. /**
  195. * @brief Update authentication configuration
  196. *
  197. * @param config New configuration
  198. */
  199. void updateConfig(AuthConfig config);
  200. private:
  201. AuthConfig m_config; ///< Authentication configuration
  202. std::shared_ptr<UserManager> m_userManager; ///< User manager instance
  203. std::unique_ptr<JWTAuth> m_jwtAuth; ///< JWT authentication instance
  204. /**
  205. * @brief Authenticate using JWT token
  206. *
  207. * @param req HTTP request
  208. * @return AuthContext Authentication context
  209. */
  210. AuthContext authenticateJwt(const httplib::Request& req);
  211. /**
  212. * @brief Authenticate using PAM
  213. *
  214. * @param req HTTP request
  215. * @return AuthContext Authentication context
  216. */
  217. AuthContext authenticatePam(const httplib::Request& req);
  218. /**
  219. * @brief Authenticate using shared key
  220. *
  221. * @param req HTTP request
  222. * @return AuthContext Authentication context
  223. */
  224. AuthContext authenticateSharedKey(const httplib::Request& req);
  225. /**
  226. * @brief Extract token from request
  227. *
  228. * @param req HTTP request
  229. * @param headerName Header name to check
  230. * @return std::string Token string, empty if not found
  231. */
  232. std::string extractToken(const httplib::Request& req, const std::string& headerName) const;
  233. /**
  234. * @brief Create guest authentication context
  235. *
  236. * @return AuthContext Guest context
  237. */
  238. AuthContext createGuestContext() const;
  239. /**
  240. * @brief Check if path matches pattern
  241. *
  242. * @param path Request path
  243. * @param patterns List of patterns to match
  244. * @return true if path matches any pattern, false otherwise
  245. */
  246. static bool pathMatchesPattern(const std::string& path,
  247. const std::vector<std::string>& patterns);
  248. /**
  249. * @brief Get required permissions for path
  250. *
  251. * @param path Request path
  252. * @return std::vector<std::string> Required permissions
  253. */
  254. std::vector<std::string> getRequiredPermissions(const std::string& path) const;
  255. /**
  256. * @brief Log authentication attempt
  257. *
  258. * @param req HTTP request
  259. * @param context Authentication context
  260. * @param success Authentication success
  261. */
  262. void logAuthAttempt(const httplib::Request& req,
  263. const AuthContext& context,
  264. bool success) const;
  265. /**
  266. * @brief Get client IP address from request
  267. *
  268. * @param req HTTP request
  269. * @return std::string Client IP address
  270. */
  271. static std::string getClientIp(const httplib::Request& req);
  272. /**
  273. * @brief Get user agent from request
  274. *
  275. * @param req HTTP request
  276. * @return std::string User agent string
  277. */
  278. static std::string getUserAgent(const httplib::Request& req);
  279. /**
  280. * @brief Validate authentication configuration
  281. *
  282. * @param config Configuration to validate
  283. * @return true if valid, false otherwise
  284. */
  285. static bool validateConfig(AuthConfig config);
  286. /**
  287. * @brief Initialize default paths
  288. */
  289. void initializeDefaultPaths();
  290. /**
  291. * @brief Check if authentication is completely disabled
  292. *
  293. * @return true if authentication disabled, false otherwise
  294. */
  295. bool isAuthenticationDisabled() const;
  296. };
  297. /**
  298. * @brief Authentication middleware factory functions
  299. */
  300. namespace AuthMiddlewareFactory {
  301. /**
  302. * @brief Create authentication middleware with default configuration
  303. *
  304. * @param userManager User manager instance
  305. * @param dataDir Data directory for user storage
  306. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  307. */
  308. std::unique_ptr<AuthMiddleware> createDefault(std::shared_ptr<UserManager> userManager,
  309. const std::string& dataDir);
  310. /**
  311. * @brief Create authentication middleware with shared key only
  312. *
  313. * @param userManager User manager instance
  314. * @param sharedKey Shared key for authentication
  315. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  316. */
  317. std::unique_ptr<AuthMiddleware> createSharedKeyOnly(std::shared_ptr<UserManager> userManager,
  318. const std::string& sharedKey);
  319. /**
  320. * @brief Create authentication middleware with multiple methods
  321. *
  322. * @param userManager User manager instance
  323. * @param config Authentication configuration
  324. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  325. */
  326. std::unique_ptr<AuthMiddleware> createMultiMethod(std::shared_ptr<UserManager> userManager,
  327. AuthConfig config);
  328. /**
  329. * @brief Create authentication middleware for development (no auth required)
  330. *
  331. * @return std::unique_ptr<AuthMiddleware> Auth middleware instance
  332. */
  333. std::unique_ptr<AuthMiddleware> createDevelopment();
  334. };
  335. #endif // AUTH_MIDDLEWARE_H