server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package webapi
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "golang.org/x/sync/errgroup"
  9. "github.com/mk6i/open-oscar-server/server/webapi/handlers"
  10. "github.com/mk6i/open-oscar-server/server/webapi/middleware"
  11. "github.com/mk6i/open-oscar-server/state"
  12. )
  13. func NewServer(listeners []string, logger *slog.Logger, handler Handler, apiKeyValidator middleware.APIKeyValidator, sessionManager *state.WebAPISessionManager) *Server {
  14. servers := make([]*http.Server, 0, len(listeners))
  15. // Create authentication middleware
  16. authMiddleware := middleware.NewAuthMiddleware(apiKeyValidator, logger)
  17. // Create handlers
  18. authHandler := &handlers.AuthHandler{
  19. AuthService: handler.AuthService,
  20. CookieBaker: handler.CookieBaker,
  21. UserManager: handler.TOCConfigStore,
  22. Logger: logger,
  23. }
  24. sessionHandler := &handlers.SessionHandler{
  25. SessionManager: sessionManager,
  26. OSCARSessionManager: handler.SessionRetriever.(handlers.SessionManager),
  27. OSCARAuthService: handler.AuthService,
  28. BuddyListService: nil,
  29. BuddyListRegistry: handler.BuddyListRegistry,
  30. BuddyBroadcaster: handler.BuddyBroadcaster,
  31. FeedbagRetriever: handler.FeedbagRetriever,
  32. FeedbagService: handler.FeedbagService,
  33. OSCARBuddyService: handler.BuddyService,
  34. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  35. Logger: logger,
  36. OServiceService: handler.OServiceService,
  37. RecalcWarning: handler.RecalcWarning,
  38. LowerWarnLevel: handler.LowerWarnLevel,
  39. ChatSessionManager: handler.ChatSessionManager,
  40. }
  41. eventsHandler := &handlers.EventsHandler{
  42. SessionManager: sessionManager,
  43. Logger: logger,
  44. }
  45. presenceHandler := &handlers.PresenceHandler{
  46. SessionManager: sessionManager,
  47. SessionRetriever: handler.SessionRetriever,
  48. FeedbagRetriever: handler.FeedbagRetriever,
  49. BuddyBroadcaster: handler.BuddyBroadcaster,
  50. ProfileManager: handler.ProfileManager,
  51. RelationshipFetcher: handler.RelationshipFetcher,
  52. Logger: logger,
  53. }
  54. buddyListHandler := handlers.NewBuddyListHandler(
  55. sessionManager,
  56. handler.BuddyListManager.(*handlers.BuddyListManager),
  57. logger,
  58. handler.FeedbagService,
  59. )
  60. // Phase 2: Messaging handler
  61. messagingHandler := &handlers.MessagingHandler{
  62. SessionManager: sessionManager,
  63. ICBMService: handler.ICBMService,
  64. Logger: logger,
  65. }
  66. // Phase 3: Preference handler
  67. preferenceHandler := &handlers.PreferenceHandler{
  68. SessionManager: sessionManager,
  69. PreferenceManager: handler.PreferenceManager,
  70. FeedbagService: handler.FeedbagService,
  71. Logger: logger,
  72. }
  73. // Phase 4: OSCAR Bridge handler
  74. oscarBridgeHandler := &handlers.OSCARBridgeHandler{
  75. SessionManager: sessionManager,
  76. OSCARAuthService: handler.AuthService,
  77. CookieBaker: handler.CookieBaker,
  78. BridgeStore: handler.OSCARBridgeStore,
  79. Config: handler.OSCARConfig,
  80. Logger: logger,
  81. }
  82. // Phase 5: Chat handler
  83. chatHandler := &handlers.ChatHandler{
  84. SessionManager: sessionManager,
  85. ChatManager: handler.ChatManager,
  86. Logger: logger,
  87. }
  88. for _, l := range listeners {
  89. mux := http.NewServeMux()
  90. // Exact root only. Pattern "GET /" matches every GET path in Go 1.22+ (prefix /), which
  91. // would steal /getAggregated and other lifestream URLs before stubs/404.
  92. mux.HandleFunc("GET /{$}", handler.GetHelloWorldHandler)
  93. // Authentication endpoint (public - no API key required for user login)
  94. // Using pattern with explicit method for Go 1.22+ routing
  95. mux.HandleFunc("POST /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  96. // Set CORS headers for public endpoint
  97. w.Header().Set("Access-Control-Allow-Origin", "*")
  98. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  99. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  100. authHandler.ClientLogin(w, r)
  101. })
  102. // Handle OPTIONS for CORS preflight
  103. mux.HandleFunc("OPTIONS /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  104. w.Header().Set("Access-Control-Allow-Origin", "*")
  105. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  106. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  107. w.WriteHeader(http.StatusNoContent)
  108. })
  109. mux.HandleFunc("GET /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  110. w.Header().Set("Access-Control-Allow-Origin", "*")
  111. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  112. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  113. authHandler.GetToken(w, r)
  114. })
  115. mux.HandleFunc("OPTIONS /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  116. w.Header().Set("Access-Control-Allow-Origin", "*")
  117. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  118. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  119. w.WriteHeader(http.StatusNoContent)
  120. })
  121. mux.HandleFunc("GET /_cqr/login/login.psp", authHandler.LoginPSP)
  122. mux.HandleFunc("POST /_cqr/login/login.psp", authHandler.LoginPSP)
  123. // Authenticated Web AIM API endpoints
  124. // SessionInstance management - supports multiple auth methods (k, a, ts+sig_sha256)
  125. mux.Handle("GET /aim/startSession", authMiddleware.AuthenticateFlexible(
  126. authMiddleware.CORSMiddleware(
  127. http.HandlerFunc(sessionHandler.StartSession))))
  128. // End session - uses aimsid for auth, no k required
  129. mux.Handle("GET /aim/endSession", authMiddleware.AuthenticateFlexible(
  130. authMiddleware.CORSMiddleware(
  131. http.HandlerFunc(sessionHandler.EndSession))))
  132. // Event fetching - uses aimsid for auth, no k required
  133. mux.Handle("GET /aim/fetchEvents", authMiddleware.AuthenticateFlexible(
  134. authMiddleware.CORSMiddleware(
  135. http.HandlerFunc(eventsHandler.FetchEvents))))
  136. // Add temp buddy - uses aimsid for auth
  137. mux.Handle("GET /aim/addTempBuddy", authMiddleware.AuthenticateFlexible(
  138. authMiddleware.CORSMiddleware(
  139. buddyListHandler.SessionMiddleware(buddyListHandler.AddTempBuddy))))
  140. mux.Handle("GET /aim/removeTempBuddy", authMiddleware.AuthenticateFlexible(
  141. authMiddleware.CORSMiddleware(
  142. buddyListHandler.SessionMiddleware(buddyListHandler.RemoveTempBuddy))))
  143. aimStub := &handlers.AimStubHandler{Logger: logger}
  144. aimRoute := func(h http.HandlerFunc) http.Handler {
  145. return authMiddleware.AuthenticateFlexible(
  146. authMiddleware.CORSMiddleware(http.HandlerFunc(h)))
  147. }
  148. mux.Handle("GET /aim/setForwardDomain", aimRoute(aimStub.SetForwardDomain))
  149. mux.Handle("GET /aim/getData", aimRoute(aimStub.GetData))
  150. conversationStub := &handlers.ConversationStubHandler{
  151. SessionManager: sessionManager,
  152. Logger: logger,
  153. }
  154. mux.Handle("GET /conversation/update", aimRoute(conversationStub.Update))
  155. mux.Handle("GET /conversation/close", aimRoute(conversationStub.Close))
  156. mux.Handle("GET /imlog/markRead", aimRoute(conversationStub.MarkRead))
  157. mux.Handle("GET /imlog/fetchStoredIMs", aimRoute(conversationStub.FetchStoredIMs))
  158. // Presence and buddy list
  159. // GetPresence supports aimsid-based auth, so we use flexible auth
  160. mux.Handle("GET /presence/get", authMiddleware.AuthenticateFlexible(
  161. authMiddleware.CORSMiddleware(
  162. http.HandlerFunc(presenceHandler.GetPresence))))
  163. mux.Handle("/buddylist/", authMiddleware.AuthenticateFlexible(
  164. authMiddleware.CORSMiddleware(buddyListHandler)))
  165. // Phase 2: Messaging endpoints
  166. // sendIM supports aimsid-based auth, so we use flexible auth.
  167. // The Web AIM client POSTs the message body (non-IE browsers); IE uses GET.
  168. sendIMHandler := authMiddleware.AuthenticateFlexible(
  169. authMiddleware.CORSMiddleware(
  170. http.HandlerFunc(messagingHandler.SendIM)))
  171. mux.Handle("GET /im/sendIM", sendIMHandler)
  172. mux.Handle("POST /im/sendIM", sendIMHandler)
  173. mux.Handle("GET /im/setTyping", authMiddleware.AuthenticateFlexible(
  174. authMiddleware.CORSMiddleware(
  175. http.HandlerFunc(messagingHandler.SetTyping))))
  176. // Phase 2: Presence management endpoints
  177. // SetState only requires aimsid, no k parameter needed
  178. mux.Handle("GET /presence/setState", authMiddleware.AuthenticateFlexible(
  179. authMiddleware.CORSMiddleware(
  180. http.HandlerFunc(presenceHandler.SetState))))
  181. // These presence endpoints support aimsid-based auth where k is not required
  182. mux.Handle("GET /presence/setStatus", authMiddleware.AuthenticateFlexible(
  183. authMiddleware.CORSMiddleware(
  184. http.HandlerFunc(presenceHandler.SetStatus))))
  185. mux.Handle("GET /presence/setProfile", authMiddleware.AuthenticateFlexible(
  186. authMiddleware.CORSMiddleware(
  187. http.HandlerFunc(presenceHandler.SetProfile))))
  188. mux.Handle("GET /presence/getProfile", authMiddleware.AuthenticateFlexible(
  189. authMiddleware.CORSMiddleware(
  190. http.HandlerFunc(presenceHandler.GetProfile))))
  191. // Phase 2: Presence icon endpoint (no auth required)
  192. mux.HandleFunc("GET /presence/icon", presenceHandler.Icon)
  193. // Phase 3: Preference management endpoints
  194. // These endpoints support aimsid-based auth, so we use a flexible auth approach
  195. mux.Handle("GET /preference/set", authMiddleware.AuthenticateFlexible(
  196. authMiddleware.CORSMiddleware(
  197. http.HandlerFunc(preferenceHandler.SetPreferences))))
  198. mux.Handle("GET /preference/get", authMiddleware.AuthenticateFlexible(
  199. authMiddleware.CORSMiddleware(
  200. http.HandlerFunc(preferenceHandler.GetPreferences))))
  201. mux.Handle("GET /preference/setPermitDeny", authMiddleware.AuthenticateFlexible(
  202. authMiddleware.CORSMiddleware(
  203. http.HandlerFunc(preferenceHandler.SetPermitDeny))))
  204. mux.Handle("GET /preference/getPermitDeny", authMiddleware.AuthenticateFlexible(
  205. authMiddleware.CORSMiddleware(
  206. http.HandlerFunc(preferenceHandler.GetPermitDeny))))
  207. // Phase 4: Advanced Features
  208. // OSCAR Bridge endpoint
  209. mux.Handle("GET /aim/startOSCARSession", authMiddleware.Authenticate(
  210. authMiddleware.CORSMiddleware(
  211. http.HandlerFunc(oscarBridgeHandler.StartOSCARSession))))
  212. // Expressions endpoint (for buddy icons, etc.)
  213. expressionsHandler := handlers.NewExpressionsHandler(logger)
  214. mux.Handle("GET /expressions/get", authMiddleware.AuthenticateFlexible(
  215. authMiddleware.CORSMiddleware(
  216. http.HandlerFunc(expressionsHandler.Get))))
  217. // Web AIM calls lifestream/* on the API host (e.g. /lifestream/getUserDetails).
  218. lifestreamStub := &handlers.UserInfoStubHandler{Logger: logger}
  219. lifestreamRoute := func(h http.HandlerFunc) http.Handler {
  220. return authMiddleware.AuthenticateFlexible(
  221. authMiddleware.CORSMiddleware(http.HandlerFunc(h)))
  222. }
  223. mux.Handle("GET /lifestream/getUserDetails", lifestreamRoute(lifestreamStub.GetUserDetails))
  224. mux.Handle("GET /lifestream/getLocationsFollowing", lifestreamRoute(lifestreamStub.GetLocationsFollowing))
  225. for _, p := range []string{
  226. "getAggregated",
  227. "getNotifications",
  228. "getSingle",
  229. "getNotificationFilter",
  230. "heyGetNotifications",
  231. "heyMarkNotifications",
  232. "deleteNotification",
  233. "commonsFollow",
  234. "commonsUnfollow",
  235. "tdAddService",
  236. "tdRemoveService",
  237. "setUserPreference",
  238. "getActivity",
  239. "addComment",
  240. "deleteComment",
  241. "deleteActivity",
  242. "addLike",
  243. "deleteLike",
  244. "setNotificationFilter",
  245. "heyTakeAction",
  246. } {
  247. mux.Handle("GET /lifestream/"+p, lifestreamRoute(lifestreamStub.EmptyOK))
  248. }
  249. // Phase 5: Chat room endpoints
  250. // All chat endpoints use aimsid for authentication
  251. mux.Handle("GET /chat/createAndJoinChat", authMiddleware.AuthenticateFlexible(
  252. authMiddleware.CORSMiddleware(
  253. http.HandlerFunc(chatHandler.CreateAndJoinChat))))
  254. mux.Handle("GET /chat/sendMessage", authMiddleware.AuthenticateFlexible(
  255. authMiddleware.CORSMiddleware(
  256. http.HandlerFunc(chatHandler.SendMessage))))
  257. mux.Handle("GET /chat/setTyping", authMiddleware.AuthenticateFlexible(
  258. authMiddleware.CORSMiddleware(
  259. http.HandlerFunc(chatHandler.SetTyping))))
  260. mux.Handle("GET /chat/leaveChat", authMiddleware.AuthenticateFlexible(
  261. authMiddleware.CORSMiddleware(
  262. http.HandlerFunc(chatHandler.LeaveChat))))
  263. // Unmatched paths (pattern "/" matches anything not covered by routes above).
  264. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  265. logger.Debug("webapi 404", "method", r.Method, "path", r.URL.Path)
  266. handlers.SendError(w, http.StatusNotFound, "not found")
  267. })
  268. servers = append(servers, &http.Server{
  269. Addr: l,
  270. Handler: middleware.RequestLogger(logger, mux),
  271. })
  272. }
  273. return &Server{
  274. servers: servers,
  275. logger: logger,
  276. }
  277. }
  278. // Server hosts an HTTP endpoint capable of handling AIM-style Kerberos
  279. // authentication. The messages are structured as SNACs transmitted over HTTP.
  280. type Server struct {
  281. servers []*http.Server
  282. logger *slog.Logger
  283. }
  284. func (s *Server) ListenAndServe() error {
  285. if len(s.servers) == 0 {
  286. s.logger.Debug("no webapi listeners defined")
  287. return nil
  288. }
  289. ctx, cancel := context.WithCancel(context.Background())
  290. defer cancel()
  291. g, _ := errgroup.WithContext(ctx)
  292. for _, server := range s.servers {
  293. g.Go(func() error {
  294. s.logger.Info("starting server", "addr", server.Addr)
  295. if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
  296. cancel()
  297. return fmt.Errorf("unable to start webapi server: %w", err)
  298. }
  299. return nil
  300. })
  301. }
  302. return g.Wait()
  303. }
  304. func (s *Server) Shutdown(ctx context.Context) error {
  305. if len(s.servers) > 0 {
  306. for _, srv := range s.servers {
  307. _ = srv.Shutdown(ctx)
  308. }
  309. s.logger.Info("shutdown complete")
  310. }
  311. return nil
  312. }