auth_handler_test.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "strings"
  12. "testing"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/stretchr/testify/assert"
  16. "github.com/mk6i/open-oscar-server/config"
  17. "github.com/mk6i/open-oscar-server/state"
  18. "github.com/mk6i/open-oscar-server/wire"
  19. )
  20. // testAuthService implements AuthService for the auth-handler tests (only
  21. // FLAPLogin and CrackCookie are exercised).
  22. type testAuthService struct {
  23. flapLogin func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error)
  24. crackCookie func(authCookie []byte) (state.ServerCookie, time.Time, error)
  25. }
  26. func (t *testAuthService) BUCPChallenge(ctx context.Context, bodyIn wire.SNAC_0x17_0x06_BUCPChallengeRequest, newUUID func() uuid.UUID) (wire.SNACMessage, error) {
  27. return wire.SNACMessage{}, nil
  28. }
  29. func (t *testAuthService) BUCPLogin(ctx context.Context, bodyIn wire.SNAC_0x17_0x02_BUCPLoginRequest, endpointCfg config.Endpoint) (wire.SNACMessage, error) {
  30. return wire.SNACMessage{}, nil
  31. }
  32. func (t *testAuthService) CrackCookie(authCookie []byte) (state.ServerCookie, time.Time, error) {
  33. if t.crackCookie != nil {
  34. return t.crackCookie(authCookie)
  35. }
  36. return state.ServerCookie{}, time.Now().Add(shortTermTTL), nil
  37. }
  38. // signedCookieFor stands in for a CookieBaker-signed cookie naming screenName.
  39. func signedCookieFor(screenName string) []byte {
  40. return []byte("signed:" + screenName)
  41. }
  42. // crackSignedCookie accepts only cookies produced by signedCookieFor, standing in
  43. // for the signature check the real baker performs. The token reads as freshly
  44. // minted; crackSignedCookieExpiring stands in for an older one.
  45. func crackSignedCookie(authCookie []byte) (state.ServerCookie, time.Time, error) {
  46. return crackSignedCookieExpiring(shortTermTTL)(authCookie)
  47. }
  48. // crackSignedCookieExpiring cracks like crackSignedCookie, reporting a token
  49. // with remaining life left on it.
  50. func crackSignedCookieExpiring(remaining time.Duration) func([]byte) (state.ServerCookie, time.Time, error) {
  51. return func(authCookie []byte) (state.ServerCookie, time.Time, error) {
  52. name, ok := strings.CutPrefix(string(authCookie), "signed:")
  53. if !ok {
  54. return state.ServerCookie{}, time.Time{}, errors.New("bad signature")
  55. }
  56. return state.ServerCookie{
  57. Service: wire.BOS,
  58. ScreenName: state.DisplayScreenName(name),
  59. TokenTTL: uint32(shortTermTTL.Seconds()),
  60. }, time.Now().Add(remaining), nil
  61. }
  62. }
  63. func (t *testAuthService) RegisterBOSSession(ctx context.Context, authCookie state.ServerCookie, conf func(sess *state.Session)) (*state.SessionInstance, error) {
  64. return nil, nil
  65. }
  66. func (t *testAuthService) FLAPLogin(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  67. if t.flapLogin != nil {
  68. return t.flapLogin(ctx, inFrame, endpointCfg)
  69. }
  70. return wire.TLVRestBlock{}, nil
  71. }
  72. func (t *testAuthService) Signout(ctx context.Context, session *state.Session) {}
  73. func (t *testAuthService) SignoutChat(ctx context.Context, sess *state.Session) {}
  74. func successfulLoginBlock() wire.TLVRestBlock {
  75. var b wire.TLVRestBlock
  76. b.Append(wire.NewTLVBE(wire.LoginTLVTagsAuthorizationCookie, loginBlockCookie))
  77. return b
  78. }
  79. // loginBlockCookie is the cookie successfulLoginBlock reports as minted by the auth
  80. // service. Handlers must hand this exact value back rather than mint their own.
  81. var loginBlockCookie = signedCookieFor("testuser")
  82. // blockWithoutCookie is a login response that reports neither an error nor a cookie.
  83. func blockWithoutCookie() wire.TLVRestBlock {
  84. var b wire.TLVRestBlock
  85. b.Append(wire.NewTLVBE(wire.LoginTLVTagsScreenName, "testuser"))
  86. return b
  87. }
  88. func failedLoginBlock() wire.TLVRestBlock {
  89. var b wire.TLVRestBlock
  90. b.Append(wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, uint16(1)))
  91. return b
  92. }
  93. func TestAuthHandler_GetToken(t *testing.T) {
  94. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("testuser"))
  95. tests := []struct {
  96. name string
  97. query string
  98. // remaining is the life left in the parked token; 0 means a fresh one.
  99. remaining time.Duration
  100. cookies []*http.Cookie
  101. checkBody func(*testing.T, string)
  102. }{
  103. {
  104. name: "Success_TokenCookie",
  105. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._0mq8wqdav",
  106. cookies: []*http.Cookie{
  107. {Name: bosTokenCookie, Value: validToken},
  108. },
  109. checkBody: func(t *testing.T, body string) {
  110. assert.Contains(t, body, "_callbacks_._0mq8wqdav(")
  111. assert.Contains(t, body, `"statusCode":200`)
  112. assert.Contains(t, body, `"loginId":"testuser"`)
  113. // The parked token is handed straight back, not re-minted.
  114. assert.Contains(t, body, `"a":"`+validToken+`"`)
  115. assert.Contains(t, body, `"expiresIn":"86400"`)
  116. },
  117. },
  118. {
  119. // getToken hands back the token minted at sign-in, so a browser that
  120. // sat on it for most of a day must be told the life that is actually
  121. // left, not the life the token was born with.
  122. name: "Success_AgedTokenReportsRemainingLife",
  123. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._0mq8wqdav",
  124. remaining: time.Hour,
  125. cookies: []*http.Cookie{
  126. {Name: bosTokenCookie, Value: validToken},
  127. },
  128. checkBody: func(t *testing.T, body string) {
  129. assert.Contains(t, body, `"statusCode":200`)
  130. assert.Contains(t, body, `"expiresIn":"3600"`)
  131. assert.NotContains(t, body, `"expiresIn":"86400"`)
  132. },
  133. },
  134. {
  135. name: "Unauthorized_NoCookie",
  136. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._abc",
  137. checkBody: func(t *testing.T, body string) {
  138. assert.Contains(t, body, `"statusCode":401`)
  139. assert.Contains(t, body, `"redirectURL"`)
  140. },
  141. },
  142. {
  143. // A token past its brief life no longer cracks, which is what makes a
  144. // later visit sign in again.
  145. name: "Unauthorized_UnsignedToken",
  146. query: "f=json&attributes=loginId&devId=dev123&c=_callbacks_._xyz",
  147. cookies: []*http.Cookie{
  148. {Name: bosTokenCookie, Value: base64.URLEncoding.EncodeToString([]byte("victim"))},
  149. },
  150. checkBody: func(t *testing.T, body string) {
  151. assert.Contains(t, body, `"statusCode":401`)
  152. assert.Contains(t, body, `"redirectURL"`)
  153. assert.NotContains(t, body, "victim")
  154. },
  155. },
  156. {
  157. // The screen name comes only from a signature-verified token, so these
  158. // forgeable plaintext cookies must not authenticate anyone.
  159. name: "Unauthorized_ForgedSSOCookies",
  160. query: "f=json&attributes=loginId&devId=dev123&c=_callbacks_._xyz",
  161. cookies: []*http.Cookie{
  162. {Name: "RSP_USER", Value: "victim"},
  163. {Name: "RSP_LOCAL", Value: "victim"},
  164. {Name: "localAuthUser", Value: "victim||victim"},
  165. },
  166. checkBody: func(t *testing.T, body string) {
  167. assert.Contains(t, body, `"statusCode":401`)
  168. assert.Contains(t, body, `"redirectURL"`)
  169. assert.NotContains(t, body, "victim")
  170. },
  171. },
  172. }
  173. for _, tt := range tests {
  174. t.Run(tt.name, func(t *testing.T) {
  175. crack := crackSignedCookie
  176. if tt.remaining > 0 {
  177. crack = crackSignedCookieExpiring(tt.remaining)
  178. }
  179. handler := &AuthHandler{
  180. AuthService: &testAuthService{crackCookie: crack},
  181. Logger: slog.Default(),
  182. }
  183. req, err := http.NewRequest(http.MethodGet, "/auth/getToken?"+tt.query, nil)
  184. assert.NoError(t, err)
  185. for _, c := range tt.cookies {
  186. req.AddCookie(c)
  187. }
  188. rr := httptest.NewRecorder()
  189. handler.GetToken(rr, req)
  190. assert.Equal(t, http.StatusOK, rr.Code)
  191. tt.checkBody(t, rr.Body.String())
  192. // Spent either way, so a reload has nothing to sign in with.
  193. assert.True(t, tokenCookieCleared(rr), "getToken should expire the token cookie")
  194. })
  195. }
  196. }
  197. // tokenCookieCleared reports whether the response expires the token cookie.
  198. func tokenCookieCleared(rr *httptest.ResponseRecorder) bool {
  199. for _, c := range rr.Result().Cookies() {
  200. if c.Name == bosTokenCookie && c.MaxAge < 0 {
  201. return true
  202. }
  203. }
  204. return false
  205. }
  206. // A second getToken must fail even inside the token's own lifetime: the cookie is
  207. // gone after the first, so every reload lands on the login page.
  208. func TestAuthHandler_GetToken_IsOneShot(t *testing.T) {
  209. handler := &AuthHandler{
  210. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  211. Logger: slog.Default(),
  212. }
  213. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("testuser"))
  214. get := func(withCookie bool) string {
  215. req := httptest.NewRequest(http.MethodGet, "/auth/getToken?f=json&attributes=loginId&devId=dev1", nil)
  216. if withCookie {
  217. req.AddCookie(&http.Cookie{Name: bosTokenCookie, Value: validToken})
  218. }
  219. rr := httptest.NewRecorder()
  220. handler.GetToken(rr, req)
  221. return rr.Body.String()
  222. }
  223. assert.Contains(t, get(true), `"statusCode":200`)
  224. // The browser dropped the cookie, so the follow-up presents nothing.
  225. assert.Contains(t, get(false), `"statusCode":401`)
  226. }
  227. func TestAuthHandler_ClientLogin(t *testing.T) {
  228. tests := []struct {
  229. name string
  230. method string
  231. contentType string
  232. body string
  233. // query is appended to the request URL, to prove it is not read.
  234. query string
  235. auth *testAuthService
  236. expectedStatusCode int
  237. checkResponse func(*testing.T, string)
  238. }{
  239. {
  240. name: "Success_FormEncoded",
  241. method: "POST",
  242. contentType: "application/x-www-form-urlencoded",
  243. body: "s=testuser&pwd=testpass&devId=dev123",
  244. auth: &testAuthService{
  245. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  246. return successfulLoginBlock(), nil
  247. },
  248. },
  249. expectedStatusCode: http.StatusOK,
  250. checkResponse: func(t *testing.T, body string) {
  251. assert.Contains(t, body, `"statusCode":200`)
  252. // The token is the cookie the auth service minted, not a re-mint.
  253. assert.Contains(t, body, `"a":"`+base64.URLEncoding.EncodeToString(loginBlockCookie)+`"`)
  254. assert.Contains(t, body, `"loginId":"testuser"`)
  255. assert.Contains(t, body, `"screenName":"testuser"`)
  256. assert.Contains(t, body, `"token"`)
  257. assert.Contains(t, body, `"sessionSecret"`)
  258. },
  259. },
  260. {
  261. // The legacy aliases the form path has always accepted alongside the
  262. // spec's s and pwd.
  263. name: "Success_LegacyFieldNames",
  264. method: "POST",
  265. contentType: "application/x-www-form-urlencoded",
  266. body: "username=testuser&password=testpass&devId=dev123",
  267. auth: &testAuthService{
  268. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  269. return successfulLoginBlock(), nil
  270. },
  271. },
  272. expectedStatusCode: http.StatusOK,
  273. checkResponse: func(t *testing.T, body string) {
  274. assert.Contains(t, body, `"statusCode":200`)
  275. assert.Contains(t, body, `"loginId":"testuser"`)
  276. },
  277. },
  278. {
  279. // "longterm" is a year, and the response reports what was granted.
  280. name: "Success_TokenTypeLongterm",
  281. method: "POST",
  282. contentType: "application/x-www-form-urlencoded",
  283. body: "s=testuser&pwd=testpass&devId=dev123&tokenType=longterm",
  284. auth: &testAuthService{
  285. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  286. return successfulLoginBlock(), nil
  287. },
  288. },
  289. expectedStatusCode: http.StatusOK,
  290. checkResponse: func(t *testing.T, body string) {
  291. assert.Contains(t, body, `"statusCode":200`)
  292. assert.Contains(t, body, `"expiresIn":"31536000"`)
  293. assert.Contains(t, body, `"tokenExpiresIn":31536000`)
  294. },
  295. },
  296. {
  297. // A bare count of seconds is a valid tokenType.
  298. name: "Success_TokenTypeSeconds",
  299. method: "POST",
  300. contentType: "application/x-www-form-urlencoded",
  301. body: "s=testuser&pwd=testpass&devId=dev123&tokenType=3600",
  302. auth: &testAuthService{
  303. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  304. return successfulLoginBlock(), nil
  305. },
  306. },
  307. expectedStatusCode: http.StatusOK,
  308. checkResponse: func(t *testing.T, body string) {
  309. assert.Contains(t, body, `"statusCode":200`)
  310. assert.Contains(t, body, `"expiresIn":"3600"`)
  311. assert.Contains(t, body, `"tokenExpiresIn":3600`)
  312. },
  313. },
  314. {
  315. // Omitting tokenType is "shortterm", a day.
  316. name: "Success_TokenTypeDefaultsToShortterm",
  317. method: "POST",
  318. contentType: "application/x-www-form-urlencoded",
  319. body: "s=testuser&pwd=testpass&devId=dev123",
  320. auth: &testAuthService{
  321. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  322. return successfulLoginBlock(), nil
  323. },
  324. },
  325. expectedStatusCode: http.StatusOK,
  326. checkResponse: func(t *testing.T, body string) {
  327. assert.Contains(t, body, `"expiresIn":"86400"`)
  328. assert.Contains(t, body, `"tokenExpiresIn":86400`)
  329. },
  330. },
  331. {
  332. // A tokenType the server cannot honour is a parameter error, and the
  333. // credentials are never checked.
  334. name: "Error_TokenTypeUnparsable",
  335. method: "POST",
  336. contentType: "application/x-www-form-urlencoded",
  337. body: "s=testuser&pwd=testpass&tokenType=forever",
  338. auth: &testAuthService{},
  339. expectedStatusCode: http.StatusBadRequest,
  340. checkResponse: func(t *testing.T, body string) {
  341. assert.Contains(t, body, `"statusCode":462`)
  342. },
  343. },
  344. {
  345. name: "Error_TokenTypeBeyondMax",
  346. method: "POST",
  347. contentType: "application/x-www-form-urlencoded",
  348. body: "s=testuser&pwd=testpass&tokenType=31536001",
  349. auth: &testAuthService{},
  350. expectedStatusCode: http.StatusBadRequest,
  351. checkResponse: func(t *testing.T, body string) {
  352. assert.Contains(t, body, `"statusCode":462`)
  353. },
  354. },
  355. {
  356. // The spec puts these in the body, and a password in a URL is one
  357. // that has already been logged. Credentials in the query string are
  358. // not credentials at all.
  359. name: "Error_CredentialsInQueryStringAreIgnored",
  360. method: "POST",
  361. contentType: "application/x-www-form-urlencoded",
  362. body: "",
  363. query: "?s=testuser&pwd=testpass&devId=dev123",
  364. auth: &testAuthService{},
  365. expectedStatusCode: http.StatusBadRequest,
  366. checkResponse: func(t *testing.T, body string) {
  367. assert.Contains(t, body, `"statusCode":460`)
  368. },
  369. },
  370. {
  371. // A body value stands on its own; the query is not consulted even to
  372. // fill a gap.
  373. name: "Success_BodyWinsOverQueryString",
  374. method: "POST",
  375. contentType: "application/x-www-form-urlencoded",
  376. body: "s=testuser&pwd=testpass&tokenType=longterm",
  377. query: "?tokenType=600",
  378. auth: &testAuthService{
  379. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  380. return successfulLoginBlock(), nil
  381. },
  382. },
  383. expectedStatusCode: http.StatusOK,
  384. checkResponse: func(t *testing.T, body string) {
  385. assert.Contains(t, body, `"expiresIn":"31536000"`)
  386. },
  387. },
  388. {
  389. name: "Error_MissingUsername",
  390. method: "POST",
  391. contentType: "application/x-www-form-urlencoded",
  392. body: "pwd=testpass",
  393. auth: &testAuthService{},
  394. expectedStatusCode: http.StatusBadRequest,
  395. checkResponse: func(t *testing.T, body string) {
  396. // The code a client reads as "you left something out", which is
  397. // not the code that means the credentials were wrong.
  398. assert.Contains(t, body, `"statusCode":460`)
  399. assert.NotContains(t, body, "statusDetailCode")
  400. assert.Contains(t, body, "username and password required")
  401. },
  402. },
  403. {
  404. name: "Error_MissingPassword",
  405. method: "POST",
  406. contentType: "application/x-www-form-urlencoded",
  407. body: "s=testuser",
  408. auth: &testAuthService{},
  409. expectedStatusCode: http.StatusBadRequest,
  410. checkResponse: func(t *testing.T, body string) {
  411. assert.Contains(t, body, `"statusCode":460`)
  412. assert.Contains(t, body, "username and password required")
  413. },
  414. },
  415. {
  416. name: "Error_AuthFailed",
  417. method: "POST",
  418. contentType: "application/x-www-form-urlencoded",
  419. body: "s=testuser&pwd=wrongpass",
  420. auth: &testAuthService{
  421. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  422. return failedLoginBlock(), nil
  423. },
  424. },
  425. expectedStatusCode: http.StatusUnauthorized,
  426. checkResponse: func(t *testing.T, body string) {
  427. // The codes a client maps to "incorrect password".
  428. assert.Contains(t, body, `"statusCode":330`)
  429. assert.Contains(t, body, `"statusDetailCode":3011`)
  430. },
  431. },
  432. {
  433. name: "Error_FLAPLoginError",
  434. method: "POST",
  435. contentType: "application/x-www-form-urlencoded",
  436. body: "s=testuser&pwd=testpass",
  437. auth: &testAuthService{
  438. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  439. return wire.TLVRestBlock{}, errors.New("boom")
  440. },
  441. },
  442. expectedStatusCode: http.StatusInternalServerError,
  443. checkResponse: func(t *testing.T, body string) {
  444. assert.Contains(t, body, "internal server error")
  445. },
  446. },
  447. {
  448. // A POST carries "f" in its body, the only place clientLogin states it.
  449. name: "Error_AuthFailed_XMLRequestedInBody",
  450. method: "POST",
  451. contentType: "application/x-www-form-urlencoded",
  452. body: "s=testuser&pwd=wrongpass&f=xml",
  453. auth: &testAuthService{
  454. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  455. return failedLoginBlock(), nil
  456. },
  457. },
  458. expectedStatusCode: http.StatusUnauthorized,
  459. checkResponse: func(t *testing.T, body string) {
  460. assert.Contains(t, body, "<statusCode>330</statusCode>")
  461. assert.Contains(t, body, "<statusDetailCode>3011</statusDetailCode>")
  462. },
  463. },
  464. {
  465. name: "Error_LoginResponseHasNoCookie",
  466. method: "POST",
  467. contentType: "application/x-www-form-urlencoded",
  468. body: "s=testuser&pwd=testpass",
  469. auth: &testAuthService{
  470. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  471. return blockWithoutCookie(), nil
  472. },
  473. },
  474. expectedStatusCode: http.StatusInternalServerError,
  475. checkResponse: func(t *testing.T, body string) {
  476. assert.Contains(t, body, "internal server error")
  477. },
  478. },
  479. }
  480. for _, tt := range tests {
  481. t.Run(tt.name, func(t *testing.T) {
  482. logger := slog.Default()
  483. handler := &AuthHandler{
  484. AuthService: tt.auth,
  485. Logger: logger,
  486. }
  487. req, err := http.NewRequest(tt.method, "/auth/clientLogin"+tt.query, strings.NewReader(tt.body))
  488. assert.NoError(t, err)
  489. req.Header.Set("Content-Type", tt.contentType)
  490. rr := httptest.NewRecorder()
  491. handler.ClientLogin(rr, req)
  492. assert.Equal(t, tt.expectedStatusCode, rr.Code)
  493. responseBody := strings.TrimSpace(rr.Body.String())
  494. if tt.checkResponse != nil {
  495. tt.checkResponse(t, responseBody)
  496. }
  497. })
  498. }
  499. }
  500. func TestAuthHandler_ClientLogin_SendsClientIdentity(t *testing.T) {
  501. tests := []struct {
  502. name string
  503. body string
  504. expectedClientID string
  505. }{
  506. {
  507. name: "DevIDNamesTheClient",
  508. body: "s=testuser&pwd=testpass&devId=dev123",
  509. expectedClientID: "dev123",
  510. },
  511. {
  512. name: "MissingDevIDFallsBack",
  513. body: "s=testuser&pwd=testpass",
  514. expectedClientID: "WebAIM",
  515. },
  516. }
  517. for _, tt := range tests {
  518. t.Run(tt.name, func(t *testing.T) {
  519. var got wire.FLAPSignonFrame
  520. handler := &AuthHandler{
  521. AuthService: &testAuthService{
  522. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  523. got = inFrame
  524. return successfulLoginBlock(), nil
  525. },
  526. },
  527. Logger: slog.Default(),
  528. }
  529. req := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader(tt.body))
  530. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  531. handler.ClientLogin(httptest.NewRecorder(), req)
  532. clientID, ok := got.String(wire.LoginTLVTagsClientIdentity)
  533. assert.True(t, ok, "signon frame should carry a client identity")
  534. assert.Equal(t, tt.expectedClientID, clientID)
  535. })
  536. }
  537. }
  538. func TestAuthHandler_ClientLogin_SendsRequestedTokenTTL(t *testing.T) {
  539. tests := []struct {
  540. name string
  541. body string
  542. wantTTL uint32
  543. }{
  544. {
  545. name: "OmittedIsShortterm",
  546. body: "s=testuser&pwd=testpass",
  547. wantTTL: 86400,
  548. },
  549. {
  550. name: "Shortterm",
  551. body: "s=testuser&pwd=testpass&tokenType=shortterm",
  552. wantTTL: 86400,
  553. },
  554. {
  555. name: "Longterm",
  556. body: "s=testuser&pwd=testpass&tokenType=longterm",
  557. wantTTL: 31536000,
  558. },
  559. {
  560. name: "ExplicitSeconds",
  561. body: "s=testuser&pwd=testpass&tokenType=600",
  562. wantTTL: 600,
  563. },
  564. }
  565. for _, tt := range tests {
  566. t.Run(tt.name, func(t *testing.T) {
  567. var got wire.FLAPSignonFrame
  568. handler := &AuthHandler{
  569. AuthService: &testAuthService{
  570. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  571. got = inFrame
  572. return successfulLoginBlock(), nil
  573. },
  574. },
  575. Logger: slog.Default(),
  576. }
  577. req := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader(tt.body))
  578. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  579. handler.ClientLogin(httptest.NewRecorder(), req)
  580. // What the client asked for is what login is asked to mint.
  581. ttl, ok := got.Uint32BE(wire.LoginTLVTagsTokenTTL)
  582. assert.True(t, ok, "signon frame should carry a token TTL")
  583. assert.Equal(t, tt.wantTTL, ttl)
  584. })
  585. }
  586. }
  587. func TestTokenTypeTTL(t *testing.T) {
  588. tests := []struct {
  589. name string
  590. tokenType string
  591. want time.Duration
  592. wantErr bool
  593. }{
  594. {name: "omitted", tokenType: "", want: shortTermTTL},
  595. {name: "shortterm", tokenType: "shortterm", want: shortTermTTL},
  596. {name: "shortterm mixed case", tokenType: "ShortTerm", want: shortTermTTL},
  597. {name: "longterm", tokenType: "longterm", want: longTermTTL},
  598. {name: "longterm padded", tokenType: " longterm ", want: longTermTTL},
  599. {name: "seconds", tokenType: "3600", want: time.Hour},
  600. {name: "one second", tokenType: "1", want: time.Second},
  601. {name: "exactly the max", tokenType: "31536000", want: longTermTTL},
  602. {name: "zero seconds", tokenType: "0", wantErr: true},
  603. {name: "one past the max", tokenType: "31536001", wantErr: true},
  604. // large enough that scaling to a Duration would overflow int64
  605. {name: "overflowing seconds", tokenType: "99999999999999999", wantErr: true},
  606. {name: "negative", tokenType: "-1", wantErr: true},
  607. {name: "unrecognized word", tokenType: "forever", wantErr: true},
  608. {name: "float", tokenType: "60.5", wantErr: true},
  609. }
  610. for _, tt := range tests {
  611. t.Run(tt.name, func(t *testing.T) {
  612. got, err := tokenTypeTTL(tt.tokenType)
  613. if tt.wantErr {
  614. assert.Error(t, err)
  615. return
  616. }
  617. assert.NoError(t, err)
  618. assert.Equal(t, tt.want, got)
  619. })
  620. }
  621. }
  622. func TestAuthHandler_LoginPSP_GET(t *testing.T) {
  623. handler := &AuthHandler{Logger: slog.Default()}
  624. req := httptest.NewRequest(http.MethodGet, "/_cqr/login/login.psp?devId=dev1&succUrl=http%3A%2F%2Flocalhost%3A8000%2F", nil)
  625. rr := httptest.NewRecorder()
  626. handler.LoginPSP(rr, req)
  627. assert.Equal(t, http.StatusOK, rr.Code)
  628. assert.Contains(t, rr.Header().Get("Content-Type"), "text/html")
  629. assert.Contains(t, rr.Body.String(), "AIM Sign In")
  630. assert.Contains(t, rr.Body.String(), `name="devId" value="dev1"`)
  631. }
  632. func TestAuthHandler_Logout(t *testing.T) {
  633. handler := &AuthHandler{Logger: slog.Default()}
  634. req := httptest.NewRequest(http.MethodGet, "/auth/logout?f=json&a=sometoken&devId=dev1&succUrl=http%3A%2F%2Flocalhost%3A8000%2F.client%2F", nil)
  635. rr := httptest.NewRecorder()
  636. handler.Logout(rr, req)
  637. assert.Equal(t, http.StatusFound, rr.Code)
  638. loc, err := url.Parse(rr.Header().Get("Location"))
  639. assert.NoError(t, err)
  640. assert.Equal(t, "/_cqr/login/login.psp", loc.Path)
  641. assert.Equal(t, "dev1", loc.Query().Get("devId"))
  642. assert.Equal(t, "http://localhost:8000/.client/", loc.Query().Get("succUrl"))
  643. // Signing out spends the token cookie, whether or not getToken already did.
  644. // A 24h token left behind would sign the next person in as this account.
  645. cleared := rr.Result().Cookies()
  646. if assert.Len(t, cleared, 1) {
  647. assert.Equal(t, bosTokenCookie, cleared[0].Name)
  648. assert.Empty(t, cleared[0].Value)
  649. assert.Less(t, cleared[0].MaxAge, 1)
  650. }
  651. }
  652. func TestAuthHandler_LoginPSP_POST_Success(t *testing.T) {
  653. var got wire.FLAPSignonFrame
  654. handler := &AuthHandler{
  655. AuthService: &testAuthService{
  656. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  657. got = inFrame
  658. return successfulLoginBlock(), nil
  659. },
  660. },
  661. Logger: slog.Default(),
  662. }
  663. form := url.Values{}
  664. form.Set("loginId", "testuser")
  665. form.Set("password", "secret")
  666. form.Set("devId", "dev1")
  667. form.Set("succUrl", "http://localhost:8000/")
  668. req := httptest.NewRequest(http.MethodPost, "/_cqr/login/login.psp", strings.NewReader(form.Encode()))
  669. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  670. rr := httptest.NewRecorder()
  671. handler.LoginPSP(rr, req)
  672. assert.Equal(t, http.StatusFound, rr.Code)
  673. assert.Equal(t, "http://localhost:8000/", rr.Header().Get("Location"))
  674. set := make(map[string]*http.Cookie)
  675. for _, c := range rr.Result().Cookies() {
  676. set[c.Name] = c
  677. }
  678. // The cookie carries the BOS token from the login response, unchanged.
  679. tokenCookie := set[bosTokenCookie]
  680. if assert.NotNil(t, tokenCookie) {
  681. assert.True(t, tokenCookie.HttpOnly)
  682. raw, err := base64.URLEncoding.DecodeString(tokenCookie.Value)
  683. assert.NoError(t, err)
  684. assert.Equal(t, loginBlockCookie, raw)
  685. // The browser drops it on the same schedule the server stops honouring it.
  686. assert.Equal(t, 86400, tokenCookie.MaxAge)
  687. }
  688. for _, name := range []string{"RSP_USER", "RSP_LOCAL", "localAuthUser"} {
  689. assert.NotContains(t, set, name)
  690. }
  691. // The Web API asks login for a token that outlives the browser round trip.
  692. ttl, ok := got.Uint32BE(wire.LoginTLVTagsTokenTTL)
  693. assert.True(t, ok)
  694. assert.Equal(t, uint32(86400), ttl)
  695. // The devId names the client on the resulting session.
  696. clientID, ok := got.String(wire.LoginTLVTagsClientIdentity)
  697. assert.True(t, ok, "signon frame should carry a client identity")
  698. assert.Equal(t, "dev1", clientID)
  699. }
  700. func TestAuthHandler_LoginPSP_POST_ServiceErrors(t *testing.T) {
  701. tests := []struct {
  702. name string
  703. flapLogin func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error)
  704. }{
  705. {
  706. name: "LoginResponseHasNoCookie",
  707. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  708. return blockWithoutCookie(), nil
  709. },
  710. },
  711. {
  712. name: "AuthServiceUnreachable",
  713. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  714. return wire.TLVRestBlock{}, errors.New("boom")
  715. },
  716. },
  717. }
  718. for _, tt := range tests {
  719. t.Run(tt.name, func(t *testing.T) {
  720. handler := &AuthHandler{
  721. AuthService: &testAuthService{flapLogin: tt.flapLogin},
  722. Logger: slog.Default(),
  723. }
  724. form := url.Values{}
  725. form.Set("loginId", "testuser")
  726. form.Set("password", "secret")
  727. req := httptest.NewRequest(http.MethodPost, "/_cqr/login/login.psp", strings.NewReader(form.Encode()))
  728. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  729. rr := httptest.NewRecorder()
  730. handler.LoginPSP(rr, req)
  731. // A broken auth service must not read as a mistyped password.
  732. assert.Equal(t, http.StatusInternalServerError, rr.Code)
  733. assert.NotContains(t, rr.Body.String(), "Invalid screen name or password")
  734. assert.Empty(t, rr.Result().Cookies())
  735. })
  736. }
  737. }
  738. func TestAuthHandler_LoginPSP_POST_InvalidCredentials(t *testing.T) {
  739. handler := &AuthHandler{
  740. AuthService: &testAuthService{
  741. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  742. return failedLoginBlock(), nil
  743. },
  744. },
  745. Logger: slog.Default(),
  746. }
  747. form := url.Values{}
  748. form.Set("loginId", "testuser")
  749. form.Set("password", "wrong")
  750. req := httptest.NewRequest(http.MethodPost, "/_cqr/login/login.psp", strings.NewReader(form.Encode()))
  751. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  752. rr := httptest.NewRecorder()
  753. handler.LoginPSP(rr, req)
  754. assert.Equal(t, http.StatusOK, rr.Code)
  755. assert.Contains(t, rr.Body.String(), "Invalid screen name or password")
  756. }
  757. func TestDefaultLoginSuccURL(t *testing.T) {
  758. req := httptest.NewRequest(http.MethodGet, "http://ras.dev/_cqr/login/login.psp", nil)
  759. assert.Equal(t, "http://ras.dev/", defaultLoginSuccURL(req))
  760. // TLS terminated upstream, so the scheme only survives in the header.
  761. req.Header.Set("X-Forwarded-Proto", "https")
  762. assert.Equal(t, "https://ras.dev/", defaultLoginSuccURL(req))
  763. }
  764. func TestSafeLoginRedirectURL(t *testing.T) {
  765. req := httptest.NewRequest(http.MethodGet, "http://localhost/_cqr/login/login.psp", nil)
  766. assert.Equal(t, "http://localhost:8000/", safeLoginRedirectURL(req, "http://localhost:8000/"))
  767. assert.Equal(t, "http://localhost/", safeLoginRedirectURL(req, "http://evil.example/"))
  768. }
  769. // getInfoHandler builds a handler whose CrackCookie returns cookie, expiring at
  770. // shortTermTTL from now unless the caller says otherwise.
  771. func getInfoHandler(cookie state.ServerCookie) *AuthHandler {
  772. return &AuthHandler{
  773. AuthService: &testAuthService{
  774. crackCookie: func([]byte) (state.ServerCookie, time.Time, error) {
  775. return cookie, time.Now().Add(time.Duration(cookie.TokenTTL) * time.Second), nil
  776. },
  777. },
  778. Logger: slog.Default(),
  779. }
  780. }
  781. func getInfoGET(h *AuthHandler, query string) *httptest.ResponseRecorder {
  782. req := httptest.NewRequest(http.MethodGet, "/auth/getInfo?f=json&devId=ic1"+query, nil)
  783. rr := httptest.NewRecorder()
  784. h.GetInfo(rr, req)
  785. return rr
  786. }
  787. func TestAuthHandler_GetInfo(t *testing.T) {
  788. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("ChattingChuck"))
  789. tests := []struct {
  790. name string
  791. query string
  792. crack func([]byte) (state.ServerCookie, time.Time, error)
  793. checkBody func(*testing.T, string)
  794. }{
  795. {
  796. name: "Success",
  797. query: "&a=" + url.QueryEscape(validToken),
  798. checkBody: func(t *testing.T, body string) {
  799. assert.Contains(t, body, `"statusCode":200`)
  800. assert.Contains(t, body, `"userData":{"loginId":"ChattingChuck","displayName":"ChattingChuck"}`)
  801. // getInfo reports; it does not mint. A token in the reply means
  802. // renewal has crept back in.
  803. assert.NotContains(t, body, `"token"`)
  804. assert.NotContains(t, body, `"expiresIn"`)
  805. },
  806. },
  807. {
  808. name: "NoToken",
  809. query: "",
  810. checkBody: func(t *testing.T, body string) {
  811. assert.Contains(t, body, `"statusCode":401`)
  812. // The web client re-authenticates from data.redirectURL on any
  813. // non-200, and reports a hard failure without it.
  814. assert.Contains(t, body, `"redirectURL":"http://example.com/_cqr/login/login.psp"`)
  815. assert.NotContains(t, body, "userData")
  816. },
  817. },
  818. {
  819. name: "MalformedToken",
  820. query: "&a=not-base64!!",
  821. checkBody: func(t *testing.T, body string) {
  822. assert.Contains(t, body, `"statusCode":401`)
  823. assert.Contains(t, body, `"redirectURL":`)
  824. assert.NotContains(t, body, "userData")
  825. },
  826. },
  827. {
  828. name: "RejectedToken",
  829. query: "&a=" + url.QueryEscape(base64.URLEncoding.EncodeToString([]byte("unsigned"))),
  830. checkBody: func(t *testing.T, body string) {
  831. assert.Contains(t, body, `"statusCode":401`)
  832. assert.Contains(t, body, `"redirectURL":`)
  833. assert.NotContains(t, body, "userData")
  834. },
  835. },
  836. }
  837. for _, tt := range tests {
  838. t.Run(tt.name, func(t *testing.T) {
  839. handler := &AuthHandler{
  840. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  841. Logger: slog.Default(),
  842. }
  843. tt.checkBody(t, getInfoGET(handler, tt.query).Body.String())
  844. })
  845. }
  846. }
  847. // TestAuthHandler_GetInfo_RejectsNonLoginTokens covers the one thing CrackCookie does
  848. // not check: what the cookie is for. One key signs every cookie, so a service-transfer
  849. // cookie verifies like a login token while recording no authentication.
  850. func TestAuthHandler_GetInfo_RejectsNonLoginTokens(t *testing.T) {
  851. tests := []struct {
  852. name string
  853. cookie state.ServerCookie
  854. wantStatus int
  855. }{
  856. {
  857. name: "login cookie is accepted",
  858. cookie: state.ServerCookie{Service: wire.BOS, ScreenName: "chuck", TokenTTL: 3600},
  859. wantStatus: 200,
  860. },
  861. {
  862. name: "chat transfer cookie is refused",
  863. cookie: state.ServerCookie{Service: wire.Chat, ScreenName: "chuck", ChatCookie: "room-1"},
  864. wantStatus: 401,
  865. },
  866. {
  867. name: "bart transfer cookie is refused",
  868. cookie: state.ServerCookie{Service: wire.BART, ScreenName: "chuck", SessionNum: 1},
  869. wantStatus: 401,
  870. },
  871. {
  872. name: "chatnav transfer cookie is refused",
  873. cookie: state.ServerCookie{Service: wire.ChatNav, ScreenName: "chuck", SessionNum: 1},
  874. wantStatus: 401,
  875. },
  876. {
  877. // The one transfer cookie issued as wire.BOS
  878. // (foodgroup/oservice.go:662). wire.BOS is the zero value, so only the
  879. // absent grant distinguishes it from a login.
  880. name: "linked-account transfer cookie is refused",
  881. cookie: state.ServerCookie{Service: wire.BOS, ScreenName: "chuck", MultiConnFlag: 1},
  882. wantStatus: 401,
  883. },
  884. {
  885. // A login cookie has no room to belong to, so one carrying a chat
  886. // cookie did not come from a login.
  887. name: "login cookie carrying a chat cookie is refused",
  888. cookie: state.ServerCookie{Service: wire.BOS, ScreenName: "chuck", ChatCookie: "room-1", TokenTTL: 3600},
  889. wantStatus: 401,
  890. },
  891. }
  892. for _, tt := range tests {
  893. t.Run(tt.name, func(t *testing.T) {
  894. token := base64.URLEncoding.EncodeToString(signedCookieFor("chuck"))
  895. body := getInfoGET(getInfoHandler(tt.cookie), "&a="+url.QueryEscape(token)).Body.String()
  896. assert.Contains(t, body, fmt.Sprintf(`"statusCode":%d`, tt.wantStatus))
  897. if tt.wantStatus != 200 {
  898. assert.NotContains(t, body, "chuck")
  899. }
  900. })
  901. }
  902. }
  903. // TestAuthHandler_GetInfo_Freshness drives both outcomes from one cookie, varying only
  904. // reqAuthFreshness. A test that used a different cookie per outcome could pass because
  905. // the cookie was rejected rather than because the freshness rule fired.
  906. func TestAuthHandler_GetInfo_Freshness(t *testing.T) {
  907. // Authenticated an hour ago: expiry is a full grant from then, so it sits
  908. // shortTermTTL-minus-an-hour in the future.
  909. hourOldAuth := func([]byte) (state.ServerCookie, time.Time, error) {
  910. cookie := state.ServerCookie{
  911. Service: wire.BOS,
  912. ScreenName: "ChattingChuck",
  913. TokenTTL: uint32(shortTermTTL.Seconds()),
  914. }
  915. return cookie, time.Now().Add(shortTermTTL - time.Hour), nil
  916. }
  917. handler := &AuthHandler{
  918. AuthService: &testAuthService{crackCookie: hourOldAuth},
  919. Logger: slog.Default(),
  920. }
  921. token := url.QueryEscape(base64.URLEncoding.EncodeToString(signedCookieFor("ChattingChuck")))
  922. t.Run("within the default window", func(t *testing.T) {
  923. body := getInfoGET(handler, "&a="+token).Body.String()
  924. assert.Contains(t, body, `"statusCode":200`)
  925. assert.Contains(t, body, `"loginId":"ChattingChuck"`)
  926. })
  927. t.Run("stale against a narrower window redirects", func(t *testing.T) {
  928. body := getInfoGET(handler, "&a="+token+"&reqAuthFreshness=60").Body.String()
  929. assert.Contains(t, body, `"statusCode":330`)
  930. assert.Contains(t, body, `"redirectURL":"http://example.com/_cqr/login/login.psp"`)
  931. // 330 says "authenticate again", so it must not also answer the question.
  932. assert.NotContains(t, body, "userData")
  933. })
  934. t.Run("fresh against a window that still covers it", func(t *testing.T) {
  935. body := getInfoGET(handler, "&a="+token+"&reqAuthFreshness=7200").Body.String()
  936. assert.Contains(t, body, `"statusCode":200`)
  937. })
  938. t.Run("unusable reqAuthFreshness is a parameter error", func(t *testing.T) {
  939. body := getInfoGET(handler, "&a="+token+"&reqAuthFreshness=soon").Body.String()
  940. assert.Contains(t, body, `"statusCode":462`)
  941. })
  942. t.Run("a cookie naming no grant is refused, not waved through", func(t *testing.T) {
  943. // Without a TokenTTL there is no issue instant, so no freshness claim can
  944. // be made; answering 200 would assert one.
  945. noTTL := getInfoHandler(state.ServerCookie{Service: wire.BOS, ScreenName: "ChattingChuck"})
  946. body := getInfoGET(noTTL, "&a="+token+"&reqAuthFreshness=99999999").Body.String()
  947. assert.Contains(t, body, `"statusCode":401`)
  948. assert.NotContains(t, body, "userData")
  949. })
  950. }
  951. // TestAuthHandler_GetInfo_AcceptsGETAndPOST pins that the parameters may arrive either
  952. // way, which is the reason the route is registered for both methods.
  953. func TestAuthHandler_GetInfo_AcceptsGETAndPOST(t *testing.T) {
  954. token := base64.URLEncoding.EncodeToString(signedCookieFor("ChattingChuck"))
  955. cookie := state.ServerCookie{
  956. Service: wire.BOS,
  957. ScreenName: "ChattingChuck",
  958. TokenTTL: uint32(shortTermTTL.Seconds()),
  959. }
  960. getBody := getInfoGET(getInfoHandler(cookie), "&a="+url.QueryEscape(token)).Body.String()
  961. form := url.Values{"f": {"json"}, "devId": {"ic1"}, "a": {token}}
  962. req := httptest.NewRequest(http.MethodPost, "/auth/getInfo", strings.NewReader(form.Encode()))
  963. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  964. rr := httptest.NewRecorder()
  965. getInfoHandler(cookie).GetInfo(rr, req)
  966. assert.Contains(t, getBody, `"loginId":"ChattingChuck"`)
  967. assert.Equal(t, getBody, rr.Body.String())
  968. }
  969. // TestAuthHandler_GetInfo_EchoesRequestID covers the paths that hand-build their
  970. // envelope, bypassing SendOK. Only a BaseResponse gets the request id filled in by
  971. // normalizeEnvelope, and a JSONP client discards a reply that is missing it.
  972. func TestAuthHandler_GetInfo_EchoesRequestID(t *testing.T) {
  973. token := url.QueryEscape(base64.URLEncoding.EncodeToString(signedCookieFor("ChattingChuck")))
  974. staleAuth := &AuthHandler{
  975. AuthService: &testAuthService{crackCookie: func([]byte) (state.ServerCookie, time.Time, error) {
  976. cookie := state.ServerCookie{Service: wire.BOS, ScreenName: "ChattingChuck", TokenTTL: uint32(shortTermTTL.Seconds())}
  977. return cookie, time.Now().Add(shortTermTTL - time.Hour), nil
  978. }},
  979. Logger: slog.Default(),
  980. }
  981. ok := &AuthHandler{
  982. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  983. Logger: slog.Default(),
  984. }
  985. tests := []struct {
  986. name string
  987. handler *AuthHandler
  988. query string
  989. wantStatus int
  990. }{
  991. {name: "200", handler: ok, query: "&a=" + token, wantStatus: 200},
  992. {name: "330", handler: staleAuth, query: "&a=" + token + "&reqAuthFreshness=60", wantStatus: 330},
  993. {name: "401", handler: ok, query: "", wantStatus: 401},
  994. {name: "462", handler: ok, query: "&a=" + token + "&reqAuthFreshness=soon", wantStatus: 462},
  995. }
  996. for _, tt := range tests {
  997. t.Run(tt.name, func(t *testing.T) {
  998. body := getInfoGET(tt.handler, tt.query+"&r=req-42").Body.String()
  999. assert.Contains(t, body, fmt.Sprintf(`"statusCode":%d`, tt.wantStatus))
  1000. assert.Contains(t, body, `"requestId":"req-42"`)
  1001. })
  1002. }
  1003. }
  1004. // TestAuthHandler_GetInfo_RefusesRenewal covers the clients that still ask this
  1005. // endpoint for a replacement token. Refusing is what lets them recover: any non-200
  1006. // sends them back through a full login.
  1007. func TestAuthHandler_GetInfo_RefusesRenewal(t *testing.T) {
  1008. token := url.QueryEscape(base64.URLEncoding.EncodeToString(signedCookieFor("ChattingChuck")))
  1009. handler := &AuthHandler{
  1010. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  1011. Logger: slog.Default(),
  1012. }
  1013. t.Run("a renewal request is refused even with a good token", func(t *testing.T) {
  1014. body := getInfoGET(handler, "&a="+token+"&renewToken=true").Body.String()
  1015. assert.Contains(t, body, `"statusCode":401`)
  1016. assert.Contains(t, body, `"redirectURL":`)
  1017. // Neither an answer nor a token: the caller is told to log in again.
  1018. assert.NotContains(t, body, "userData")
  1019. assert.NotContains(t, body, `"token"`)
  1020. })
  1021. t.Run("renewToken=false still gets an answer", func(t *testing.T) {
  1022. // Only an actual request to renew is refused. A client spelling out that
  1023. // it does not want one is asking the question this endpoint answers.
  1024. body := getInfoGET(handler, "&a="+token+"&renewToken=false").Body.String()
  1025. assert.Contains(t, body, `"statusCode":200`)
  1026. assert.Contains(t, body, `"loginId":"ChattingChuck"`)
  1027. })
  1028. t.Run("an ordinary request is unaffected", func(t *testing.T) {
  1029. body := getInfoGET(handler, "&a="+token).Body.String()
  1030. assert.Contains(t, body, `"statusCode":200`)
  1031. })
  1032. }