auth_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package handlers
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "log/slog"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "github.com/google/uuid"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/mk6i/open-oscar-server/state"
  14. "github.com/mk6i/open-oscar-server/wire"
  15. )
  16. // testAuthService implements AuthService for ClientLogin tests (only FLAPLogin and
  17. // CrackCookie are exercised).
  18. type testAuthService struct {
  19. flapLogin func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error)
  20. crackCookie func(authCookie []byte) (state.ServerCookie, error)
  21. }
  22. func (t *testAuthService) BUCPChallenge(ctx context.Context, bodyIn wire.SNAC_0x17_0x06_BUCPChallengeRequest, newUUID func() uuid.UUID) (wire.SNACMessage, error) {
  23. return wire.SNACMessage{}, nil
  24. }
  25. func (t *testAuthService) BUCPLogin(ctx context.Context, bodyIn wire.SNAC_0x17_0x02_BUCPLoginRequest, advertisedHost string) (wire.SNACMessage, error) {
  26. return wire.SNACMessage{}, nil
  27. }
  28. func (t *testAuthService) CrackCookie(authCookie []byte) (state.ServerCookie, error) {
  29. if t.crackCookie != nil {
  30. return t.crackCookie(authCookie)
  31. }
  32. return state.ServerCookie{}, nil
  33. }
  34. // signedCookieFor stands in for a CookieBaker-signed cookie naming screenName.
  35. func signedCookieFor(screenName string) []byte {
  36. return []byte("signed:" + screenName)
  37. }
  38. // crackSignedCookie accepts only cookies produced by signedCookieFor, standing in
  39. // for the signature check the real baker performs.
  40. func crackSignedCookie(authCookie []byte) (state.ServerCookie, error) {
  41. name, ok := strings.CutPrefix(string(authCookie), "signed:")
  42. if !ok {
  43. return state.ServerCookie{}, errors.New("bad signature")
  44. }
  45. return state.ServerCookie{ScreenName: state.DisplayScreenName(name)}, nil
  46. }
  47. func (t *testAuthService) RegisterBOSSession(ctx context.Context, authCookie state.ServerCookie, conf func(sess *state.Session)) (*state.SessionInstance, error) {
  48. return nil, nil
  49. }
  50. func (t *testAuthService) FLAPLogin(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  51. if t.flapLogin != nil {
  52. return t.flapLogin(ctx, inFrame, advertisedHost)
  53. }
  54. return wire.TLVRestBlock{}, nil
  55. }
  56. func (t *testAuthService) Signout(ctx context.Context, session *state.Session) {}
  57. func (t *testAuthService) SignoutChat(ctx context.Context, sess *state.Session) {}
  58. func successfulLoginBlock() wire.TLVRestBlock {
  59. var b wire.TLVRestBlock
  60. b.Append(wire.NewTLVBE(wire.LoginTLVTagsAuthorizationCookie, loginBlockCookie))
  61. return b
  62. }
  63. // loginBlockCookie is the cookie successfulLoginBlock reports as minted by the auth
  64. // service. Handlers must hand this exact value back rather than mint their own.
  65. var loginBlockCookie = signedCookieFor("testuser")
  66. // blockWithoutCookie is a login response that reports neither an error nor a cookie.
  67. func blockWithoutCookie() wire.TLVRestBlock {
  68. var b wire.TLVRestBlock
  69. b.Append(wire.NewTLVBE(wire.LoginTLVTagsScreenName, "testuser"))
  70. return b
  71. }
  72. func failedLoginBlock() wire.TLVRestBlock {
  73. var b wire.TLVRestBlock
  74. b.Append(wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, uint16(1)))
  75. return b
  76. }
  77. func TestAuthHandler_GetToken(t *testing.T) {
  78. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("testuser"))
  79. tests := []struct {
  80. name string
  81. query string
  82. cookies []*http.Cookie
  83. checkBody func(*testing.T, string)
  84. }{
  85. {
  86. name: "Success_TokenCookie",
  87. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._0mq8wqdav",
  88. cookies: []*http.Cookie{
  89. {Name: bosTokenCookie, Value: validToken},
  90. },
  91. checkBody: func(t *testing.T, body string) {
  92. assert.Contains(t, body, "_callbacks_._0mq8wqdav(")
  93. assert.Contains(t, body, `"statusCode":200`)
  94. assert.Contains(t, body, `"loginId":"testuser"`)
  95. // The parked token is handed straight back, not re-minted.
  96. assert.Contains(t, body, `"a":"`+validToken+`"`)
  97. assert.Contains(t, body, `"expiresIn":"60"`)
  98. },
  99. },
  100. {
  101. name: "Unauthorized_NoCookie",
  102. query: "f=json&attributes=loginId&devId=ao1yOLlHVHhsa3o6&c=_callbacks_._abc",
  103. checkBody: func(t *testing.T, body string) {
  104. assert.Contains(t, body, `"statusCode":401`)
  105. assert.Contains(t, body, `"redirectURL"`)
  106. },
  107. },
  108. {
  109. // A token past its brief life no longer cracks, which is what makes a
  110. // later visit sign in again.
  111. name: "Unauthorized_UnsignedToken",
  112. query: "f=json&attributes=loginId&devId=dev123&c=_callbacks_._xyz",
  113. cookies: []*http.Cookie{
  114. {Name: bosTokenCookie, Value: base64.URLEncoding.EncodeToString([]byte("victim"))},
  115. },
  116. checkBody: func(t *testing.T, body string) {
  117. assert.Contains(t, body, `"statusCode":401`)
  118. assert.Contains(t, body, `"redirectURL"`)
  119. assert.NotContains(t, body, "victim")
  120. },
  121. },
  122. {
  123. // The screen name comes only from a signature-verified token, so these
  124. // forgeable plaintext cookies must not authenticate anyone.
  125. name: "Unauthorized_ForgedSSOCookies",
  126. query: "f=json&attributes=loginId&devId=dev123&c=_callbacks_._xyz",
  127. cookies: []*http.Cookie{
  128. {Name: "RSP_USER", Value: "victim"},
  129. {Name: "RSP_LOCAL", Value: "victim"},
  130. {Name: "localAuthUser", Value: "victim||victim"},
  131. },
  132. checkBody: func(t *testing.T, body string) {
  133. assert.Contains(t, body, `"statusCode":401`)
  134. assert.Contains(t, body, `"redirectURL"`)
  135. assert.NotContains(t, body, "victim")
  136. },
  137. },
  138. }
  139. for _, tt := range tests {
  140. t.Run(tt.name, func(t *testing.T) {
  141. handler := &AuthHandler{
  142. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  143. Logger: slog.Default(),
  144. }
  145. req, err := http.NewRequest(http.MethodGet, "/auth/getToken?"+tt.query, nil)
  146. assert.NoError(t, err)
  147. for _, c := range tt.cookies {
  148. req.AddCookie(c)
  149. }
  150. rr := httptest.NewRecorder()
  151. handler.GetToken(rr, req)
  152. assert.Equal(t, http.StatusOK, rr.Code)
  153. tt.checkBody(t, rr.Body.String())
  154. // Spent either way, so a reload has nothing to sign in with.
  155. assert.True(t, tokenCookieCleared(rr), "getToken should expire the token cookie")
  156. })
  157. }
  158. }
  159. // tokenCookieCleared reports whether the response expires the token cookie.
  160. func tokenCookieCleared(rr *httptest.ResponseRecorder) bool {
  161. for _, c := range rr.Result().Cookies() {
  162. if c.Name == bosTokenCookie && c.MaxAge < 0 {
  163. return true
  164. }
  165. }
  166. return false
  167. }
  168. // A second getToken must fail even inside the token's own lifetime: the cookie is
  169. // gone after the first, so every reload lands on the login page.
  170. func TestAuthHandler_GetToken_IsOneShot(t *testing.T) {
  171. handler := &AuthHandler{
  172. AuthService: &testAuthService{crackCookie: crackSignedCookie},
  173. Logger: slog.Default(),
  174. }
  175. validToken := base64.URLEncoding.EncodeToString(signedCookieFor("testuser"))
  176. get := func(withCookie bool) string {
  177. req := httptest.NewRequest(http.MethodGet, "/auth/getToken?f=json&attributes=loginId&devId=dev1", nil)
  178. if withCookie {
  179. req.AddCookie(&http.Cookie{Name: bosTokenCookie, Value: validToken})
  180. }
  181. rr := httptest.NewRecorder()
  182. handler.GetToken(rr, req)
  183. return rr.Body.String()
  184. }
  185. assert.Contains(t, get(true), `"statusCode":200`)
  186. // The browser dropped the cookie, so the follow-up presents nothing.
  187. assert.Contains(t, get(false), `"statusCode":401`)
  188. }
  189. func TestAuthHandler_ClientLogin(t *testing.T) {
  190. tests := []struct {
  191. name string
  192. method string
  193. contentType string
  194. body string
  195. auth *testAuthService
  196. expectedStatusCode int
  197. checkResponse func(*testing.T, string)
  198. }{
  199. {
  200. name: "Success_JSONBody",
  201. method: "POST",
  202. contentType: "application/json",
  203. body: `{"username":"testuser","password":"testpass","devId":"dev123"}`,
  204. auth: &testAuthService{
  205. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  206. return successfulLoginBlock(), nil
  207. },
  208. },
  209. expectedStatusCode: http.StatusOK,
  210. checkResponse: func(t *testing.T, body string) {
  211. assert.Contains(t, body, `"statusCode":200`)
  212. // The token is the cookie the auth service minted, not a re-mint.
  213. assert.Contains(t, body, `"a":"`+base64.URLEncoding.EncodeToString(loginBlockCookie)+`"`)
  214. assert.Contains(t, body, `"loginId":"testuser"`)
  215. assert.Contains(t, body, `"screenName":"testuser"`)
  216. assert.Contains(t, body, `"token"`)
  217. assert.Contains(t, body, `"sessionSecret"`)
  218. },
  219. },
  220. {
  221. // A caller that states a charset is still sending JSON.
  222. name: "Success_JSONBodyWithCharset",
  223. method: "POST",
  224. contentType: "application/json; charset=utf-8",
  225. body: `{"username":"testuser","password":"testpass","devId":"dev123"}`,
  226. auth: &testAuthService{
  227. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  228. return successfulLoginBlock(), nil
  229. },
  230. },
  231. expectedStatusCode: http.StatusOK,
  232. checkResponse: func(t *testing.T, body string) {
  233. assert.Contains(t, body, `"statusCode":200`)
  234. assert.Contains(t, body, `"loginId":"testuser"`)
  235. },
  236. },
  237. {
  238. name: "Success_FormEncoded",
  239. method: "POST",
  240. contentType: "application/x-www-form-urlencoded",
  241. body: "s=testuser&pwd=testpass&devId=dev123",
  242. auth: &testAuthService{
  243. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  244. return successfulLoginBlock(), nil
  245. },
  246. },
  247. expectedStatusCode: http.StatusOK,
  248. checkResponse: func(t *testing.T, body string) {
  249. assert.Contains(t, body, `"statusCode":200`)
  250. assert.Contains(t, body, `"loginId":"testuser"`)
  251. },
  252. },
  253. {
  254. name: "Error_MissingUsername",
  255. method: "POST",
  256. contentType: "application/json",
  257. body: `{"username":"","password":"testpass"}`,
  258. auth: &testAuthService{},
  259. expectedStatusCode: http.StatusBadRequest,
  260. checkResponse: func(t *testing.T, body string) {
  261. // The code a client reads as "you left something out", which is
  262. // not the code that means the credentials were wrong.
  263. assert.Contains(t, body, `"statusCode":460`)
  264. assert.NotContains(t, body, "statusDetailCode")
  265. assert.Contains(t, body, "username and password required")
  266. },
  267. },
  268. {
  269. name: "Error_MissingPassword",
  270. method: "POST",
  271. contentType: "application/json",
  272. body: `{"username":"testuser","password":""}`,
  273. auth: &testAuthService{},
  274. expectedStatusCode: http.StatusBadRequest,
  275. checkResponse: func(t *testing.T, body string) {
  276. assert.Contains(t, body, `"statusCode":460`)
  277. assert.Contains(t, body, "username and password required")
  278. },
  279. },
  280. {
  281. name: "Error_AuthFailed",
  282. method: "POST",
  283. contentType: "application/json",
  284. body: `{"username":"testuser","password":"wrongpass"}`,
  285. auth: &testAuthService{
  286. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  287. return failedLoginBlock(), nil
  288. },
  289. },
  290. expectedStatusCode: http.StatusUnauthorized,
  291. checkResponse: func(t *testing.T, body string) {
  292. // The codes a client maps to "incorrect password".
  293. assert.Contains(t, body, `"statusCode":330`)
  294. assert.Contains(t, body, `"statusDetailCode":3011`)
  295. },
  296. },
  297. {
  298. name: "Error_FLAPLoginError",
  299. method: "POST",
  300. contentType: "application/json",
  301. body: `{"username":"testuser","password":"testpass"}`,
  302. auth: &testAuthService{
  303. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  304. return wire.TLVRestBlock{}, errors.New("boom")
  305. },
  306. },
  307. expectedStatusCode: http.StatusInternalServerError,
  308. checkResponse: func(t *testing.T, body string) {
  309. assert.Contains(t, body, "internal server error")
  310. },
  311. },
  312. {
  313. name: "Error_InvalidJSON",
  314. method: "POST",
  315. contentType: "application/json",
  316. body: `{invalid json`,
  317. auth: &testAuthService{},
  318. expectedStatusCode: http.StatusBadRequest,
  319. checkResponse: func(t *testing.T, body string) {
  320. assert.Contains(t, body, "invalid JSON format")
  321. },
  322. },
  323. {
  324. // A POST carries "f" in its body, the only place clientLogin states it.
  325. name: "Error_AuthFailed_XMLRequestedInBody",
  326. method: "POST",
  327. contentType: "application/x-www-form-urlencoded",
  328. body: "s=testuser&pwd=wrongpass&f=xml",
  329. auth: &testAuthService{
  330. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  331. return failedLoginBlock(), nil
  332. },
  333. },
  334. expectedStatusCode: http.StatusUnauthorized,
  335. checkResponse: func(t *testing.T, body string) {
  336. assert.Contains(t, body, "<statusCode>330</statusCode>")
  337. assert.Contains(t, body, "<statusDetailCode>3011</statusDetailCode>")
  338. },
  339. },
  340. {
  341. name: "Error_LoginResponseHasNoCookie",
  342. method: "POST",
  343. contentType: "application/json",
  344. body: `{"username":"testuser","password":"testpass"}`,
  345. auth: &testAuthService{
  346. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  347. return blockWithoutCookie(), nil
  348. },
  349. },
  350. expectedStatusCode: http.StatusInternalServerError,
  351. checkResponse: func(t *testing.T, body string) {
  352. assert.Contains(t, body, "internal server error")
  353. },
  354. },
  355. }
  356. for _, tt := range tests {
  357. t.Run(tt.name, func(t *testing.T) {
  358. logger := slog.Default()
  359. handler := &AuthHandler{
  360. AuthService: tt.auth,
  361. Logger: logger,
  362. }
  363. req, err := http.NewRequest(tt.method, "/auth/clientLogin", strings.NewReader(tt.body))
  364. assert.NoError(t, err)
  365. req.Header.Set("Content-Type", tt.contentType)
  366. rr := httptest.NewRecorder()
  367. handler.ClientLogin(rr, req)
  368. assert.Equal(t, tt.expectedStatusCode, rr.Code)
  369. responseBody := strings.TrimSpace(rr.Body.String())
  370. if tt.checkResponse != nil {
  371. tt.checkResponse(t, responseBody)
  372. }
  373. })
  374. }
  375. }
  376. func TestAuthHandler_ClientLogin_SendsClientIdentity(t *testing.T) {
  377. tests := []struct {
  378. name string
  379. body string
  380. expectedClientID string
  381. }{
  382. {
  383. name: "DevIDNamesTheClient",
  384. body: `{"username":"testuser","password":"testpass","devId":"dev123"}`,
  385. expectedClientID: "dev123",
  386. },
  387. {
  388. name: "MissingDevIDFallsBack",
  389. body: `{"username":"testuser","password":"testpass"}`,
  390. expectedClientID: "WebAIM",
  391. },
  392. }
  393. for _, tt := range tests {
  394. t.Run(tt.name, func(t *testing.T) {
  395. var got wire.FLAPSignonFrame
  396. handler := &AuthHandler{
  397. AuthService: &testAuthService{
  398. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  399. got = inFrame
  400. return successfulLoginBlock(), nil
  401. },
  402. },
  403. Logger: slog.Default(),
  404. }
  405. req := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader(tt.body))
  406. req.Header.Set("Content-Type", "application/json")
  407. handler.ClientLogin(httptest.NewRecorder(), req)
  408. clientID, ok := got.String(wire.LoginTLVTagsClientIdentity)
  409. assert.True(t, ok, "signon frame should carry a client identity")
  410. assert.Equal(t, tt.expectedClientID, clientID)
  411. })
  412. }
  413. }