web_session_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package model
  4. import (
  5. "bytes"
  6. "database/sql"
  7. "encoding/json"
  8. "testing"
  9. "time"
  10. "github.com/go-webauthn/webauthn/webauthn"
  11. )
  12. func TestNewWebSession(t *testing.T) {
  13. const userAgent = "test-agent"
  14. const ip = "127.0.0.1"
  15. session, secret := NewWebSession(userAgent, ip)
  16. if session == nil {
  17. t.Fatal("NewWebSession returned a nil session")
  18. }
  19. if secret == "" {
  20. t.Error("NewWebSession returned an empty secret")
  21. }
  22. if session.ID == "" {
  23. t.Error("NewWebSession produced an empty ID")
  24. }
  25. if session.ID == secret {
  26. t.Error("session ID and secret must not be equal")
  27. }
  28. if len(session.SecretHash) == 0 {
  29. t.Error("NewWebSession produced an empty SecretHash")
  30. }
  31. if session.CSRF() == "" {
  32. t.Error("NewWebSession produced an empty CSRF token")
  33. }
  34. if session.UserAgent != userAgent {
  35. t.Errorf("UserAgent = %q, want %q", session.UserAgent, userAgent)
  36. }
  37. if session.IP != ip {
  38. t.Errorf("IP = %q, want %q", session.IP, ip)
  39. }
  40. if session.IsAuthenticated() {
  41. t.Error("a fresh session must not be authenticated")
  42. }
  43. if session.IsDirty() {
  44. t.Error("a fresh session must not be dirty")
  45. }
  46. if !session.VerifySecret(secret) {
  47. t.Error("VerifySecret rejected the secret returned by NewWebSession")
  48. }
  49. }
  50. func TestNewWebSession_ProducesUniqueIdentities(t *testing.T) {
  51. s1, secret1 := NewWebSession("", "")
  52. s2, secret2 := NewWebSession("", "")
  53. if s1.ID == s2.ID {
  54. t.Error("successive NewWebSession calls produced the same ID")
  55. }
  56. if secret1 == secret2 {
  57. t.Error("successive NewWebSession calls produced the same secret")
  58. }
  59. if bytes.Equal(s1.SecretHash, s2.SecretHash) {
  60. t.Error("successive NewWebSession calls produced the same SecretHash")
  61. }
  62. if s1.CSRF() == s2.CSRF() {
  63. t.Error("successive NewWebSession calls produced the same CSRF token")
  64. }
  65. }
  66. func TestWebSession_Rotate(t *testing.T) {
  67. session, originalSecret := NewWebSession("agent", "ip")
  68. originalID := session.ID
  69. originalHash := bytes.Clone(session.SecretHash)
  70. originalCSRF := session.CSRF()
  71. // Bind a user so we can verify Rotate preserves the user binding.
  72. session.SetUser(&User{ID: 42})
  73. oldID, newSecret := session.Rotate()
  74. if oldID != originalID {
  75. t.Errorf("Rotate returned oldID = %q, want %q", oldID, originalID)
  76. }
  77. if newSecret == "" {
  78. t.Error("Rotate returned an empty new secret")
  79. }
  80. if newSecret == originalSecret {
  81. t.Error("Rotate returned the same secret as before")
  82. }
  83. if session.ID == originalID {
  84. t.Error("Rotate did not change the session ID")
  85. }
  86. if bytes.Equal(session.SecretHash, originalHash) {
  87. t.Error("Rotate did not change the SecretHash")
  88. }
  89. if session.VerifySecret(originalSecret) {
  90. t.Error("VerifySecret must reject the pre-rotation secret")
  91. }
  92. if !session.VerifySecret(newSecret) {
  93. t.Error("VerifySecret must accept the post-rotation secret")
  94. }
  95. if session.CSRF() != originalCSRF {
  96. t.Error("Rotate must preserve the CSRF token so in-flight forms remain valid")
  97. }
  98. if !session.IsAuthenticated() {
  99. t.Error("Rotate must preserve the user binding")
  100. }
  101. if id, _ := session.UserID(); id != 42 {
  102. t.Errorf("Rotate corrupted user ID: got %d, want 42", id)
  103. }
  104. }
  105. func TestWebSession_VerifySecret(t *testing.T) {
  106. good, goodSecret := NewWebSession("", "")
  107. testCases := []struct {
  108. name string
  109. hash []byte
  110. secret string
  111. want bool
  112. }{
  113. {"correct secret", good.SecretHash, goodSecret, true},
  114. {"wrong secret", good.SecretHash, "not-the-right-secret", false},
  115. {"empty secret", good.SecretHash, "", false},
  116. {"nil hash", nil, goodSecret, false},
  117. {"empty hash and secret", nil, "", false},
  118. }
  119. for _, tc := range testCases {
  120. t.Run(tc.name, func(t *testing.T) {
  121. s := &WebSession{SecretHash: tc.hash}
  122. if got := s.VerifySecret(tc.secret); got != tc.want {
  123. t.Errorf("VerifySecret(%q) = %v, want %v", tc.secret, got, tc.want)
  124. }
  125. })
  126. }
  127. }
  128. func TestWebSession_UserBindingLifecycle(t *testing.T) {
  129. session, _ := NewWebSession("", "")
  130. if session.IsAuthenticated() {
  131. t.Error("a fresh session must not be authenticated")
  132. }
  133. if id, ok := session.UserID(); ok || id != 0 {
  134. t.Errorf("UserID() = (%d, %v), want (0, false)", id, ok)
  135. }
  136. user := &User{ID: 99, Language: "fr_FR", Theme: "dark_serif"}
  137. session.SetUser(user)
  138. if !session.IsAuthenticated() {
  139. t.Error("session must be authenticated after SetUser")
  140. }
  141. if id, ok := session.UserID(); !ok || id != 99 {
  142. t.Errorf("UserID() = (%d, %v), want (99, true)", id, ok)
  143. }
  144. if session.Language() != "fr_FR" {
  145. t.Errorf("SetUser did not copy Language: got %q, want %q", session.Language(), "fr_FR")
  146. }
  147. if session.Theme() != "dark_serif" {
  148. t.Errorf("SetUser did not copy Theme: got %q, want %q", session.Theme(), "dark_serif")
  149. }
  150. if !session.IsDirty() {
  151. t.Error("SetUser must mark the session dirty")
  152. }
  153. session.ClearUser()
  154. if session.IsAuthenticated() {
  155. t.Error("session must not be authenticated after ClearUser")
  156. }
  157. if id, ok := session.UserID(); ok || id != 0 {
  158. t.Errorf("UserID() after ClearUser = (%d, %v), want (0, false)", id, ok)
  159. }
  160. }
  161. func TestWebSession_SetUser_NilIsNoop(t *testing.T) {
  162. session, _ := NewWebSession("", "")
  163. session.SetUser(nil)
  164. if session.IsAuthenticated() {
  165. t.Error("SetUser(nil) must not authenticate the session")
  166. }
  167. if session.IsDirty() {
  168. t.Error("SetUser(nil) must not mark the session dirty")
  169. }
  170. }
  171. func TestWebSession_UserIDStorageRoundTrip(t *testing.T) {
  172. testCases := []struct {
  173. name string
  174. in sql.NullInt64
  175. }{
  176. {"null", sql.NullInt64{}},
  177. {"zero valid", sql.NullInt64{Int64: 0, Valid: true}},
  178. {"positive valid", sql.NullInt64{Int64: 42, Valid: true}},
  179. }
  180. for _, tc := range testCases {
  181. t.Run(tc.name, func(t *testing.T) {
  182. session := &WebSession{}
  183. session.ScanUserID(tc.in)
  184. if got := session.NullUserID(); got != tc.in {
  185. t.Errorf("round-trip = %+v, want %+v", got, tc.in)
  186. }
  187. if got := session.IsAuthenticated(); got != tc.in.Valid {
  188. t.Errorf("IsAuthenticated() = %v, want %v", got, tc.in.Valid)
  189. }
  190. })
  191. }
  192. }
  193. func TestWebSession_ScanUserID_ClearsPreviousValue(t *testing.T) {
  194. session := &WebSession{}
  195. session.ScanUserID(sql.NullInt64{Int64: 1, Valid: true})
  196. session.ScanUserID(sql.NullInt64{})
  197. if session.IsAuthenticated() {
  198. t.Error("ScanUserID with an invalid value must clear the user binding")
  199. }
  200. }
  201. func TestWebSession_LanguageAndThemeDefaults(t *testing.T) {
  202. session := &WebSession{}
  203. if got := session.Language(); got != defaultSessionLanguage {
  204. t.Errorf("default Language() = %q, want %q", got, defaultSessionLanguage)
  205. }
  206. if got := session.Theme(); got != defaultSessionTheme {
  207. t.Errorf("default Theme() = %q, want %q", got, defaultSessionTheme)
  208. }
  209. session.SetLanguage("de_DE")
  210. session.SetTheme("light_sans_serif")
  211. if got := session.Language(); got != "de_DE" {
  212. t.Errorf("Language() = %q, want %q", got, "de_DE")
  213. }
  214. if got := session.Theme(); got != "light_sans_serif" {
  215. t.Errorf("Theme() = %q, want %q", got, "light_sans_serif")
  216. }
  217. if !session.IsDirty() {
  218. t.Error("SetLanguage/SetTheme must mark the session dirty")
  219. }
  220. }
  221. func TestWebSession_OAuth2FlowLifecycle(t *testing.T) {
  222. session := &WebSession{}
  223. if session.OAuth2State() != "" {
  224. t.Error("OAuth2State() must be empty by default")
  225. }
  226. if session.OAuth2CodeVerifier() != "" {
  227. t.Error("OAuth2CodeVerifier() must be empty by default")
  228. }
  229. session.StartOAuth2Flow("state-token", "code-verifier")
  230. if got := session.OAuth2State(); got != "state-token" {
  231. t.Errorf("OAuth2State() = %q, want %q", got, "state-token")
  232. }
  233. if got := session.OAuth2CodeVerifier(); got != "code-verifier" {
  234. t.Errorf("OAuth2CodeVerifier() = %q, want %q", got, "code-verifier")
  235. }
  236. if !session.IsDirty() {
  237. t.Error("StartOAuth2Flow must mark the session dirty")
  238. }
  239. session.ClearOAuth2Flow()
  240. if session.OAuth2State() != "" {
  241. t.Errorf("OAuth2State() after Clear = %q, want empty", session.OAuth2State())
  242. }
  243. if session.OAuth2CodeVerifier() != "" {
  244. t.Errorf("OAuth2CodeVerifier() after Clear = %q, want empty", session.OAuth2CodeVerifier())
  245. }
  246. }
  247. func TestWebSession_ConsumeMessages(t *testing.T) {
  248. t.Run("no messages", func(t *testing.T) {
  249. session := &WebSession{}
  250. success, errMsg := session.ConsumeMessages()
  251. if success != "" || errMsg != "" {
  252. t.Errorf("ConsumeMessages() = (%q, %q), want empty", success, errMsg)
  253. }
  254. if session.IsDirty() {
  255. t.Error("ConsumeMessages with no messages must not mark the session dirty")
  256. }
  257. })
  258. t.Run("returns and clears", func(t *testing.T) {
  259. session := &WebSession{}
  260. session.SetSuccessMessage("saved")
  261. session.SetErrorMessage("nope")
  262. session.dirty = false // isolate the dirty contribution of ConsumeMessages
  263. success, errMsg := session.ConsumeMessages()
  264. if success != "saved" || errMsg != "nope" {
  265. t.Errorf("ConsumeMessages() = (%q, %q), want (%q, %q)", success, errMsg, "saved", "nope")
  266. }
  267. if !session.IsDirty() {
  268. t.Error("ConsumeMessages with messages must mark the session dirty")
  269. }
  270. success, errMsg = session.ConsumeMessages()
  271. if success != "" || errMsg != "" {
  272. t.Errorf("second ConsumeMessages() = (%q, %q), want empty", success, errMsg)
  273. }
  274. })
  275. }
  276. func TestWebSession_ConsumeWebAuthnSession(t *testing.T) {
  277. t.Run("no data", func(t *testing.T) {
  278. session := &WebSession{}
  279. if got := session.ConsumeWebAuthnSession(); got != nil {
  280. t.Errorf("ConsumeWebAuthnSession() = %v, want nil", got)
  281. }
  282. if session.IsDirty() {
  283. t.Error("ConsumeWebAuthnSession with no data must not mark the session dirty")
  284. }
  285. })
  286. t.Run("returns and clears", func(t *testing.T) {
  287. data := &webauthn.SessionData{}
  288. session := &WebSession{}
  289. session.SetWebAuthn(data)
  290. session.dirty = false // isolate the dirty contribution of ConsumeWebAuthnSession
  291. if got := session.ConsumeWebAuthnSession(); got != data {
  292. t.Errorf("ConsumeWebAuthnSession() = %p, want %p", got, data)
  293. }
  294. if !session.IsDirty() {
  295. t.Error("ConsumeWebAuthnSession with data must mark the session dirty")
  296. }
  297. if got := session.ConsumeWebAuthnSession(); got != nil {
  298. t.Errorf("second ConsumeWebAuthnSession() = %v, want nil", got)
  299. }
  300. })
  301. }
  302. func TestWebSession_MarkForceRefreshed(t *testing.T) {
  303. session := &WebSession{}
  304. if got := session.LastForceRefresh(); !got.IsZero() {
  305. t.Errorf("default LastForceRefresh() = %v, want zero time", got)
  306. }
  307. before := time.Now().UTC()
  308. session.MarkForceRefreshed()
  309. after := time.Now().UTC()
  310. got := session.LastForceRefresh()
  311. if got.Before(before) || got.After(after) {
  312. t.Errorf("LastForceRefresh() = %v, want between %v and %v", got, before, after)
  313. }
  314. if !session.IsDirty() {
  315. t.Error("MarkForceRefreshed must mark the session dirty")
  316. }
  317. }
  318. func TestWebSession_StateRoundTrip(t *testing.T) {
  319. original := &WebSession{}
  320. original.SetLanguage("de_DE")
  321. original.SetTheme("light_sans_serif")
  322. original.SetSuccessMessage("saved")
  323. original.SetErrorMessage("oops")
  324. original.StartOAuth2Flow("state-token", "code-verifier")
  325. original.MarkForceRefreshed()
  326. originalRefreshAt := original.LastForceRefresh()
  327. data, err := original.MarshalState()
  328. if err != nil {
  329. t.Fatalf("MarshalState() error: %v", err)
  330. }
  331. if !json.Valid(data) {
  332. t.Errorf("MarshalState() produced invalid JSON: %s", data)
  333. }
  334. restored := &WebSession{}
  335. if err := restored.UnmarshalState(data); err != nil {
  336. t.Fatalf("UnmarshalState() error: %v", err)
  337. }
  338. if got := restored.Language(); got != "de_DE" {
  339. t.Errorf("Language() = %q, want %q", got, "de_DE")
  340. }
  341. if got := restored.Theme(); got != "light_sans_serif" {
  342. t.Errorf("Theme() = %q, want %q", got, "light_sans_serif")
  343. }
  344. if got := restored.OAuth2State(); got != "state-token" {
  345. t.Errorf("OAuth2State() = %q, want %q", got, "state-token")
  346. }
  347. if got := restored.OAuth2CodeVerifier(); got != "code-verifier" {
  348. t.Errorf("OAuth2CodeVerifier() = %q, want %q", got, "code-verifier")
  349. }
  350. if got := restored.LastForceRefresh(); !got.Equal(originalRefreshAt) {
  351. t.Errorf("LastForceRefresh() = %v, want %v", got, originalRefreshAt)
  352. }
  353. success, errMsg := restored.ConsumeMessages()
  354. if success != "saved" || errMsg != "oops" {
  355. t.Errorf("ConsumeMessages() = (%q, %q), want (%q, %q)", success, errMsg, "saved", "oops")
  356. }
  357. }
  358. func TestWebSession_UnmarshalState_EmptyDataResetsState(t *testing.T) {
  359. session := &WebSession{}
  360. session.SetLanguage("fr_FR")
  361. session.StartOAuth2Flow("s", "v")
  362. if err := session.UnmarshalState(nil); err != nil {
  363. t.Fatalf("UnmarshalState(nil) error: %v", err)
  364. }
  365. if got := session.Language(); got != defaultSessionLanguage {
  366. t.Errorf("UnmarshalState(nil) did not reset Language: got %q", got)
  367. }
  368. if session.OAuth2State() != "" {
  369. t.Error("UnmarshalState(nil) did not reset OAuth2 state")
  370. }
  371. }