Skip to content

Commit

Permalink
Merge pull request #46 from chainguard-dev/create-pull-request/patch
Browse files Browse the repository at this point in the history
Export mono/sdk: refs/heads/main
  • Loading branch information
cmdpdx authored Jul 2, 2024
2 parents 027bbbb + 29edc01 commit bc4c759
Show file tree
Hide file tree
Showing 17 changed files with 2,400 additions and 355 deletions.
228 changes: 228 additions & 0 deletions auth/deviceflow/token_getter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
/*
Copyright 2024 Chainguard, Inc.
SPDX-License-Identifier: Apache-2.0
*/

package deviceflow

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"

"github.com/coreos/go-oidc/v3/oidc"
"github.com/sigstore/sigstore/pkg/oauthflow"
"golang.org/x/oauth2"
)

// Forked from: https://github.com/sigstore/sigstore/blob/8cd960fb1915c526bd838df6341b027634434985/pkg/oauthflow/device.go
// Changes from source:
// - Remove deprecated functions.
// - Remove PKCE since Auth0 doesn't support it for device flow.
// - Add `client_id` to token endpoint polling requests, since Auth0 requires it.

type deviceResp struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
Interval int `json:"interval"`
ExpiresIn int `json:"expires_in"`
}

type tokenResp struct {
IDToken string `json:"id_token"`
Error string `json:"error"`
}

var _ oauthflow.TokenGetter = (*TokenGetter)(nil)

// TokenGetter fetches an OIDC Identity token using the Device Code Grant flow as specified in RFC8628
type TokenGetter struct {
messagePrinter func(string)
sleeper func(time.Duration)
issuer string
codeURL string
}

type Option func(tg *TokenGetter)

func WithMessagePrinter(fn func(string)) Option {
return func(tg *TokenGetter) {
tg.messagePrinter = fn
}
}

func WithSleeper(fn func(time.Duration)) Option {
return func(tg *TokenGetter) {
tg.sleeper = fn
}
}

// NewTokenGetter creates a new TokenGetter that retrieves an OIDC Identity Token using a Device Code Grant
func NewTokenGetter(issuer string, opts ...Option) *TokenGetter {
tg := &TokenGetter{
messagePrinter: func(s string) { fmt.Fprintln(os.Stderr, s) },
sleeper: time.Sleep,
issuer: issuer,
}

for _, opt := range opts {
opt(tg)
}
return tg
}

func (d *TokenGetter) deviceFlow(p *oidc.Provider, clientID, redirectURL string, scopes []string) (string, error) {
data := url.Values{
"client_id": []string{clientID},
"scope": []string{strings.Join(scopes, " ")},
}
if redirectURL != "" {
// If a redirect uri is provided then use it
data["redirect_uri"] = []string{redirectURL}
}

codeURL, err := d.CodeURL()
if err != nil {
return "", err
}
/* #nosec */
resp, err := http.PostForm(codeURL, data)
if err != nil {
return "", err
}
defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%s: %s", resp.Status, b)
}

parsed := deviceResp{}
if err := json.Unmarshal(b, &parsed); err != nil {
return "", err
}

d.messagePrinter(fmt.Sprintf("Enter the verification code %s in your browser at: %s", parsed.UserCode, parsed.VerificationURI))
d.messagePrinter(fmt.Sprintf("Code will be valid for %d seconds", parsed.ExpiresIn))
d.sleeper(time.Duration(parsed.Interval) * time.Second)

for {
data := url.Values{
"client_id": []string{clientID},
"grant_type": []string{"urn:ietf:params:oauth:grant-type:device_code"},
"device_code": []string{parsed.DeviceCode},
}

/* #nosec */
resp, err := http.PostForm(p.Endpoint().TokenURL, data)
if err != nil {
return "", err
}
defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
tr := tokenResp{}
if err := json.Unmarshal(b, &tr); err != nil {
return "", err
}

if tr.IDToken != "" {
d.messagePrinter("Token received!")
return tr.IDToken, nil
}
switch tr.Error {
case "access_denied", "expired_token":
return "", fmt.Errorf("error obtaining token: %s", tr.Error)
case "authorization_pending":
d.sleeper(time.Duration(parsed.Interval) * time.Second)
case "slow_down":
// Add ten seconds if we got told to slow down
d.sleeper(time.Duration(parsed.Interval)*time.Second + 10*time.Second)
default:
return "", fmt.Errorf("unexpected error in device flow: %s", tr.Error)
}
}
}

// GetIDToken gets an OIDC ID Token from the specified provider using the device code grant flow
func (d *TokenGetter) GetIDToken(p *oidc.Provider, cfg oauth2.Config) (*oauthflow.OIDCIDToken, error) {
idToken, err := d.deviceFlow(p, cfg.ClientID, cfg.RedirectURL, cfg.Scopes)
if err != nil {
return nil, err
}
verifier := p.Verifier(&oidc.Config{ClientID: cfg.ClientID})
parsedIDToken, err := verifier.Verify(context.Background(), idToken)
if err != nil {
return nil, err
}

subj, err := oauthflow.SubjectFromToken(parsedIDToken)
if err != nil {
return nil, err
}

return &oauthflow.OIDCIDToken{
RawString: idToken,
Subject: subj,
}, nil
}

// CodeURL fetches the device authorization endpoint URL from the provider's well-known configuration endpoint
func (d *TokenGetter) CodeURL() (string, error) {
if d.codeURL != "" {
return d.codeURL, nil
}

wellKnown := strings.TrimSuffix(d.issuer, "/") + "/.well-known/openid-configuration"
/* #nosec */
httpClient := &http.Client{
Timeout: 3 * time.Second,
}
resp, err := httpClient.Get(wellKnown)
if err != nil {
return "", err
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("unable to read response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%s: %s", resp.Status, body)
}

providerConfig := struct {
Issuer string `json:"issuer"`
DeviceEndpoint string `json:"device_authorization_endpoint"`
}{}
if err = json.Unmarshal(body, &providerConfig); err != nil {
return "", fmt.Errorf("oidc: failed to decode provider discovery object: %w", err)
}

if d.issuer != providerConfig.Issuer {
return "", fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", d.issuer, providerConfig.Issuer)
}

if providerConfig.DeviceEndpoint == "" {
return "", fmt.Errorf("oidc: device authorization endpoint not returned by provider")
}

d.codeURL = providerConfig.DeviceEndpoint
return d.codeURL, nil
}
7 changes: 5 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ require (
github.com/microcosm-cc/bluemonday v1.0.26
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/russross/blackfriday/v2 v2.1.0
github.com/sigstore/sigstore v1.8.6
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8
golang.org/x/oauth2 v0.21.0
google.golang.org/genproto/googleapis/api v0.0.0-20240528184218-531527333157
google.golang.org/genproto/googleapis/api v0.0.0-20240610135401-a8a62080eff3
google.golang.org/grpc v1.64.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.4.0
google.golang.org/protobuf v1.34.2
Expand Down Expand Up @@ -50,6 +51,8 @@ require (
github.com/prometheus/common v0.53.0 // indirect
github.com/prometheus/procfs v0.15.0 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/segmentio/ksuid v1.0.4 // indirect
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.52.0 // indirect
go.opentelemetry.io/otel v1.27.0 // indirect
go.opentelemetry.io/otel/metric v1.27.0 // indirect
Expand All @@ -61,6 +64,6 @@ require (
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240617180043-68d350f18fd4 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
26 changes: 22 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-rod/rod v0.116.1 h1:BDMZY3qm/14SmvHBV7DoFUhXeJ2MbUYgumQ88b+v2WE=
github.com/go-rod/rod v0.116.1/go.mod h1:3Ash9fYwznqz9S1uLQgQRStur4fCXjoxxGW+ym6TYjU=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
Expand Down Expand Up @@ -119,7 +121,13 @@ github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=
github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=
github.com/sigstore/sigstore v1.8.6 h1:g066b/Nw5r5oxhNv4XqJUUzVcyf1b07itUueiQe7rZM=
github.com/sigstore/sigstore v1.8.6/go.mod h1:UOBrJd9JBQ81DrkpGljzsIFXEtfC30raHvLWFWG857U=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
Expand All @@ -130,6 +138,16 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/ysmood/fetchup v0.2.3 h1:ulX+SonA0Vma5zUFXtv52Kzip/xe7aj4vqT5AJwQ+ZQ=
github.com/ysmood/fetchup v0.2.3/go.mod h1:xhibcRKziSvol0H1/pj33dnKrYyI2ebIvz5cOOkYGns=
github.com/ysmood/goob v0.4.0 h1:HsxXhyLBeGzWXnqVKtmT9qM7EuVs/XOgkX7T6r1o1AQ=
github.com/ysmood/goob v0.4.0/go.mod h1:u6yx7ZhS4Exf2MwciFr6nIM8knHQIE22lFpWHnfql18=
github.com/ysmood/got v0.40.0 h1:ZQk1B55zIvS7zflRrkGfPDrPG3d7+JOza1ZkNxcc74Q=
github.com/ysmood/got v0.40.0/go.mod h1:W7DdpuX6skL3NszLmAsC5hT7JAhuLZhByVzHTq874Qg=
github.com/ysmood/gson v0.7.3 h1:QFkWbTH8MxyUTKPkVWAENJhxqdBa4lYTQWqZCiLG6kE=
github.com/ysmood/gson v0.7.3/go.mod h1:3Kzs5zDl21g5F/BlLTNcuAGAYLKt2lV5G8D1zF3RNmg=
github.com/ysmood/leakless v0.8.0 h1:BzLrVoiwxikpgEQR0Lk8NyBN5Cit2b1z+u0mgL4ZJak=
github.com/ysmood/leakless v0.8.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
Expand Down Expand Up @@ -246,10 +264,10 @@ google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto/googleapis/api v0.0.0-20240528184218-531527333157 h1:7whR9kGa5LUwFtpLm2ArCEejtnxlGeLbAyjFY8sGNFw=
google.golang.org/genproto/googleapis/api v0.0.0-20240528184218-531527333157/go.mod h1:99sLkeliLXfdj2J75X3Ho+rrVCaJze0uwN7zDDkjPVU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 h1:1GBuWVLM/KMVUv1t1En5Gs+gFZCNd360GGb4sSxtrhU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0=
google.golang.org/genproto/googleapis/api v0.0.0-20240610135401-a8a62080eff3 h1:QW9+G6Fir4VcRXVH8x3LilNAb6cxBGLa6+GM4hRwexE=
google.golang.org/genproto/googleapis/api v0.0.0-20240610135401-a8a62080eff3/go.mod h1:kdrSS/OiLkPrNUpzD4aHgCq2rVuC/YRxok32HXZ4vRE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240617180043-68d350f18fd4 h1:Di6ANFilr+S60a4S61ZM00vLdw0IrQOSMS2/6mrnOU0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240617180043-68d350f18fd4/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY=
google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
Expand Down
30 changes: 19 additions & 11 deletions proto/platform/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
advisory "chainguard.dev/sdk/proto/platform/advisory/v1"
platformauth "chainguard.dev/sdk/proto/platform/auth/v1"
iam "chainguard.dev/sdk/proto/platform/iam/v1"
notifications "chainguard.dev/sdk/proto/platform/notifications/v1"
platformoidc "chainguard.dev/sdk/proto/platform/oidc/v1"
ping "chainguard.dev/sdk/proto/platform/ping/v1"
registry "chainguard.dev/sdk/proto/platform/registry/v1"
Expand All @@ -31,6 +32,7 @@ type Clients interface {
Registry() registry.Clients
Advisory() advisory.Clients
Ping() ping.Clients
Notifications() notifications.Clients

Close() error
}
Expand Down Expand Up @@ -60,21 +62,23 @@ func NewPlatformClients(ctx context.Context, apiURL string, cred credentials.Per
}

return &clients{
iam: iam.NewClientsFromConnection(conn),
tenant: tenant.NewClientsFromConnection(conn),
registry: registry.NewClientsFromConnection(conn),
advisory: advisory.NewClientsFromConnection(conn),
ping: ping.NewClientsFromConnection(conn),
conn: conn,
iam: iam.NewClientsFromConnection(conn),
tenant: tenant.NewClientsFromConnection(conn),
registry: registry.NewClientsFromConnection(conn),
advisory: advisory.NewClientsFromConnection(conn),
ping: ping.NewClientsFromConnection(conn),
notifications: notifications.NewClientsFromConnection(conn),
conn: conn,
}, nil
}

type clients struct {
iam iam.Clients
tenant tenant.Clients
registry registry.Clients
advisory advisory.Clients
ping ping.Clients
iam iam.Clients
tenant tenant.Clients
registry registry.Clients
advisory advisory.Clients
ping ping.Clients
notifications notifications.Clients

conn *grpc.ClientConn
}
Expand All @@ -99,6 +103,10 @@ func (c *clients) Ping() ping.Clients {
return c.ping
}

func (c *clients) Notifications() notifications.Clients {
return c.notifications
}

func (c *clients) Close() error {
return c.conn.Close()
}
Expand Down
Loading

0 comments on commit bc4c759

Please sign in to comment.