2016-07-25 20:00:28 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2017-03-08 18:33:19 +00:00
|
|
|
"context"
|
2016-07-25 20:00:28 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"path"
|
2016-08-11 03:51:58 +00:00
|
|
|
"sync/atomic"
|
2016-07-25 20:00:28 +00:00
|
|
|
"time"
|
|
|
|
|
2016-10-05 23:38:20 +00:00
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
|
2016-11-22 23:35:46 +00:00
|
|
|
"github.com/Sirupsen/logrus"
|
2017-01-14 09:18:48 +00:00
|
|
|
"github.com/gorilla/handlers"
|
2016-07-25 20:00:28 +00:00
|
|
|
"github.com/gorilla/mux"
|
|
|
|
|
2016-08-11 05:31:42 +00:00
|
|
|
"github.com/coreos/dex/connector"
|
|
|
|
"github.com/coreos/dex/storage"
|
2016-07-25 20:00:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Connector is a connector with metadata.
|
|
|
|
type Connector struct {
|
|
|
|
ID string
|
|
|
|
DisplayName string
|
|
|
|
Connector connector.Connector
|
|
|
|
}
|
|
|
|
|
|
|
|
// Config holds the server's configuration options.
|
2016-08-20 00:24:49 +00:00
|
|
|
//
|
|
|
|
// Multiple servers using the same storage are expected to be configured identically.
|
2016-07-25 20:00:28 +00:00
|
|
|
type Config struct {
|
|
|
|
Issuer string
|
|
|
|
|
|
|
|
// The backing persistence layer.
|
|
|
|
Storage storage.Storage
|
|
|
|
|
|
|
|
// Strategies for federated identity.
|
|
|
|
Connectors []Connector
|
|
|
|
|
2016-08-20 00:24:49 +00:00
|
|
|
// Valid values are "code" to enable the code flow and "token" to enable the implicit
|
|
|
|
// flow. If no response types are supplied this value defaults to "code".
|
|
|
|
SupportedResponseTypes []string
|
|
|
|
|
2017-01-14 09:18:48 +00:00
|
|
|
// List of allowed origins for CORS requests on discovery, token and keys endpoint.
|
2016-12-29 09:25:16 +00:00
|
|
|
// If none are indicated, CORS requests are disabled. Passing in "*" will allow any
|
|
|
|
// domain.
|
2017-01-14 09:18:48 +00:00
|
|
|
AllowedOrigins []string
|
2016-12-29 09:25:16 +00:00
|
|
|
|
2016-10-07 18:53:01 +00:00
|
|
|
// If enabled, the server won't prompt the user to approve authorization requests.
|
|
|
|
// Logging in implies approval.
|
|
|
|
SkipApprovalScreen bool
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
RotateKeysAfter time.Duration // Defaults to 6 hours.
|
|
|
|
IDTokensValidFor time.Duration // Defaults to 24 hours
|
|
|
|
|
2016-10-13 01:51:32 +00:00
|
|
|
GCFrequency time.Duration // Defaults to 5 minutes
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
// If specified, the server will use this function for determining time.
|
|
|
|
Now func() time.Time
|
2016-08-25 20:10:19 +00:00
|
|
|
|
2016-10-05 23:38:20 +00:00
|
|
|
EnablePasswordDB bool
|
|
|
|
|
2016-11-30 22:26:54 +00:00
|
|
|
Web WebConfig
|
2016-11-22 23:35:46 +00:00
|
|
|
|
|
|
|
Logger logrus.FieldLogger
|
2016-11-30 22:26:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// WebConfig holds the server's frontend templates and asset configuration.
|
|
|
|
//
|
|
|
|
// These are currently very custom to CoreOS and it's not recommended that
|
|
|
|
// outside users attempt to customize these.
|
|
|
|
type WebConfig struct {
|
|
|
|
// A filepath to web static.
|
|
|
|
//
|
|
|
|
// It is expected to contain the following directories:
|
|
|
|
//
|
|
|
|
// * static - Static static served at "( issuer URL )/static".
|
|
|
|
// * templates - HTML templates controlled by dex.
|
|
|
|
// * themes/(theme) - Static static served at "( issuer URL )/theme".
|
|
|
|
//
|
|
|
|
Dir string
|
|
|
|
|
|
|
|
// Defaults to "( issuer URL )/theme/logo.png"
|
|
|
|
LogoURL string
|
|
|
|
|
|
|
|
// Defaults to "dex"
|
|
|
|
Issuer string
|
|
|
|
|
|
|
|
// Defaults to "coreos"
|
|
|
|
Theme string
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func value(val, defaultValue time.Duration) time.Duration {
|
|
|
|
if val == 0 {
|
|
|
|
return defaultValue
|
|
|
|
}
|
|
|
|
return val
|
|
|
|
}
|
|
|
|
|
|
|
|
// Server is the top level object.
|
|
|
|
type Server struct {
|
|
|
|
issuerURL url.URL
|
|
|
|
|
|
|
|
// Read-only map of connector IDs to connectors.
|
|
|
|
connectors map[string]Connector
|
|
|
|
|
|
|
|
storage storage.Storage
|
|
|
|
|
|
|
|
mux http.Handler
|
|
|
|
|
2016-08-25 20:10:19 +00:00
|
|
|
templates *templates
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
// If enabled, don't prompt user for approval after logging in through connector.
|
|
|
|
skipApproval bool
|
|
|
|
|
2016-08-20 00:24:49 +00:00
|
|
|
supportedResponseTypes map[string]bool
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
now func() time.Time
|
|
|
|
|
|
|
|
idTokensValidFor time.Duration
|
2016-11-22 23:35:46 +00:00
|
|
|
|
|
|
|
logger logrus.FieldLogger
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
2016-10-04 07:26:04 +00:00
|
|
|
// NewServer constructs a server from the provided config.
|
2016-10-13 01:51:32 +00:00
|
|
|
func NewServer(ctx context.Context, c Config) (*Server, error) {
|
|
|
|
return newServer(ctx, c, defaultRotationStrategy(
|
2016-07-25 20:00:28 +00:00
|
|
|
value(c.RotateKeysAfter, 6*time.Hour),
|
|
|
|
value(c.IDTokensValidFor, 24*time.Hour),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
|
2016-10-13 01:51:32 +00:00
|
|
|
func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) (*Server, error) {
|
2016-07-25 20:00:28 +00:00
|
|
|
issuerURL, err := url.Parse(c.Issuer)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("server: can't parse issuer URL")
|
|
|
|
}
|
2016-10-05 23:38:20 +00:00
|
|
|
if c.EnablePasswordDB {
|
|
|
|
c.Connectors = append(c.Connectors, Connector{
|
|
|
|
ID: "local",
|
|
|
|
DisplayName: "Email",
|
|
|
|
Connector: newPasswordDB(c.Storage),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
if len(c.Connectors) == 0 {
|
|
|
|
return nil, errors.New("server: no connectors specified")
|
|
|
|
}
|
|
|
|
if c.Storage == nil {
|
|
|
|
return nil, errors.New("server: storage cannot be nil")
|
|
|
|
}
|
2016-08-20 00:24:49 +00:00
|
|
|
if len(c.SupportedResponseTypes) == 0 {
|
|
|
|
c.SupportedResponseTypes = []string{responseTypeCode}
|
|
|
|
}
|
|
|
|
|
|
|
|
supported := make(map[string]bool)
|
|
|
|
for _, respType := range c.SupportedResponseTypes {
|
|
|
|
switch respType {
|
2017-01-09 18:46:16 +00:00
|
|
|
case responseTypeCode, responseTypeIDToken, responseTypeToken:
|
2016-08-20 00:24:49 +00:00
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unsupported response_type %q", respType)
|
|
|
|
}
|
|
|
|
supported[respType] = true
|
|
|
|
}
|
2016-07-25 20:00:28 +00:00
|
|
|
|
2016-11-30 22:26:54 +00:00
|
|
|
web := webConfig{
|
|
|
|
dir: c.Web.Dir,
|
|
|
|
logoURL: c.Web.LogoURL,
|
|
|
|
issuerURL: c.Issuer,
|
|
|
|
issuer: c.Web.Issuer,
|
|
|
|
theme: c.Web.Theme,
|
|
|
|
}
|
|
|
|
|
|
|
|
static, theme, tmpls, err := loadWebConfig(web)
|
2016-08-25 20:10:19 +00:00
|
|
|
if err != nil {
|
2016-11-30 22:26:54 +00:00
|
|
|
return nil, fmt.Errorf("server: failed to load web static: %v", err)
|
2016-08-25 20:10:19 +00:00
|
|
|
}
|
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
now := c.Now
|
|
|
|
if now == nil {
|
|
|
|
now = time.Now
|
|
|
|
}
|
|
|
|
|
|
|
|
s := &Server{
|
2017-01-14 09:18:48 +00:00
|
|
|
issuerURL: *issuerURL,
|
|
|
|
connectors: make(map[string]Connector),
|
|
|
|
storage: newKeyCacher(c.Storage, now),
|
|
|
|
supportedResponseTypes: supported,
|
|
|
|
idTokensValidFor: value(c.IDTokensValidFor, 24*time.Hour),
|
|
|
|
skipApproval: c.SkipApprovalScreen,
|
|
|
|
now: now,
|
|
|
|
templates: tmpls,
|
|
|
|
logger: c.Logger,
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, conn := range c.Connectors {
|
|
|
|
s.connectors[conn.ID] = conn
|
|
|
|
}
|
|
|
|
|
|
|
|
r := mux.NewRouter()
|
|
|
|
handleFunc := func(p string, h http.HandlerFunc) {
|
|
|
|
r.HandleFunc(path.Join(issuerURL.Path, p), h)
|
|
|
|
}
|
2016-11-30 22:26:54 +00:00
|
|
|
handlePrefix := func(p string, h http.Handler) {
|
|
|
|
prefix := path.Join(issuerURL.Path, p)
|
|
|
|
r.PathPrefix(prefix).Handler(http.StripPrefix(prefix, h))
|
|
|
|
}
|
2017-01-14 09:18:48 +00:00
|
|
|
handleWithCORS := func(p string, h http.HandlerFunc) {
|
|
|
|
var handler http.Handler = h
|
|
|
|
if len(c.AllowedOrigins) > 0 {
|
|
|
|
corsOption := handlers.AllowedOrigins(c.AllowedOrigins)
|
|
|
|
handler = handlers.CORS(corsOption)(handler)
|
|
|
|
}
|
|
|
|
r.Handle(path.Join(issuerURL.Path, p), handler)
|
|
|
|
}
|
2016-12-14 22:17:59 +00:00
|
|
|
r.NotFoundHandler = http.HandlerFunc(http.NotFound)
|
2016-07-25 20:00:28 +00:00
|
|
|
|
2016-08-25 23:18:09 +00:00
|
|
|
discoveryHandler, err := s.discoveryHandler()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-01-14 09:18:48 +00:00
|
|
|
handleWithCORS("/.well-known/openid-configuration", discoveryHandler)
|
2016-08-25 23:18:09 +00:00
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
// TODO(ericchiang): rate limit certain paths based on IP.
|
2017-01-14 09:18:48 +00:00
|
|
|
handleWithCORS("/token", s.handleToken)
|
|
|
|
handleWithCORS("/keys", s.handlePublicKeys)
|
2016-07-25 20:00:28 +00:00
|
|
|
handleFunc("/auth", s.handleAuthorization)
|
|
|
|
handleFunc("/auth/{connector}", s.handleConnectorLogin)
|
2016-10-27 17:08:08 +00:00
|
|
|
handleFunc("/callback", s.handleConnectorCallback)
|
2016-07-25 20:00:28 +00:00
|
|
|
handleFunc("/approval", s.handleApproval)
|
2016-10-04 23:45:52 +00:00
|
|
|
handleFunc("/healthz", s.handleHealth)
|
2016-11-30 22:26:54 +00:00
|
|
|
handlePrefix("/static", static)
|
|
|
|
handlePrefix("/theme", theme)
|
2016-07-25 20:00:28 +00:00
|
|
|
s.mux = r
|
|
|
|
|
2016-12-12 22:54:01 +00:00
|
|
|
s.startKeyRotation(ctx, rotationStrategy, now)
|
|
|
|
s.startGarbageCollection(ctx, value(c.GCFrequency, 5*time.Minute), now)
|
2016-10-13 01:51:32 +00:00
|
|
|
|
2016-07-25 20:00:28 +00:00
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
s.mux.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) absPath(pathItems ...string) string {
|
|
|
|
paths := make([]string, len(pathItems)+1)
|
|
|
|
paths[0] = s.issuerURL.Path
|
|
|
|
copy(paths[1:], pathItems)
|
|
|
|
return path.Join(paths...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) absURL(pathItems ...string) string {
|
|
|
|
u := s.issuerURL
|
|
|
|
u.Path = s.absPath(pathItems...)
|
|
|
|
return u.String()
|
|
|
|
}
|
2016-08-11 03:51:58 +00:00
|
|
|
|
2016-10-05 23:38:20 +00:00
|
|
|
func newPasswordDB(s storage.Storage) interface {
|
|
|
|
connector.Connector
|
|
|
|
connector.PasswordConnector
|
|
|
|
} {
|
|
|
|
return passwordDB{s}
|
|
|
|
}
|
|
|
|
|
|
|
|
type passwordDB struct {
|
|
|
|
s storage.Storage
|
|
|
|
}
|
|
|
|
|
2016-11-18 21:40:41 +00:00
|
|
|
func (db passwordDB) Login(ctx context.Context, s connector.Scopes, email, password string) (connector.Identity, bool, error) {
|
2016-10-05 23:38:20 +00:00
|
|
|
p, err := db.s.GetPassword(email)
|
|
|
|
if err != nil {
|
|
|
|
if err != storage.ErrNotFound {
|
2016-12-12 22:54:01 +00:00
|
|
|
return connector.Identity{}, false, fmt.Errorf("get password: %v", err)
|
2016-10-05 23:38:20 +00:00
|
|
|
}
|
2016-11-01 21:03:22 +00:00
|
|
|
return connector.Identity{}, false, nil
|
2016-10-05 23:38:20 +00:00
|
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword(p.Hash, []byte(password)); err != nil {
|
|
|
|
return connector.Identity{}, false, nil
|
|
|
|
}
|
|
|
|
return connector.Identity{
|
|
|
|
UserID: p.UserID,
|
|
|
|
Username: p.Username,
|
|
|
|
Email: p.Email,
|
|
|
|
EmailVerified: true,
|
|
|
|
}, true, nil
|
|
|
|
}
|
|
|
|
|
2016-11-18 21:40:41 +00:00
|
|
|
func (db passwordDB) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) {
|
|
|
|
// If the user has been deleted, the refresh token will be rejected.
|
|
|
|
p, err := db.s.GetPassword(identity.Email)
|
|
|
|
if err != nil {
|
|
|
|
if err == storage.ErrNotFound {
|
|
|
|
return connector.Identity{}, errors.New("user not found")
|
|
|
|
}
|
|
|
|
return connector.Identity{}, fmt.Errorf("get password: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// User removed but a new user with the same email exists.
|
|
|
|
if p.UserID != identity.UserID {
|
|
|
|
return connector.Identity{}, errors.New("user not found")
|
|
|
|
}
|
|
|
|
|
|
|
|
// If a user has updated their username, that will be reflected in the
|
|
|
|
// refreshed token.
|
|
|
|
//
|
|
|
|
// No other fields are expected to be refreshable as email is effectively used
|
|
|
|
// as an ID and this implementation doesn't deal with groups.
|
|
|
|
identity.Username = p.Username
|
|
|
|
|
|
|
|
return identity, nil
|
|
|
|
}
|
|
|
|
|
2016-08-11 03:51:58 +00:00
|
|
|
// newKeyCacher returns a storage which caches keys so long as the next
|
|
|
|
func newKeyCacher(s storage.Storage, now func() time.Time) storage.Storage {
|
|
|
|
if now == nil {
|
|
|
|
now = time.Now
|
|
|
|
}
|
|
|
|
return &keyCacher{Storage: s, now: now}
|
|
|
|
}
|
|
|
|
|
|
|
|
type keyCacher struct {
|
|
|
|
storage.Storage
|
|
|
|
|
|
|
|
now func() time.Time
|
|
|
|
keys atomic.Value // Always holds nil or type *storage.Keys.
|
|
|
|
}
|
|
|
|
|
|
|
|
func (k *keyCacher) GetKeys() (storage.Keys, error) {
|
|
|
|
keys, ok := k.keys.Load().(*storage.Keys)
|
|
|
|
if ok && keys != nil && k.now().Before(keys.NextRotation) {
|
|
|
|
return *keys, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
storageKeys, err := k.Storage.GetKeys()
|
|
|
|
if err != nil {
|
|
|
|
return storageKeys, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if k.now().Before(storageKeys.NextRotation) {
|
|
|
|
k.keys.Store(&storageKeys)
|
|
|
|
}
|
|
|
|
return storageKeys, nil
|
|
|
|
}
|
2016-10-13 01:51:32 +00:00
|
|
|
|
2016-12-12 22:54:01 +00:00
|
|
|
func (s *Server) startGarbageCollection(ctx context.Context, frequency time.Duration, now func() time.Time) {
|
2016-10-13 01:51:32 +00:00
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
case <-time.After(frequency):
|
2016-12-12 22:54:01 +00:00
|
|
|
if r, err := s.storage.GarbageCollect(now()); err != nil {
|
|
|
|
s.logger.Errorf("garbage collection failed: %v", err)
|
2016-10-14 04:55:56 +00:00
|
|
|
} else if r.AuthRequests > 0 || r.AuthCodes > 0 {
|
2017-04-04 16:47:53 +00:00
|
|
|
s.logger.Infof("garbage collection run, delete auth requests=%d, auth codes=%d", r.AuthRequests, r.AuthCodes)
|
2016-10-13 01:51:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return
|
|
|
|
}
|