4
0

auth_test.go 15 KB

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