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
54 changes: 54 additions & 0 deletions claimrolemapping/check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package claimrolemapping

import (
"github.com/rs/zerolog"

"github.com/dioad/config/configcheck"
)

// AcceptUnauthenticatedRiskKey is the second opt-in allow-unauthenticated
// needs, as it is named in configuration.
const AcceptUnauthenticatedRiskKey = "accept-unauthenticated-risk"

// Check reports to c how a service authenticates its API callers: either with
// jwt-validators (jwtValidators is how many are configured), or, for local
// development only, with allow-unauthenticated. Exactly one of the two must be
// configured. c is positioned at the configuration root, where the keys sit.
//
// allow-unauthenticated bypasses authentication and every RBAC check, so it
// also needs accept-unauthenticated-risk. That key without
// allow-unauthenticated has no effect and is reported. A claim-role mapping
// with debug set logs every claim map it evaluates, which carries personal and
// organisational data, so it needs enableDebug (the service's enable-debug)
// too: that keeps a copied rule from switching it on in production by itself.
func (c ExtractorConfig) Check(findings *configcheck.Collector, jwtValidators int, enableDebug bool) {
unauthenticated := c.Unauthenticated()
switch {
case unauthenticated && !c.AcceptUnauthenticatedRisk:
findings.Field("allow-unauthenticated").Errorf("bypasses authentication and RBAC; set %s: true to confirm this is not a production deployment", AcceptUnauthenticatedRiskKey)
case !unauthenticated && c.AcceptUnauthenticatedRisk:
findings.Field(AcceptUnauthenticatedRiskKey).Errorf("is set but has no effect without allow-unauthenticated, remove it")
}
if unauthenticated && jwtValidators > 0 {
findings.Field("allow-unauthenticated").Errorf("and jwt-validators are mutually exclusive")
}
if !unauthenticated && jwtValidators == 0 {
findings.Field("jwt-validators").Errorf("is required when allow-unauthenticated is false")
}
if enableDebug {
return
}
for i, m := range c.ClaimRoleMappings {
if m.Debug {
findings.Field("claim-role-mappings").Index(i).Field("debug").Errorf("logs claim values for role %q; it requires enable-debug", m.Role)
}
}
}

// LogUnauthenticated logs, at error level, the startup messages for a service
// running with allow-unauthenticated, so every service words the risk
// identically and an error-level alert on startup logs catches it.
func LogUnauthenticated(logger zerolog.Logger) {
logger.Error().Msg("JWT validation is disabled — all API requests are accepted without authentication")
logger.Error().Msg("allow-unauthenticated is enabled: all authentication and RBAC checks are bypassed — do NOT use in production")
}
80 changes: 80 additions & 0 deletions claimrolemapping/check_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package claimrolemapping_test

import (
"bytes"
"testing"

"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"

"github.com/dioad/config/configcheck"

"github.com/dioad/auth/claimrolemapping"
)

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

yes, no := true, false
debugRule := []claimrolemapping.ClaimRoleMappingConfig{{Role: "admin", Debug: true}}

tests := []struct {
name string
cfg claimrolemapping.ExtractorConfig
validators int
debug bool
want []configcheck.Finding
}{
{name: "validators only", validators: 1},
{name: "unauthenticated with acknowledgement", cfg: claimrolemapping.ExtractorConfig{AllowUnauthenticated: &yes, AcceptUnauthenticatedRisk: true}},
{
name: "unauthenticated without acknowledgement",
cfg: claimrolemapping.ExtractorConfig{AllowUnauthenticated: &yes},
want: []configcheck.Finding{{Path: "allow-unauthenticated", Message: "bypasses authentication and RBAC; set accept-unauthenticated-risk: true to confirm this is not a production deployment"}},
},
{
name: "unauthenticated with validators",
cfg: claimrolemapping.ExtractorConfig{AllowUnauthenticated: &yes, AcceptUnauthenticatedRisk: true},
validators: 1,
want: []configcheck.Finding{{Path: "allow-unauthenticated", Message: "and jwt-validators are mutually exclusive"}},
},
{
name: "neither validators nor unauthenticated",
cfg: claimrolemapping.ExtractorConfig{AllowUnauthenticated: &no},
want: []configcheck.Finding{{Path: "jwt-validators", Message: "is required when allow-unauthenticated is false"}},
},
{
name: "acknowledgement without unauthenticated",
cfg: claimrolemapping.ExtractorConfig{AcceptUnauthenticatedRisk: true},
validators: 1,
want: []configcheck.Finding{{Path: "accept-unauthenticated-risk", Message: "is set but has no effect without allow-unauthenticated, remove it"}},
},
{
name: "debug rule without enable-debug",
cfg: claimrolemapping.ExtractorConfig{ClaimRoleMappings: debugRule},
validators: 1,
want: []configcheck.Finding{{Path: "claim-role-mappings[0].debug", Message: `logs claim values for role "admin"; it requires enable-debug`}},
},
{name: "debug rule with enable-debug", cfg: claimrolemapping.ExtractorConfig{ClaimRoleMappings: debugRule}, validators: 1, debug: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

c := configcheck.NewCollector()
tc.cfg.Check(c, tc.validators, tc.debug)

assert.Equal(t, tc.want, c.Findings())
})
}
}

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

var buf bytes.Buffer
claimrolemapping.LogUnauthenticated(zerolog.New(&buf))

assert.Equal(t, 2, bytes.Count(buf.Bytes(), []byte(`"level":"error"`)))
assert.Contains(t, buf.String(), "allow-unauthenticated is enabled")
}
13 changes: 11 additions & 2 deletions claimrolemapping/claimrolemapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,17 @@ type ExtractorConfig struct {
// can tell "not set at this level" (nil) apart from an explicit false -
// a plain bool can't distinguish the two, which would let a true default
// silently override a service's explicit false.
AllowUnauthenticated *bool `mapstructure:"allow-unauthenticated"`
ClaimRoleMappings []ClaimRoleMappingConfig `mapstructure:"claim-role-mappings"`
AllowUnauthenticated *bool `mapstructure:"allow-unauthenticated"`
// AcceptUnauthenticatedRisk is the second opt-in AllowUnauthenticated needs
// before Check accepts it. One flag copied into a production config by
// mistake is then not enough to open the API.
AcceptUnauthenticatedRisk bool `mapstructure:"accept-unauthenticated-risk"`
ClaimRoleMappings []ClaimRoleMappingConfig `mapstructure:"claim-role-mappings"`
}

// Unauthenticated reports whether allow-unauthenticated is set.
func (c ExtractorConfig) Unauthenticated() bool {
return c.AllowUnauthenticated != nil && *c.AllowUnauthenticated
}

// BuildExtractorConfig constructs a per-source DefaultExtractorConfig from
Expand Down
32 changes: 32 additions & 0 deletions http/server/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package server

import (
"fmt"

"github.com/dioad/auth"
nethttp "github.com/dioad/net/http"

"github.com/dioad/auth/http/middleware"
"github.com/dioad/auth/oidc"
)

// APIMiddlewares returns the authentication half of an API's middleware
// chain, in order: bearer token validation against validators, then principal
// extraction with extractor. Token validation is left out when there are no
// validators, which is the allow-unauthenticated case, so every request
// reaches the principal extractor with no token.
//
// Put anything that must run before authentication, such as a header check,
// ahead of the result, and anything that needs the principal, such as a rate
// limiter keyed by principal, after it. opts are passed to OAuth2ValidatorHandler.
func APIMiddlewares(validators []oidc.ValidatorConfig, extractor auth.PrincipalExtractor, opts ...ValidatorHandlerOption) ([]nethttp.Middleware, error) {
var chain []nethttp.Middleware
if len(validators) > 0 {
validate, err := OAuth2ValidatorHandler(validators, opts...)
if err != nil {
return nil, fmt.Errorf("building JWT middleware: %w", err)
}
chain = append(chain, validate)
}
return append(chain, middleware.PrincipalExtractionHandler(extractor)), nil
}
55 changes: 55 additions & 0 deletions http/server/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package server_test

import (
"net/http"
"net/http/httptest"
"testing"

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

"github.com/dioad/auth"
"github.com/dioad/auth/http/server"
"github.com/dioad/auth/oidc"
nethttp "github.com/dioad/net/http"
)

func serve(t *testing.T, chain []nethttp.Middleware, r *http.Request) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
nethttp.Chain(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
}), chain...).ServeHTTP(rec, r)
return rec
}

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

chain, err := server.APIMiddlewares(nil, auth.NewAllowAllPrincipalExtractor())
require.NoError(t, err)

assert.Len(t, chain, 1)
rec := serve(t, chain, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil))
assert.Equal(t, http.StatusNoContent, rec.Code)
}

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

validators := []oidc.ValidatorConfig{{Issuer: "https://issuer.example", HMACSecret: "0123456789abcdef0123456789abcdef", AllowInsecureHMAC: true}}
chain, err := server.APIMiddlewares(validators, auth.NewAllowAllPrincipalExtractor())
require.NoError(t, err)

assert.Len(t, chain, 2, "validation runs before principal extraction")
rec := serve(t, chain, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil))
assert.Equal(t, http.StatusUnauthorized, rec.Code)
}

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

_, err := server.APIMiddlewares([]oidc.ValidatorConfig{{}}, auth.NewAllowAllPrincipalExtractor())

assert.ErrorContains(t, err, "building JWT middleware")
}
95 changes: 95 additions & 0 deletions oidc/probe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package oidc

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
)

// ProbeValidators checks that every identity provider behind validators
// answers OIDC discovery and serves at least one signing key, using doer for
// the requests (nil means http.DefaultClient), and returns every failure
// joined. It returns nil when no validator fetches keys, so it is safe to call
// for any configuration; see KeyFetchingIssuers.
//
// It is for a readiness check. A pass means each issuer was reachable just
// now; it does not prove the validators' own key caches are current.
func ProbeValidators(ctx context.Context, validators []ValidatorConfig, doer HTTPDoer) error {
if doer == nil {
doer = http.DefaultClient
}
issuers := KeyFetchingIssuers(validators)
errs := make([]error, len(issuers))
var wg sync.WaitGroup
for i, issuer := range issuers {
wg.Go(func() { errs[i] = probeIssuer(ctx, doer, issuer) })
}
wg.Wait()
return errors.Join(errs...)
}

// KeyFetchingIssuers returns the distinct issuers whose signing keys the
// validators discover, resolving each the way dioad/auth's validator does:
// the configured issuer, else the endpoint URL. HMAC validators use a static
// secret and fetch nothing.
func KeyFetchingIssuers(validators []ValidatorConfig) []string {
var issuers []string
seen := make(map[string]bool)
for _, v := range validators {
if v.HMACSecret != "" {
continue
}
issuer := v.Issuer
if issuer == "" {
issuer = v.URL
}
if issuer == "" || seen[issuer] {
continue
}
seen[issuer] = true
issuers = append(issuers, issuer)
}
return issuers
}

// probeIssuer fetches issuer's discovery document and then its JWKS, and
// requires at least one key.
func probeIssuer(ctx context.Context, doer HTTPDoer, issuer string) error {
endpoint, err := NewEndpoint(issuer, WithHTTPDoer(doer))
if err != nil {
return fmt.Errorf("%s: %w", issuer, err)
}
discovered, err := endpoint.DiscoveredConfiguration(ctx)
if err != nil {
return fmt.Errorf("%s: discovery: %w", issuer, err)
}
if discovered.JWKSURI == "" {
return fmt.Errorf("%s: discovery document has no jwks_uri", issuer)
}

req, err := http.NewRequestWithContext(ctx, http.MethodGet, discovered.JWKSURI, nil)
if err != nil {
return fmt.Errorf("%s: jwks: %w", issuer, err)
}
resp, err := doer.Do(req)
if err != nil {
return fmt.Errorf("%s: jwks: %w", issuer, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s: jwks: status %d", issuer, resp.StatusCode)
}
var keySet struct {
Keys []json.RawMessage `json:"keys"`
}
if err := json.NewDecoder(resp.Body).Decode(&keySet); err != nil {
return fmt.Errorf("%s: jwks: %w", issuer, err)
}
if len(keySet.Keys) == 0 {
return fmt.Errorf("%s: jwks has no keys", issuer)
}
return nil
}
Loading
Loading