(t *testing.T)
| 343 | } |
| 344 | |
| 345 | func TestSessionExpiry(t *testing.T) { |
| 346 | t.Parallel() |
| 347 | |
| 348 | ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) |
| 349 | defer cancel() |
| 350 | dc := coderdtest.DeploymentValues(t) |
| 351 | |
| 352 | db, pubsub := dbtestutil.NewDB(t) |
| 353 | adminClient := coderdtest.New(t, &coderdtest.Options{ |
| 354 | DeploymentValues: dc, |
| 355 | Database: db, |
| 356 | Pubsub: pubsub, |
| 357 | }) |
| 358 | adminUser := coderdtest.CreateFirstUser(t, adminClient) |
| 359 | |
| 360 | // This is a hack, but we need the admin account to have a long expiry |
| 361 | // otherwise the test will flake, so we only update the expiry config after |
| 362 | // the admin account has been created. |
| 363 | // |
| 364 | // We don't support updating the deployment config after startup, but for |
| 365 | // this test it works because we don't copy the value (and we use pointers). |
| 366 | dc.Sessions.DefaultDuration = serpent.Duration(time.Second) |
| 367 | |
| 368 | userClient, _ := coderdtest.CreateAnotherUser(t, adminClient, adminUser.OrganizationID) |
| 369 | |
| 370 | // Find the session cookie, and ensure it has the correct expiry. |
| 371 | token := userClient.SessionToken() |
| 372 | apiKey, err := db.GetAPIKeyByID(ctx, strings.Split(token, "-")[0]) |
| 373 | require.NoError(t, err) |
| 374 | |
| 375 | require.EqualValues(t, dc.Sessions.DefaultDuration.Value().Seconds(), apiKey.LifetimeSeconds) |
| 376 | require.WithinDuration(t, apiKey.CreatedAt.Add(dc.Sessions.DefaultDuration.Value()), apiKey.ExpiresAt, 2*time.Second) |
| 377 | |
| 378 | // Update the session token to be expired so we can test that it is |
| 379 | // rejected for extra points. |
| 380 | err = db.UpdateAPIKeyByID(ctx, database.UpdateAPIKeyByIDParams{ |
| 381 | ID: apiKey.ID, |
| 382 | LastUsed: apiKey.LastUsed, |
| 383 | ExpiresAt: dbtime.Now().Add(-time.Hour), |
| 384 | IPAddress: apiKey.IPAddress, |
| 385 | }) |
| 386 | require.NoError(t, err) |
| 387 | |
| 388 | _, err = userClient.User(ctx, codersdk.Me) |
| 389 | require.Error(t, err) |
| 390 | var sdkErr *codersdk.Error |
| 391 | if assert.ErrorAs(t, err, &sdkErr) { |
| 392 | require.Equal(t, http.StatusUnauthorized, sdkErr.StatusCode()) |
| 393 | require.Contains(t, sdkErr.Message, "session has expired") |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // TestSessionCookieMaxAge verifies that the session cookie is a persistent |
| 398 | // cookie (has MaxAge set) rather than a session cookie. Standalone PWAs |
nothing calls this directly
no test coverage detected