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
32 changes: 18 additions & 14 deletions cmd/dex/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,19 +95,23 @@ type password storage.Password

func (p *password) UnmarshalJSON(b []byte) error {
var data struct {
Email string `json:"email"`
Username string `json:"username"`
UserID string `json:"userID"`
Hash string `json:"hash"`
HashFromEnv string `json:"hashFromEnv"`
Email string `json:"email"`
Username string `json:"username"`
PreferredUsername string `json:"preferredUsername"`
UserID string `json:"userID"`
Hash string `json:"hash"`
HashFromEnv string `json:"hashFromEnv"`
Groups []string `json:"groups"`
}
if err := json.Unmarshal(b, &data); err != nil {
return err
}
*p = password(storage.Password{
Email: data.Email,
Username: data.Username,
UserID: data.UserID,
Email: data.Email,
Username: data.Username,
PreferredUsername: data.PreferredUsername,
UserID: data.UserID,
Groups: data.Groups,
})
if len(data.Hash) == 0 && len(data.HashFromEnv) > 0 {
data.Hash = os.Getenv(data.HashFromEnv)
Expand Down Expand Up @@ -275,12 +279,12 @@ var (
_ StorageConfig = (*ent.MySQL)(nil)
)

func getORMBasedSQLStorage(normal, entBased StorageConfig) func() StorageConfig {
func getORMBasedSQLStorage(normal, entBased func() StorageConfig) func() StorageConfig {
return func() StorageConfig {
if featureflags.EntEnabled.Enabled() {
return entBased
return entBased()
}
return normal
return normal()
}
}

Expand Down Expand Up @@ -309,9 +313,9 @@ var storages = map[string]func() StorageConfig{
"etcd": func() StorageConfig { return new(etcd.Etcd) },
"kubernetes": func() StorageConfig { return new(kubernetes.Config) },
"memory": func() StorageConfig { return new(memory.Config) },
"sqlite3": getORMBasedSQLStorage(&sql.SQLite3{}, &ent.SQLite3{}),
"postgres": getORMBasedSQLStorage(&sql.Postgres{}, &ent.Postgres{}),
"mysql": getORMBasedSQLStorage(&sql.MySQL{}, &ent.MySQL{}),
"sqlite3": getORMBasedSQLStorage(func() StorageConfig { return new(sql.SQLite3) }, func() StorageConfig { return new(ent.SQLite3) }),
"postgres": getORMBasedSQLStorage(func() StorageConfig { return new(sql.Postgres) }, func() StorageConfig { return new(ent.Postgres) }),
"mysql": getORMBasedSQLStorage(func() StorageConfig { return new(sql.MySQL) }, func() StorageConfig { return new(ent.MySQL) }),
}

// UnmarshalJSON allows Storage to implement the unmarshaler interface to
Expand Down
17 changes: 13 additions & 4 deletions cmd/dex/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ staticPasswords:
# bcrypt hash of the string "password"
hash: "$2a$10$33EMT0cVYVlPy6WAMCLsceLYjWhuHpbz5yuZxu/GAFj03J9Lytjuy"
username: "admin"
preferredUsername: "admin-public"
groups:
- "team-a"
- "team-a/admins"
userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
- email: "foo@example.com"
# base64'd value of the same bcrypt hash above. We want to be able to parse both of these
Expand Down Expand Up @@ -206,10 +210,15 @@ additionalFeatures: [
EnablePasswordDB: true,
StaticPasswords: []password{
{
Email: "admin@example.com",
Hash: []byte("$2a$10$33EMT0cVYVlPy6WAMCLsceLYjWhuHpbz5yuZxu/GAFj03J9Lytjuy"),
Username: "admin",
UserID: "08a8684b-db88-4b73-90a9-3cd1661f5466",
Email: "admin@example.com",
Hash: []byte("$2a$10$33EMT0cVYVlPy6WAMCLsceLYjWhuHpbz5yuZxu/GAFj03J9Lytjuy"),
Username: "admin",
PreferredUsername: "admin-public",
UserID: "08a8684b-db88-4b73-90a9-3cd1661f5466",
Groups: []string{
"team-a",
"team-a/admins",
},
},
{
Email: "foo@example.com",
Expand Down
4 changes: 4 additions & 0 deletions config.dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@ staticPasswords:
- email: "admin@example.com"
hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
username: "admin"
preferredUsername: "admin"
groups:
- "team-a"
- "team-a/admins"
userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
13 changes: 12 additions & 1 deletion config.yaml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,15 @@ enablePasswordDB: true
# A static list of passwords for the password connector.
#
# Alternatively, passwords my be added/updated through the gRPC API.
# staticPasswords: []
# staticPasswords:
# - email: "user@example.com"
# # bcrypt hash of the string "password"
# hash: "$2a$10$examplehash..."
# username: "user-login"
# # Optional. Maps to OIDC "preferred_username" claim.
# preferredUsername: "user-public"
# # Optional. Maps to OIDC "groups" claim (when 'groups' scope is requested).
# groups:
# - "team-a"
# - "team-a/admins"
# userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
4 changes: 4 additions & 0 deletions examples/config-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,8 @@ staticPasswords:
# bcrypt hash of the string "password": $(echo password | htpasswd -BinC 10 admin | cut -d: -f2)
hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
username: "admin"
preferredUsername: "admin"
groups:
- "team-a"
- "team-a/admins"
userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
4 changes: 4 additions & 0 deletions examples/k8s/dex.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ data:
# bcrypt hash of the string "password": $(echo password | htpasswd -BinC 10 admin | cut -d: -f2)
hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
username: "admin"
preferredUsername: "admin"
groups:
- "team-a"
- "team-a/admins"
userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
---
apiVersion: v1
Expand Down
80 changes: 80 additions & 0 deletions server/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/AppsFlyer/go-sundheit/checks"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
"golang.org/x/oauth2"

"github.com/dexidp/dex/storage"
Expand Down Expand Up @@ -402,6 +403,85 @@ func TestHandlePassword(t *testing.T) {
}
}

func TestHandlePassword_LocalPasswordDBClaims(t *testing.T) {
ctx := t.Context()

// Setup a dex server.
httpServer, s := newTestServer(t, func(c *Config) {
c.PasswordConnector = "local"
})
defer httpServer.Close()

// Client credentials for password grant.
client := storage.Client{
ID: "test",
Secret: "barfoo",
RedirectURIs: []string{"foo://bar.com/", "https://auth.example.com"},
}
require.NoError(t, s.storage.CreateClient(ctx, client))

// Enable local connector.
localConn := storage.Connector{
ID: "local",
Type: LocalConnector,
Name: "Email",
ResourceVersion: "1",
}
require.NoError(t, s.storage.CreateConnector(ctx, localConn))
_, err := s.OpenConnector(localConn)
require.NoError(t, err)

// Create a user in the password DB with groups and preferred_username.
pw := "secret"
hash, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
require.NoError(t, err)
require.NoError(t, s.storage.CreatePassword(ctx, storage.Password{
Email: "user@example.com",
Username: "user-login",
PreferredUsername: "user-public",
UserID: "user-id",
Groups: []string{"team-a", "team-a/admins"},
Hash: hash,
}))

u, err := url.Parse(s.issuerURL.String())
require.NoError(t, err)
u.Path = path.Join(u.Path, "/token")

v := url.Values{}
v.Add("scope", "openid profile email groups")
v.Add("grant_type", "password")
v.Add("username", "user@example.com")
v.Add("password", pw)

req, _ := http.NewRequest("POST", u.String(), bytes.NewBufferString(v.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth("test", "barfoo")

rr := httptest.NewRecorder()
s.ServeHTTP(rr, req)
require.Equal(t, http.StatusOK, rr.Code)

var tokenResponse struct {
IDToken string `json:"id_token"`
}
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &tokenResponse))
require.NotEmpty(t, tokenResponse.IDToken)

p, err := oidc.NewProvider(ctx, httpServer.URL)
require.NoError(t, err)
idToken, err := p.Verifier(&oidc.Config{SkipClientIDCheck: true}).Verify(ctx, tokenResponse.IDToken)
require.NoError(t, err)

var claims struct {
PreferredUsername string `json:"preferred_username"`
Groups []string `json:"groups"`
}
require.NoError(t, idToken.Claims(&claims))
require.Equal(t, "user-public", claims.PreferredUsername)
require.Equal(t, []string{"team-a", "team-a/admins"}, claims.Groups)
}

func TestHandlePasswordLoginWithSkipApproval(t *testing.T) {
ctx := t.Context()

Expand Down
14 changes: 9 additions & 5 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,10 +565,12 @@ func (db passwordDB) Login(ctx context.Context, s connector.Scopes, email, passw
return connector.Identity{}, false, nil
}
return connector.Identity{
UserID: p.UserID,
Username: p.Username,
Email: p.Email,
EmailVerified: true,
UserID: p.UserID,
Username: p.Username,
PreferredUsername: p.PreferredUsername,
Email: p.Email,
EmailVerified: true,
Groups: p.Groups,
}, true, nil
}

Expand All @@ -591,8 +593,10 @@ func (db passwordDB) Refresh(ctx context.Context, s connector.Scopes, identity c
// 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.
// as an ID.
identity.Username = p.Username
identity.PreferredUsername = p.PreferredUsername
identity.Groups = p.Groups

return identity, nil
}
Expand Down
20 changes: 12 additions & 8 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1279,10 +1279,12 @@ func TestPasswordDB(t *testing.T) {
}

s.CreatePassword(ctx, storage.Password{
Email: "jane@example.com",
Username: "jane",
UserID: "foobar",
Hash: h,
Email: "jane@example.com",
Username: "jane",
PreferredUsername: "jane-public",
UserID: "foobar",
Groups: []string{"team-a", "team-a/admins"},
Hash: h,
})

tests := []struct {
Expand All @@ -1298,10 +1300,12 @@ func TestPasswordDB(t *testing.T) {
username: "jane@example.com",
password: pw,
wantIdentity: connector.Identity{
Email: "jane@example.com",
Username: "jane",
UserID: "foobar",
EmailVerified: true,
Email: "jane@example.com",
Username: "jane",
PreferredUsername: "jane-public",
UserID: "foobar",
EmailVerified: true,
Groups: []string{"team-a", "team-a/admins"},
},
},
{
Expand Down
20 changes: 12 additions & 8 deletions storage/conformance/conformance.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,10 +456,12 @@ func testPasswordCRUD(t *testing.T, s storage.Storage) {
}

password1 := storage.Password{
Email: "jane@example.com",
Hash: passwordHash1,
Username: "jane",
UserID: "foobar",
Email: "jane@example.com",
Hash: passwordHash1,
Username: "jane",
PreferredUsername: "jane-public",
UserID: "foobar",
Groups: []string{"team-a", "team-a/admins"},
}
if err := s.CreatePassword(ctx, password1); err != nil {
t.Fatalf("create password token: %v", err)
Expand All @@ -475,10 +477,12 @@ func testPasswordCRUD(t *testing.T, s storage.Storage) {
}

password2 := storage.Password{
Email: "john@example.com",
Hash: passwordHash2,
Username: "john",
UserID: "barfoo",
Email: "john@example.com",
Hash: passwordHash2,
Username: "john",
PreferredUsername: "john-public",
UserID: "barfoo",
Groups: []string{"team-b"},
}
if err := s.CreatePassword(ctx, password2); err != nil {
t.Fatalf("create password token: %v", err)
Expand Down
4 changes: 4 additions & 0 deletions storage/ent/client/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ func (d *Database) CreatePassword(ctx context.Context, password storage.Password
SetEmail(password.Email).
SetHash(password.Hash).
SetUsername(password.Username).
SetPreferredUsername(password.PreferredUsername).
SetUserID(password.UserID).
SetGroups(password.Groups).
Save(ctx)
if err != nil {
return convertDBError("create password: %w", err)
Expand Down Expand Up @@ -86,7 +88,9 @@ func (d *Database) UpdatePassword(ctx context.Context, email string, updater fun
SetEmail(newPassword.Email).
SetHash(newPassword.Hash).
SetUsername(newPassword.Username).
SetPreferredUsername(newPassword.PreferredUsername).
SetUserID(newPassword.UserID).
SetGroups(newPassword.Groups).
Save(ctx)
if err != nil {
return rollback(tx, "update password uploading: %w", err)
Expand Down
10 changes: 6 additions & 4 deletions storage/ent/client/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,12 @@ func toStorageRefreshToken(r *db.RefreshToken) storage.RefreshToken {

func toStoragePassword(p *db.Password) storage.Password {
return storage.Password{
Email: p.Email,
Hash: p.Hash,
Username: p.Username,
UserID: p.UserID,
Email: p.Email,
Hash: p.Hash,
Username: p.Username,
PreferredUsername: p.PreferredUsername,
UserID: p.UserID,
Groups: p.Groups,
}
}

Expand Down
2 changes: 2 additions & 0 deletions storage/ent/db/migrate/schema.go

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

Loading