setupTest will configure a fake IDP and a externalauth.Config for testing. The Fake's userinfo endpoint is used for validating tokens. No http servers are started so use the fake IDP's HTTPClient to make requests. The returned token is a fully valid token for the IDP. Feel free to manipulate it to t
(t *testing.T, settings testConfig)
| 1440 | // The returned token is a fully valid token for the IDP. Feel free to manipulate it |
| 1441 | // to test different scenarios. |
| 1442 | func setupOauth2Test(t *testing.T, settings testConfig) (*oidctest.FakeIDP, *externalauth.Config, database.ExternalAuthLink) { |
| 1443 | t.Helper() |
| 1444 | |
| 1445 | if settings.ExternalAuthOpt == nil { |
| 1446 | settings.ExternalAuthOpt = func(_ *externalauth.Config) {} |
| 1447 | } |
| 1448 | |
| 1449 | const providerID = "test-idp" |
| 1450 | fake := oidctest.NewFakeIDP(t, |
| 1451 | append([]oidctest.FakeIDPOpt{oidctest.WithPKCE()}, settings.FakeIDPOpts...)..., |
| 1452 | ) |
| 1453 | |
| 1454 | f := promoauth.NewFactory(prometheus.NewRegistry()) |
| 1455 | cid, cs := fake.AppCredentials() |
| 1456 | config := &externalauth.Config{ |
| 1457 | InstrumentedOAuth2Config: f.New("test-oauth2", |
| 1458 | fake.OIDCConfig(t, nil, settings.CoderOIDCConfigOpts...)), |
| 1459 | ID: providerID, |
| 1460 | ClientID: cid, |
| 1461 | ClientSecret: cs, |
| 1462 | ValidateURL: fake.WellknownConfig().UserInfoURL, |
| 1463 | RevokeURL: fake.WellknownConfig().RevokeURL, |
| 1464 | RevokeTimeout: 1 * time.Second, |
| 1465 | CodeChallengeMethodsSupported: []promoauth.Oauth2PKCEChallengeMethod{promoauth.PKCEChallengeMethodSha256}, |
| 1466 | } |
| 1467 | settings.ExternalAuthOpt(config) |
| 1468 | |
| 1469 | oauthToken, err := fake.GenerateAuthenticatedToken(jwt.MapClaims{ |
| 1470 | "email": "test@coder.com", |
| 1471 | }) |
| 1472 | require.NoError(t, err) |
| 1473 | |
| 1474 | now := time.Now() |
| 1475 | link := database.ExternalAuthLink{ |
| 1476 | ProviderID: providerID, |
| 1477 | UserID: uuid.New(), |
| 1478 | CreatedAt: now, |
| 1479 | UpdatedAt: now, |
| 1480 | OAuthAccessToken: oauthToken.AccessToken, |
| 1481 | OAuthRefreshToken: oauthToken.RefreshToken, |
| 1482 | // The caller can manually expire this if they want. |
| 1483 | OAuthExpiry: now.Add(time.Hour), |
| 1484 | } |
| 1485 | |
| 1486 | if settings.DB != nil { |
| 1487 | // Feel free to insert additional things like the user, etc if required. |
| 1488 | link, err = settings.DB.InsertExternalAuthLink(context.Background(), database.InsertExternalAuthLinkParams{ |
| 1489 | ProviderID: link.ProviderID, |
| 1490 | UserID: link.UserID, |
| 1491 | CreatedAt: link.CreatedAt, |
| 1492 | UpdatedAt: link.UpdatedAt, |
| 1493 | OAuthAccessToken: link.OAuthAccessToken, |
| 1494 | OAuthRefreshToken: link.OAuthRefreshToken, |
| 1495 | OAuthExpiry: link.OAuthExpiry, |
| 1496 | }) |
| 1497 | require.NoError(t, err, "failed to insert link into DB") |
| 1498 | } |
| 1499 |
no test coverage detected