auth_handler_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "log/slog"
  7. "net/http"
  8. "net/http/httptest"
  9. "net/url"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/google/uuid"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/mk6i/open-oscar-server/config"
  16. "github.com/mk6i/open-oscar-server/state"
  17. "github.com/mk6i/open-oscar-server/wire"
  18. )
  19. // testAuthService implements AuthService for ClientLogin tests (only FLAPLogin and
  20. // CrackCookie are exercised).
  21. type testAuthService struct {
  22. flapLogin func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error)
  23. crackCookie func(authCookie []byte) (state.ServerCookie, time.Time, error)
  24. }
  25. func (t *testAuthService) BUCPChallenge(ctx context.Context, bodyIn wire.SNAC_0x17_0x06_BUCPChallengeRequest, newUUID func() uuid.UUID) (wire.SNACMessage, error) {
  26. return wire.SNACMessage{}, nil
  27. }
  28. func (t *testAuthService) BUCPLogin(ctx context.Context, bodyIn wire.SNAC_0x17_0x02_BUCPLoginRequest, endpointCfg config.Endpoint) (wire.SNACMessage, error) {
  29. return wire.SNACMessage{}, nil
  30. }
  31. func (t *testAuthService) CrackCookie(authCookie []byte) (state.ServerCookie, time.Time, error) {
  32. if t.crackCookie != nil {
  33. return t.crackCookie(authCookie)
  34. }
  35. return state.ServerCookie{}, time.Now().Add(shortTermTTL), nil
  36. }
  37. // signedCookieFor stands in for a CookieBaker-signed cookie naming screenName.
  38. func signedCookieFor(screenName string) []byte {
  39. return []byte("signed:" + screenName)
  40. }
  41. // crackSignedCookie accepts only cookies produced by signedCookieFor, standing in
  42. // for the signature check the real baker performs. The token reads as freshly
  43. // minted; crackSignedCookieExpiring stands in for an older one.
  44. func crackSignedCookie(authCookie []byte) (state.ServerCookie, time.Time, error) {
  45. return crackSignedCookieExpiring(shortTermTTL)(authCookie)
  46. }
  47. // crackSignedCookieExpiring cracks like crackSignedCookie, reporting a token
  48. // with remaining life left on it.
  49. func crackSignedCookieExpiring(remaining time.Duration) func([]byte) (state.ServerCookie, time.Time, error) {
  50. return func(authCookie []byte) (state.ServerCookie, time.Time, error) {
  51. name, ok := strings.CutPrefix(string(authCookie), "signed:")
  52. if !ok {
  53. return state.ServerCookie{}, time.Time{}, errors.New("bad signature")
  54. }
  55. return state.ServerCookie{ScreenName: state.DisplayScreenName(name)}, time.Now().Add(remaining), nil
  56. }
  57. }
  58. func (t *testAuthService) RegisterBOSSession(ctx context.Context, authCookie state.ServerCookie, conf func(sess *state.Session)) (*state.SessionInstance, error) {
  59. return nil, nil
  60. }
  61. func (t *testAuthService) FLAPLogin(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  62. if t.flapLogin != nil {
  63. return t.flapLogin(ctx, inFrame, endpointCfg)
  64. }
  65. return wire.TLVRestBlock{}, nil
  66. }
  67. func (t *testAuthService) Signout(ctx context.Context, session *state.Session) {}
  68. func (t *testAuthService) SignoutChat(ctx context.Context, sess *state.Session) {}
  69. func successfulLoginBlock() wire.TLVRestBlock {
  70. var b wire.TLVRestBlock
  71. b.Append(wire.NewTLVBE(wire.LoginTLVTagsAuthorizationCookie, loginBlockCookie))
  72. return b
  73. }
  74. // loginBlockCookie is the cookie successfulLoginBlock reports as minted by the auth
  75. // service. Handlers must hand this exact value back rather than mint their own.
  76. var loginBlockCookie = signedCookieFor("testuser")
  77. // blockWithoutCookie is a login response that reports neither an error nor a cookie.
  78. func blockWithoutCookie() wire.TLVRestBlock {
  79. var b wire.TLVRestBlock
  80. b.Append(wire.NewTLVBE(wire.LoginTLVTagsScreenName, "testuser"))
  81. return b
  82. }
  83. func failedLoginBlock() wire.TLVRestBlock {
  84. var b wire.TLVRestBlock
  85. b.Append(wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, uint16(1)))
  86. return b
  87. }
  88. func TestAuthHandler_GetToken(t *testing.T) {
  89. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("testuser"))
  90. tests := []struct {
  91. name string
  92. query string
  93. // remaining is the life left in the parked token; 0 means a fresh one.
  94. remaining time.Duration
  95. cookies []*http.Cookie
  96. checkBody func(*testing.T, string)
  97. }{
  98. {
  99. name: "Success_TokenCookie",
  100. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._0mq8wqdav",
  101. cookies: []*http.Cookie{
  102. {Name: bosTokenCookie, Value: validToken},
  103. },
  104. checkBody: func(t *testing.T, body string) {
  105. assert.Contains(t, body, "_callbacks_._0mq8wqdav(")
  106. assert.Contains(t, body, `"statusCode":200`)
  107. assert.Contains(t, body, `"loginId":"testuser"`)
  108. // The parked token is handed straight back, not re-minted.
  109. assert.Contains(t, body, `"a":"`+validToken+`"`)
  110. assert.Contains(t, body, `"expiresIn":"86400"`)
  111. },
  112. },
  113. {
  114. // getToken hands back the token minted at sign-in, so a browser that
  115. // sat on it for most of a day must be told the life that is actually
  116. // left, not the life the token was born with.
  117. name: "Success_AgedTokenReportsRemainingLife",
  118. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._0mq8wqdav",
  119. remaining: time.Hour,
  120. cookies: []*http.Cookie{
  121. {Name: bosTokenCookie, Value: validToken},
  122. },
  123. checkBody: func(t *testing.T, body string) {
  124. assert.Contains(t, body, `"statusCode":200`)
  125. assert.Contains(t, body, `"expiresIn":"3600"`)
  126. assert.NotContains(t, body, `"expiresIn":"86400"`)
  127. },
  128. },
  129. {
  130. name: "Unauthorized_NoCookie",
  131. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._abc",
  132. checkBody: func(t *testing.T, body string) {
  133. assert.Contains(t, body, `"statusCode":401`)
  134. assert.Contains(t, body, `"redirectURL"`)
  135. },
  136. },
  137. {
  138. // A token past its brief life no longer cracks, which is what makes a
  139. // later visit sign in again.
  140. name: "Unauthorized_UnsignedToken",
  141. query: "f=json&attributes=loginId&devId=dev123&c=_callbacks_._xyz",
  142. cookies: []*http.Cookie{
  143. {Name: bosTokenCookie, Value: base64.URLEncoding.EncodeToString([]byte("victim"))},
  144. },
  145. checkBody: func(t *testing.T, body string) {
  146. assert.Contains(t, body, `"statusCode":401`)
  147. assert.Contains(t, body, `"redirectURL"`)
  148. assert.NotContains(t, body, "victim")
  149. },
  150. },
  151. {
  152. // The screen name comes only from a signature-verified token, so these
  153. // forgeable plaintext cookies must not authenticate anyone.
  154. name: "Unauthorized_ForgedSSOCookies",
  155. query: "f=json&attributes=loginId&devId=dev123&c=_callbacks_._xyz",
  156. cookies: []*http.Cookie{
  157. {Name: "RSP_USER", Value: "victim"},
  158. {Name: "RSP_LOCAL", Value: "victim"},
  159. {Name: "localAuthUser", Value: "victim||victim"},
  160. },
  161. checkBody: func(t *testing.T, body string) {
  162. assert.Contains(t, body, `"statusCode":401`)
  163. assert.Contains(t, body, `"redirectURL"`)
  164. assert.NotContains(t, body, "victim")
  165. },
  166. },
  167. }
  168. for _, tt := range tests {
  169. t.Run(tt.name, func(t *testing.T) {
  170. crack := crackSignedCookie
  171. if tt.remaining > 0 {
  172. crack = crackSignedCookieExpiring(tt.remaining)
  173. }
  174. handler := &AuthHandler{
  175. AuthService: &testAuthService{crackCookie: crack},
  176. Logger: slog.Default(),
  177. }
  178. req, err := http.NewRequest(http.MethodGet, "/auth/getToken?"+tt.query, nil)
  179. assert.NoError(t, err)
  180. for _, c := range tt.cookies {
  181. req.AddCookie(c)
  182. }
  183. rr := httptest.NewRecorder()
  184. handler.GetToken(rr, req)
  185. assert.Equal(t, http.StatusOK, rr.Code)
  186. tt.checkBody(t, rr.Body.String())
  187. // Spent either way, so a reload has nothing to sign in with.
  188. assert.True(t, tokenCookieCleared(rr), "getToken should expire the token cookie")
  189. })
  190. }
  191. }
  192. // tokenCookieCleared reports whether the response expires the token cookie.
  193. func tokenCookieCleared(rr *httptest.ResponseRecorder) bool {
  194. for _, c := range rr.Result().Cookies() {
  195. if c.Name == bosTokenCookie && c.MaxAge < 0 {
  196. return true
  197. }
  198. }
  199. return false
  200. }
  201. // A second getToken must fail even inside the token's own lifetime: the cookie is
  202. // gone after the first, so every reload lands on the login page.
  203. func TestAuthHandler_GetToken_IsOneShot(t *testing.T) {
  204. handler := &AuthHandler{
  205. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  206. Logger: slog.Default(),
  207. }
  208. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("testuser"))
  209. get := func(withCookie bool) string {
  210. req := httptest.NewRequest(http.MethodGet, "/auth/getToken?f=json&attributes=loginId&devId=dev1", nil)
  211. if withCookie {
  212. req.AddCookie(&http.Cookie{Name: bosTokenCookie, Value: validToken})
  213. }
  214. rr := httptest.NewRecorder()
  215. handler.GetToken(rr, req)
  216. return rr.Body.String()
  217. }
  218. assert.Contains(t, get(true), `"statusCode":200`)
  219. // The browser dropped the cookie, so the follow-up presents nothing.
  220. assert.Contains(t, get(false), `"statusCode":401`)
  221. }
  222. func TestAuthHandler_ClientLogin(t *testing.T) {
  223. tests := []struct {
  224. name string
  225. method string
  226. contentType string
  227. body string
  228. // query is appended to the request URL, to prove it is not read.
  229. query string
  230. auth *testAuthService
  231. expectedStatusCode int
  232. checkResponse func(*testing.T, string)
  233. }{
  234. {
  235. name: "Success_FormEncoded",
  236. method: "POST",
  237. contentType: "application/x-www-form-urlencoded",
  238. body: "s=testuser&pwd=testpass&devId=dev123",
  239. auth: &testAuthService{
  240. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  241. return successfulLoginBlock(), nil
  242. },
  243. },
  244. expectedStatusCode: http.StatusOK,
  245. checkResponse: func(t *testing.T, body string) {
  246. assert.Contains(t, body, `"statusCode":200`)
  247. // The token is the cookie the auth service minted, not a re-mint.
  248. assert.Contains(t, body, `"a":"`+base64.URLEncoding.EncodeToString(loginBlockCookie)+`"`)
  249. assert.Contains(t, body, `"loginId":"testuser"`)
  250. assert.Contains(t, body, `"screenName":"testuser"`)
  251. assert.Contains(t, body, `"token"`)
  252. assert.Contains(t, body, `"sessionSecret"`)
  253. },
  254. },
  255. {
  256. // The legacy aliases the form path has always accepted alongside the
  257. // spec's s and pwd.
  258. name: "Success_LegacyFieldNames",
  259. method: "POST",
  260. contentType: "application/x-www-form-urlencoded",
  261. body: "username=testuser&password=testpass&devId=dev123",
  262. auth: &testAuthService{
  263. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  264. return successfulLoginBlock(), nil
  265. },
  266. },
  267. expectedStatusCode: http.StatusOK,
  268. checkResponse: func(t *testing.T, body string) {
  269. assert.Contains(t, body, `"statusCode":200`)
  270. assert.Contains(t, body, `"loginId":"testuser"`)
  271. },
  272. },
  273. {
  274. // "longterm" is a year, and the response reports what was granted.
  275. name: "Success_TokenTypeLongterm",
  276. method: "POST",
  277. contentType: "application/x-www-form-urlencoded",
  278. body: "s=testuser&pwd=testpass&devId=dev123&tokenType=longterm",
  279. auth: &testAuthService{
  280. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  281. return successfulLoginBlock(), nil
  282. },
  283. },
  284. expectedStatusCode: http.StatusOK,
  285. checkResponse: func(t *testing.T, body string) {
  286. assert.Contains(t, body, `"statusCode":200`)
  287. assert.Contains(t, body, `"expiresIn":"31536000"`)
  288. assert.Contains(t, body, `"tokenExpiresIn":31536000`)
  289. },
  290. },
  291. {
  292. // A bare count of seconds is a valid tokenType.
  293. name: "Success_TokenTypeSeconds",
  294. method: "POST",
  295. contentType: "application/x-www-form-urlencoded",
  296. body: "s=testuser&pwd=testpass&devId=dev123&tokenType=3600",
  297. auth: &testAuthService{
  298. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  299. return successfulLoginBlock(), nil
  300. },
  301. },
  302. expectedStatusCode: http.StatusOK,
  303. checkResponse: func(t *testing.T, body string) {
  304. assert.Contains(t, body, `"statusCode":200`)
  305. assert.Contains(t, body, `"expiresIn":"3600"`)
  306. assert.Contains(t, body, `"tokenExpiresIn":3600`)
  307. },
  308. },
  309. {
  310. // Omitting tokenType is "shortterm", a day.
  311. name: "Success_TokenTypeDefaultsToShortterm",
  312. method: "POST",
  313. contentType: "application/x-www-form-urlencoded",
  314. body: "s=testuser&pwd=testpass&devId=dev123",
  315. auth: &testAuthService{
  316. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  317. return successfulLoginBlock(), nil
  318. },
  319. },
  320. expectedStatusCode: http.StatusOK,
  321. checkResponse: func(t *testing.T, body string) {
  322. assert.Contains(t, body, `"expiresIn":"86400"`)
  323. assert.Contains(t, body, `"tokenExpiresIn":86400`)
  324. },
  325. },
  326. {
  327. // A tokenType the server cannot honour is a parameter error, and the
  328. // credentials are never checked.
  329. name: "Error_TokenTypeUnparsable",
  330. method: "POST",
  331. contentType: "application/x-www-form-urlencoded",
  332. body: "s=testuser&pwd=testpass&tokenType=forever",
  333. auth: &testAuthService{},
  334. expectedStatusCode: http.StatusBadRequest,
  335. checkResponse: func(t *testing.T, body string) {
  336. assert.Contains(t, body, `"statusCode":462`)
  337. },
  338. },
  339. {
  340. name: "Error_TokenTypeBeyondMax",
  341. method: "POST",
  342. contentType: "application/x-www-form-urlencoded",
  343. body: "s=testuser&pwd=testpass&tokenType=31536001",
  344. auth: &testAuthService{},
  345. expectedStatusCode: http.StatusBadRequest,
  346. checkResponse: func(t *testing.T, body string) {
  347. assert.Contains(t, body, `"statusCode":462`)
  348. },
  349. },
  350. {
  351. // The spec puts these in the body, and a password in a URL is one
  352. // that has already been logged. Credentials in the query string are
  353. // not credentials at all.
  354. name: "Error_CredentialsInQueryStringAreIgnored",
  355. method: "POST",
  356. contentType: "application/x-www-form-urlencoded",
  357. body: "",
  358. query: "?s=testuser&pwd=testpass&devId=dev123",
  359. auth: &testAuthService{},
  360. expectedStatusCode: http.StatusBadRequest,
  361. checkResponse: func(t *testing.T, body string) {
  362. assert.Contains(t, body, `"statusCode":460`)
  363. },
  364. },
  365. {
  366. // A body value stands on its own; the query is not consulted even to
  367. // fill a gap.
  368. name: "Success_BodyWinsOverQueryString",
  369. method: "POST",
  370. contentType: "application/x-www-form-urlencoded",
  371. body: "s=testuser&pwd=testpass&tokenType=longterm",
  372. query: "?tokenType=600",
  373. auth: &testAuthService{
  374. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  375. return successfulLoginBlock(), nil
  376. },
  377. },
  378. expectedStatusCode: http.StatusOK,
  379. checkResponse: func(t *testing.T, body string) {
  380. assert.Contains(t, body, `"expiresIn":"31536000"`)
  381. },
  382. },
  383. {
  384. name: "Error_MissingUsername",
  385. method: "POST",
  386. contentType: "application/x-www-form-urlencoded",
  387. body: "pwd=testpass",
  388. auth: &testAuthService{},
  389. expectedStatusCode: http.StatusBadRequest,
  390. checkResponse: func(t *testing.T, body string) {
  391. // The code a client reads as "you left something out", which is
  392. // not the code that means the credentials were wrong.
  393. assert.Contains(t, body, `"statusCode":460`)
  394. assert.NotContains(t, body, "statusDetailCode")
  395. assert.Contains(t, body, "username and password required")
  396. },
  397. },
  398. {
  399. name: "Error_MissingPassword",
  400. method: "POST",
  401. contentType: "application/x-www-form-urlencoded",
  402. body: "s=testuser",
  403. auth: &testAuthService{},
  404. expectedStatusCode: http.StatusBadRequest,
  405. checkResponse: func(t *testing.T, body string) {
  406. assert.Contains(t, body, `"statusCode":460`)
  407. assert.Contains(t, body, "username and password required")
  408. },
  409. },
  410. {
  411. name: "Error_AuthFailed",
  412. method: "POST",
  413. contentType: "application/x-www-form-urlencoded",
  414. body: "s=testuser&pwd=wrongpass",
  415. auth: &testAuthService{
  416. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  417. return failedLoginBlock(), nil
  418. },
  419. },
  420. expectedStatusCode: http.StatusUnauthorized,
  421. checkResponse: func(t *testing.T, body string) {
  422. // The codes a client maps to "incorrect password".
  423. assert.Contains(t, body, `"statusCode":330`)
  424. assert.Contains(t, body, `"statusDetailCode":3011`)
  425. },
  426. },
  427. {
  428. name: "Error_FLAPLoginError",
  429. method: "POST",
  430. contentType: "application/x-www-form-urlencoded",
  431. body: "s=testuser&pwd=testpass",
  432. auth: &testAuthService{
  433. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  434. return wire.TLVRestBlock{}, errors.New("boom")
  435. },
  436. },
  437. expectedStatusCode: http.StatusInternalServerError,
  438. checkResponse: func(t *testing.T, body string) {
  439. assert.Contains(t, body, "internal server error")
  440. },
  441. },
  442. {
  443. // A POST carries "f" in its body, the only place clientLogin states it.
  444. name: "Error_AuthFailed_XMLRequestedInBody",
  445. method: "POST",
  446. contentType: "application/x-www-form-urlencoded",
  447. body: "s=testuser&pwd=wrongpass&f=xml",
  448. auth: &testAuthService{
  449. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  450. return failedLoginBlock(), nil
  451. },
  452. },
  453. expectedStatusCode: http.StatusUnauthorized,
  454. checkResponse: func(t *testing.T, body string) {
  455. assert.Contains(t, body, "<statusCode>330</statusCode>")
  456. assert.Contains(t, body, "<statusDetailCode>3011</statusDetailCode>")
  457. },
  458. },
  459. {
  460. name: "Error_LoginResponseHasNoCookie",
  461. method: "POST",
  462. contentType: "application/x-www-form-urlencoded",
  463. body: "s=testuser&pwd=testpass",
  464. auth: &testAuthService{
  465. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  466. return blockWithoutCookie(), nil
  467. },
  468. },
  469. expectedStatusCode: http.StatusInternalServerError,
  470. checkResponse: func(t *testing.T, body string) {
  471. assert.Contains(t, body, "internal server error")
  472. },
  473. },
  474. }
  475. for _, tt := range tests {
  476. t.Run(tt.name, func(t *testing.T) {
  477. logger := slog.Default()
  478. handler := &AuthHandler{
  479. AuthService: tt.auth,
  480. Logger: logger,
  481. }
  482. req, err := http.NewRequest(tt.method, "/auth/clientLogin"+tt.query, strings.NewReader(tt.body))
  483. assert.NoError(t, err)
  484. req.Header.Set("Content-Type", tt.contentType)
  485. rr := httptest.NewRecorder()
  486. handler.ClientLogin(rr, req)
  487. assert.Equal(t, tt.expectedStatusCode, rr.Code)
  488. responseBody := strings.TrimSpace(rr.Body.String())
  489. if tt.checkResponse != nil {
  490. tt.checkResponse(t, responseBody)
  491. }
  492. })
  493. }
  494. }
  495. func TestAuthHandler_ClientLogin_SendsClientIdentity(t *testing.T) {
  496. tests := []struct {
  497. name string
  498. body string
  499. expectedClientID string
  500. }{
  501. {
  502. name: "DevIDNamesTheClient",
  503. body: "s=testuser&pwd=testpass&devId=dev123",
  504. expectedClientID: "dev123",
  505. },
  506. {
  507. name: "MissingDevIDFallsBack",
  508. body: "s=testuser&pwd=testpass",
  509. expectedClientID: "WebAIM",
  510. },
  511. }
  512. for _, tt := range tests {
  513. t.Run(tt.name, func(t *testing.T) {
  514. var got wire.FLAPSignonFrame
  515. handler := &AuthHandler{
  516. AuthService: &testAuthService{
  517. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  518. got = inFrame
  519. return successfulLoginBlock(), nil
  520. },
  521. },
  522. Logger: slog.Default(),
  523. }
  524. req := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader(tt.body))
  525. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  526. handler.ClientLogin(httptest.NewRecorder(), req)
  527. clientID, ok := got.String(wire.LoginTLVTagsClientIdentity)
  528. assert.True(t, ok, "signon frame should carry a client identity")
  529. assert.Equal(t, tt.expectedClientID, clientID)
  530. })
  531. }
  532. }
  533. func TestAuthHandler_ClientLogin_SendsRequestedTokenTTL(t *testing.T) {
  534. tests := []struct {
  535. name string
  536. body string
  537. wantTTL uint32
  538. }{
  539. {
  540. name: "OmittedIsShortterm",
  541. body: "s=testuser&pwd=testpass",
  542. wantTTL: 86400,
  543. },
  544. {
  545. name: "Shortterm",
  546. body: "s=testuser&pwd=testpass&tokenType=shortterm",
  547. wantTTL: 86400,
  548. },
  549. {
  550. name: "Longterm",
  551. body: "s=testuser&pwd=testpass&tokenType=longterm",
  552. wantTTL: 31536000,
  553. },
  554. {
  555. name: "ExplicitSeconds",
  556. body: "s=testuser&pwd=testpass&tokenType=600",
  557. wantTTL: 600,
  558. },
  559. }
  560. for _, tt := range tests {
  561. t.Run(tt.name, func(t *testing.T) {
  562. var got wire.FLAPSignonFrame
  563. handler := &AuthHandler{
  564. AuthService: &testAuthService{
  565. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  566. got = inFrame
  567. return successfulLoginBlock(), nil
  568. },
  569. },
  570. Logger: slog.Default(),
  571. }
  572. req := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader(tt.body))
  573. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  574. handler.ClientLogin(httptest.NewRecorder(), req)
  575. // What the client asked for is what login is asked to mint.
  576. ttl, ok := got.Uint32BE(wire.LoginTLVTagsTokenTTL)
  577. assert.True(t, ok, "signon frame should carry a token TTL")
  578. assert.Equal(t, tt.wantTTL, ttl)
  579. })
  580. }
  581. }
  582. func TestTokenTypeTTL(t *testing.T) {
  583. tests := []struct {
  584. name string
  585. tokenType string
  586. want time.Duration
  587. wantErr bool
  588. }{
  589. {name: "omitted", tokenType: "", want: shortTermTTL},
  590. {name: "shortterm", tokenType: "shortterm", want: shortTermTTL},
  591. {name: "shortterm mixed case", tokenType: "ShortTerm", want: shortTermTTL},
  592. {name: "longterm", tokenType: "longterm", want: longTermTTL},
  593. {name: "longterm padded", tokenType: " longterm ", want: longTermTTL},
  594. {name: "seconds", tokenType: "3600", want: time.Hour},
  595. {name: "one second", tokenType: "1", want: time.Second},
  596. {name: "exactly the max", tokenType: "31536000", want: longTermTTL},
  597. {name: "zero seconds", tokenType: "0", wantErr: true},
  598. {name: "one past the max", tokenType: "31536001", wantErr: true},
  599. // large enough that scaling to a Duration would overflow int64
  600. {name: "overflowing seconds", tokenType: "99999999999999999", wantErr: true},
  601. {name: "negative", tokenType: "-1", wantErr: true},
  602. {name: "unrecognized word", tokenType: "forever", wantErr: true},
  603. {name: "float", tokenType: "60.5", wantErr: true},
  604. }
  605. for _, tt := range tests {
  606. t.Run(tt.name, func(t *testing.T) {
  607. got, err := tokenTypeTTL(tt.tokenType)
  608. if tt.wantErr {
  609. assert.Error(t, err)
  610. return
  611. }
  612. assert.NoError(t, err)
  613. assert.Equal(t, tt.want, got)
  614. })
  615. }
  616. }
  617. func TestAuthHandler_LoginPSP_GET(t *testing.T) {
  618. handler := &AuthHandler{Logger: slog.Default()}
  619. req := httptest.NewRequest(http.MethodGet, "/_cqr/login/login.psp?devId=dev1&succUrl=http%3A%2F%2Flocalhost%3A8000%2F", nil)
  620. rr := httptest.NewRecorder()
  621. handler.LoginPSP(rr, req)
  622. assert.Equal(t, http.StatusOK, rr.Code)
  623. assert.Contains(t, rr.Header().Get("Content-Type"), "text/html")
  624. assert.Contains(t, rr.Body.String(), "AIM Sign In")
  625. assert.Contains(t, rr.Body.String(), `name="devId" value="dev1"`)
  626. }
  627. func TestAuthHandler_Logout(t *testing.T) {
  628. handler := &AuthHandler{Logger: slog.Default()}
  629. req := httptest.NewRequest(http.MethodGet, "/auth/logout?f=json&a=sometoken&devId=dev1&succUrl=http%3A%2F%2Flocalhost%3A8000%2F.client%2F", nil)
  630. rr := httptest.NewRecorder()
  631. handler.Logout(rr, req)
  632. assert.Equal(t, http.StatusFound, rr.Code)
  633. loc, err := url.Parse(rr.Header().Get("Location"))
  634. assert.NoError(t, err)
  635. assert.Equal(t, "/_cqr/login/login.psp", loc.Path)
  636. assert.Equal(t, "dev1", loc.Query().Get("devId"))
  637. assert.Equal(t, "http://localhost:8000/.client/", loc.Query().Get("succUrl"))
  638. // Signing out spends the token cookie, whether or not getToken already did.
  639. // A 24h token left behind would sign the next person in as this account.
  640. cleared := rr.Result().Cookies()
  641. if assert.Len(t, cleared, 1) {
  642. assert.Equal(t, bosTokenCookie, cleared[0].Name)
  643. assert.Empty(t, cleared[0].Value)
  644. assert.Less(t, cleared[0].MaxAge, 1)
  645. }
  646. }
  647. func TestAuthHandler_LoginPSP_POST_Success(t *testing.T) {
  648. var got wire.FLAPSignonFrame
  649. handler := &AuthHandler{
  650. AuthService: &testAuthService{
  651. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  652. got = inFrame
  653. return successfulLoginBlock(), nil
  654. },
  655. },
  656. Logger: slog.Default(),
  657. }
  658. form := url.Values{}
  659. form.Set("loginId", "testuser")
  660. form.Set("password", "secret")
  661. form.Set("devId", "dev1")
  662. form.Set("succUrl", "http://localhost:8000/")
  663. req := httptest.NewRequest(http.MethodPost, "/_cqr/login/login.psp", strings.NewReader(form.Encode()))
  664. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  665. rr := httptest.NewRecorder()
  666. handler.LoginPSP(rr, req)
  667. assert.Equal(t, http.StatusFound, rr.Code)
  668. assert.Equal(t, "http://localhost:8000/", rr.Header().Get("Location"))
  669. set := make(map[string]*http.Cookie)
  670. for _, c := range rr.Result().Cookies() {
  671. set[c.Name] = c
  672. }
  673. // The cookie carries the BOS token from the login response, unchanged.
  674. tokenCookie := set[bosTokenCookie]
  675. if assert.NotNil(t, tokenCookie) {
  676. assert.True(t, tokenCookie.HttpOnly)
  677. raw, err := base64.URLEncoding.DecodeString(tokenCookie.Value)
  678. assert.NoError(t, err)
  679. assert.Equal(t, loginBlockCookie, raw)
  680. // The browser drops it on the same schedule the server stops honouring it.
  681. assert.Equal(t, 86400, tokenCookie.MaxAge)
  682. }
  683. for _, name := range []string{"RSP_USER", "RSP_LOCAL", "localAuthUser"} {
  684. assert.NotContains(t, set, name)
  685. }
  686. // The Web API asks login for a token that outlives the browser round trip.
  687. ttl, ok := got.Uint32BE(wire.LoginTLVTagsTokenTTL)
  688. assert.True(t, ok)
  689. assert.Equal(t, uint32(86400), ttl)
  690. // The devId names the client on the resulting session.
  691. clientID, ok := got.String(wire.LoginTLVTagsClientIdentity)
  692. assert.True(t, ok, "signon frame should carry a client identity")
  693. assert.Equal(t, "dev1", clientID)
  694. }
  695. func TestAuthHandler_LoginPSP_POST_ServiceErrors(t *testing.T) {
  696. tests := []struct {
  697. name string
  698. flapLogin func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error)
  699. }{
  700. {
  701. name: "LoginResponseHasNoCookie",
  702. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  703. return blockWithoutCookie(), nil
  704. },
  705. },
  706. {
  707. name: "AuthServiceUnreachable",
  708. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  709. return wire.TLVRestBlock{}, errors.New("boom")
  710. },
  711. },
  712. }
  713. for _, tt := range tests {
  714. t.Run(tt.name, func(t *testing.T) {
  715. handler := &AuthHandler{
  716. AuthService: &testAuthService{flapLogin: tt.flapLogin},
  717. Logger: slog.Default(),
  718. }
  719. form := url.Values{}
  720. form.Set("loginId", "testuser")
  721. form.Set("password", "secret")
  722. req := httptest.NewRequest(http.MethodPost, "/_cqr/login/login.psp", strings.NewReader(form.Encode()))
  723. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  724. rr := httptest.NewRecorder()
  725. handler.LoginPSP(rr, req)
  726. // A broken auth service must not read as a mistyped password.
  727. assert.Equal(t, http.StatusInternalServerError, rr.Code)
  728. assert.NotContains(t, rr.Body.String(), "Invalid screen name or password")
  729. assert.Empty(t, rr.Result().Cookies())
  730. })
  731. }
  732. }
  733. func TestAuthHandler_LoginPSP_POST_InvalidCredentials(t *testing.T) {
  734. handler := &AuthHandler{
  735. AuthService: &testAuthService{
  736. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error) {
  737. return failedLoginBlock(), nil
  738. },
  739. },
  740. Logger: slog.Default(),
  741. }
  742. form := url.Values{}
  743. form.Set("loginId", "testuser")
  744. form.Set("password", "wrong")
  745. req := httptest.NewRequest(http.MethodPost, "/_cqr/login/login.psp", strings.NewReader(form.Encode()))
  746. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  747. rr := httptest.NewRecorder()
  748. handler.LoginPSP(rr, req)
  749. assert.Equal(t, http.StatusOK, rr.Code)
  750. assert.Contains(t, rr.Body.String(), "Invalid screen name or password")
  751. }
  752. func TestDefaultLoginSuccURL(t *testing.T) {
  753. req := httptest.NewRequest(http.MethodGet, "http://ras.dev/_cqr/login/login.psp", nil)
  754. assert.Equal(t, "http://ras.dev/", defaultLoginSuccURL(req))
  755. // TLS terminated upstream, so the scheme only survives in the header.
  756. req.Header.Set("X-Forwarded-Proto", "https")
  757. assert.Equal(t, "https://ras.dev/", defaultLoginSuccURL(req))
  758. }
  759. func TestSafeLoginRedirectURL(t *testing.T) {
  760. req := httptest.NewRequest(http.MethodGet, "http://localhost/_cqr/login/login.psp", nil)
  761. assert.Equal(t, "http://localhost:8000/", safeLoginRedirectURL(req, "http://localhost:8000/"))
  762. assert.Equal(t, "http://localhost/", safeLoginRedirectURL(req, "http://evil.example/"))
  763. }