Skip to content
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
36 changes: 31 additions & 5 deletions internal/models/custom_oauth_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ const (
ProviderTypeOIDC ProviderType = "oidc"
)

// ClientAuthMethod is how Auth authenticates to a custom provider's token
// endpoint.
type ClientAuthMethod string

const (
// ClientAuthMethodClientSecret sends the stored client secret.
ClientAuthMethodClientSecret ClientAuthMethod = "client_secret"
// ClientAuthMethodPrivateKeyJWT sends a signed client assertion (RFC 7523).
// No client secret is stored.
ClientAuthMethodPrivateKeyJWT ClientAuthMethod = "private_key_jwt"
)

// CustomOAuthProvider represents a custom OAuth2 or OIDC provider configuration
type CustomOAuthProvider struct {
ID uuid.UUID `db:"id" json:"id"`
Expand All @@ -32,7 +44,6 @@ type CustomOAuthProvider struct {
Identifier string `db:"identifier" json:"identifier"`
Name string `db:"name" json:"name"`
ClientID string `db:"client_id" json:"client_id"`
ClientSecret string `db:"client_secret" json:"-"` // Encrypted via EncryptedString, never expose in JSON
AcceptableClientIDs slices.String `db:"acceptable_client_ids" json:"acceptable_client_ids"`
Scopes slices.String `db:"scopes" json:"scopes"`
PKCEEnabled bool `db:"pkce_enabled" json:"pkce_enabled"`
Expand All @@ -44,6 +55,15 @@ type CustomOAuthProvider struct {
Enabled bool `db:"enabled" json:"enabled"`
EmailOptional bool `db:"email_optional" json:"email_optional"`

// Client authentication to the token endpoint.
ClientAuthMethod ClientAuthMethod `db:"client_auth_method" json:"client_auth_method"`
// ClientSecret is encrypted via EncryptedString and never exposed in JSON.
// It is empty for private_key_jwt providers.
ClientSecret string `db:"client_secret" json:"-"`
// ClientAssertionAudience overrides the aud claim of client assertions,
// which defaults to the provider's issuer. Only used with private_key_jwt.
ClientAssertionAudience *string `db:"client_assertion_audience" json:"client_assertion_audience,omitempty"`

// OIDC-specific fields (null for OAuth2 providers)
Issuer *string `db:"issuer" json:"issuer,omitempty"`
DiscoveryURL *string `db:"discovery_url" json:"discovery_url,omitempty"`
Expand Down Expand Up @@ -88,16 +108,18 @@ func (p *CustomOAuthProvider) SetClientSecret(secret string, dbEncryption conf.D
// GetClientSecret decrypts and returns the client secret using the configured
// database decryption keys. It expects the client secret to be stored in
// encrypted form when encryption is enabled, but will also handle plaintext
// secrets (for deployments where encryption is not yet configured).
// secrets (for deployments where encryption is not yet configured). It returns
// an empty string for providers without a secret (private_key_jwt).
func (p *CustomOAuthProvider) GetClientSecret(dbEncryption conf.DatabaseEncryptionConfiguration) (string, error) {
if p.ClientSecret == "" {
secret := p.ClientSecret
if secret == "" {
return "", nil
}

es := crypto.ParseEncryptedString(p.ClientSecret)
es := crypto.ParseEncryptedString(secret)
if es == nil {
// Not an encrypted string – treat as plaintext.
return p.ClientSecret, nil
return secret, nil
}

if dbEncryption.DecryptionKeys == nil {
Expand Down Expand Up @@ -288,6 +310,10 @@ func CreateCustomOAuthProvider(tx *storage.Connection, provider *CustomOAuthProv
if provider.CustomClaimsAllowlist == nil {
provider.CustomClaimsAllowlist = slices.String{}
}
// pop inserts every column, so the column default doesn't apply
if provider.ClientAuthMethod == "" {
provider.ClientAuthMethod = ClientAuthMethodClientSecret
}

if err := tx.Create(provider); err != nil {
return errors.Wrap(err, "error creating custom OAuth provider")
Expand Down
92 changes: 92 additions & 0 deletions internal/models/custom_oauth_provider_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package models

import (
"encoding/json"
"testing"

"github.com/gobuffalo/pop/v6/slices"
Expand Down Expand Up @@ -171,6 +172,7 @@ func (ts *CustomOAuthProviderTestSuite) TestStringSliceSerialization() {
Identifier: "custom:string-slice-test",
Name: "String Slice Test",
ClientID: "client-id",
ClientSecret: "test-client-secret",
Scopes: slices.String{"openid", "profile", "email"},
AcceptableClientIDs: slices.String{"ios-client", "android-client", "web-client"},
AuthorizationURL: stringPtr("https://example.com/authorize"),
Expand Down Expand Up @@ -205,6 +207,7 @@ func (ts *CustomOAuthProviderTestSuite) TestCustomClaimsAllowlistSerialization()
Identifier: "custom:allowlist-test",
Name: "Allowlist Test",
ClientID: "client-id",
ClientSecret: "test-client-secret",
AuthorizationURL: stringPtr("https://example.com/authorize"),
TokenURL: stringPtr("https://example.com/token"),
UserinfoURL: stringPtr("https://example.com/userinfo"),
Expand Down Expand Up @@ -254,6 +257,7 @@ func (ts *CustomOAuthProviderTestSuite) TestAttributeMappingSerialization() {
Identifier: "custom:mapping-test",
Name: "Mapping Test",
ClientID: "client-id",
ClientSecret: "test-client-secret",
AuthorizationURL: stringPtr("https://example.com/authorize"),
TokenURL: stringPtr("https://example.com/token"),
UserinfoURL: stringPtr("https://example.com/userinfo"),
Expand Down Expand Up @@ -286,6 +290,7 @@ func (ts *CustomOAuthProviderTestSuite) TestAuthorizationParamsSerialization() {
Identifier: "custom:params-test",
Name: "Params Test",
ClientID: "client-id",
ClientSecret: "test-client-secret",
AuthorizationURL: stringPtr("https://example.com/authorize"),
TokenURL: stringPtr("https://example.com/token"),
UserinfoURL: stringPtr("https://example.com/userinfo"),
Expand Down Expand Up @@ -324,6 +329,7 @@ func (ts *CustomOAuthProviderTestSuite) TestOIDCDiscoverySerialization() {
Identifier: "custom:oidc-discovery-test",
Name: "OIDC Discovery Test",
ClientID: "client-id",
ClientSecret: "test-client-secret",
Issuer: &issuer,
CachedDiscovery: discovery,
PKCEEnabled: true,
Expand Down Expand Up @@ -371,6 +377,7 @@ func (ts *CustomOAuthProviderTestSuite) TestGetDiscoveryURL() {
Identifier: "custom:oidc-auto-discovery",
Name: "OIDC Auto Discovery",
ClientID: "client-id",
ClientSecret: "test-client-secret",
Issuer: &issuer1,
PKCEEnabled: true,
Enabled: true,
Expand All @@ -389,6 +396,7 @@ func (ts *CustomOAuthProviderTestSuite) TestGetDiscoveryURL() {
Identifier: "custom:oidc-explicit-discovery",
Name: "OIDC Explicit Discovery",
ClientID: "client-id",
ClientSecret: "test-client-secret",
Issuer: &issuer2,
DiscoveryURL: &explicitDiscoveryURL,
PKCEEnabled: true,
Expand Down Expand Up @@ -491,6 +499,90 @@ func (ts *CustomOAuthProviderTestSuite) TestClientSecretRoundTripThroughDB() {
assert.Equal(ts.T(), secret, decrypted)
}

// Client auth method

func (ts *CustomOAuthProviderTestSuite) newPrivateKeyJWTProvider(identifier string) *CustomOAuthProvider {
issuer := "https://oidc-" + identifier + ".example.com"
return &CustomOAuthProvider{
ProviderType: ProviderTypeOIDC,
Identifier: "custom:" + identifier,
Name: "Private Key JWT Provider",
ClientID: "test-client-id",
Issuer: &issuer,
ClientAuthMethod: ClientAuthMethodPrivateKeyJWT,
PKCEEnabled: true,
Enabled: true,
}
}

func (ts *CustomOAuthProviderTestSuite) TestClientAuthMethodDefaultsToClientSecret() {
provider := ts.createTestProvider(ProviderTypeOIDC, "custom:default-method")

found, err := FindCustomOAuthProviderByID(ts.db, provider.ID)
require.NoError(ts.T(), err)
assert.Equal(ts.T(), ClientAuthMethodClientSecret, found.ClientAuthMethod)
assert.Nil(ts.T(), found.ClientAssertionAudience)
assert.NotEmpty(ts.T(), found.ClientSecret)
}

func (ts *CustomOAuthProviderTestSuite) TestPrivateKeyJWTProviderRoundTrip() {
provider := ts.newPrivateKeyJWTProvider("pkjwt-roundtrip")
provider.ClientAssertionAudience = stringPtr("https://issuer.example.com/token")
require.NoError(ts.T(), CreateCustomOAuthProvider(ts.db, provider))

found, err := FindCustomOAuthProviderByID(ts.db, provider.ID)
require.NoError(ts.T(), err)
assert.Equal(ts.T(), ClientAuthMethodPrivateKeyJWT, found.ClientAuthMethod)
assert.Equal(ts.T(), "https://issuer.example.com/token", *found.ClientAssertionAudience)
assert.Empty(ts.T(), found.ClientSecret)

// stored as an empty string, never NULL, so versions that predate
// client_auth_method can still read the row
var secretIsNull bool
require.NoError(ts.T(), ts.db.RawQuery(
"select client_secret is null from "+provider.TableName()+" where id = ?", provider.ID,
).First(&secretIsNull))
assert.False(ts.T(), secretIsNull)

secret, err := found.GetClientSecret(ts.config.Security.DBEncryption)
require.NoError(ts.T(), err)
assert.Empty(ts.T(), secret)

// the method and audience are exposed in JSON, the secret never is
data, err := json.Marshal(found)
require.NoError(ts.T(), err)
var raw map[string]any
require.NoError(ts.T(), json.Unmarshal(data, &raw))
assert.Equal(ts.T(), "private_key_jwt", raw["client_auth_method"])
assert.Equal(ts.T(), "https://issuer.example.com/token", raw["client_assertion_audience"])
assert.NotContains(ts.T(), raw, "client_secret")
}

func (ts *CustomOAuthProviderTestSuite) TestSwitchClientAuthMethod() {
provider := ts.createTestProvider(ProviderTypeOIDC, "custom:switch-method")

// to private_key_jwt, clearing the secret as the admin API does
provider.ClientAuthMethod = ClientAuthMethodPrivateKeyJWT
provider.ClientSecret = ""
require.NoError(ts.T(), UpdateCustomOAuthProvider(ts.db, provider))

found, err := FindCustomOAuthProviderByID(ts.db, provider.ID)
require.NoError(ts.T(), err)
assert.Equal(ts.T(), ClientAuthMethodPrivateKeyJWT, found.ClientAuthMethod)
assert.Empty(ts.T(), found.ClientSecret)

// back to client_secret with a new secret
found.ClientAuthMethod = ClientAuthMethodClientSecret
require.NoError(ts.T(), found.SetClientSecret("new-client-secret", ts.config.Security.DBEncryption))
require.NoError(ts.T(), UpdateCustomOAuthProvider(ts.db, found))

found, err = FindCustomOAuthProviderByID(ts.db, provider.ID)
require.NoError(ts.T(), err)
secret, err := found.GetClientSecret(ts.config.Security.DBEncryption)
require.NoError(ts.T(), err)
assert.Equal(ts.T(), "new-client-secret", secret)
}

func TestGetDiscoveryURLStripsTrailingSlashes(t *testing.T) {
tests := []struct {
name string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- Let custom OAuth providers authenticate to the token endpoint with either a
-- client secret or a signed client assertion (private_key_jwt, RFC 7523).
-- Existing rows default to client_secret and keep their secret.
--
-- client_secret stays NOT NULL: private_key_jwt providers store an empty
-- string instead, so versions that predate this migration can still read every
-- row during a rolling deploy or after a rollback.
--
-- The allowed methods, which methods need a secret, and the audience length
-- are enforced by the admin API, not by check constraints.
/* auth_migration: 20261116120000 */
alter table only {{ index .Options "Namespace" }}.custom_oauth_providers
add column if not exists client_auth_method text not null default 'client_secret',
-- Optional override for the assertion aud claim, which defaults to the
-- provider's issuer.
add column if not exists client_assertion_audience text null;
Loading