TestOAuth2CoderClient verfies a codersdk client can be used with an oauth client.
(t *testing.T)
| 1650 | |
| 1651 | // TestOAuth2CoderClient verfies a codersdk client can be used with an oauth client. |
| 1652 | func TestOAuth2CoderClient(t *testing.T) { |
| 1653 | t.Parallel() |
| 1654 | |
| 1655 | owner := coderdtest.New(t, nil) |
| 1656 | first := coderdtest.CreateFirstUser(t, owner) |
| 1657 | |
| 1658 | // Setup an oauth app |
| 1659 | ctx := testutil.Context(t, testutil.WaitLong) |
| 1660 | app, err := owner.PostOAuth2ProviderApp(ctx, codersdk.PostOAuth2ProviderAppRequest{ |
| 1661 | Name: "new-app", |
| 1662 | CallbackURL: "http://localhost", |
| 1663 | }) |
| 1664 | require.NoError(t, err) |
| 1665 | |
| 1666 | appsecret, err := owner.PostOAuth2ProviderAppSecret(ctx, app.ID) |
| 1667 | require.NoError(t, err) |
| 1668 | |
| 1669 | cfg := &oauth2.Config{ |
| 1670 | ClientID: app.ID.String(), |
| 1671 | ClientSecret: appsecret.ClientSecretFull, |
| 1672 | Endpoint: oauth2.Endpoint{ |
| 1673 | AuthURL: app.Endpoints.Authorization, |
| 1674 | DeviceAuthURL: app.Endpoints.DeviceAuth, |
| 1675 | TokenURL: app.Endpoints.Token, |
| 1676 | AuthStyle: oauth2.AuthStyleInParams, |
| 1677 | }, |
| 1678 | RedirectURL: app.CallbackURL, |
| 1679 | Scopes: []string{}, |
| 1680 | } |
| 1681 | |
| 1682 | // Make a new user |
| 1683 | client, user := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID) |
| 1684 | |
| 1685 | // Do an OAuth2 token exchange and get a new client with an oauth token. |
| 1686 | state := uuid.NewString() |
| 1687 | verifier, challenge := generatePKCE() |
| 1688 | |
| 1689 | // Get an OAuth2 code for a token exchange. |
| 1690 | code, err := oidctest.OAuth2GetCode( |
| 1691 | cfg.AuthCodeURL(state, |
| 1692 | oauth2.SetAuthURLParam("code_challenge", challenge), |
| 1693 | oauth2.SetAuthURLParam("code_challenge_method", "S256"), |
| 1694 | ), |
| 1695 | func(req *http.Request) (*http.Response, error) { |
| 1696 | // Change to POST to simulate the form submission. |
| 1697 | req.Method = http.MethodPost |
| 1698 | |
| 1699 | // Prevent automatic redirect following. |
| 1700 | client.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { |
| 1701 | return http.ErrUseLastResponse |
| 1702 | } |
| 1703 | return client.Request(ctx, req.Method, req.URL.String(), nil) |
| 1704 | }, |
| 1705 | ) |
| 1706 | require.NoError(t, err) |
| 1707 | |
| 1708 | token, err := cfg.Exchange(ctx, code, |
| 1709 | oauth2.SetAuthURLParam("code_verifier", verifier), |
nothing calls this directly
no test coverage detected