server.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package webapi
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "time"
  9. "golang.org/x/sync/errgroup"
  10. "github.com/mk6i/open-oscar-server/server/webapi/handlers"
  11. "github.com/mk6i/open-oscar-server/server/webapi/middleware"
  12. "github.com/mk6i/open-oscar-server/state"
  13. )
  14. func NewServer(listeners []string, logger *slog.Logger, handler Handler, apiKeyValidator middleware.APIKeyValidator, sessionManager *state.WebAPISessionManager) *Server {
  15. servers := make([]*http.Server, 0, len(listeners))
  16. authMiddleware := middleware.NewAuthMiddleware(apiKeyValidator, logger)
  17. authHandler := &handlers.AuthHandler{
  18. AuthService: handler.AuthService,
  19. CookieBaker: handler.CookieBaker,
  20. Logger: logger,
  21. }
  22. sessionHandler := &handlers.SessionHandler{
  23. SessionManager: sessionManager,
  24. OSCARAuthService: handler.AuthService,
  25. FeedbagService: handler.FeedbagService,
  26. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  27. IconSource: handler.IconSource,
  28. Logger: logger,
  29. OServiceService: handler.OServiceService,
  30. }
  31. eventsHandler := &handlers.EventsHandler{
  32. SessionManager: sessionManager,
  33. Logger: logger,
  34. }
  35. presenceHandler := &handlers.PresenceHandler{
  36. SessionManager: sessionManager,
  37. FeedbagService: handler.FeedbagService,
  38. BuddyBroadcaster: handler.BuddyBroadcaster,
  39. LocateService: handler.LocateService,
  40. IconSource: handler.IconSource,
  41. Logger: logger,
  42. }
  43. buddyListHandler := &handlers.BuddyListHandler{
  44. BuddyListManager: handler.BuddyListManager.(*handlers.BuddyListManager),
  45. Logger: logger,
  46. FeedbagService: handler.FeedbagService,
  47. }
  48. messagingHandler := &handlers.MessagingHandler{
  49. SessionManager: sessionManager,
  50. ICBMService: handler.ICBMService,
  51. LocateService: handler.LocateService,
  52. FeedbagService: handler.FeedbagService,
  53. Logger: logger,
  54. }
  55. preferenceHandler := &handlers.PreferenceHandler{
  56. SessionManager: sessionManager,
  57. FeedbagService: handler.FeedbagService,
  58. Logger: logger,
  59. }
  60. memberDirHandler := &handlers.MemberDirHandler{
  61. DirSearchService: handler.DirSearchService,
  62. LocateService: handler.LocateService,
  63. Logger: logger,
  64. }
  65. oscarBridgeHandler := &handlers.OSCARBridgeHandler{
  66. SessionManager: sessionManager,
  67. OSCARAuthService: handler.AuthService,
  68. CookieBaker: handler.CookieBaker,
  69. Config: handler.OSCARConfig,
  70. Logger: logger,
  71. }
  72. for _, l := range listeners {
  73. mux := http.NewServeMux()
  74. // Exact root only. Pattern "GET /" matches every GET path in Go 1.22+ (prefix /), which
  75. // would steal /getAggregated and other lifestream URLs before stubs/404.
  76. mux.HandleFunc("GET /{$}", handler.GetHelloWorldHandler)
  77. // Authentication endpoint (public - no API key required for user login)
  78. // Using pattern with explicit method for Go 1.22+ routing
  79. mux.HandleFunc("POST /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  80. // Set CORS headers for public endpoint
  81. w.Header().Set("Access-Control-Allow-Origin", "*")
  82. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  83. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  84. authHandler.ClientLogin(w, r)
  85. })
  86. // Handle OPTIONS for CORS preflight
  87. mux.HandleFunc("OPTIONS /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  88. w.Header().Set("Access-Control-Allow-Origin", "*")
  89. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  90. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  91. w.WriteHeader(http.StatusNoContent)
  92. })
  93. mux.HandleFunc("GET /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  94. w.Header().Set("Access-Control-Allow-Origin", "*")
  95. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  96. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  97. authHandler.GetToken(w, r)
  98. })
  99. mux.HandleFunc("OPTIONS /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  100. w.Header().Set("Access-Control-Allow-Origin", "*")
  101. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  102. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  103. w.WriteHeader(http.StatusNoContent)
  104. })
  105. // Web AIM navigates the browser here on File > Logout; clear SSO state
  106. // and redirect to the login screen.
  107. mux.HandleFunc("GET /auth/logout", authHandler.Logout)
  108. mux.HandleFunc("GET /_cqr/login/login.psp", authHandler.LoginPSP)
  109. mux.HandleFunc("POST /_cqr/login/login.psp", authHandler.LoginPSP)
  110. // Authenticated Web AIM API endpoints
  111. // SessionInstance management - supports multiple auth methods (k, a, ts+sig_sha256)
  112. mux.Handle("GET /aim/startSession", authMiddleware.AuthenticateFlexible(
  113. authMiddleware.CORSMiddleware(
  114. http.HandlerFunc(sessionHandler.StartSession))))
  115. // End session - uses aimsid for auth, no k required
  116. mux.Handle("GET /aim/endSession", authMiddleware.AuthenticateFlexible(
  117. authMiddleware.CORSMiddleware(
  118. authMiddleware.RequireSession(sessionManager, sessionHandler.EndSession))))
  119. // Event fetching - uses aimsid for auth, no k required
  120. mux.Handle("GET /aim/fetchEvents", authMiddleware.AuthenticateFlexible(
  121. authMiddleware.CORSMiddleware(
  122. authMiddleware.RequireSession(sessionManager, eventsHandler.FetchEvents))))
  123. // Add temp buddy - uses aimsid for auth
  124. mux.Handle("GET /aim/addTempBuddy", authMiddleware.AuthenticateFlexible(
  125. authMiddleware.CORSMiddleware(
  126. authMiddleware.RequireSession(sessionManager, buddyListHandler.AddTempBuddy))))
  127. mux.Handle("GET /aim/removeTempBuddy", authMiddleware.AuthenticateFlexible(
  128. authMiddleware.CORSMiddleware(
  129. authMiddleware.RequireSession(sessionManager, buddyListHandler.RemoveTempBuddy))))
  130. aimStub := &handlers.AimStubHandler{Logger: logger}
  131. aimRoute := func(h http.HandlerFunc) http.Handler {
  132. return authMiddleware.AuthenticateFlexible(
  133. authMiddleware.CORSMiddleware(http.HandlerFunc(h)))
  134. }
  135. mux.Handle("GET /aim/setForwardDomain", aimRoute(aimStub.SetForwardDomain))
  136. mux.Handle("GET /aim/getData", aimRoute(aimStub.GetData))
  137. conversationStub := &handlers.ConversationStubHandler{
  138. SessionManager: sessionManager,
  139. Logger: logger,
  140. }
  141. mux.Handle("GET /conversation/update", aimRoute(conversationStub.Update))
  142. mux.Handle("GET /conversation/close", aimRoute(conversationStub.Close))
  143. mux.Handle("GET /imlog/markRead", aimRoute(conversationStub.MarkRead))
  144. mux.Handle("GET /imlog/fetchStoredIMs", authMiddleware.AuthenticateFlexible(
  145. authMiddleware.CORSMiddleware(
  146. authMiddleware.RequireSession(sessionManager, conversationStub.FetchStoredIMs))))
  147. // Presence and buddy list
  148. // GetPresence supports aimsid-based auth, so we use flexible auth
  149. mux.Handle("GET /presence/get", authMiddleware.AuthenticateFlexible(
  150. authMiddleware.CORSMiddleware(
  151. authMiddleware.RequireSession(sessionManager, presenceHandler.GetPresence))))
  152. buddyListRoute := func(h func(http.ResponseWriter, *http.Request, *state.WebAPISession)) http.Handler {
  153. return authMiddleware.AuthenticateFlexible(
  154. authMiddleware.CORSMiddleware(
  155. authMiddleware.RequireSession(sessionManager, h)))
  156. }
  157. mux.Handle("GET /buddylist/addBuddy", buddyListRoute(buddyListHandler.AddBuddy))
  158. mux.Handle("GET /buddylist/addGroup", buddyListRoute(buddyListHandler.AddGroup))
  159. mux.Handle("GET /buddylist/removeBuddy", buddyListRoute(buddyListHandler.RemoveBuddy))
  160. mux.Handle("GET /buddylist/removeGroup", buddyListRoute(buddyListHandler.RemoveGroup))
  161. mux.Handle("GET /buddylist/renameGroup", buddyListRoute(buddyListHandler.RenameGroup))
  162. mux.Handle("GET /buddylist/moveBuddy", buddyListRoute(buddyListHandler.MoveBuddy))
  163. mux.Handle("GET /buddylist/setBuddyAttribute", buddyListRoute(buddyListHandler.SetBuddyAttribute))
  164. mux.Handle("GET /buddylist/setGroupAttribute", buddyListRoute(buddyListHandler.SetGroupAttribute))
  165. // sendIM supports aimsid-based auth, so we use flexible auth.
  166. // The Web AIM client POSTs the message body (non-IE browsers); IE uses GET.
  167. sendIMHandler := authMiddleware.AuthenticateFlexible(
  168. authMiddleware.CORSMiddleware(
  169. authMiddleware.RequireSession(sessionManager, messagingHandler.SendIM)))
  170. mux.Handle("GET /im/sendIM", sendIMHandler)
  171. mux.Handle("POST /im/sendIM", sendIMHandler)
  172. mux.Handle("GET /im/setTyping", authMiddleware.AuthenticateFlexible(
  173. authMiddleware.CORSMiddleware(
  174. authMiddleware.RequireSession(sessionManager, messagingHandler.SetTyping))))
  175. // SetState only requires aimsid, no k parameter needed
  176. mux.Handle("GET /presence/setState", authMiddleware.AuthenticateFlexible(
  177. authMiddleware.CORSMiddleware(
  178. authMiddleware.RequireSession(sessionManager, presenceHandler.SetState))))
  179. // These presence endpoints support aimsid-based auth where k is not required
  180. mux.Handle("GET /presence/setStatus", authMiddleware.AuthenticateFlexible(
  181. authMiddleware.CORSMiddleware(
  182. authMiddleware.RequireSession(sessionManager, presenceHandler.SetStatus))))
  183. mux.Handle("GET /presence/setProfile", authMiddleware.AuthenticateFlexible(
  184. authMiddleware.CORSMiddleware(
  185. authMiddleware.RequireSession(sessionManager, presenceHandler.SetProfile))))
  186. mux.Handle("GET /presence/getProfile", authMiddleware.AuthenticateFlexible(
  187. authMiddleware.CORSMiddleware(
  188. authMiddleware.RequireSession(sessionManager, presenceHandler.GetProfile))))
  189. mux.HandleFunc("GET /presence/icon", presenceHandler.Icon)
  190. // Member directory search and self directory-info retrieval. Both use
  191. // aimsid-based auth, so we use flexible auth.
  192. mux.Handle("GET /memberDir/search", authMiddleware.AuthenticateFlexible(
  193. authMiddleware.CORSMiddleware(
  194. authMiddleware.RequireSession(sessionManager, memberDirHandler.Search))))
  195. mux.Handle("GET /memberDir/get", authMiddleware.AuthenticateFlexible(
  196. authMiddleware.CORSMiddleware(
  197. authMiddleware.RequireSession(sessionManager, memberDirHandler.Get))))
  198. mux.Handle("GET /memberDir/update", authMiddleware.AuthenticateFlexible(
  199. authMiddleware.CORSMiddleware(
  200. authMiddleware.RequireSession(sessionManager, memberDirHandler.Update))))
  201. // These endpoints support aimsid-based auth, so we use a flexible auth approach
  202. mux.Handle("GET /preference/set", authMiddleware.AuthenticateFlexible(
  203. authMiddleware.CORSMiddleware(
  204. authMiddleware.RequireSession(sessionManager, preferenceHandler.SetPreferences))))
  205. mux.Handle("GET /preference/get", authMiddleware.AuthenticateFlexible(
  206. authMiddleware.CORSMiddleware(
  207. authMiddleware.RequireSession(sessionManager, preferenceHandler.GetPreferences))))
  208. mux.Handle("GET /preference/setPermitDeny", authMiddleware.AuthenticateFlexible(
  209. authMiddleware.CORSMiddleware(
  210. authMiddleware.RequireSession(sessionManager, preferenceHandler.SetPermitDeny))))
  211. mux.Handle("GET /preference/getPermitDeny", authMiddleware.AuthenticateFlexible(
  212. authMiddleware.CORSMiddleware(
  213. authMiddleware.RequireSession(sessionManager, preferenceHandler.GetPermitDeny))))
  214. // OSCAR Bridge endpoint
  215. mux.Handle("GET /aim/startOSCARSession", authMiddleware.Authenticate(
  216. authMiddleware.CORSMiddleware(
  217. http.HandlerFunc(oscarBridgeHandler.StartOSCARSession))))
  218. // Expressions endpoint (for buddy icons, etc.).
  219. //
  220. // Unauthenticated, like /presence/icon: the buddyIcon URLs this serves are
  221. // published to the client and loaded as plain <img> sources, which carry
  222. // neither an aimsid nor an API key. Threading a session token through them
  223. // instead would leak it into the DOM and defeat caching, since these URLs
  224. // outlive the session that produced them. Buddy icons are public assets.
  225. expressionsHandler := handlers.NewExpressionsHandler(handler.IconSource, logger)
  226. mux.Handle("GET /expressions/get", authMiddleware.CORSMiddleware(
  227. http.HandlerFunc(expressionsHandler.Get)))
  228. // Web AIM calls lifestream/* on the API host (e.g. /lifestream/getUserDetails).
  229. lifestreamStub := &handlers.UserInfoStubHandler{Logger: logger}
  230. lifestreamRoute := func(h http.HandlerFunc) http.Handler {
  231. return authMiddleware.AuthenticateFlexible(
  232. authMiddleware.CORSMiddleware(http.HandlerFunc(h)))
  233. }
  234. // getUserDetails returns a minimal AIM identity. Every other lifestream/*
  235. // method is an unimplemented social-feed feature; the subtree catch-all
  236. // acknowledges them with an empty 200 so the client doesn't error.
  237. mux.Handle("GET /lifestream/getUserDetails", lifestreamRoute(lifestreamStub.GetUserDetails))
  238. mux.Handle("GET /lifestream/", lifestreamRoute(lifestreamStub.EmptyOK))
  239. // Unmatched paths (pattern "/" matches anything not covered by routes above).
  240. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  241. logger.Debug("webapi 404", "method", r.Method, "path", r.URL.Path)
  242. handlers.SendError(w, http.StatusNotFound, "not found")
  243. })
  244. servers = append(servers, &http.Server{
  245. Addr: l,
  246. Handler: middleware.RequestLogger(logger, mux),
  247. })
  248. }
  249. shutdownCtx, shutdownCancel := context.WithCancel(context.Background())
  250. sessionHandler.FnSessCfg = func(sess *state.Session) {
  251. sess.OnSessionClose(func() {
  252. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  253. defer cancel()
  254. if !shuttingDown(shutdownCtx) {
  255. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(ctx, sess.IdentScreenName()); err != nil {
  256. logger.ErrorContext(ctx, "error sending buddy departure notifications", "err", err.Error())
  257. }
  258. }
  259. // buddy list must be cleared before session is closed, otherwise
  260. // there will be a race condition that could cause the buddy list
  261. // be prematurely deleted.
  262. if err := handler.BuddyListRegistry.UnregisterBuddyList(ctx, sess.IdentScreenName()); err != nil {
  263. logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  264. }
  265. handler.ChatSessionManager.RemoveUserFromAllChats(sess.IdentScreenName())
  266. handler.AuthService.Signout(ctx, sess)
  267. })
  268. }
  269. sessionHandler.FnSessInit = func(instance *state.SessionInstance) func() error {
  270. return func() error {
  271. // make buddy list visible to other users
  272. if err := handler.BuddyListRegistry.RegisterBuddyList(shutdownCtx, instance.IdentScreenName()); err != nil {
  273. return fmt.Errorf("unable to init buddy list: %w", err)
  274. }
  275. // restore warning level from last session
  276. if err := handler.RecalcWarning(shutdownCtx, instance); err != nil {
  277. return fmt.Errorf("failed to recalculate warning level: %w", err)
  278. }
  279. // periodically decay warning level
  280. go handler.LowerWarnLevel(shutdownCtx, instance)
  281. return nil
  282. }
  283. }
  284. sessionHandler.FnInstanceClose = func(instance *state.SessionInstance) func() {
  285. return func() {
  286. if shuttingDown(shutdownCtx) {
  287. return
  288. }
  289. if instance.Session().Invisible() {
  290. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(shutdownCtx, instance.IdentScreenName()); err != nil {
  291. logger.ErrorContext(shutdownCtx, "error sending buddy departure notifications", "err", err.Error())
  292. }
  293. } else {
  294. if err := handler.BuddyBroadcaster.BroadcastBuddyArrived(shutdownCtx, instance.IdentScreenName(), instance.Session().TLVUserInfo()); err != nil {
  295. logger.ErrorContext(shutdownCtx, "error sending buddy arrival notifications", "err", err.Error())
  296. }
  297. }
  298. }
  299. }
  300. return &Server{
  301. servers: servers,
  302. logger: logger,
  303. sessionManager: sessionManager,
  304. shutdownCtx: shutdownCtx,
  305. shutdownCancel: shutdownCancel,
  306. }
  307. }
  308. // Server hosts an HTTP endpoint capable of handling AIM-style Kerberos
  309. // authentication. The messages are structured as SNACs transmitted over HTTP.
  310. //
  311. // shutdownCtx bounds the lifetime of the background session reaper: ListenAndServe
  312. // drives it, and Shutdown (or a failed listener) calls shutdownCancel to unwind.
  313. type Server struct {
  314. servers []*http.Server
  315. logger *slog.Logger
  316. sessionManager *state.WebAPISessionManager
  317. shutdownCtx context.Context
  318. shutdownCancel context.CancelFunc
  319. }
  320. func (s *Server) ListenAndServe() error {
  321. if len(s.servers) == 0 {
  322. s.logger.Debug("no webapi listeners defined")
  323. return nil
  324. }
  325. g, ctx := errgroup.WithContext(s.shutdownCtx)
  326. g.Go(func() error {
  327. s.sessionManager.Run(ctx)
  328. return nil
  329. })
  330. for _, server := range s.servers {
  331. g.Go(func() error {
  332. s.logger.Info("starting server", "addr", server.Addr)
  333. if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
  334. s.shutdownCancel()
  335. return fmt.Errorf("unable to start webapi server: %w", err)
  336. }
  337. return nil
  338. })
  339. }
  340. return g.Wait()
  341. }
  342. func (s *Server) Shutdown(ctx context.Context) error {
  343. s.logger.Debug("Initiating graceful shutdown...")
  344. s.shutdownCancel() // stop the session reaper so ListenAndServe's errgroup can drain
  345. for _, srv := range s.servers {
  346. _ = srv.Shutdown(ctx)
  347. }
  348. s.sessionManager.Shutdown()
  349. s.logger.Info("shutdown complete")
  350. return nil
  351. }
  352. func shuttingDown(ctx context.Context) bool {
  353. select {
  354. case <-ctx.Done():
  355. // server is shutting down, don't send buddy notifications
  356. return true
  357. default:
  358. }
  359. return false
  360. }