diff --git a/claimrolemapping/check.go b/claimrolemapping/check.go new file mode 100644 index 0000000..ebe5232 --- /dev/null +++ b/claimrolemapping/check.go @@ -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") +} diff --git a/claimrolemapping/check_test.go b/claimrolemapping/check_test.go new file mode 100644 index 0000000..c74ac93 --- /dev/null +++ b/claimrolemapping/check_test.go @@ -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") +} diff --git a/claimrolemapping/claimrolemapping.go b/claimrolemapping/claimrolemapping.go index 1debe15..fc1faf5 100644 --- a/claimrolemapping/claimrolemapping.go +++ b/claimrolemapping/claimrolemapping.go @@ -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 diff --git a/http/server/api.go b/http/server/api.go new file mode 100644 index 0000000..951c8e0 --- /dev/null +++ b/http/server/api.go @@ -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 +} diff --git a/http/server/api_test.go b/http/server/api_test.go new file mode 100644 index 0000000..1a4ed74 --- /dev/null +++ b/http/server/api_test.go @@ -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") +} diff --git a/oidc/probe.go b/oidc/probe.go new file mode 100644 index 0000000..dd638d1 --- /dev/null +++ b/oidc/probe.go @@ -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 +} diff --git a/oidc/probe_test.go b/oidc/probe_test.go new file mode 100644 index 0000000..b33de93 --- /dev/null +++ b/oidc/probe_test.go @@ -0,0 +1,145 @@ +package oidc_test + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dioad/auth/oidc" +) + +// fakeIssuer serves an OIDC discovery document and a JWKS, counting discovery +// requests. +type fakeIssuer struct { + *httptest.Server + + discoveries atomic.Int32 +} + +func newFakeIssuer(t *testing.T, jwks string) *fakeIssuer { + t.Helper() + idp := &fakeIssuer{} + idp.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/.well-known/openid-configuration": + idp.discoveries.Add(1) + _, _ = w.Write([]byte(`{"issuer":"` + idp.URL + `","jwks_uri":"` + idp.URL + `/jwks"}`)) + case "/jwks": + _, _ = w.Write([]byte(jwks)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(idp.Close) + return idp +} + +const oneKey = `{"keys":[{"kty":"RSA","kid":"k1"}]}` + +func TestProbeValidators_PassesWithoutKeyFetchingValidators(t *testing.T) { + t.Parallel() + + hmac := []oidc.ValidatorConfig{{Issuer: "https://issuer.example", HMACSecret: "s3cr3t", AllowInsecureHMAC: true}} + + assert.NoError(t, oidc.ProbeValidators(t.Context(), nil, nil)) + assert.NoError(t, oidc.ProbeValidators(t.Context(), hmac, nil)) + assert.Empty(t, oidc.KeyFetchingIssuers(hmac)) +} + +func TestProbeValidators_ProbesTheIssuerTheValidatorUses(t *testing.T) { + t.Parallel() + + down := httptest.NewServer(http.NotFoundHandler()) + t.Cleanup(down.Close) + + tests := []struct { + name string + validator func(up string) oidc.ValidatorConfig + wantErr bool + }{ + {"issuer set", func(up string) oidc.ValidatorConfig { return oidc.ValidatorConfig{Issuer: up} }, false}, + {"issuer falls back to the endpoint URL", func(up string) oidc.ValidatorConfig { return oidc.ValidatorConfig{URL: up} }, false}, + {"issuer wins over the endpoint URL", func(up string) oidc.ValidatorConfig { + return oidc.ValidatorConfig{Issuer: down.URL, URL: up} + }, true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + idp := newFakeIssuer(t, oneKey) + + err := oidc.ProbeValidators(t.Context(), []oidc.ValidatorConfig{tc.validator(idp.URL)}, nil) + + if tc.wantErr { + assert.ErrorContains(t, err, down.URL) + return + } + assert.NoError(t, err) + }) + } +} + +func TestProbeValidators_RejectsAnEmptyKeySet(t *testing.T) { + t.Parallel() + + idp := newFakeIssuer(t, `{"keys":[]}`) + + err := oidc.ProbeValidators(t.Context(), []oidc.ValidatorConfig{{Issuer: idp.URL}}, nil) + + assert.ErrorContains(t, err, "jwks has no keys") +} + +func TestProbeValidators_NamesOnlyTheIssuersThatFail(t *testing.T) { + t.Parallel() + + up := newFakeIssuer(t, oneKey) + down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(down.Close) + + err := oidc.ProbeValidators(t.Context(), []oidc.ValidatorConfig{{Issuer: up.URL}, {Issuer: down.URL}}, nil) + + require.ErrorContains(t, err, down.URL+": discovery") + assert.NotContains(t, err.Error(), up.URL+":") +} + +func TestProbeValidators_ProbesEachDistinctIssuerOnce(t *testing.T) { + t.Parallel() + + idp := newFakeIssuer(t, oneKey) + + err := oidc.ProbeValidators(t.Context(), []oidc.ValidatorConfig{{Issuer: idp.URL}, {Issuer: idp.URL}}, nil) + + require.NoError(t, err) + assert.Equal(t, int32(1), idp.discoveries.Load()) +} + +func TestProbeValidators_AHangingIssuerIsBoundedByTheContext(t *testing.T) { + t.Parallel() + + release := make(chan struct{}) + hang := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + select { + case <-release: + case <-r.Context().Done(): + } + })) + t.Cleanup(func() { close(release); hang.Close() }) + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) + defer cancel() + + start := time.Now() + err := oidc.ProbeValidators(ctx, []oidc.ValidatorConfig{{Issuer: hang.URL}}, nil) + + require.Error(t, err) + assert.Less(t, time.Since(start), 5*time.Second) +}