Esempio n. 1
0
func (c *Core) Start(ctx *cli.Context) {
	c.Ctx.Start()

	var private, public []byte
	j := jwt.New(private, public)
	m := middleware.New(c.Ctx.Policies, j)
	c.accountHandler = accounts.NewHandler(c.Ctx.Accounts, m)
	c.clientHandler = clients.NewHandler(c.Ctx.Osins, m)
	c.connectionHandler = connections.NewHandler(c.Ctx.Connections, m)
	c.providers = provider.NewRegistry(providers)
	c.oauthHandler = &oauth.Handler{
		Accounts:    c.Ctx.Accounts,
		Policies:    c.Ctx.Policies,
		Guard:       c.guard,
		Connections: c.Ctx.Connections,
		Providers:   c.providers,
		Issuer:      c.issuer,
		Audience:    c.audience,
		JWT:         j,
		OAuthConfig: oauth.DefaultConfig(),
		OAuthStore:  c.Ctx.Osins,
	}

	extractor := m.ExtractAuthentication
	router := mux.NewRouter()
	c.accountHandler.SetRoutes(router, extractor)
	c.connectionHandler.SetRoutes(router, extractor)
	c.clientHandler.SetRoutes(router, extractor)
	c.oauthHandler.SetRoutes(router)

	http.Handle("/", router)
	http.ListenAndServe(listenOn, nil)
}
Esempio n. 2
0
func TestNewContextFromAuthorization(t *testing.T) {
	for _, c := range []struct {
		id              string
		privateKey      []byte
		publicKey       []byte
		authorization   string
		isAuthenticated bool
	}{
		{
			"1",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// {"foo": "bar"}
			"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
			false,
		},
		{
			"2",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// {"subject": "nonexistent"}
			"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWJqZWN0Ijoibm9uZXhpc3RlbnQifQ.jDUnvVMQHrhuIRUr8qAJ0g-ZKArdiJ21LAPDktmV56KFknX712Yxdder78YjEjxvGOvgtxLpCiay0cV5pvcWLuFW65Ys1P1SwdmdebtWfiGQwBy2Ggm3MrHjD_-r5JNAxFZjFZfZ1Fk-JlSZ97r8S7gYfDSAkxhpDmDy5Bm8e5_xsGDNp8dByuXop7QEtJb_igaa0APWa2ZOp3oTgxjD4CP6ZX6N5fGjtwjJWx5wHt7JaKXq8CRG8elm7LnNezYyJxeHECVctQGVv3HUjJxKf0l7wZXbG87BrG2M7otT8Py2sJP8X4wYL0DEsbErkEieV4D-KEBqpkvfXOrDGMFNRQ",
			false,
		},
		{
			"3",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// not a valid token
			"Bearer eyJ0eXAaOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWJqZWN0IjoiMTMyIn0.WDC51GK5wIQPd00MqLjFy3AU3gNsvsCpWk5e8RObVxBqcYAdv-UwMfEUAFE6Y50C5pQ1t8_LHfxJYNfcW3fj_x5FXckdbqvpXHi-psxuDwk_rancpjZQegcutqYRH37_lnJ8lIq65ZgxnyYnQKGOMl3w7etK1gOvqEcP_eHn8HG0jeVk0SDZm82x0JXSk0lrVEEjWmWYtXEsLz0E4clNPUW37K9eyjYFKnyVCIPfmGwTlkDLjANsyu0P6kFiV28V1_XedtJXDI3MmG2SxSHogDhZJLb298JBwod0d6wTyygI9mUbX-C0PklTJTxIhSs7Pc6unNlWnbyL8Z4FJrdSEw",
			false,
		},
		{
			"4",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			//		{
			//			"exp": 1924975619,
			//			"iat": 1924975619,
			//			"nbf": 0
			//			"aud": "tests",
			//			"subject": "foo"
			//		}
			"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtYXgiLCJleHAiOjE5MjQ5NzU2MTksIm5iZiI6MCwiaWF0IjoxOTI0OTc1NjE5LCJhdWQiOiJ0ZXN0cyIsInN1YmplY3QiOiJmb28ifQ.lvjLGnLO3mZSS63fomK-KH2mhLXjjg9b13opiN7jY4MrXE_DaR0Lum8a_RcqqSTXbpHxYSIPV9Ji7zM_X1bvBtsPpBE1PR3_PrdD5_uIDQ-UWPVzozxhOvuZzU7qHx3TFQClZ6tYIXYioTszz9zQHiE4hj1x6Z_shWPfczELGyD0HnEC3o_w7IFfYO_L0YDN_vkuqr6yS5kaPIsoCF_iHuhTzoBAEIpUENlxSpCPuxR9aMaJ-BQDInHoPc1h-VvkgOdR_iENQdOUePObw17ywdGkRk6C5kRHSxjca-ULGcDn36NZ54SEPolcGbjs3vVA1g0jQARKIcTVw6Uu7x0s6Q",
			true,
		},
		{
			"5",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			"",
			false,
		},
	} {
		message := "ok"
		ctx := context.Background()

		j := hjwt.New(c.privateKey, c.publicKey)

		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx = NewContextFromAuthorization(ctx, r, j, ladonStore)
			assert.Equal(t, c.isAuthenticated, IsAuthenticatedFromContext(ctx), "Case %s", c.id)
			fmt.Fprintln(w, message)
		}))
		defer ts.Close()

		client := &http.Client{}
		req, err := http.NewRequest("GET", ts.URL, nil)
		require.Nil(t, err)
		req.Header.Set("Authorization", c.authorization)
		res, err := client.Do(req)
		require.Nil(t, err)

		result, err := ioutil.ReadAll(res.Body)
		res.Body.Close()

		require.Nil(t, err)
		assert.Equal(t, message+"\n", string(result))
	}
}
Esempio n. 3
0
func TestNewContextFromAuthorization(t *testing.T) {
	for _, c := range []struct {
		id              string
		privateKey      []byte
		publicKey       []byte
		authorization   string
		isAuthenticated bool
	}{
		{
			"1",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// {"foo": "bar"}
			"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
			false,
		},
		{
			"2",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// {"subject": "nonexistent"}
			"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWJqZWN0Ijoibm9uZXhpc3RlbnQifQ.jDUnvVMQHrhuIRUr8qAJ0g-ZKArdiJ21LAPDktmV56KFknX712Yxdder78YjEjxvGOvgtxLpCiay0cV5pvcWLuFW65Ys1P1SwdmdebtWfiGQwBy2Ggm3MrHjD_-r5JNAxFZjFZfZ1Fk-JlSZ97r8S7gYfDSAkxhpDmDy5Bm8e5_xsGDNp8dByuXop7QEtJb_igaa0APWa2ZOp3oTgxjD4CP6ZX6N5fGjtwjJWx5wHt7JaKXq8CRG8elm7LnNezYyJxeHECVctQGVv3HUjJxKf0l7wZXbG87BrG2M7otT8Py2sJP8X4wYL0DEsbErkEieV4D-KEBqpkvfXOrDGMFNRQ",
			false,
		},
		{
			"3",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			// not a valid token
			"Bearer eyJ0eXAaOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWJqZWN0IjoiMTMyIn0.WDC51GK5wIQPd00MqLjFy3AU3gNsvsCpWk5e8RObVxBqcYAdv-UwMfEUAFE6Y50C5pQ1t8_LHfxJYNfcW3fj_x5FXckdbqvpXHi-psxuDwk_rancpjZQegcutqYRH37_lnJ8lIq65ZgxnyYnQKGOMl3w7etK1gOvqEcP_eHn8HG0jeVk0SDZm82x0JXSk0lrVEEjWmWYtXEsLz0E4clNPUW37K9eyjYFKnyVCIPfmGwTlkDLjANsyu0P6kFiV28V1_XedtJXDI3MmG2SxSHogDhZJLb298JBwod0d6wTyygI9mUbX-C0PklTJTxIhSs7Pc6unNlWnbyL8Z4FJrdSEw",
			false,
		},
		{
			"4",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			//		{
			//			"exp": "2099-10-31T15:03:52.4620974+01:00",
			//			"iat": "2014-10-31T13:03:52.4620974+01:00",
			//			"nbf": "2014-10-31T13:03:52.4620974+01:00",
			//			"sub": "132"
			//		}
			"Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDk5LTEwLTMxVDE1OjAzOjUyLjQ2MjA5NzQrMDE6MDAiLCJpYXQiOiIyMDE0LTEwLTMxVDEzOjAzOjUyLjQ2MjA5NzQrMDE6MDAiLCJuYmYiOiIyMDE0LTEwLTMxVDEzOjAzOjUyLjQ2MjA5NzQrMDE6MDAiLCJzdWIiOiIxMzIifQ.qnZr-msiG5GkVTDTyY3g26c5Edho36_E9CaANyCBVOrXWRfRPDMf7E2vrdZubO5tXlfKRgM_1avFQVWZhqrdrGBO8DiBa5OGX9IdAZaclqQFjg7vRSyIFllSs4zP4QREG4YL0qwiYGKS4SBcCS2LNfbaJfrKP_zUReXRAlWNdeFAw6zsGzlAtHQO_O0HnJCEB_wEBIkMIxdI2f-1yyTZJInyvY_wrFDkCkTfkmmW8EHzO2R44FXmaudxDCG1YAeN6WssAwgzBjR8WaQ2M_8VUYWN9TCDc3Fx58XWRTtWL_coDI9R6WtqaPkyr2_qn1Un3y3yLCGdVglRYnhJL1YCXA",
			true,
		},
		{
			"5",
			[]byte(hjwt.TestCertificates[0][1]),
			[]byte(hjwt.TestCertificates[1][1]),
			"",
			false,
		},
	} {
		message := "ok"
		ctx := context.Background()

		j := hjwt.New(c.privateKey, c.publicKey)

		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx = NewContextFromAuthorization(ctx, r, j, ladonStore)
			assert.Equal(t, c.isAuthenticated, IsAuthenticatedFromContext(ctx), "Case %s", c.id)
			fmt.Fprintln(w, message)
		}))
		defer ts.Close()

		client := &http.Client{}
		req, err := http.NewRequest("GET", ts.URL, nil)
		require.Nil(t, err)
		req.Header.Set("Authorization", c.authorization)
		res, err := client.Do(req)
		require.Nil(t, err)

		result, err := ioutil.ReadAll(res.Body)
		res.Body.Close()

		require.Nil(t, err)
		assert.Equal(t, message+"\n", string(result))
	}
}
Esempio n. 4
0
	"golang.org/x/net/context"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
	"time"
)

var (
	mw    *middleware.Middleware
	store *postgres.Store
	o     *opg.Storage
)

var jwtService = hjwt.New([]byte(hjwt.TestCertificates[0][1]), []byte(hjwt.TestCertificates[1][1]))

func TestMain(m *testing.M) {
	c, db, err := dockertest.OpenPostgreSQLContainerConnection(15, time.Second)
	if err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	}

	defer c.KillRemove()

	store = postgres.New(db)
	mw = &middleware.Middleware{}
	o = opg.New(db)
	if err := store.CreateSchemas(); err != nil {
		log.Fatalf("Could not create schemas: %s", err)
	}
Esempio n. 5
0
func TestMain(m *testing.M) {
	c, db, err := dockertest.OpenPostgreSQLContainerConnection(15, time.Second)
	if err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	}
	defer c.KillRemove()

	accountStore := acpg.New(&hash.BCrypt{10}, db)
	policyStore := ppg.New(db)
	osinStore := opg.New(db)
	connectionStore := cpg.New(db)
	stateStore := oapg.New(db)
	registry := provider.NewRegistry([]provider.Provider{&prov{}})
	j := hjwt.New([]byte(hjwt.TestCertificates[0][1]), []byte(hjwt.TestCertificates[1][1]))

	if err := connectionStore.CreateSchemas(); err != nil {
		log.Fatalf("Could not set up schemas: %v", err)
	} else if err := policyStore.CreateSchemas(); err != nil {
		log.Fatalf("Could not set up schemas: %v", err)
	} else if err := accountStore.CreateSchemas(); err != nil {
		log.Fatalf("Could not set up schemas: %v", err)
	} else if err := osinStore.CreateSchemas(); err != nil {
		log.Fatalf("Could not set up schemas: %v", err)
	} else if err := stateStore.CreateSchemas(); err != nil {
		log.Fatalf("Could not set up schemas: %v", err)
	}

	handler = &Handler{
		OAuthConfig: DefaultConfig(),
		OAuthStore:  osinStore,
		JWT:         j,
		Accounts:    accountStore,
		Policies:    policyStore,
		Guard:       new(guard.Guard),
		Connections: connectionStore,
		States:      stateStore,
		Providers:   registry,
		Issuer:      "hydra",
		Audience:    "tests",
		Middleware:  host.New(policyStore, j),
	}

	pol := policy.DefaultPolicy{
		ID: uuid.New(), Description: "",
		Effect:      policy.AllowAccess,
		Subjects:    []string{},
		Permissions: []string{"authorize"},
		Resources:   []string{"/oauth2/authorize"},
		Conditions:  []policy.DefaultCondition{},
	}

	if err := osinStore.CreateClient(&osin.DefaultClient{clientID, "secret", "/callback", ""}); err != nil {
		log.Fatalf("Could create client: %s", err)
	} else if err := osinStore.CreateClient(&osin.DefaultClient{"working-client-2", "secret", "/callback", ""}); err != nil {
		log.Fatalf("Could create client: %s", err)
	} else if _, err := accountStore.Create(account.CreateAccountRequest{
		ID:       accID,
		Username: "******",
		Password: "******",
		Data:     "{}",
	}); err != nil {
		log.Fatalf("Could create account: %s", err)
	} else if err := policyStore.Create(&pol); err != nil {
		log.Fatalf("Could create client: %s", err)
	} else if err := connectionStore.Create(&connection.DefaultConnection{
		ID:            uuid.New(),
		Provider:      "MockProvider",
		LocalSubject:  accID,
		RemoteSubject: "remote-id",
	}); err != nil {
		log.Fatalf("Could create client: %s", err)
	}

	os.Exit(m.Run())
}
Esempio n. 6
0
func (c *Core) Start(ctx *cli.Context) error {
	c.Ctx.Start()

	private, err := jwt.LoadCertificate(jwtPrivateKeyPath)
	if err != nil {
		return fmt.Errorf("Could not load private key: %s", err)
	}

	public, err := jwt.LoadCertificate(jwtPublicKeyPath)
	if err != nil {
		return fmt.Errorf("Could not load public key: %s", err)
	}

	j := jwt.New(private, public)
	m := middleware.New(c.Ctx.Policies, j)
	c.guard = new(guard.Guard)
	c.accountHandler = accounts.NewHandler(c.Ctx.Accounts, m)
	c.clientHandler = clients.NewHandler(c.Ctx.Osins, m)
	c.connectionHandler = connections.NewHandler(c.Ctx.Connections, m)
	c.providers = provider.NewRegistry(providers)
	c.policyHandler = policies.NewHandler(c.Ctx.Policies, m, c.guard, j, c.Ctx.Osins)
	c.oauthHandler = &oauth.Handler{
		Accounts:       c.Ctx.Accounts,
		Policies:       c.Ctx.Policies,
		Guard:          c.guard,
		Connections:    c.Ctx.Connections,
		Providers:      c.providers,
		Issuer:         c.issuer,
		Audience:       c.audience,
		JWT:            j,
		OAuthConfig:    oauth.DefaultConfig(),
		OAuthStore:     c.Ctx.Osins,
		States:         c.Ctx.States,
		SignUpLocation: locations["signUp"],
		SignInLocation: locations["signIn"],
		Middleware:     host.New(c.Ctx.Policies, j),
	}

	extractor := m.ExtractAuthentication
	router := mux.NewRouter()
	c.accountHandler.SetRoutes(router, extractor)
	c.connectionHandler.SetRoutes(router, extractor)
	c.clientHandler.SetRoutes(router, extractor)
	c.oauthHandler.SetRoutes(router, extractor)
	c.policyHandler.SetRoutes(router, extractor)

	// TODO un-hack this, add database check, add error response
	router.HandleFunc("/alive", func(w http.ResponseWriter, r *http.Request) {
		pkg.WriteJSON(w, &struct {
			Status string `json:"status"`
		}{
			Status: "alive",
		})
	})

	if forceHTTP == "force" {
		http.Handle("/", router)
		log.Warn("You're using HTTP without TLS encryption. This is dangerously unsafe and you should not do this.")
		if err := http.ListenAndServe(listenOn, nil); err != nil {
			return fmt.Errorf("Could not serve HTTP server because %s", err)
		}
		return nil
	}

	http.Handle("/", router)
	srv := &http.Server{Addr: listenOn}
	http2.ConfigureServer(srv, &http2.Server{})
	if err := srv.ListenAndServeTLS(tlsCertPath, tlsKeyPath); err != nil {
		return fmt.Errorf("Could not serve HTTP/2 server because %s", err)
	}
	return nil
}