Merge pull request #458 from bobbyrullo/load_static_cross_clients

Load trustedPeers in no DB mode, add x-client to example app
This commit is contained in:
bobbyrullo 2016-06-09 16:29:36 -07:00 committed by GitHub
commit ae56f6de85
18 changed files with 468 additions and 98 deletions

View file

@ -94,16 +94,24 @@ func ValidRedirectURL(rURL *url.URL, redirectURLs []url.URL) (url.URL, error) {
return url.URL{}, ErrorInvalidRedirectURL
}
func ClientsFromReader(r io.Reader) ([]Client, error) {
// LoadableClient contains sufficient information for creating a Client and its related entities.
type LoadableClient struct {
Client Client
TrustedPeers []string
}
func ClientsFromReader(r io.Reader) ([]LoadableClient, error) {
var c []struct {
ID string `json:"id"`
Secret string `json:"secret"`
RedirectURLs []string `json:"redirectURLs"`
Admin bool `json:"admin"`
TrustedPeers []string `json:"trustedPeers"`
}
if err := json.NewDecoder(r).Decode(&c); err != nil {
return nil, err
}
clients := make([]Client, len(c))
clients := make([]LoadableClient, len(c))
for i, client := range c {
if client.ID == "" {
return nil, errors.New("clients must have an ID")
@ -120,7 +128,8 @@ func ClientsFromReader(r io.Reader) ([]Client, error) {
redirectURIs[j] = *uri
}
clients[i] = Client{
clients[i] = LoadableClient{
Client: Client{
Credentials: oidc.ClientCredentials{
ID: client.ID,
Secret: client.Secret,
@ -128,6 +137,9 @@ func ClientsFromReader(r io.Reader) ([]Client, error) {
Metadata: oidc.ClientMetadata{
RedirectURIs: redirectURIs,
},
Admin: client.Admin,
},
TrustedPeers: client.TrustedPeers,
}
}
return clients, nil

View file

@ -13,11 +13,13 @@ import (
var (
goodSecret1 = base64.URLEncoding.EncodeToString([]byte("my_secret"))
goodSecret2 = base64.URLEncoding.EncodeToString([]byte("my_other_secret"))
goodSecret3 = base64.URLEncoding.EncodeToString([]byte("yet_another_secret"))
goodClient1 = `{
"id": "my_id",
"secret": "` + goodSecret1 + `",
"redirectURLs": ["https://client.example.com"]
"redirectURLs": ["https://client.example.com"],
"admin": true
}`
goodClient2 = `{
@ -26,6 +28,13 @@ var (
"redirectURLs": ["https://client2.example.com","https://client2_a.example.com"]
}`
goodClient3 = `{
"id": "yet_another_id",
"secret": "` + goodSecret3 + `",
"redirectURLs": ["https://client3.example.com","https://client3_a.example.com"],
"trustedPeers":["goodClient1", "goodClient2"]
}`
badURLClient = `{
"id": "my_id",
"secret": "` + goodSecret1 + `",
@ -51,17 +60,18 @@ var (
func TestClientsFromReader(t *testing.T) {
tests := []struct {
json string
want []Client
want []LoadableClient
wantErr bool
}{
{
json: "[]",
want: []Client{},
want: []LoadableClient{},
},
{
json: "[" + goodClient1 + "]",
want: []Client{
want: []LoadableClient{
{
Client: Client{
Credentials: oidc.ClientCredentials{
ID: "my_id",
Secret: goodSecret1,
@ -71,13 +81,16 @@ func TestClientsFromReader(t *testing.T) {
mustParseURL(t, "https://client.example.com"),
},
},
Admin: true,
},
},
},
},
{
json: "[" + strings.Join([]string{goodClient1, goodClient2}, ",") + "]",
want: []Client{
want: []LoadableClient{
{
Client: Client{
Credentials: oidc.ClientCredentials{
ID: "my_id",
Secret: goodSecret1,
@ -87,8 +100,11 @@ func TestClientsFromReader(t *testing.T) {
mustParseURL(t, "https://client.example.com"),
},
},
Admin: true,
},
},
{
Client: Client{
Credentials: oidc.ClientCredentials{
ID: "my_other_id",
Secret: goodSecret2,
@ -102,6 +118,27 @@ func TestClientsFromReader(t *testing.T) {
},
},
},
},
{
json: "[" + goodClient3 + "]",
want: []LoadableClient{
{
Client: Client{
Credentials: oidc.ClientCredentials{
ID: "yet_another_id",
Secret: goodSecret3,
},
Metadata: oidc.ClientMetadata{
RedirectURIs: []url.URL{
mustParseURL(t, "https://client3.example.com"),
mustParseURL(t, "https://client3_a.example.com"),
},
},
},
TrustedPeers: []string{"goodClient1", "goodClient2"},
},
},
},
{
json: "[" + badURLClient + "]",
wantErr: true,

View file

@ -24,8 +24,9 @@ func makeTestFixtures() *testFixtures {
f := &testFixtures{}
dbMap := db.NewMemDB()
clients := []client.Client{
clients := []client.LoadableClient{
{
Client: client.Client{
Credentials: oidc.ClientCredentials{
ID: "client.example.com",
Secret: goodSecret,
@ -37,6 +38,7 @@ func makeTestFixtures() *testFixtures {
},
Admin: true,
},
},
}
clientIDGenerator := func(hostport string) (string, error) {
return hostport, nil

View file

@ -212,14 +212,23 @@ func (r *clientRepo) All(tx repo.Transaction) ([]client.Client, error) {
return cs, nil
}
func NewClientRepoFromClients(dbm *gorp.DbMap, cs []client.Client) (client.ClientRepo, error) {
func NewClientRepoFromClients(dbm *gorp.DbMap, cs []client.LoadableClient) (client.ClientRepo, error) {
repo := NewClientRepo(dbm).(*clientRepo)
for _, c := range cs {
cm, err := newClientModel(c)
cm, err := newClientModel(c.Client)
if err != nil {
return nil, err
}
err = repo.executor(nil).Insert(cm)
if err != nil {
return nil, err
}
err = repo.SetTrustedPeers(nil, c.Client.Credentials.ID, c.TrustedPeers)
if err != nil {
return nil, err
}
}
return repo, nil
}
@ -304,14 +313,6 @@ func (r *clientRepo) SetTrustedPeers(tx repo.Transaction, clientID string, clien
return err
}
// Verify that all the clients are valid
for _, curID := range clientIDs {
_, err := r.get(tx, curID)
if err != nil {
return err
}
}
// Set the clients
rows := []interface{}{}
for _, curID := range clientIDs {

237
examples/app/assets.go Normal file
View file

@ -0,0 +1,237 @@
// Code generated by go-bindata.
// sources:
// data/index.html
// DO NOT EDIT!
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
func bindataRead(data []byte, name string) ([]byte, error) {
gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err)
}
var buf bytes.Buffer
_, err = io.Copy(&buf, gz)
clErr := gz.Close()
if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err)
}
if clErr != nil {
return nil, err
}
return buf.Bytes(), nil
}
type asset struct {
bytes []byte
info os.FileInfo
}
type bindataFileInfo struct {
name string
size int64
mode os.FileMode
modTime time.Time
}
func (fi bindataFileInfo) Name() string {
return fi.name
}
func (fi bindataFileInfo) Size() int64 {
return fi.size
}
func (fi bindataFileInfo) Mode() os.FileMode {
return fi.mode
}
func (fi bindataFileInfo) ModTime() time.Time {
return fi.modTime
}
func (fi bindataFileInfo) IsDir() bool {
return false
}
func (fi bindataFileInfo) Sys() interface{} {
return nil
}
var _dataIndexHtml = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\x7c\x91\xbd\x6e\x03\x21\x10\x84\x7b\x3f\xc5\x8a\x2a\x29\x2c\xfa\x08\x9f\x94\x3e\x55\x5e\x20\xe2\xb8\xb5\xbd\x12\x3f\x27\x58\xa2\xf8\xed\xb3\x88\x38\xc7\x45\x91\xbb\x19\xc1\x7e\x03\xb3\xe6\xca\xc1\x4f\x07\x00\x33\xa7\xe5\xd6\x84\xc8\x73\xca\x01\xac\x63\x4a\xf1\xa4\xb4\x4f\x17\x8a\xaa\x1f\xc9\x21\xdb\xd9\xe3\xdd\x35\x9f\x37\xd3\xec\x32\xc1\x6b\xe5\x2b\x46\x26\x67\x19\x41\x60\x2f\xc3\x85\x96\xb4\x9b\x00\x78\x72\x29\x04\x7b\x2c\xb8\xda\x2c\x13\x0b\x78\x2a\x0c\xe9\x0c\xce\x93\x60\x8e\xb4\x94\xe7\x31\x42\x4b\xc6\xdf\x48\x43\x71\xad\x0c\x7c\x5b\xf1\xa4\x18\xbf\x58\x41\xb4\x41\xb4\xcb\xa9\x94\x8f\x4e\x52\xd3\xcf\xf0\x61\x60\xfd\x3e\x46\x74\xff\xda\xdd\x8f\xc8\x52\xe7\x40\x02\xfd\xb4\xbe\x8a\x7d\x1b\x3a\x31\xba\xf5\xf5\x6f\x75\x19\x2f\xf2\x15\xcc\x5b\x7b\x0f\x98\xef\xfb\xcb\x1b\xd6\xe8\xbe\x1b\xa3\xfb\xb2\xbe\x03\x00\x00\xff\xff\x27\x69\xf8\xf2\xb4\x01\x00\x00")
func dataIndexHtmlBytes() ([]byte, error) {
return bindataRead(
_dataIndexHtml,
"data/index.html",
)
}
func dataIndexHtml() (*asset, error) {
bytes, err := dataIndexHtmlBytes()
if err != nil {
return nil, err
}
info := bindataFileInfo{name: "data/index.html", size: 436, mode: os.FileMode(420), modTime: time.Unix(1465417812, 0)}
a := &asset{bytes: bytes, info: info}
return a, nil
}
// Asset loads and returns the asset for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func Asset(name string) ([]byte, error) {
cannonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[cannonicalName]; ok {
a, err := f()
if err != nil {
return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err)
}
return a.bytes, nil
}
return nil, fmt.Errorf("Asset %s not found", name)
}
// MustAsset is like Asset but panics when Asset would return an error.
// It simplifies safe initialization of global variables.
func MustAsset(name string) []byte {
a, err := Asset(name)
if err != nil {
panic("asset: Asset(" + name + "): " + err.Error())
}
return a
}
// AssetInfo loads and returns the asset info for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func AssetInfo(name string) (os.FileInfo, error) {
cannonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[cannonicalName]; ok {
a, err := f()
if err != nil {
return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err)
}
return a.info, nil
}
return nil, fmt.Errorf("AssetInfo %s not found", name)
}
// AssetNames returns the names of the assets.
func AssetNames() []string {
names := make([]string, 0, len(_bindata))
for name := range _bindata {
names = append(names, name)
}
return names
}
// _bindata is a table, holding each asset generator, mapped to its name.
var _bindata = map[string]func() (*asset, error){
"data/index.html": dataIndexHtml,
}
// AssetDir returns the file names below a certain
// directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the
// following hierarchy:
// data/
// foo.txt
// img/
// a.png
// b.png
// then AssetDir("data") would return []string{"foo.txt", "img"}
// AssetDir("data/img") would return []string{"a.png", "b.png"}
// AssetDir("foo.txt") and AssetDir("notexist") would return an error
// AssetDir("") will return []string{"data"}.
func AssetDir(name string) ([]string, error) {
node := _bintree
if len(name) != 0 {
cannonicalName := strings.Replace(name, "\\", "/", -1)
pathList := strings.Split(cannonicalName, "/")
for _, p := range pathList {
node = node.Children[p]
if node == nil {
return nil, fmt.Errorf("Asset %s not found", name)
}
}
}
if node.Func != nil {
return nil, fmt.Errorf("Asset %s not found", name)
}
rv := make([]string, 0, len(node.Children))
for childName := range node.Children {
rv = append(rv, childName)
}
return rv, nil
}
type bintree struct {
Func func() (*asset, error)
Children map[string]*bintree
}
var _bintree = &bintree{nil, map[string]*bintree{
"data": &bintree{nil, map[string]*bintree{
"index.html": &bintree{dataIndexHtml, map[string]*bintree{}},
}},
}}
// RestoreAsset restores an asset under the given directory
func RestoreAsset(dir, name string) error {
data, err := Asset(name)
if err != nil {
return err
}
info, err := AssetInfo(name)
if err != nil {
return err
}
err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))
if err != nil {
return err
}
err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())
if err != nil {
return err
}
err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())
if err != nil {
return err
}
return nil
}
// RestoreAssets restores an asset under the given directory recursively
func RestoreAssets(dir, name string) error {
children, err := AssetDir(name)
// File
if err != nil {
return RestoreAsset(dir, name)
}
// Dir
for _, child := range children {
err = RestoreAssets(dir, filepath.Join(name, child))
if err != nil {
return err
}
}
return nil
}
func _filePath(dir, name string) string {
cannonicalName := strings.Replace(name, "\\", "/", -1)
return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...)
}

View file

@ -0,0 +1,21 @@
<html>
<body>
<form action="/login">
<table>
<tr>
<td> Authenticate for:
<br>
(comma-separated list of client-ids)
</td>
<td> <input type="text" name="cross_client"> </td>
</tr>
</table>
<input type="submit" value="Login">
</form>
<form action="/register">
<input type="submit" value="Register">
</form>
</body>
</html>

View file

@ -1,5 +1,8 @@
package main
//go:generate go-bindata -pkg main -o assets.go data/
//go:generate gofmt -w assets.go
import (
"bytes"
"crypto/tls"
@ -7,11 +10,13 @@ import (
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/coreos/go-oidc/jose"
@ -21,8 +26,11 @@ import (
pflag "github.com/coreos/dex/pkg/flag"
phttp "github.com/coreos/dex/pkg/http"
"github.com/coreos/dex/pkg/log"
"github.com/coreos/dex/scope"
)
var indexTemplate *template.Template
func main() {
fs := flag.NewFlagSet("oidc-app", flag.ExitOnError)
listen := fs.String("listen", "http://127.0.0.1:5555", "")
@ -136,8 +144,14 @@ func main() {
Handler: hdlr,
}
log.Infof("Binding to %s...", httpsrv.Addr)
indexBytes, err := Asset("data/index.html")
if err != nil {
log.Fatalf("could not load template: %q", err)
}
indexTemplate = template.Must(template.New("root").Parse(string(indexBytes)))
log.Infof("Binding to %s...", httpsrv.Addr)
if useTLS {
log.Info("Key and cert file provided. Using TLS")
log.Fatal(httpsrv.ListenAndServeTLS(*certFile, *keyFile))
@ -167,13 +181,22 @@ func NewClientHandler(c *oidc.Client, issuer string, cbURL url.URL) http.Handler
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("<a href='/login'>login</a>"))
w.Write([]byte("<br>"))
w.Write([]byte("<a href='/register'>register</a>"))
err := indexTemplate.Execute(w, nil)
if err != nil {
phttp.WriteError(w, http.StatusInternalServerError,
fmt.Sprintf("unable to execute template: %v", err))
}
}
func handleLoginFunc(c *oidc.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
phttp.WriteError(w, http.StatusBadRequest,
fmt.Sprintf("Could not parse request: %v", err))
}
oac, err := c.OAuthClient()
if err != nil {
panic("unable to proceed")
@ -183,6 +206,22 @@ func handleLoginFunc(c *oidc.Client) http.HandlerFunc {
if err != nil {
panic("unable to proceed")
}
xClient := r.Form.Get("cross_client")
if xClient != "" {
xClients := strings.Split(xClient, ",")
for i, x := range xClients {
xClients[i] = scope.ScopeGoogleCrossClient + x
}
q := u.Query()
scope := q.Get("scope")
scopes := strings.Split(scope, " ")
scopes = append(scopes, xClients...)
scope = strings.Join(scopes, " ")
q.Set("scope", scope)
u.RawQuery = q.Encode()
}
http.Redirect(w, r, u.String(), http.StatusFound)
}
}

View file

@ -27,14 +27,15 @@ func TestClientSample(t *testing.T) {
}
memDB := db.NewMemDB()
repo := db.NewClientRepo(memDB)
for _, c := range clients {
repo.New(nil, c)
repo, err := db.NewClientRepoFromClients(memDB, clients)
if err != nil {
t.Fatalf("Error creating Clients: %v", err)
}
mgr := manager.NewClientManager(repo, db.TransactionFactory(memDB), manager.ManagerOptions{})
for i, c := range clients {
ok, err := mgr.Authenticate(c.Credentials)
ok, err := mgr.Authenticate(c.Client.Credentials)
if !ok {
t.Errorf("case %d: couldn't authenticate", i)
}

View file

@ -25,7 +25,7 @@ func TestClientCreate(t *testing.T) {
},
},
}
cis := []client.Client{ci}
cis := []client.LoadableClient{{Client: ci}}
srv, err := mockServer(cis)
if err != nil {

View file

@ -82,7 +82,7 @@ func makeUserObjects(users []user.UserWithRemoteIdentities, passwords []user.Pas
return dbMap, ur, pwr, um
}
func makeClientRepoAndManager(dbMap *gorp.DbMap, clients []client.Client) (client.ClientRepo, *clientmanager.ClientManager, error) {
func makeClientRepoAndManager(dbMap *gorp.DbMap, clients []client.LoadableClient) (client.ClientRepo, *clientmanager.ClientManager, error) {
clientIDGenerator := func(hostport string) (string, error) {
return hostport, nil
}

View file

@ -24,7 +24,7 @@ import (
"github.com/coreos/dex/user"
)
func mockServer(cis []client.Client) (*server.Server, error) {
func mockServer(cis []client.LoadableClient) (*server.Server, error) {
dbMap := db.NewMemDB()
k, err := key.GeneratePrivateKey()
if err != nil {
@ -144,7 +144,10 @@ func TestHTTPExchangeTokenRefreshToken(t *testing.T) {
}
dbMap := db.NewMemDB()
clientRepo, clientManager, err := makeClientRepoAndManager(dbMap, []client.Client{ci})
clientRepo, clientManager, err := makeClientRepoAndManager(dbMap,
[]client.LoadableClient{{
Client: ci,
}})
if err != nil {
t.Fatalf("Failed to create client identity manager: " + err.Error())
}
@ -300,7 +303,7 @@ func TestHTTPClientCredsToken(t *testing.T) {
},
},
}
cis := []client.Client{ci}
cis := []client.LoadableClient{{Client: ci}}
srv, err := mockServer(cis)
if err != nil {

View file

@ -101,8 +101,9 @@ func makeUserAPITestFixtures() *userAPITestFixtures {
f := &userAPITestFixtures{}
dbMap, _, _, um := makeUserObjects(userUsers, userPasswords)
clients := []client.Client{
client.Client{
clients := []client.LoadableClient{
{
Client: client.Client{
Credentials: oidc.ClientCredentials{
ID: testClientID,
Secret: testClientSecret,
@ -113,7 +114,9 @@ func makeUserAPITestFixtures() *userAPITestFixtures {
},
},
},
client.Client{
},
{
Client: client.Client{
Credentials: oidc.ClientCredentials{
ID: userBadClientID,
Secret: base64.URLEncoding.EncodeToString([]byte("secret")),
@ -124,6 +127,7 @@ func makeUserAPITestFixtures() *userAPITestFixtures {
},
},
},
},
}
_, clientManager, err := makeClientRepoAndManager(dbMap, clients)

View file

@ -245,7 +245,7 @@ func TestList(t *testing.T) {
for i, tt := range tests {
f, err := makeTestFixturesWithOptions(testFixtureOptions{
clients: tt.cs,
clients: clientsToLoadableClients(tt.cs),
})
if err != nil {
t.Fatalf("error making test fixtures: %v", err)

View file

@ -222,7 +222,7 @@ func loadUsersFromReader(r io.Reader) (users []user.UserWithRemoteIdentities, pw
}
// loadClients parses the clients.json file and returns a list of clients.
func loadClients(filepath string) ([]client.Client, error) {
func loadClients(filepath string) ([]client.LoadableClient, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err

View file

@ -223,7 +223,7 @@ func TestHandleAuthFuncResponsesMultipleRedirectURLs(t *testing.T) {
},
}
f, err := makeTestFixturesWithOptions(testFixtureOptions{
clients: clients,
clients: clientsToLoadableClients(clients),
})
if err != nil {
t.Fatalf("error making test fixtures: %v", err)

View file

@ -103,7 +103,7 @@ type testFixtures struct {
}
type testFixtureOptions struct {
clients []client.Client
clients []client.LoadableClient
}
func sequentialGenerateCodeFunc() sessionmanager.GenerateCodeFunc {
@ -167,10 +167,11 @@ func makeTestFixturesWithOptions(options testFixtureOptions) (*testFixtures, err
return nil, err
}
var clients []client.Client
var clients []client.LoadableClient
if options.clients == nil {
clients = []client.Client{
client.Client{
clients = []client.LoadableClient{
{
Client: client.Client{
Credentials: testClientCredentials,
Metadata: oidc.ClientMetadata{
RedirectURIs: []url.URL{
@ -178,6 +179,7 @@ func makeTestFixturesWithOptions(options testFixtureOptions) (*testFixtures, err
},
},
},
},
}
} else {
clients = options.clients
@ -258,3 +260,13 @@ func makeTestFixturesWithOptions(options testFixtureOptions) (*testFixtures, err
},
}, nil
}
func clientsToLoadableClients(cs []client.Client) []client.LoadableClient {
lcs := make([]client.LoadableClient, len(cs), len(cs))
for i, c := range cs {
lcs[i] = client.LoadableClient{
Client: c,
}
}
return lcs
}

View file

@ -2,7 +2,8 @@
{
"id": "XXX",
"secret": "c2VjcmV0ZQ==",
"redirectURLs": ["http://127.0.0.1:5555/callback"]
"redirectURLs": ["http://127.0.0.1:5555/callback"],
"trustedPeers": ["example-app"]
},
{
"id": "example-app",

View file

@ -176,7 +176,7 @@ func makeTestFixtures() (*UsersAPI, *testEmailer) {
secGen := func() ([]byte, error) {
return []byte("secret"), nil
}
clientRepo, err := db.NewClientRepoFromClients(dbMap, []client.Client{ci})
clientRepo, err := db.NewClientRepoFromClients(dbMap, []client.LoadableClient{{Client: ci}})
if err != nil {
panic("Failed to create client manager: " + err.Error())
}