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

Implement JWT structure and logic for ID token in the provider mock #162

Merged
merged 3 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0
github.com/coreos/go-oidc/v3 v3.11.0
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
github.com/go-jose/go-jose/v4 v4.0.2
github.com/godbus/dbus/v5 v5.1.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/k0kubun/pp v3.0.1+incompatible
github.com/microsoftgraph/msgraph-sdk-go v1.48.0
Expand All @@ -28,7 +30,6 @@ require (
github.com/cjlapao/common-go v0.0.39 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-jose/go-jose/v4 v4.0.2 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ 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/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
Expand Down
10 changes: 3 additions & 7 deletions internal/broker/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ type isAuthenticatedCtx struct {
}

type option struct {
// skipJWTSignatureCheck is used to skip the JWT validation done by the oidc web server.
skipJWTSignatureCheck bool
providerInfo providers.ProviderInfoer
providerInfo providers.ProviderInfoer
}

// Option is a func that allows to override some of the broker default settings.
Expand All @@ -103,9 +101,7 @@ func New(cfg Config, args ...Option) (b *Broker, err error) {
defer decorate.OnError(&err, "could not create broker")

opts := option{
// This is to avoid too much complexity in the tests.
skipJWTSignatureCheck: false,
providerInfo: providers.CurrentProviderInfo(),
providerInfo: providers.CurrentProviderInfo(),
}
for _, arg := range args {
arg(&opts)
Expand Down Expand Up @@ -139,7 +135,7 @@ func New(cfg Config, args ...Option) (b *Broker, err error) {
b = &Broker{
providerInfo: opts.providerInfo,
issuerURL: cfg.IssuerURL,
oidcCfg: oidc.Config{ClientID: cfg.ClientID, InsecureSkipSignatureCheck: opts.skipJWTSignatureCheck},
oidcCfg: oidc.Config{ClientID: cfg.ClientID},
cachePath: cfg.CachePath,
homeDirPath: homeDirPath,
allowedSSHSuffixes: cfg.AllowedSSHSuffixes,
Expand Down
2 changes: 1 addition & 1 deletion internal/broker/broker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,7 @@ func TestFetchUserInfo(t *testing.T) {
mockInfoer.Groups = []info.Group{}
}

b, err := broker.New(brokerCfg, broker.WithSkipSignatureCheck(), broker.WithCustomProviderInfo(mockInfoer))
b, err := broker.New(brokerCfg, broker.WithCustomProviderInfo(mockInfoer))
require.NoError(t, err, "Setup: New should not have returned an error")

if tc.username == "" {
Expand Down
24 changes: 13 additions & 11 deletions internal/broker/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import (
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"fmt"
"strings"
"testing"
"time"

"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/require"
"github.com/ubuntu/authd-oidc-brokers/internal/broker"
"github.com/ubuntu/authd-oidc-brokers/internal/providers/info"
Expand All @@ -35,7 +35,6 @@ func newBrokerForTests(t *testing.T, cfg broker.Config) (b *broker.Broker) {

b, err := broker.New(
cfg,
broker.WithSkipSignatureCheck(),
broker.WithCustomProviderInfo(&testutils.MockProviderInfoer{
Groups: []info.Group{
{Name: "remote-group", UGID: "12345"},
Expand Down Expand Up @@ -142,15 +141,18 @@ func generateCachedInfo(t *testing.T, preexistentToken, issuer string) *broker.A
username = preexistentToken
}

idToken := fmt.Sprintf(`{
"iss": "%s",
"sub": "saved-user-id",
"aud": "test-client-id",
"name": "saved-user",
"exp": 9999999999,
"preferred_username": "%s"
}`, issuer, username)
encodedToken := fmt.Sprintf(".%s.", base64.RawURLEncoding.EncodeToString([]byte(idToken)))
idToken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iss": issuer,
"sub": "saved-user-id",
"aud": "test-client-id",
"exp": 9999999999,
"name": "test-user",
"preferred_username": username,
"email": "test-user@anotheremail.com",
"email_verified": true,
})
encodedToken, err := idToken.SignedString(testutils.MockKey)
require.NoError(t, err, "Setup: signing token should not have failed")

tok, ok := testTokens[preexistentToken]
if !ok {
Expand Down
7 changes: 0 additions & 7 deletions internal/broker/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,6 @@ package broker

import "github.com/ubuntu/authd-oidc-brokers/internal/providers"

// WithSkipSignatureCheck returns an option that skips the JWT signature check.
func WithSkipSignatureCheck() Option {
return func(o *option) {
o.skipJWTSignatureCheck = true
}
}

// WithCustomProviderInfo returns an option that sets a custom provider infoer for the broker.
func WithCustomProviderInfo(p providers.ProviderInfoer) Option {
return func(o *option) {
Expand Down
98 changes: 85 additions & 13 deletions internal/testutils/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ package testutils

import (
"context"
"encoding/base64"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"math/big"
"net"
"net/http"
"net/http/httptest"
Expand All @@ -14,11 +18,51 @@ import (
"time"

"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-jose/go-jose/v4"
"github.com/golang-jwt/jwt/v5"
"github.com/ubuntu/authd-oidc-brokers/internal/consts"
"github.com/ubuntu/authd-oidc-brokers/internal/providers/info"
"golang.org/x/oauth2"
)

// MockKey is the RSA key used to sign the JWTs for the mock provider.
var MockKey *rsa.PrivateKey

var mockCertificate *x509.Certificate

func init() {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(fmt.Sprintf("Setup: Could not generate RSA key for the Mock: %v", err))
}
MockKey = key

certTemplate := &x509.Certificate{
SerialNumber: big.NewInt(2024),
Subject: pkix.Name{
Organization: []string{"Mocks ltd."},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(0, 0, 1),
SubjectKeyId: []byte{1, 2, 3, 4, 5},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
KeyUsage: x509.KeyUsageDigitalSignature,
IsCA: true,
BasicConstraintsValid: true,
}

c, err := x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, &MockKey.PublicKey, MockKey)
if err != nil {
panic("Setup: Could not create certificate for the Mock")
}

cert, err := x509.ParseCertificate(c)
if err != nil {
panic("Setup: Could not parse certificate for the Mock")
}
mockCertificate = cert
}

// ProviderHandler is a function that handles a request to the mock provider.
type ProviderHandler func(http.ResponseWriter, *http.Request)

Expand Down Expand Up @@ -55,6 +99,7 @@ func StartMockProvider(address string, args ...OptionProvider) (*httptest.Server
"/.well-known/openid-configuration": DefaultOpenIDHandler(server.URL),
"/device_auth": DefaultDeviceAuthHandler(),
"/token": DefaultTokenHandler(server.URL, consts.DefaultScopes),
"/keys": DefaultJWKHandler(),
},
}
for _, arg := range args {
Expand Down Expand Up @@ -135,19 +180,21 @@ func DefaultTokenHandler(serverURL string, scopes []string) ProviderHandler {
// Mimics user going through auth process
time.Sleep(2 * time.Second)

idToken := fmt.Sprintf(`{
"iss": "%s",
"sub": "test-user-id",
"aud": "test-client-id",
"exp": 9999999999,
"name": "test-user",
idToken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iss": serverURL,
"sub": "test-user-id",
"aud": "test-client-id",
"exp": 9999999999,
"name": "test-user",
"preferred_username": "test-user@email.com",
"email": "test-user@anotheremail.com",
"email_verified": true
}`, serverURL)
"email": "test-user@anotheremail.com",
"email_verified": true,
})

// The token must be JWT formatted, even though we ignore the validation in the broker during the tests.
rawToken := fmt.Sprintf(".%s.", base64.RawURLEncoding.EncodeToString([]byte(idToken)))
rawToken, err := idToken.SignedString(MockKey)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}

response := fmt.Sprintf(`{
"access_token": "accesstoken",
Expand All @@ -159,10 +206,35 @@ func DefaultTokenHandler(serverURL string, scopes []string) ProviderHandler {
}`, strings.Join(scopes, " "), rawToken)

w.Header().Add("Content-Type", "application/json")
_, err := w.Write([]byte(response))
if _, err := w.Write([]byte(response)); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
}

// DefaultJWKHandler returns a handler that provides the signing keys from the broker.
//
// Meant to be used an the endpoint for /keys.
func DefaultJWKHandler() ProviderHandler {
return func(w http.ResponseWriter, r *http.Request) {
jwk := jose.JSONWebKey{
Key: &MockKey.PublicKey,
KeyID: "fa834459-66c6-475a-852f-444262a07c13_sig_rs256",
Algorithm: "RS256",
Use: "sig",
Certificates: []*x509.Certificate{mockCertificate},
}

encodedJWK, err := jwk.MarshalJSON()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}

response := fmt.Sprintf(`{"keys": [%s]}`, encodedJWK)
w.Header().Add("Content-Type", "application/json")
if _, err := w.Write([]byte(response)); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
}

Expand Down
Loading