auth_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. name: "Success_FormEncoded",
  222. method: "POST",
  223. contentType: "application/x-www-form-urlencoded",
  224. body: "s=testuser&pwd=testpass&devId=dev123",
  225. auth: &testAuthService{
  226. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  227. return successfulLoginBlock(), nil
  228. },
  229. },
  230. expectedStatusCode: http.StatusOK,
  231. checkResponse: func(t *testing.T, body string) {
  232. assert.Contains(t, body, `"statusCode":200`)
  233. assert.Contains(t, body, `"loginId":"testuser"`)
  234. },
  235. },
  236. {
  237. name: "Error_MissingUsername",
  238. method: "POST",
  239. contentType: "application/json",
  240. body: `{"username":"","password":"testpass"}`,
  241. auth: &testAuthService{},
  242. expectedStatusCode: http.StatusBadRequest,
  243. checkResponse: func(t *testing.T, body string) {
  244. assert.Contains(t, body, "username and password required")
  245. },
  246. },
  247. {
  248. name: "Error_MissingPassword",
  249. method: "POST",
  250. contentType: "application/json",
  251. body: `{"username":"testuser","password":""}`,
  252. auth: &testAuthService{},
  253. expectedStatusCode: http.StatusBadRequest,
  254. checkResponse: func(t *testing.T, body string) {
  255. assert.Contains(t, body, "username and password required")
  256. },
  257. },
  258. {
  259. name: "Error_AuthFailed",
  260. method: "POST",
  261. contentType: "application/json",
  262. body: `{"username":"testuser","password":"wrongpass"}`,
  263. auth: &testAuthService{
  264. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  265. return failedLoginBlock(), nil
  266. },
  267. },
  268. expectedStatusCode: http.StatusUnauthorized,
  269. checkResponse: func(t *testing.T, body string) {
  270. assert.Contains(t, body, "username and password required")
  271. },
  272. },
  273. {
  274. name: "Error_FLAPLoginError",
  275. method: "POST",
  276. contentType: "application/json",
  277. body: `{"username":"testuser","password":"testpass"}`,
  278. auth: &testAuthService{
  279. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  280. return wire.TLVRestBlock{}, errors.New("boom")
  281. },
  282. },
  283. expectedStatusCode: http.StatusInternalServerError,
  284. checkResponse: func(t *testing.T, body string) {
  285. assert.Contains(t, body, "internal server error")
  286. },
  287. },
  288. {
  289. name: "Error_InvalidJSON",
  290. method: "POST",
  291. contentType: "application/json",
  292. body: `{invalid json`,
  293. auth: &testAuthService{},
  294. expectedStatusCode: http.StatusBadRequest,
  295. checkResponse: func(t *testing.T, body string) {
  296. assert.Contains(t, body, "invalid JSON format")
  297. },
  298. },
  299. {
  300. name: "Error_LoginResponseHasNoCookie",
  301. method: "POST",
  302. contentType: "application/json",
  303. body: `{"username":"testuser","password":"testpass"}`,
  304. auth: &testAuthService{
  305. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  306. return blockWithoutCookie(), nil
  307. },
  308. },
  309. expectedStatusCode: http.StatusInternalServerError,
  310. checkResponse: func(t *testing.T, body string) {
  311. assert.Contains(t, body, "internal server error")
  312. },
  313. },
  314. }
  315. for _, tt := range tests {
  316. t.Run(tt.name, func(t *testing.T) {
  317. logger := slog.Default()
  318. handler := &AuthHandler{
  319. AuthService: tt.auth,
  320. Logger: logger,
  321. }
  322. req, err := http.NewRequest(tt.method, "/auth/clientLogin", strings.NewReader(tt.body))
  323. assert.NoError(t, err)
  324. req.Header.Set("Content-Type", tt.contentType)
  325. rr := httptest.NewRecorder()
  326. handler.ClientLogin(rr, req)
  327. assert.Equal(t, tt.expectedStatusCode, rr.Code)
  328. responseBody := strings.TrimSpace(rr.Body.String())
  329. if tt.checkResponse != nil {
  330. tt.checkResponse(t, responseBody)
  331. }
  332. })
  333. }
  334. }
  335. func TestAuthHandler_ClientLogin_SendsClientIdentity(t *testing.T) {
  336. tests := []struct {
  337. name string
  338. body string
  339. expectedClientID string
  340. }{
  341. {
  342. name: "DevIDNamesTheClient",
  343. body: `{"username":"testuser","password":"testpass","devId":"dev123"}`,
  344. expectedClientID: "dev123",
  345. },
  346. {
  347. name: "MissingDevIDFallsBack",
  348. body: `{"username":"testuser","password":"testpass"}`,
  349. expectedClientID: "WebAIM",
  350. },
  351. }
  352. for _, tt := range tests {
  353. t.Run(tt.name, func(t *testing.T) {
  354. var got wire.FLAPSignonFrame
  355. handler := &AuthHandler{
  356. AuthService: &testAuthService{
  357. flapLogin: func(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error) {
  358. got = inFrame
  359. return successfulLoginBlock(), nil
  360. },
  361. },
  362. Logger: slog.Default(),
  363. }
  364. req := httptest.NewRequest(http.MethodPost, "/auth/clientLogin", strings.NewReader(tt.body))
  365. req.Header.Set("Content-Type", "application/json")
  366. handler.ClientLogin(httptest.NewRecorder(), req)
  367. clientID, ok := got.String(wire.LoginTLVTagsClientIdentity)
  368. assert.True(t, ok, "signon frame should carry a client identity")
  369. assert.Equal(t, tt.expectedClientID, clientID)
  370. })
  371. }
  372. }