diff --git a/README.md b/README.md index b04b123..d356860 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 @@ -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 } diff --git a/client_test.go b/client_test.go new file mode 100644 index 0000000..dcf24c7 --- /dev/null +++ b/client_test.go @@ -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") + } + }) + } +} diff --git a/configuration.go b/configuration.go index 9fc24dd..37e028f 100644 --- a/configuration.go +++ b/configuration.go @@ -1,6 +1,9 @@ package sociable -import "os" +import ( + "net/http" + "os" +) type config struct { Key string @@ -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 } @@ -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 diff --git a/driver.go b/driver.go index 918a3a7..c19287b 100644 --- a/driver.go +++ b/driver.go @@ -2,9 +2,11 @@ package sociable import ( "context" + "fmt" "net/http" "strings" + "github.com/coreos/go-oidc/v3/oidc" "golang.org/x/oauth2" ) @@ -24,7 +26,10 @@ 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 @@ -32,12 +37,40 @@ type DriverContract interface { 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() diff --git a/driver.redirect.go b/driver.redirect.go index 69c547c..d97490e 100644 --- a/driver.redirect.go +++ b/driver.redirect.go @@ -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() @@ -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 { diff --git a/driver.token.go b/driver.token.go index 85dfb94..b387852 100644 --- a/driver.token.go +++ b/driver.token.go @@ -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) } diff --git a/driver.user.go b/driver.user.go index 2dc91c2..8999ac8 100644 --- a/driver.user.go +++ b/driver.user.go @@ -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) @@ -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 @@ -78,7 +84,9 @@ 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) } @@ -86,7 +94,7 @@ func (self driver) Callback(w http.ResponseWriter, r *http.Request) (*oauth2.Tok // 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 } } diff --git a/errors.go b/errors.go index 0dbd032..eb0505b 100644 --- a/errors.go +++ b/errors.go @@ -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") diff --git a/fake.go b/fake.go index e5045c4..33d6e39 100644 --- a/fake.go +++ b/fake.go @@ -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 { diff --git a/fake_test.go b/fake_test.go index 518056f..865e5d3 100644 --- a/fake_test.go +++ b/fake_test.go @@ -27,6 +27,11 @@ func TestFakeRedirectsNowhere(t *testing.T) { if len(recorder.Result().Cookies()) != 0 { t.Error("a handshake was stored") } + + url, err := m.Driver("github").AuthURL(recorder, httptest.NewRequest(http.MethodGet, "/auth", nil)) + if err != nil || url != "https://sociable.fake/github/authorize" { + t.Errorf("AuthURL = %q, %v", url, err) + } } func TestFakeAnswersTheCallback(t *testing.T) { diff --git a/helpers_test.go b/helpers_test.go index 45340b1..6f9f2aa 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -317,3 +317,15 @@ func (self *memorySession) Pull(_ http.ResponseWriter, _ *http.Request, key stri return value, nil } + +// parse is the query of an auth URL. +func parse(t *testing.T, raw string) url.Values { + t.Helper() + + parsed, err := url.Parse(raw) + if err != nil { + t.Fatal(err) + } + + return parsed.Query() +}