mirror of
https://github.com/coder/coder.git
synced 2025-07-15 22:20:27 +00:00
feat: add oauth2 token exchange (#12196)
Co-authored-by: Steven Masley <stevenmasley@gmail.com>
This commit is contained in:
@ -1,14 +1,17 @@
|
||||
package oidctest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/database"
|
||||
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
||||
@ -114,3 +117,52 @@ func (h *LoginHelper) ForceRefresh(t *testing.T, db database.Store, user *coders
|
||||
_, err := user.User(testutil.Context(t, testutil.WaitShort), "me")
|
||||
require.NoError(t, err, "user must be able to be fetched")
|
||||
}
|
||||
|
||||
// OAuth2GetCode emulates a user clicking "allow" on the IDP page. When doing
|
||||
// unit tests, it's easier to skip this step sometimes. It does make an actual
|
||||
// request to the IDP, so it should be equivalent to doing this "manually" with
|
||||
// actual requests.
|
||||
func OAuth2GetCode(rawAuthURL string, doRequest func(req *http.Request) (*http.Response, error)) (string, error) {
|
||||
authURL, err := url.Parse(rawAuthURL)
|
||||
if err != nil {
|
||||
return "", xerrors.Errorf("failed to parse auth URL: %w", err)
|
||||
}
|
||||
|
||||
r, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawAuthURL, nil)
|
||||
if err != nil {
|
||||
return "", xerrors.Errorf("failed to create auth request: %w", err)
|
||||
}
|
||||
|
||||
expCode := http.StatusTemporaryRedirect
|
||||
resp, err := doRequest(r)
|
||||
if err != nil {
|
||||
return "", xerrors.Errorf("request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != expCode {
|
||||
return "", codersdk.ReadBodyAsError(resp)
|
||||
}
|
||||
|
||||
to := resp.Header.Get("Location")
|
||||
if to == "" {
|
||||
return "", xerrors.Errorf("expected redirect location")
|
||||
}
|
||||
|
||||
toURL, err := url.Parse(to)
|
||||
if err != nil {
|
||||
return "", xerrors.Errorf("failed to parse redirect location: %w", err)
|
||||
}
|
||||
|
||||
code := toURL.Query().Get("code")
|
||||
if code == "" {
|
||||
return "", xerrors.Errorf("expected code in redirect location")
|
||||
}
|
||||
|
||||
state := authURL.Query().Get("state")
|
||||
newState := toURL.Query().Get("state")
|
||||
if newState != state {
|
||||
return "", xerrors.Errorf("expected state %q, got %q", state, newState)
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user