Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pkg/oauth2: consider session cancellation #182

Merged
merged 6 commits into from Jun 13, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 12 additions & 1 deletion cmd/telemeter-server/main.go
Expand Up @@ -23,6 +23,8 @@ import (
"strings"
"time"

"github.com/prometheus/client_golang/prometheus"

oidc "github.com/coreos/go-oidc"
"github.com/oklog/run"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -250,8 +252,17 @@ func (o *Options) Run() error {
Endpoint: provider.Endpoint(),
}

grantsTotal := prometheus.NewCounter(
prometheus.CounterOpts{
Name: "telemeter_password_credentials_grants_total",
Help: "Tracks the number of resource owner password credential grants.",
},
)

prometheus.MustRegister(grantsTotal)

src := telemeter_oauth2.NewPasswordCredentialsTokenSource(
ctx, &cfg,
ctx, &cfg, grantsTotal.Inc,
o.AuthorizeUsername, o.AuthorizePassword,
)

Expand Down
59 changes: 43 additions & 16 deletions pkg/oauth2/token_source.go
Expand Up @@ -3,6 +3,7 @@ package oauth2
import (
"context"
"fmt"
"net/http"
"sync"
"time"

Expand All @@ -13,6 +14,7 @@ type passwordCredentialsTokenSource struct {
ctx context.Context
cfg *oauth2.Config
username, password string
grantsCounter func()

mu sync.Mutex // protects the fields below
refreshToken *oauth2.Token
Expand All @@ -32,20 +34,17 @@ type passwordCredentialsTokenSource struct {
// using the given resource owner and password.
//
// It is safe for concurrent use.
func NewPasswordCredentialsTokenSource(ctx context.Context, cfg *oauth2.Config, username, password string) *passwordCredentialsTokenSource {
func NewPasswordCredentialsTokenSource(ctx context.Context, cfg *oauth2.Config, grantsCounter func(), username, password string) *passwordCredentialsTokenSource {
return &passwordCredentialsTokenSource{
ctx: ctx,
username: username,
password: password,
cfg: cfg,
ctx: ctx,
username: username,
password: password,
cfg: cfg,
grantsCounter: grantsCounter,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typically the actual metric is passed in here, or even grouped in a metrics struct

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was just to ease testing, but I can pass a metrics struct here (or the counter interface) too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

adressed

}
}

func (c *passwordCredentialsTokenSource) Token() (*oauth2.Token, error) {
return c.token(time.Now)
}

func (c *passwordCredentialsTokenSource) token(now func() time.Time) (*oauth2.Token, error) {
c.mu.Lock()
defer c.mu.Unlock()

Expand All @@ -56,6 +55,12 @@ func (c *passwordCredentialsTokenSource) token(now func() time.Time) (*oauth2.To

if c.refreshToken.Valid() {
tok, err = c.accessTokenSource.Token()

rerr, ok := err.(*oauth2.RetrieveError)
if ok && rerr.Response != nil && rerr.Response.StatusCode == http.StatusBadRequest {
return c.passwordCredentialsToken()
}

if err != nil {
return nil, fmt.Errorf("access token source failed: %v", err)
}
Expand All @@ -65,26 +70,48 @@ func (c *passwordCredentialsTokenSource) token(now func() time.Time) (*oauth2.To
if tok.RefreshToken == c.refreshToken.RefreshToken {
return tok, nil
}
} else {
tok, err = c.cfg.PasswordCredentialsToken(c.ctx, c.username, c.password)

err = c.setRefreshToken(tok)
if err != nil {
return nil, fmt.Errorf("password credentials token source failed: %v", err)
return nil, err
}

c.accessTokenSource = c.cfg.TokenSource(c.ctx, tok)
return tok, nil
}

return c.passwordCredentialsToken()
}

func (c *passwordCredentialsTokenSource) passwordCredentialsToken() (*oauth2.Token, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn’t happen too often, but it would be good to know when it does. Let’s add a counter metric to understand how often this happens.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed 👍 added a metric, PTAL

c.grantsCounter()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it seems to me we may want to differentiate in a successful and errored token retrieval no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have that indication (status code returned by tollbooth) already in the oauth client metric, i.e. client_api_requests_total{client="oauth",code="..."}. This metric is also used to set up alerting.

Would it be idiomatic to add a err="false|true" here?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but it's differentiated in terms of refresh token use and credentials flow? if so lgtm

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed oob:

  1. The existing client_api_requests_total metric does not differentiate the cause of the refresh. I added the cause label for that reason.
  2. We'll add a status label here to have more insight on the result of the password grant operation.

ptal


tok, err := c.cfg.PasswordCredentialsToken(c.ctx, c.username, c.password)
if err != nil {
return nil, fmt.Errorf("password credentials token source failed: %v", err)
}

c.accessTokenSource = c.cfg.TokenSource(c.ctx, tok)

err = c.setRefreshToken(tok)
if err != nil {
return nil, err
}

return tok, nil
}

func (c *passwordCredentialsTokenSource) setRefreshToken(tok *oauth2.Token) error {
expires, ok := tok.Extra("refresh_expires_in").(float64)
if !ok {
return nil, fmt.Errorf("refresh_expires_in is not a float64, but %T", tok.Extra("refresh_expires_in"))
return fmt.Errorf("refresh_expires_in is not a float64, but %T", tok.Extra("refresh_expires_in"))
}

// create a dummy access token to reuse calculation logic for the Valid() method
c.refreshToken = &oauth2.Token{
AccessToken: tok.RefreshToken,
RefreshToken: tok.RefreshToken,
Expiry: now().Add(time.Duration(int64(expires)) * time.Second),
Expiry: time.Now().Add(time.Duration(int64(expires)) * time.Second),
}

return tok, nil
return nil
}