Skip to content
Open
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
25 changes: 23 additions & 2 deletions coderd/coderdtest/oidctest/idp.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,9 @@ type FakeIDP struct {
hookAuthenticateClient func(t testing.TB, req *http.Request) (url.Values, error)
serve bool
// optional middlewares
middlewares chi.Middlewares
defaultExpire time.Duration
middlewares chi.Middlewares
defaultExpire time.Duration
omitEmailVerifiedDefault bool
}

func StatusError(code int, err error) error {
Expand Down Expand Up @@ -378,6 +379,15 @@ func WithIssuer(issuer string) func(*FakeIDP) {
}
}

// WithOmitEmailVerifiedDefault suppresses the default email_verified=true
// injection in encodeClaims. Use this for tests that exercise the handler's
// absent-claim rejection path.
func WithOmitEmailVerifiedDefault() func(*FakeIDP) {
return func(f *FakeIDP) {
f.omitEmailVerifiedDefault = true
}
}

type With429Arguments struct {
AllPaths bool
TokenPath bool
Expand Down Expand Up @@ -907,6 +917,17 @@ func (f *FakeIDP) encodeClaims(t testing.TB, claims jwt.MapClaims) string {
claims["iss"] = f.locked.Issuer()
}

// Default email_verified to true so that tests that do not care
// about the email_verified flow are not forced to set it.
// Tests that need a different value can set it explicitly.
// Use WithOmitEmailVerifiedDefault() to suppress this default
// for tests that need to exercise the absent-claim path.
if !f.omitEmailVerifiedDefault {
if _, ok := claims["email_verified"]; !ok {
claims["email_verified"] = true
}
}

signed, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(f.locked.PrivateKey())
require.NoError(t, err)

Expand Down
89 changes: 69 additions & 20 deletions coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package coderd
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
Expand Down Expand Up @@ -1339,29 +1340,41 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
return
}

verifiedRaw, ok := mergedClaims["email_verified"]
if ok {
verified, ok := verifiedRaw.(bool)
if ok && !verified {
if !api.OIDCConfig.IgnoreEmailVerified {
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: http.StatusForbidden,
HideStatus: true,
Title: "Email not verified",
Description: fmt.Sprintf(
"Verify the %q email address on your OIDC provider to authenticate!",
email,
),
Actions: []site.Action{
{URL: "/login", Text: "Back to login"},
},
})
return
}
logger.Warn(ctx, "allowing unverified oidc email", slog.F("email", email))
// Determine whether the email is verified. Default to unverified
// so that a missing claim or an unrecognized type is fail-closed.
emailVerified := false
verifiedRaw, hasVerifiedClaim := mergedClaims["email_verified"]
if hasVerifiedClaim {
v, coerceOK := coerceEmailVerified(verifiedRaw)
if coerceOK {
emailVerified = v
} else {
logger.Warn(ctx, "unrecognized email_verified claim type, treating as unverified",
slog.F("type", fmt.Sprintf("%T", verifiedRaw)),
slog.F("value", verifiedRaw),
)
}
}

if !emailVerified {
if !api.OIDCConfig.IgnoreEmailVerified {
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: http.StatusForbidden,
HideStatus: true,
Title: "Email not verified",
Description: fmt.Sprintf(
"Verify the %q email address on your OIDC provider to authenticate!",
email,
),
Actions: []site.Action{
{URL: "/login", Text: "Back to login"},
},
})
return
}
logger.Warn(ctx, "allowing unverified oidc email", slog.F("email", email))
}

// The username is a required property in Coder. We make a best-effort
// attempt at using what the claims provide, but if that fails we will
// generate a random username.
Expand Down Expand Up @@ -2171,3 +2184,39 @@ func wrongLoginTypeHTTPError(user database.LoginType, params database.LoginType)
params, user, addedMsg),
}
}

// coerceEmailVerified attempts to convert an OIDC email_verified claim to a
// boolean. Some IdPs (e.g. SAML-to-OIDC bridges, certain Azure AD B2C
// configurations) return email_verified as a string ("true"/"false") or a
// number (1/0) rather than a native JSON boolean. This function handles
// those variants so that non-bool representations cannot silently bypass
// the verification check.
//
// Returns (value, true) on successful coercion, or (false, false) if the
// value is nil or an unrecognized type.
func coerceEmailVerified(v interface{}) (verified bool, ok bool) {
switch val := v.(type) {
case bool:
return val, true
case string:
b, err := strconv.ParseBool(val)
if err != nil {
return false, false
}
return b, true
case json.Number:
n, err := val.Int64()
if err != nil {
return false, false
}
return n != 0, true
case float64:
return val != 0, true
case int64:
return val != 0, true
case int:
return val != 0, true
default:
return false, false
}
}
65 changes: 65 additions & 0 deletions coderd/userauth_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package coderd

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"
)

func TestCoerceEmailVerified(t *testing.T) {
t.Parallel()

tests := []struct {
name string
input interface{}
wantBool bool
wantOK bool
}{
// Native booleans
{name: "BoolTrue", input: true, wantBool: true, wantOK: true},
{name: "BoolFalse", input: false, wantBool: false, wantOK: true},

// Strings
{name: "StringTrue", input: "true", wantBool: true, wantOK: true},
{name: "StringFalse", input: "false", wantBool: false, wantOK: true},
{name: "StringOne", input: "1", wantBool: true, wantOK: true},
{name: "StringZero", input: "0", wantBool: false, wantOK: true},
{name: "StringTRUE", input: "TRUE", wantBool: true, wantOK: true},
{name: "StringFALSE", input: "FALSE", wantBool: false, wantOK: true},
{name: "StringT", input: "t", wantBool: true, wantOK: true},
{name: "StringF", input: "f", wantBool: false, wantOK: true},
{name: "StringInvalid", input: "invalid", wantBool: false, wantOK: false},
{name: "StringEmpty", input: "", wantBool: false, wantOK: false},

// json.Number (when decoder uses UseNumber)
{name: "JSONNumberOne", input: json.Number("1"), wantBool: true, wantOK: true},
{name: "JSONNumberZero", input: json.Number("0"), wantBool: false, wantOK: true},
{name: "JSONNumberInvalid", input: json.Number("abc"), wantBool: false, wantOK: false},

// float64 (default JSON numeric type)
{name: "Float64One", input: float64(1), wantBool: true, wantOK: true},
{name: "Float64Zero", input: float64(0), wantBool: false, wantOK: true},

// Integer types
{name: "IntOne", input: int(1), wantBool: true, wantOK: true},
{name: "IntZero", input: int(0), wantBool: false, wantOK: true},
{name: "Int64One", input: int64(1), wantBool: true, wantOK: true},
{name: "Int64Zero", input: int64(0), wantBool: false, wantOK: true},

// Nil and unsupported types
{name: "Nil", input: nil, wantBool: false, wantOK: false},
{name: "Slice", input: []string{}, wantBool: false, wantOK: false},
{name: "Map", input: map[string]string{}, wantBool: false, wantOK: false},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

gotBool, gotOK := coerceEmailVerified(tc.input)
assert.Equal(t, tc.wantBool, gotBool, "bool value mismatch")
assert.Equal(t, tc.wantOK, gotOK, "ok value mismatch")
})
}
}
Loading
Loading