Skip to content

feat: Add GitHub OAuth #1050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Apr 23, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Initial oauth
  • Loading branch information
kylecarbs committed Apr 15, 2022
commit a63d27b72a3c54401d2de08701f6159aae92e409
7 changes: 7 additions & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type Options struct {

AWSCertificates awsidentity.Certificates
GoogleTokenValidator *idtoken.Validator
GithubOAuth2Provider GithubOAuth2Provider

SecureAuthCookie bool
SSHKeygenAlgorithm gitsshkey.Algorithm
Expand Down Expand Up @@ -142,6 +143,12 @@ func New(options *Options) (http.Handler, func()) {
r.Post("/first", api.postFirstUser)
r.Post("/login", api.postLogin)
r.Post("/logout", api.postLogout)
r.Route("/auth", func(r chi.Router) {
r.Route("/callback/github", func(r chi.Router) {
r.Use(httpmw.ExtractOAuth2(options.GithubOAuth2Provider))
r.Get("/", api.userAuthGithub)
})
})
r.Group(func(r chi.Router) {
r.Use(httpmw.ExtractAPIKey(options.Database, nil))
r.Post("/", api.postUsers)
Expand Down
2 changes: 2 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import (

type Options struct {
AWSInstanceIdentity awsidentity.Certificates
GithubOAuth2Provider coderd.GithubOAuth2Provider
GoogleInstanceIdentity *idtoken.Validator
SSHKeygenAlgorithm gitsshkey.Algorithm
}
Expand Down Expand Up @@ -115,6 +116,7 @@ func New(t *testing.T, options *Options) *codersdk.Client {
Pubsub: pubsub,

AWSCertificates: options.AWSInstanceIdentity,
GithubOAuth2Provider: options.GithubOAuth2Provider,
GoogleTokenValidator: options.GoogleInstanceIdentity,
SSHKeygenAlgorithm: options.SSHKeygenAlgorithm,
})
Expand Down
10 changes: 10 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,16 @@ func (q *fakeQuerier) GetWorkspacesByUserID(_ context.Context, req database.GetW
return workspaces, nil
}

func (q *fakeQuerier) GetOrganizations(_ context.Context) ([]database.Organization, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

if len(q.organizations) == 0 {
return nil, sql.ErrNoRows
}
return q.organizations, nil
}

func (q *fakeQuerier) GetOrganizationByID(_ context.Context, id uuid.UUID) (database.Organization, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()
Expand Down
1 change: 1 addition & 0 deletions coderd/database/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions coderd/database/queries/organizations.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
-- name: GetOrganizations :many
SELECT
*
FROM
organizations;

-- name: GetOrganizationByID :one
SELECT
*
Expand Down
124 changes: 124 additions & 0 deletions coderd/httpmw/oauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package httpmw

import (
"context"
"fmt"
"net/http"

"golang.org/x/oauth2"

"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/cryptorand"
)

const (
oauth2StateCookieName = "oauth_state"
oauth2RedirectCookieName = "oauth_redirect"
)

type oauth2StateKey struct{}

type OAuth2State struct {
Token *oauth2.Token
Redirect string
}

// OAuth2Provider exposes a subset of *oauth2.Config functions for easier testing.
// *oauth2.Config should be used instead of implementing this in production.
type OAuth2Provider interface {
AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string
Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
}

// OAuth2 returns the state from an oauth request.
func OAuth2(r *http.Request) OAuth2State {
oauth, ok := r.Context().Value(oauth2StateKey{}).(OAuth2State)
if !ok {
panic("developer error: oauth middleware not provided")
}
return oauth
}

// ExtractOAuth2 adds a middleware for handling OAuth2 callbacks.
// Any route that does not have a "code" URL parameter will be redirected
// to the handler configuration provided.
func ExtractOAuth2(provider OAuth2Provider) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")

if code == "" {
// If the code isn't provided, we'll redirect!
state, err := cryptorand.String(32)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: fmt.Sprintf("generate state string: %s", err),
})
return
}

http.SetCookie(rw, &http.Cookie{
Name: oauth2StateCookieName,
Value: state,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
// Redirect must always be specified, otherwise
// an old redirect could apply!
http.SetCookie(rw, &http.Cookie{
Name: oauth2RedirectCookieName,
Value: r.URL.Query().Get("redirect"),
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})

http.Redirect(rw, r, provider.AuthCodeURL(state, oauth2.AccessTypeOffline), http.StatusTemporaryRedirect)
return
}

if state == "" {
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
Message: "state must be provided",
})
return
}

stateCookie, err := r.Cookie(oauth2StateCookieName)
if err != nil {
httpapi.Write(rw, http.StatusUnauthorized, httpapi.Response{
Message: fmt.Sprintf("%q cookie must be provided", oauth2StateCookieName),
})
return
}
if stateCookie.Value != state {
httpapi.Write(rw, http.StatusUnauthorized, httpapi.Response{
Message: "state mismatched",
})
return
}

var redirect string
stateRedirect, err := r.Cookie(oauth2RedirectCookieName)
if err == nil {
redirect = stateRedirect.Value
}

oauthToken, err := provider.Exchange(r.Context(), code)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: fmt.Sprintf("exchange oauth code: %s", err),
})
return
}

ctx := context.WithValue(r.Context(), oauth2StateKey{}, OAuth2State{
Token: oauthToken,
Redirect: redirect,
})
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}
97 changes: 97 additions & 0 deletions coderd/httpmw/oauth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package httpmw_test

import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"

"github.com/coder/coder/coderd/httpmw"
)

type testOAuth2Provider struct {
}

func (*testOAuth2Provider) AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string {
return "?state=" + url.QueryEscape(state)
}

func (*testOAuth2Provider) Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: "hello",
}, nil
}

func TestOAuth2(t *testing.T) {
t.Parallel()
t.Run("RedirectWithoutCode", func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?redirect="+url.QueryEscape("/dashboard"), nil)
res := httptest.NewRecorder()
httpmw.ExtractOAuth2(&testOAuth2Provider{})(nil).ServeHTTP(res, req)
location := res.Header().Get("Location")
if !assert.NotEmpty(t, location) {
return
}
require.Len(t, res.Result().Cookies(), 2)
cookie := res.Result().Cookies()[1]
require.Equal(t, "/dashboard", cookie.Value)
})
t.Run("NoState", func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?code=something", nil)
res := httptest.NewRecorder()
httpmw.ExtractOAuth2(&testOAuth2Provider{})(nil).ServeHTTP(res, req)
require.Equal(t, http.StatusBadRequest, res.Result().StatusCode)
})
t.Run("NoStateCookie", func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?code=something&state=test", nil)
res := httptest.NewRecorder()
httpmw.ExtractOAuth2(&testOAuth2Provider{})(nil).ServeHTTP(res, req)
require.Equal(t, http.StatusUnauthorized, res.Result().StatusCode)
})
t.Run("MismatchedState", func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?code=something&state=test", nil)
req.AddCookie(&http.Cookie{
Name: "oauth_state",
Value: "mismatch",
})
res := httptest.NewRecorder()
httpmw.ExtractOAuth2(&testOAuth2Provider{})(nil).ServeHTTP(res, req)
require.Equal(t, http.StatusUnauthorized, res.Result().StatusCode)
})
t.Run("ExchangeCodeAndState", func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest("GET", "/?code=test&state=something", nil)
req.AddCookie(&http.Cookie{
Name: "oauth_state",
Value: "something",
})
req.AddCookie(&http.Cookie{
Name: "oauth_redirect",
Value: "/dashboard",
})
res := httptest.NewRecorder()
httpmw.ExtractOAuth2(&testOAuth2Provider{})(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
state := httpmw.OAuth2(r)
require.Equal(t, "/dashboard", state.Redirect)
})).ServeHTTP(res, req)
})

// t.Run("ExchangeCodeAndState", func(t *testing.T) {
// t.Parallel()
// req := httptest.NewRequest("GET", "/?code=test&state="+url.QueryEscape(state), nil)
// res := httptest.NewRecorder()
// ExtractOAuth(log, cipher, &testOAuthProvider{})(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// rw.WriteHeader(http.StatusOK)
// })).ServeHTTP(res, req)
// assert.Equal(t, res.Result().StatusCode, http.StatusOK)
// })
}
Loading