Skip to content

Commit

Permalink
Merge 9bb555f into 00bdd28
Browse files Browse the repository at this point in the history
  • Loading branch information
arekkas committed Nov 22, 2016
2 parents 00bdd28 + 9bb555f commit 549b80d
Show file tree
Hide file tree
Showing 12 changed files with 131 additions and 32 deletions.
18 changes: 10 additions & 8 deletions cmd/cli/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@ import (
)

type Handler struct {
Clients *ClientHandler
Policies *PolicyHandler
Keys *JWKHandler
Warden *WardenHandler
Clients *ClientHandler
Policies *PolicyHandler
Keys *JWKHandler
Warden *WardenHandler
Revocation *RevocationHandler
}

func NewHandler(c *config.Config) *Handler {
return &Handler{
Clients: newClientHandler(c),
Policies: newPolicyHandler(c),
Keys: newJWKHandler(c),
Warden: newWardenHandler(c),
Clients: newClientHandler(c),
Policies: newPolicyHandler(c),
Keys: newJWKHandler(c),
Warden: newWardenHandler(c),
Revocation: newRevocationHandler(c),
}
}
41 changes: 41 additions & 0 deletions cmd/cli/handler_recovation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cli

import (
"context"
"fmt"
"github.com/ory-am/hydra/config"
"github.com/ory-am/hydra/oauth2"
"github.com/ory-am/hydra/pkg"
"github.com/spf13/cobra"
"golang.org/x/oauth2/clientcredentials"
)

type RevocationHandler struct {
Config *config.Config
M *oauth2.HTTPRecovator
}

func newRevocationHandler(c *config.Config) *RevocationHandler {
return &RevocationHandler{
Config: c,
M: &oauth2.HTTPRecovator{},
}
}

func (h *RevocationHandler) RevokeToken(cmd *cobra.Command, args []string) {
h.M.Endpoint = h.Config.Resolve("/oauth2/revoke")
h.M.Config = &clientcredentials.Config{
ClientID: h.Config.ClientID,
ClientSecret: h.Config.ClientSecret,
}

if len(args) != 1 {
fmt.Print(cmd.UsageString())
return
}

token := args[0]
err := h.M.RevokeToken(context.Background(), args[0])
pkg.Must(err, "Could not revoke token: %s", err)
fmt.Printf("Revoked token %s", token)
}
1 change: 1 addition & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func TestExecute(t *testing.T) {
{args: []string{"keys", "create", "foo", "-a", "HS256"}},
{args: []string{"keys", "get", "foo"}},
{args: []string{"keys", "delete", "foo"}},
{args: []string{"token", "revoke", "foo"}},
{args: []string{"token", "client"}},
{args: []string{"token", "user", "--no-open"}, wait: func() bool {
time.Sleep(time.Millisecond * 10)
Expand Down
6 changes: 3 additions & 3 deletions cmd/server/handler_oauth2_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,9 @@ func newOAuth2Handler(c *config.Config, router *httprouter.Router, km jwk.Manage
DefaultChallengeLifespan: c.GetChallengeTokenLifespan(),
DefaultIDTokenLifespan: c.GetIDTokenLifespan(),
},
ConsentURL: *consentURL,
H: &herodot.JSON{},
AccessTokenLifespan:c.GetAccessTokenLifespan(),
ConsentURL: *consentURL,
H: &herodot.JSON{},
AccessTokenLifespan: c.GetAccessTokenLifespan(),
}

handler.SetRoutes(router)
Expand Down
17 changes: 17 additions & 0 deletions cmd/token_revoke.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package cmd

import (
"github.com/spf13/cobra"
)

// validateCmd represents the validate command
var tokenRevokeCmd = &cobra.Command{
Use: "revoke <token>",
Short: "Revoke an access or refresh token",
Run: cmdHandler.Revocation.RevokeToken,
}

func init() {
tokenCmd.AddCommand(tokenRevokeCmd)

}
2 changes: 1 addition & 1 deletion cmd/token_validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
// validateCmd represents the validate command
var tokenValidatorCmd = &cobra.Command{
Use: "validate <token>",
Short: "Check if an access token is valid.",
Short: "Check if an access token is valid",
Run: cmdHandler.Warden.IsAuthorized,
}

Expand Down
27 changes: 23 additions & 4 deletions docs/sdk/go.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,43 @@ var keySet, err = hydra.JWK.GetKeySet("app-tls-keys")
var err = hydra.JWK.DeleteKeySet("app-tls-keys")
```

Validate access token, uses [`ory-am/hydra/warden.HTTPWarden`](warden/warden_http.go):

```go
import "golang.org/x/net/context"
import "github.com/ory-am/hydra/firewall"

func anyHttpHandler(w http.ResponseWriter, r *http.Request) {
// Check if a token is valid and the token's subject fulfills the policy based access request.
ctx, err := hydra.Introspection.IntrospectToken(context.Background(), "access-token", "photos", "files")
fmt.Sprintf("%s", ctx.Subject)
}
```

Validate requests with the Warden, uses [`ory-am/hydra/warden.HTTPWarden`](warden/warden_http.go):

```go
import "golang.org/x/net/context"
import "github.com/ory-am/hydra/firewall"

func anyHttpHandler(w http.ResponseWriter, r *http.Request) {
// Check if a token is valid and is allowed to operate given scopes
ctx, err := hydra.Warden.TokenValid(context.Background(), firewall.TokenFromRequest(r), "photos", "files")
fmt.Sprintf("%s", ctx.Subject)

// Check if a token is valid and the token's subject fulfills the policy based access request.
ctx, err := hydra.Warden.TokenAllowed(context.Background(), "access-token", &firewall.TokenAccessRequest{
Resource: "matrix",
Action: "create",
Context: ladon.Context{},
}, "photos", "files")
fmt.Sprintf("%s", ctx.Subject)

// Do the same thing but without a token
ctx, err := hydra.Warden.IsAllowed(context.Background(), &firewall.AccessRequest{
// Because no token is defined, we need to specify the subject manually
Subject: "peter",
Resource: "matrix",
Action: "create",
Context: ladon.Context{},
})
fmt.Sprintf("%s", ctx.Subject)
}
```

Expand Down
2 changes: 1 addition & 1 deletion firewall/warden.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ type Firewall interface {
// TokenFromRequest returns an access token from the HTTP Authorization header.
//
// func anyHttpHandler(w http.ResponseWriter, r *http.Request) {
// ctx, err := firewall.TokenValid(context.Background(), firewall.TokenFromRequest(r), "photos", "files")
// ctx, err := firewall.TokenAllowed(context.Background(), firewall.TokenFromRequest(r), "photos", "files")
// fmt.Sprintf("%s", ctx.Subject)
// }
TokenFromRequest(r *http.Request) string
Expand Down
21 changes: 13 additions & 8 deletions oauth2/fosite_store_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"encoding/json"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/jmoiron/sqlx"
"github.com/ory-am/fosite"
"github.com/ory-am/hydra/client"
Expand Down Expand Up @@ -69,6 +70,10 @@ type sqlData struct {
}

func sqlSchemaFromRequest(signature string, r fosite.Requester) (*sqlData, error) {
if r.GetSession() == nil {
logrus.Debugf("Got an empty session in sqlSchemaFromRequest")
}

session, err := json.Marshal(r.GetSession())
if err != nil {
return nil, errors.Wrap(err, "")
Expand All @@ -86,13 +91,13 @@ func sqlSchemaFromRequest(signature string, r fosite.Requester) (*sqlData, error
}, nil
}

func (s *sqlData) ToRequest(session fosite.Session, cm client.Manager) (*fosite.Request, error) {
if session == nil {
return nil, errors.New("Session undefined")
}

if err := json.Unmarshal(s.Session, session); err != nil {
return nil, errors.Wrap(err, "")
func (s *sqlData) toRequest(session fosite.Session, cm client.Manager) (*fosite.Request, error) {
if session != nil {
if err := json.Unmarshal(s.Session, session); err != nil {
return nil, errors.Wrap(err, "")
}
} else {
logrus.Debugf("Got an empty session in toRequest")
}

c, err := cm.GetClient(s.Client)
Expand Down Expand Up @@ -144,7 +149,7 @@ func (s *FositeSQLStore) findSessionBySignature(signature string, session fosite
return nil, errors.Wrap(err, "")
}

return d.ToRequest(session, s.Manager)
return d.toRequest(session, s.Manager)
}

func (s *FositeSQLStore) deleteSession(signature string, table string) error {
Expand Down
6 changes: 3 additions & 3 deletions oauth2/handler_consent_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package oauth2

import (
"net/http/httptest"
"net/http"
"io/ioutil"
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)

Expand Down
14 changes: 14 additions & 0 deletions oauth2/revocator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/ory-am/hydra/herodot"
"github.com/ory-am/hydra/oauth2"
"github.com/ory-am/hydra/pkg"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
"golang.org/x/oauth2/clientcredentials"
)
Expand Down Expand Up @@ -87,6 +88,7 @@ func TestRevoke(t *testing.T) {
for _, c := range []struct {
token string
expectErr bool
assert func(*testing.T)
}{
{
token: "invalid",
Expand All @@ -95,6 +97,9 @@ func TestRevoke(t *testing.T) {
{
token: tokensRecovator[0][1],
expectErr: false,
assert: func(t *testing.T) {
assert.Len(t, fositeStoreRecovator.AccessTokens, 2)
},
},
{
token: tokensRecovator[0][1],
Expand All @@ -103,15 +108,24 @@ func TestRevoke(t *testing.T) {
{
token: tokensRecovator[2][1],
expectErr: false,
assert: func(t *testing.T) {
assert.Len(t, fositeStoreRecovator.AccessTokens, 1)
},
},
{
token: tokensRecovator[1][1],
expectErr: false,
assert: func(t *testing.T) {
assert.Len(t, fositeStoreRecovator.AccessTokens, 0)
},
},
} {
t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) {
err := w.RevokeToken(context.Background(), c.token)
pkg.AssertError(t, c.expectErr, err)
if c.assert != nil {
c.assert(t)
}
})
}
}
Expand Down
8 changes: 4 additions & 4 deletions oauth2/session.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package oauth2

import (
"github.com/ory-am/fosite/handler/openid"
"github.com/ory-am/fosite/token/jwt"
"github.com/ory-am/fosite"
"bytes"
"encoding/gob"
"github.com/ory-am/fosite"
"github.com/ory-am/fosite/handler/openid"
"github.com/ory-am/fosite/token/jwt"
)

type Session struct {
Expand Down Expand Up @@ -35,4 +35,4 @@ func (s *Session) Clone() fosite.Session {
_ = enc.Encode(s)
_ = dec.Decode(&clone)
return &clone
}
}

0 comments on commit 549b80d

Please sign in to comment.