Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ http.HandleFunc("/auth/google/callback", func(w http.ResponseWriter, r *http.Req
| `WithKey` | encrypts the cookie that carries the handshake between redirect and callback. Any string. |
| `WithSession` | an application's own session, instead of the cookie. `WithKey` is then not needed. |
| `WithAPIURL` | the application's own URL. A `RedirectURL` given as a path is resolved against it, and `https://` marks the cookie Secure behind a proxy. |
| `WithClient` | the HTTP client every call to a provider goes through: the exchange, the refresh, the profile and discovery. A traced transport there traces all of it. |
| `WithDriver[Provider]` | registers a provider type under a name, with its `ClientID`, `ClientSecret`, `RedirectURL` and, for a self-hosted provider, `BaseURL`. |

`APP_KEY` and `API_URL` are read from the environment when the option is not given.
Expand All @@ -59,6 +60,9 @@ social.Driver("google").RedirectURL("https://other.example/cb").Redirect(w, r)
social.Driver("google").Stateless().Redirect(w, r) // no session, no state check
```

`AuthURL(w, r)` is `Redirect` without the redirecting, for a handler that
sends the browser itself. It still starts the handshake.

## Tokens

```go
Expand All @@ -75,6 +79,7 @@ switch {
case errors.Is(err, sociable.ErrAccessDenied): // the person said no
case errors.Is(err, sociable.ErrInvalidState): // not started here, already used, or tampered with
case errors.Is(err, sociable.ErrUnknownDriver): // no driver configured under that name
case errors.Is(err, sociable.ErrDriverNotConfigured): // no credentials, endpoints or redirect URL
case errors.Is(err, sociable.ErrIDToken): // the OpenID Connect id token did not verify
case err != nil: // the provider refused, the exchange or the profile failed
}
Expand Down
138 changes: 138 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package sociable

import (
"errors"
"net/http"
"net/http/httptest"
"testing"

"golang.org/x/oauth2"
)

// unhosted has no endpoints until it is told where its host is.
type unhosted struct{ stub }

func (unhosted) Endpoint(c Credentials) oauth2.Endpoint {
if c.BaseURL == "" {
return oauth2.Endpoint{}
}

return stub{}.Endpoint(c)
}

// recording is a transport that counts what went through it.
type recording struct {
paths []string
}

func (self *recording) RoundTrip(request *http.Request) (*http.Response, error) {
self.paths = append(self.paths, request.URL.Path)

return http.DefaultTransport.RoundTrip(request)
}

func TestWithClientCarriesEveryCall(t *testing.T) {
t.Parallel()

server := newProviderServer(t)
transport := &recording{}
m := manager[stub](server, WithClient(&http.Client{Transport: transport}))

if _, err := signIn(t, m.Driver("stub")); err != nil {
t.Fatal(err)
}

if _, err := m.Driver("stub").RefreshToken(t.Context(), "old"); err != nil {
t.Fatal(err)
}

if _, err := m.Driver("stub").UserFromToken(t.Context(), &oauth2.Token{AccessToken: "at"}); err != nil {
t.Fatal(err)
}

want := []string{"/token", "/user", "/token", "/user"}
if len(transport.paths) != len(want) {
t.Fatalf("through the client: %v, want %v", transport.paths, want)
}

for index, path := range want {
if transport.paths[index] != path {
t.Errorf("call %d went to %s, want %s", index, transport.paths[index], path)
}
}
}

func TestAuthURL(t *testing.T) {
t.Parallel()

m := manager[stub](newProviderServer(t))

recorder := httptest.NewRecorder()

url, err := m.Driver("stub").AuthURL(recorder, httptest.NewRequest(http.MethodGet, "/auth", nil))
if err != nil {
t.Fatal(err)
}

if recorder.Code != http.StatusOK || recorder.Header().Get("Location") != "" {
t.Errorf("AuthURL redirected: %d %s", recorder.Code, recorder.Header().Get("Location"))
}

if len(recorder.Result().Cookies()) != 1 {
t.Error("the handshake was not started")
}

query := parse(t, url)
if query.Get("state") == "" || query.Get("code_challenge") == "" || query.Get("client_id") != "id" {
t.Errorf("url = %s", url)
}

if _, err := m.Driver("nope").AuthURL(recorder, httptest.NewRequest(http.MethodGet, "/auth", nil)); !errors.Is(err, ErrUnknownDriver) {
t.Errorf("unknown: %v", err)
}
}

func TestDriverNotConfigured(t *testing.T) {
t.Parallel()

server := newProviderServer(t)

cases := map[string]Credentials{
"no client id": {ClientSecret: "s", BaseURL: server.URL, RedirectURL: "/cb"},
"no endpoints": {ClientID: "id", ClientSecret: "s", RedirectURL: "/cb"},
"no redirect url": {ClientID: "id", ClientSecret: "s", BaseURL: server.URL},
}

for name, credentials := range cases {
t.Run(name, func(t *testing.T) {
t.Parallel()

m := New(WithKey("k"), WithAPIURL("https://app.example"), WithDriver[unhosted]("stub", credentials))
w, r := httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)

if err := m.Driver("stub").Redirect(w, r); !errors.Is(err, ErrDriverNotConfigured) {
t.Errorf("Redirect: %v", err)
}

if _, err := m.Driver("stub").AuthURL(w, r); !errors.Is(err, ErrDriverNotConfigured) {
t.Errorf("AuthURL: %v", err)
}

if _, err := m.Driver("stub").User(w, r); !errors.Is(err, ErrDriverNotConfigured) {
t.Errorf("User: %v", err)
}

if _, err := m.Driver("stub").Callback(w, r); !errors.Is(err, ErrDriverNotConfigured) {
t.Errorf("Callback: %v", err)
}

if _, err := m.Driver("stub").RefreshToken(t.Context(), "r"); !errors.Is(err, ErrDriverNotConfigured) {
t.Errorf("RefreshToken: %v", err)
}

if len(w.Result().Cookies()) != 0 {
t.Error("a handshake was started for a driver that cannot finish it")
}
})
}
}
17 changes: 16 additions & 1 deletion configuration.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package sociable

import "os"
import (
"net/http"
"os"
)

type config struct {
Key string
Expand All @@ -13,6 +16,10 @@ type config struct {
// Session holds the handshake. nil is a cookie encrypted under Key.
Session Session

// Client talks to the providers: the exchange, the refresh, the profile
// and discovery all go through it. nil is http.DefaultClient.
Client *http.Client

Drivers map[string]DriverContract
}

Expand All @@ -38,6 +45,14 @@ func WithSession(session Session) option {
}
}

// WithClient sets the HTTP client every call to a provider goes through, so
// a traced or timed-out transport there covers all of them.
func WithClient(client *http.Client) option {
return func(m *Manager) {
m.config.Client = client
}
}

func WithAPIURL(url string) option {
return func(m *Manager) {
m.config.APIURL = url
Expand Down
35 changes: 34 additions & 1 deletion driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package sociable

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

"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)

Expand All @@ -24,20 +26,51 @@ type driver struct {
stateless bool
}

type DriverContract interface {
// DriverContract is what Driver hands back: Socialite's provider surface, the
// chain that shapes a redirect and the calls that run the flow. A fake
// implements it too.
type DriverContract interface { //nolint:interfacebloat // Socialite's surface, all of it.
Scopes(scopes ...string) DriverContract
SetScopes(scopes ...string) DriverContract
With(params map[string]string) DriverContract
RedirectURL(url string) DriverContract
Stateless() DriverContract

Redirect(w http.ResponseWriter, r *http.Request) error
AuthURL(w http.ResponseWriter, r *http.Request) (string, error)
User(w http.ResponseWriter, r *http.Request) (*User, error)
Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Token, error)
UserFromToken(ctx context.Context, token *oauth2.Token) (*User, error)
RefreshToken(ctx context.Context, refreshToken string) (*oauth2.Token, error)
}

// configured is whether the driver can talk to its provider at all. A
// deployment without credentials, a preview or a test, should refuse the
// route rather than redirect somewhere half-built.
func (self driver) configured() error {
config := self.config()

if config.ClientID == "" || config.Endpoint.AuthURL == "" || config.Endpoint.TokenURL == "" || config.RedirectURL == "" {
return fmt.Errorf("%w: %s", ErrDriverNotConfigured, self.name)
}

return nil
}

// outbound is the context every call to the provider is made with: it
// carries the configured client to x/oauth2 and to go-oidc.
func (self driver) outbound(ctx context.Context) context.Context {
self.manager.mutex.RLock()
client := self.manager.config.Client
self.manager.mutex.RUnlock()

if client == nil {
return ctx
}

return oidc.ClientContext(context.WithValue(ctx, oauth2.HTTPClient, client), client)
}

// session is the configured one, or a cookie under Key.
func (self driver) session() (Session, error) {
self.manager.mutex.RLock()
Expand Down
23 changes: 19 additions & 4 deletions driver.redirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,24 @@ const (
// sends along are kept in the session, so the callback can check what came
// back and finish the exchange.
func (self driver) Redirect(w http.ResponseWriter, r *http.Request) error {
url, err := self.AuthURL(w, r)
if err != nil {
return err
}

http.Redirect(w, r, url, http.StatusFound)
return nil
}

// AuthURL is Redirect without the redirecting, for a handler that sends the
// browser itself. It still starts the handshake for this browser.
func (self driver) AuthURL(w http.ResponseWriter, r *http.Request) (string, error) {
if self.name == "" {
return ErrUnknownDriver
return "", ErrUnknownDriver
}

if err := self.configured(); err != nil {
return "", err
}

config := self.config()
Expand Down Expand Up @@ -65,12 +81,11 @@ func (self driver) Redirect(w http.ResponseWriter, r *http.Request) error {

if !self.stateless {
if err := self.remember(w, r, issued); err != nil {
return err
return "", err
}
}

http.Redirect(w, r, config.AuthCodeURL(issued.State, options...), http.StatusFound)
return nil
return config.AuthCodeURL(issued.State, options...), nil
}

func (self driver) remember(w http.ResponseWriter, r *http.Request, issued handshake) error {
Expand Down
6 changes: 5 additions & 1 deletion driver.token.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ func (self driver) RefreshToken(ctx context.Context, refreshToken string) (*oaut
return nil, ErrUnknownDriver
}

token, err := self.config().TokenSource(ctx, &oauth2.Token{RefreshToken: refreshToken}).Token()
if err := self.configured(); err != nil {
return nil, err
}

token, err := self.config().TokenSource(self.outbound(ctx), &oauth2.Token{RefreshToken: refreshToken}).Token()
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrExchange, err)
}
Expand Down
12 changes: 10 additions & 2 deletions driver.user.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func (self driver) User(w http.ResponseWriter, r *http.Request) (*User, error) {
// the token attached. The client presents the token and refreshes it when
// it can.
func (self driver) userFor(ctx context.Context, token *oauth2.Token) (*User, error) {
ctx = self.outbound(ctx)

raw, err := self.provider.GetUserByToken(ctx, self.config().Client(ctx, token), token, self.credentials)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrProfile, err)
Expand All @@ -58,6 +60,10 @@ func (self driver) userFor(ctx context.Context, token *oauth2.Token) (*User, err
// checked against the query, a refusal reported, and the code exchanged for
// a token.
func (self driver) Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Token, error) {
if err := self.configured(); err != nil {
return nil, err
}

issued, err := self.recall(w, r)
if err != nil {
return nil, err
Expand All @@ -78,15 +84,17 @@ func (self driver) Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Tok
options = append(options, oauth2.VerifierOption(issued.Verifier))
}

token, err := self.config().Exchange(r.Context(), query.Get("code"), options...)
ctx := self.outbound(r.Context())

token, err := self.config().Exchange(ctx, query.Get("code"), options...)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrExchange, err)
}

// An ID token comes only with an OpenID Connect request, which is what
// asking for openid makes it.
if issuer, ok := self.provider.(openIDProvider); ok && slices.Contains(self.scoped(), "openid") {
if err := self.verifyIDToken(r.Context(), issuer.Issuer(), token, issued.Nonce); err != nil {
if err := self.verifyIDToken(ctx, issuer.Issuer(), token, issued.Nonce); err != nil {
return nil, err
}
}
Expand Down
5 changes: 4 additions & 1 deletion errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import (
)

var (
ErrUnknownDriver = errors.New("sociable: unknown driver")
ErrUnknownDriver = errors.New("sociable: unknown driver")

// ErrDriverNotConfigured means the driver has no client id, no endpoints
// or no redirect URL. Refuse the route rather than redirect.
ErrDriverNotConfigured = errors.New("sociable: driver not configured")

ErrMissingKeyOrSession = errors.New("sociable: a Key or a Session is required")
Expand Down
8 changes: 7 additions & 1 deletion fake.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,16 @@ type fakeDriver struct {

// Redirect is a 302 to a URL nobody serves. No session, no state, no PKCE.
func (self fakeDriver) Redirect(w http.ResponseWriter, r *http.Request) error {
http.Redirect(w, r, "https://sociable.fake/"+self.name+"/authorize", http.StatusFound)
url, _ := self.AuthURL(w, r)
http.Redirect(w, r, url, http.StatusFound)
return nil
}

// AuthURL is the URL Redirect goes to.
func (self fakeDriver) AuthURL(http.ResponseWriter, *http.Request) (string, error) {
return "https://sociable.fake/" + self.name + "/authorize", nil
}

// User is the user Fake was given. Nothing on the request is read.
func (self fakeDriver) User(w http.ResponseWriter, r *http.Request) (*User, error) {
if self.user != nil {
Expand Down
Loading
Loading