memberdir_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package webapi
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "github.com/mk6i/open-oscar-server/state"
  11. "github.com/mk6i/open-oscar-server/wire"
  12. )
  13. // defaultMemberDirLimit caps how many directory search results are returned
  14. // when the client does not specify nToGet.
  15. const defaultMemberDirLimit = 100
  16. // maxMemberDirTargets caps how many screen names a single memberDir/get may
  17. // resolve. Every target costs its own directory lookup, and the web client only
  18. // ever asks for one, so this bounds the fan-out an arbitrary "t" list can force.
  19. const maxMemberDirTargets = 20
  20. // dirInfoTags are the directory fields carried in both the ODir get reply and
  21. // the locate set request. SetDirectoryInfo replaces every column, so
  22. // memberDir/update re-sends all of them to preserve fields the web form (which
  23. // only edits first/last name) does not touch.
  24. var dirInfoTags = []uint16{
  25. wire.ODirTLVFirstName,
  26. wire.ODirTLVLastName,
  27. wire.ODirTLVMiddleName,
  28. wire.ODirTLVMaidenName,
  29. wire.ODirTLVCountry,
  30. wire.ODirTLVState,
  31. wire.ODirTLVCity,
  32. wire.ODirTLVNickName,
  33. wire.ODirTLVZIP,
  34. wire.ODirTLVAddress,
  35. }
  36. // MemberDirHandler handles Web AIM API member-directory endpoints
  37. // (memberDir/search, memberDir/get, and memberDir/update).
  38. type MemberDirHandler struct {
  39. DirSearchService DirSearchService
  40. LocateService LocateService
  41. Logger *slog.Logger
  42. }
  43. // MemberDirProfile is the per-result directory profile the web client consumes.
  44. // The client keys users by AimID and, for its own directory info, renders
  45. // FirstName/LastName.
  46. type MemberDirProfile struct {
  47. AimID string `json:"aimId" xml:"aimId"`
  48. DisplayID string `json:"displayId,omitempty" xml:"displayId,omitempty"`
  49. FirstName string `json:"firstName,omitempty" xml:"firstName,omitempty"`
  50. LastName string `json:"lastName,omitempty" xml:"lastName,omitempty"`
  51. State string `json:"state,omitempty" xml:"state,omitempty"`
  52. City string `json:"city,omitempty" xml:"city,omitempty"`
  53. Country string `json:"country,omitempty" xml:"country,omitempty"`
  54. }
  55. // MemberDirInfo wraps a profile in the "info" envelope the client expects:
  56. // results are read as data.results.infoArray[i].profile for search and
  57. // data.infoArray[0].profile for get.
  58. type MemberDirInfo struct {
  59. Profile MemberDirProfile `json:"profile" xml:"profile"`
  60. }
  61. // MemberDirResults wraps a directory search result set.
  62. type MemberDirResults struct {
  63. Results MemberDirSearchResults `json:"results" xml:"results"`
  64. }
  65. // MemberDirSearchResults is the matched profile list plus its counters. All three
  66. // counters are required: clients read them strictly.
  67. type MemberDirSearchResults struct {
  68. NTotal int `json:"nTotal" xml:"nTotal"`
  69. NSkipped int `json:"nSkipped" xml:"nSkipped"`
  70. NProfiles int `json:"nProfiles" xml:"nProfiles"`
  71. InfoArray []MemberDirInfo `json:"infoArray" xml:"infoArray>info"`
  72. }
  73. // MemberDirInfoArray is the list of matched profiles.
  74. type MemberDirInfoArray struct {
  75. InfoArray []MemberDirInfo `json:"infoArray" xml:"infoArray>info"`
  76. }
  77. // Search handles GET /memberDir/search. The web client sends the raw add-contact
  78. // input as a "match" parameter shaped like "keyword=<x>" or
  79. // "firstName=<x>,lastName=<y>". We translate that into an OSCAR ODir InfoQuery
  80. // and let the ODir service pick the search mode.
  81. func (h *MemberDirHandler) Search(w http.ResponseWriter, r *http.Request, session *Session) {
  82. ctx := r.Context()
  83. fields := parseMatch(r.URL.Query().Get("match"))
  84. self := session.ScreenName.IdentScreenName()
  85. // ODir matches interests, names and email but never the screen name, so an
  86. // identity lookup runs alongside the directory search.
  87. profiles := make([]MemberDirProfile, 0, 8)
  88. seen := make(map[string]bool)
  89. addProfile := func(profile MemberDirProfile) {
  90. // Exclude the requesting user from their own search results.
  91. if profile.AimID == "" || profile.AimID == self.String() || seen[profile.AimID] {
  92. return
  93. }
  94. seen[profile.AimID] = true
  95. profiles = append(profiles, profile)
  96. }
  97. if profile, found := h.exactScreenNameMatch(ctx, fields["keyword"]); found {
  98. addProfile(profile)
  99. }
  100. // A failed directory search is not fatal: the screen-name match may still stand.
  101. if reply, err := h.DirSearchService.InfoQuery(ctx, wire.SNACFrame{}, buildDirInfoQuery(fields)); err != nil {
  102. h.Logger.ErrorContext(ctx, "memberDir search failed", "err", err.Error())
  103. } else if body, ok := reply.Body.(wire.SNAC_0x0F_0x03_InfoReply); ok && body.Status == wire.ODirSearchResponseOK {
  104. for _, result := range body.Results.List {
  105. profile := MemberDirProfile{}
  106. if sn, ok := result.String(wire.ODirTLVScreenName); ok && sn != "" {
  107. profile.DisplayID = sn
  108. profile.AimID = state.NewIdentScreenName(sn).String()
  109. }
  110. profile.FirstName, _ = result.String(wire.ODirTLVFirstName)
  111. profile.LastName, _ = result.String(wire.ODirTLVLastName)
  112. profile.State, _ = result.String(wire.ODirTLVState)
  113. profile.City, _ = result.String(wire.ODirTLVCity)
  114. profile.Country, _ = result.String(wire.ODirTLVCountry)
  115. addProfile(profile)
  116. }
  117. }
  118. limit := defaultMemberDirLimit
  119. if v := r.URL.Query().Get("nToGet"); v != "" {
  120. if n, err := strconv.Atoi(v); err == nil && n > 0 {
  121. limit = n
  122. }
  123. }
  124. skip := 0
  125. if v := r.URL.Query().Get("nToSkip"); v != "" {
  126. if n, err := strconv.Atoi(v); err == nil && n > 0 {
  127. skip = n
  128. }
  129. }
  130. // matched counts every profile the query matched; infoArray holds the page of
  131. // them this response carries, after nToSkip and nToGet are applied.
  132. matched := 0
  133. infoArray := make([]MemberDirInfo, 0, len(profiles))
  134. for _, profile := range profiles {
  135. matched++
  136. if matched <= skip {
  137. continue
  138. }
  139. if len(infoArray) >= limit {
  140. continue
  141. }
  142. infoArray = append(infoArray, MemberDirInfo{Profile: profile})
  143. }
  144. h.Logger.DebugContext(ctx, "memberDir search",
  145. "aimsid", session.AimSID,
  146. "match", r.URL.Query().Get("match"),
  147. "results", len(infoArray),
  148. )
  149. SendOK(w, r, &MemberDirResults{Results: MemberDirSearchResults{
  150. NTotal: matched,
  151. NSkipped: skip,
  152. NProfiles: len(infoArray),
  153. InfoArray: infoArray,
  154. }}, h.Logger)
  155. }
  156. // exactScreenNameMatch resolves query as a screen name, reporting whether a user
  157. // by that name exists along with their directory profile.
  158. func (h *MemberDirHandler) exactScreenNameMatch(ctx context.Context, query string) (MemberDirProfile, bool) {
  159. query = strings.TrimSpace(query)
  160. if query == "" {
  161. return MemberDirProfile{}, false
  162. }
  163. reply, err := h.LocateService.DirInfo(ctx, wire.SNACFrame{}, wire.SNAC_0x02_0x0B_LocateGetDirInfo{ScreenName: query})
  164. if err != nil {
  165. h.Logger.ErrorContext(ctx, "memberDir search: screen name lookup failed",
  166. "screenName", query, "err", err.Error())
  167. return MemberDirProfile{}, false
  168. }
  169. body, ok := reply.Body.(wire.SNAC_0x02_0x0C_LocateGetDirReply)
  170. if !ok {
  171. return MemberDirProfile{}, false
  172. }
  173. // DirInfo answers for any name, appending directory TLVs only for a user that
  174. // exists, so their presence — not their values — is the existence test.
  175. if !body.HasTag(wire.ODirTLVFirstName) {
  176. return MemberDirProfile{}, false
  177. }
  178. profile := MemberDirProfile{
  179. AimID: state.NewIdentScreenName(query).String(),
  180. DisplayID: query,
  181. }
  182. profile.FirstName, _ = body.String(wire.ODirTLVFirstName)
  183. profile.LastName, _ = body.String(wire.ODirTLVLastName)
  184. profile.State, _ = body.String(wire.ODirTLVState)
  185. profile.City, _ = body.String(wire.ODirTLVCity)
  186. profile.Country, _ = body.String(wire.ODirTLVCountry)
  187. return profile, true
  188. }
  189. // Get handles GET /memberDir/get. The "t" param names the screen names to look
  190. // up, defaulting to the caller when absent. Each returned profile carries the
  191. // identity of the target it describes.
  192. func (h *MemberDirHandler) Get(w http.ResponseWriter, r *http.Request, session *Session) {
  193. ctx := r.Context()
  194. targets := parseTargets(r.URL.Query().Get("t"))
  195. if len(targets) == 0 {
  196. targets = []string{session.ScreenName.String()}
  197. }
  198. if len(targets) > maxMemberDirTargets {
  199. h.Logger.WarnContext(ctx, "memberDir get: truncating oversized target list",
  200. "aimsid", session.AimSID,
  201. "requested", len(targets),
  202. "cap", maxMemberDirTargets,
  203. )
  204. targets = targets[:maxMemberDirTargets]
  205. }
  206. infoArray := make([]MemberDirInfo, 0, len(targets))
  207. for _, target := range targets {
  208. reply, err := h.LocateService.DirInfo(ctx, wire.SNACFrame{}, wire.SNAC_0x02_0x0B_LocateGetDirInfo{ScreenName: target})
  209. if err != nil {
  210. h.Logger.ErrorContext(ctx, "memberDir get failed", "screenName", target, "err", err.Error())
  211. continue
  212. }
  213. body, ok := reply.Body.(wire.SNAC_0x02_0x0C_LocateGetDirReply)
  214. if !ok {
  215. continue
  216. }
  217. profile := MemberDirProfile{}
  218. profile.FirstName, _ = body.String(wire.ODirTLVFirstName)
  219. profile.LastName, _ = body.String(wire.ODirTLVLastName)
  220. profile.State, _ = body.String(wire.ODirTLVState)
  221. profile.City, _ = body.String(wire.ODirTLVCity)
  222. profile.Country, _ = body.String(wire.ODirTLVCountry)
  223. profile.AimID = state.NewIdentScreenName(target).String()
  224. profile.DisplayID = target
  225. infoArray = append(infoArray, MemberDirInfo{Profile: profile})
  226. }
  227. h.Logger.DebugContext(ctx, "memberDir get",
  228. "aimsid", session.AimSID,
  229. "targets", len(targets),
  230. )
  231. SendOK(w, r, &MemberDirInfoArray{InfoArray: infoArray}, h.Logger)
  232. }
  233. // Update handles /memberDir/update over GET and POST. Clients send repeated
  234. // "set=key=value" params; first and last name are persisted to the directory
  235. // record and every other field is ignored, having nowhere to be stored.
  236. //
  237. // SetDirectoryInfo replaces the whole directory record, so we read the current
  238. // info first and re-send every field, overlaying only what the form changed.
  239. func (h *MemberDirHandler) Update(w http.ResponseWriter, r *http.Request, session *Session) {
  240. ctx := r.Context()
  241. sets := memberDirSets(r)
  242. // Seed from the current record so untouched fields survive the replace. A
  243. // failed read must abort: writing a record we couldn't seed would blank
  244. // every field the form doesn't edit.
  245. reply, err := h.LocateService.DirInfo(ctx, wire.SNACFrame{}, wire.SNAC_0x02_0x0B_LocateGetDirInfo{ScreenName: session.ScreenName.String()})
  246. if err != nil {
  247. h.Logger.ErrorContext(ctx, "memberDir update: failed to read current dir info", "err", err.Error())
  248. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "failed to update directory info", h.Logger)
  249. return
  250. }
  251. body, ok := reply.Body.(wire.SNAC_0x02_0x0C_LocateGetDirReply)
  252. if !ok {
  253. h.Logger.ErrorContext(ctx, "memberDir update: unexpected dir info reply", "body", fmt.Sprintf("%T", reply.Body))
  254. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "failed to update directory info", h.Logger)
  255. return
  256. }
  257. values := make(map[uint16]string, len(dirInfoTags))
  258. for _, tag := range dirInfoTags {
  259. if v, ok := body.String(tag); ok {
  260. values[tag] = v
  261. }
  262. }
  263. // Overlay the form's edits. Assign unconditionally so clearing a name field
  264. // (the client sends "firstName=" with an empty value) is honored.
  265. if v, ok := sets["firstName"]; ok {
  266. values[wire.ODirTLVFirstName] = v
  267. }
  268. if v, ok := sets["lastName"]; ok {
  269. values[wire.ODirTLVLastName] = v
  270. }
  271. inBody := wire.SNAC_0x02_0x09_LocateSetDirInfo{}
  272. for _, tag := range dirInfoTags {
  273. inBody.Append(wire.NewTLVBE(tag, values[tag]))
  274. }
  275. if _, err := h.LocateService.SetDirInfo(ctx, session.OSCARSession, wire.SNACFrame{}, inBody); err != nil {
  276. h.Logger.ErrorContext(ctx, "memberDir update failed", "err", err.Error())
  277. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "failed to update directory info", h.Logger)
  278. return
  279. }
  280. h.Logger.InfoContext(ctx, "memberDir update",
  281. "aimsid", session.AimSID,
  282. "firstName", values[wire.ODirTLVFirstName],
  283. "lastName", values[wire.ODirTLVLastName],
  284. )
  285. SendOK(w, r, struct{}{}, h.Logger)
  286. }
  287. // buildDirInfoQuery maps the web client's parsed "match" fields onto ODir search
  288. // TLVs. The client only ever sends two shapes: "firstName=<x>,lastName=<y>"
  289. // (input split on the last space) or "keyword=<x>" (everything else). Name
  290. // search takes precedence over interest-keyword search.
  291. func buildDirInfoQuery(fields map[string]string) wire.SNAC_0x0F_0x02_InfoQuery {
  292. inBody := wire.SNAC_0x0F_0x02_InfoQuery{}
  293. switch {
  294. case fields["firstName"] != "" || fields["lastName"] != "":
  295. if v := fields["firstName"]; v != "" {
  296. inBody.Append(wire.NewTLVBE(wire.ODirTLVFirstName, v))
  297. }
  298. if v := fields["lastName"]; v != "" {
  299. inBody.Append(wire.NewTLVBE(wire.ODirTLVLastName, v))
  300. }
  301. case fields["keyword"] != "":
  302. // "keyword" carries either an interest or an identifier. An address can
  303. // only be the latter, and ODir searches email directly.
  304. if kw := fields["keyword"]; strings.Contains(kw, "@") {
  305. inBody.Append(wire.NewTLVBE(wire.ODirTLVEmailAddress, kw))
  306. } else {
  307. inBody.Append(wire.NewTLVBE(wire.ODirTLVInterest, kw))
  308. }
  309. }
  310. return inBody
  311. }
  312. // parseMatch splits a client's "match" value ("key=value,key=value") into a field
  313. // map. Values may carry a second layer of escaping, so they are unescaped
  314. // after the split, the separators never being escaped themselves.
  315. func parseMatch(match string) map[string]string {
  316. fields := make(map[string]string)
  317. for pair := range strings.SplitSeq(match, ",") {
  318. key, val, ok := strings.Cut(pair, "=")
  319. if !ok {
  320. continue
  321. }
  322. if key = strings.TrimSpace(key); key == "" {
  323. continue
  324. }
  325. if unescaped, err := url.PathUnescape(val); err == nil {
  326. val = unescaped
  327. }
  328. fields[key] = strings.TrimSpace(val)
  329. }
  330. return fields
  331. }
  332. // memberDirSets reads the repeated "set" params into a field map. Body values arrive
  333. // doubly encoded and need a second unescape; query values are already decoded, and
  334. // unescaping those again would corrupt a literal '%'.
  335. func memberDirSets(r *http.Request) map[string]string {
  336. fields := parseSet(r.URL.Query()["set"])
  337. for key, val := range parseSet(bodyValues(r, "set")) {
  338. if decoded, err := url.QueryUnescape(val); err == nil {
  339. val = decoded
  340. }
  341. fields[key] = val
  342. }
  343. return fields
  344. }
  345. // parseSet parses the repeated "set=key=value" params the update form sends
  346. // into a field map.
  347. func parseSet(sets []string) map[string]string {
  348. fields := make(map[string]string)
  349. for _, s := range sets {
  350. key, val, ok := strings.Cut(s, "=")
  351. if !ok {
  352. continue
  353. }
  354. if key = strings.TrimSpace(key); key != "" {
  355. fields[key] = strings.TrimSpace(val)
  356. }
  357. }
  358. return fields
  359. }
  360. // parseTargets splits a comma-separated "t" screen-name list, trimming blanks.
  361. func parseTargets(t string) []string {
  362. var targets []string
  363. for name := range strings.SplitSeq(t, ",") {
  364. if name = strings.TrimSpace(name); name != "" {
  365. targets = append(targets, name)
  366. }
  367. }
  368. return targets
  369. }