linter pass

This commit is contained in:
Joe Kralicky 2024-10-24 17:56:30 -04:00
parent f1d2799a9f
commit 8049ca54d0
No known key found for this signature in database
GPG key ID: 75C4875F34A9FB79
13 changed files with 51 additions and 50 deletions

View file

@ -76,3 +76,6 @@ issues:
- text: "G112:" - text: "G112:"
linters: linters:
- gosec - gosec
- text: "G402: TLS MinVersion too low."
linters:
- gosec

View file

@ -93,7 +93,7 @@ func TestHTTP(t *testing.T) {
env := testenv.New(t) env := testenv.New(t)
up := upstreams.HTTP(nil) up := upstreams.HTTP(nil)
up.Handle("/foo", func(w http.ResponseWriter, r *http.Request) { up.Handle("/foo", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "hello world") fmt.Fprintln(w, "hello world")
}) })
@ -130,7 +130,7 @@ func TestClientCert(t *testing.T) {
env.Add(scenarios.DownstreamMTLS(config.MTLSEnforcementRejectConnection)) env.Add(scenarios.DownstreamMTLS(config.MTLSEnforcementRejectConnection))
up := upstreams.HTTP(nil) up := upstreams.HTTP(nil)
up.Handle("/foo", func(w http.ResponseWriter, r *http.Request) { up.Handle("/foo", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "hello world") fmt.Fprintln(w, "hello world")
}) })

View file

@ -24,7 +24,7 @@ func BenchmarkStartupLatency(b *testing.B) {
env.AddUpstream(up) env.AddUpstream(up)
env.Start() env.Start()
snippets.WaitStartupComplete(b, env, 60*time.Minute) snippets.WaitStartupComplete(env, 60*time.Minute)
env.Stop() env.Stop()
} }
@ -41,7 +41,7 @@ func BenchmarkAppendRoutes(b *testing.B) {
env.AddUpstream(up) env.AddUpstream(up)
env.Start() env.Start()
snippets.WaitStartupComplete(b, env) snippets.WaitStartupComplete(env)
for i := range n { for i := range n {
env.Add(up.Route(). env.Add(up.Route().
From(env.SubdomainURL(fmt.Sprintf("from-%d", i))). From(env.SubdomainURL(fmt.Sprintf("from-%d", i))).

View file

@ -31,7 +31,7 @@ func BenchmarkRequestLatency(b *testing.B) {
env.Add(scenarios.NewIDP(users)) env.Add(scenarios.NewIDP(users))
up := upstreams.HTTP(nil) up := upstreams.HTTP(nil)
up.Handle("/", func(w http.ResponseWriter, r *http.Request) { up.Handle("/", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("OK")) w.Write([]byte("OK"))
}) })
routes := make([]testenv.Route, n) routes := make([]testenv.Route, n)
@ -43,7 +43,7 @@ func BenchmarkRequestLatency(b *testing.B) {
env.AddUpstream(up) env.AddUpstream(up)
env.Start() env.Start()
snippets.WaitStartupComplete(b, env) snippets.WaitStartupComplete(env)
b.StartTimer() b.StartTimer()

View file

@ -480,7 +480,7 @@ func (e *environment) Start() {
mod.Value.Modify(cfg) mod.Value.Modify(cfg)
require.NoError(e.t, cfg.Options.Validate(), "invoking modifier resulted in an invalid configuration:\nadded by: "+mod.Caller) require.NoError(e.t, cfg.Options.Validate(), "invoking modifier resulted in an invalid configuration:\nadded by: "+mod.Caller)
} }
return pomerium.Run(e.ctx, e.src, pomerium.WithOverrideFileManager(fileMgr)) return pomerium.Run(ctx, e.src, pomerium.WithOverrideFileManager(fileMgr))
})) }))
for i, task := range e.tasks { for i, task := range e.tasks {
@ -702,14 +702,13 @@ func (e *environment) ReportError(check health.Check, err error, attributes ...h
} }
// ReportOK implements health.Provider. // ReportOK implements health.Provider.
func (e *environment) ReportOK(check health.Check, attributes ...health.Attr) { func (e *environment) ReportOK(_ health.Check, _ ...health.Attr) {}
}
func (e *environment) advanceState(newState EnvironmentState) { func (e *environment) advanceState(newState EnvironmentState) {
e.stateMu.Lock() e.stateMu.Lock()
defer e.stateMu.Unlock() defer e.stateMu.Unlock()
if e.state != newState>>1 { if e.state != newState>>1 {
panic(fmt.Sprintf("internal test environment bug: invalid state: expected=%s, actual=%s", EnvironmentState(newState>>1), e.state)) panic(fmt.Sprintf("internal test environment bug: invalid state: expected=%s, actual=%s", newState>>1, e.state))
} }
e.debugf("state %s -> %s", e.state.String(), newState.String()) e.debugf("state %s -> %s", e.state.String(), newState.String())
e.state = newState e.state = newState

View file

@ -235,7 +235,7 @@ func (lr *LogRecorder) DumpToFile(file string) {
require.NoError(lr.t, err) require.NoError(lr.t, err)
enc := json.NewEncoder(f) enc := json.NewEncoder(f)
for _, log := range lr.recordedLogs { for _, log := range lr.recordedLogs {
enc.Encode(log) _ = enc.Encode(log)
} }
f.Close() f.Close()
} }

View file

@ -39,14 +39,14 @@ func (b *PolicyRoute) Modify(cfg *config.Config) {
} }
// From implements Route. // From implements Route.
func (b *PolicyRoute) From(fromUrl values.Value[string]) Route { func (b *PolicyRoute) From(fromURL values.Value[string]) Route {
b.from = fromUrl b.from = fromURL
return b return b
} }
// To implements Route. // To implements Route.
func (b *PolicyRoute) To(toUrl values.Value[string]) Route { func (b *PolicyRoute) To(toURL values.Value[string]) Route {
b.to = append(b.to, toUrl) b.to = append(b.to, toURL)
return b return b
} }

View file

@ -34,7 +34,6 @@ import (
type IDP struct { type IDP struct {
id values.Value[string] id values.Value[string]
url values.Value[string] url values.Value[string]
serverCert *testenv.Certificate
publicJWK jose.JSONWebKey publicJWK jose.JSONWebKey
signingKey jose.SigningKey signingKey jose.SigningKey
@ -43,12 +42,12 @@ type IDP struct {
} }
// Attach implements testenv.Modifier. // Attach implements testenv.Modifier.
func (i *IDP) Attach(ctx context.Context) { func (idp *IDP) Attach(ctx context.Context) {
env := testenv.EnvFromContext(ctx) env := testenv.EnvFromContext(ctx)
router := upstreams.HTTP(nil) router := upstreams.HTTP(nil)
i.url = values.Bind2(env.SubdomainURL("mock-idp"), router.Port(), func(urlStr string, port int) string { idp.url = values.Bind2(env.SubdomainURL("mock-idp"), router.Port(), func(urlStr string, port int) string {
u, _ := url.Parse(urlStr) u, _ := url.Parse(urlStr)
host, _, _ := net.SplitHostPort(u.Host) host, _, _ := net.SplitHostPort(u.Host)
return u.ResolveReference(&url.URL{ return u.ResolveReference(&url.URL{
@ -57,10 +56,10 @@ func (i *IDP) Attach(ctx context.Context) {
}).String() }).String()
}) })
var err error var err error
i.stateEncoder, err = jws.NewHS256Signer(env.SharedSecret()) idp.stateEncoder, err = jws.NewHS256Signer(env.SharedSecret())
env.Require().NoError(err) env.Require().NoError(err)
i.id = values.Bind2(i.url, env.AuthenticateURL(), func(idpUrl, authUrl string) string { idp.id = values.Bind2(idp.url, env.AuthenticateURL(), func(idpUrl, authUrl string) string {
provider := identity.Provider{ provider := identity.Provider{
AuthenticateServiceUrl: authUrl, AuthenticateServiceUrl: authUrl,
ClientId: "CLIENT_ID", ClientId: "CLIENT_ID",
@ -72,36 +71,36 @@ func (i *IDP) Attach(ctx context.Context) {
return provider.Hash() return provider.Hash()
}) })
router.Handle("/.well-known/jwks.json", func(w http.ResponseWriter, r *http.Request) { router.Handle("/.well-known/jwks.json", func(w http.ResponseWriter, _ *http.Request) {
json.NewEncoder(w).Encode(&jose.JSONWebKeySet{ _ = json.NewEncoder(w).Encode(&jose.JSONWebKeySet{
Keys: []jose.JSONWebKey{i.publicJWK}, Keys: []jose.JSONWebKey{idp.publicJWK},
}) })
}) })
router.Handle("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { router.Handle("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
log.Ctx(ctx).Debug().Str("method", r.Method).Str("uri", r.RequestURI).Send() log.Ctx(ctx).Debug().Str("method", r.Method).Str("uri", r.RequestURI).Send()
rootUrl, _ := url.Parse(i.url.Value()) rootURL, _ := url.Parse(idp.url.Value())
json.NewEncoder(w).Encode(map[string]interface{}{ _ = json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": rootUrl.String(), "issuer": rootURL.String(),
"authorization_endpoint": rootUrl.ResolveReference(&url.URL{Path: "/oidc/auth"}).String(), "authorization_endpoint": rootURL.ResolveReference(&url.URL{Path: "/oidc/auth"}).String(),
"token_endpoint": rootUrl.ResolveReference(&url.URL{Path: "/oidc/token"}).String(), "token_endpoint": rootURL.ResolveReference(&url.URL{Path: "/oidc/token"}).String(),
"jwks_uri": rootUrl.ResolveReference(&url.URL{Path: "/.well-known/jwks.json"}).String(), "jwks_uri": rootURL.ResolveReference(&url.URL{Path: "/.well-known/jwks.json"}).String(),
"userinfo_endpoint": rootUrl.ResolveReference(&url.URL{Path: "/oidc/userinfo"}).String(), "userinfo_endpoint": rootURL.ResolveReference(&url.URL{Path: "/oidc/userinfo"}).String(),
"id_token_signing_alg_values_supported": []string{ "id_token_signing_alg_values_supported": []string{
"ES256", "ES256",
}, },
}) })
}) })
router.Handle("/oidc/auth", i.HandleAuth) router.Handle("/oidc/auth", idp.HandleAuth)
router.Handle("/oidc/token", i.HandleToken) router.Handle("/oidc/token", idp.HandleToken)
router.Handle("/oidc/userinfo", i.HandleUserInfo) router.Handle("/oidc/userinfo", idp.HandleUserInfo)
env.AddUpstream(router) env.AddUpstream(router)
} }
// Modify implements testenv.Modifier. // Modify implements testenv.Modifier.
func (i *IDP) Modify(cfg *config.Config) { func (idp *IDP) Modify(cfg *config.Config) {
cfg.Options.Provider = "oidc" cfg.Options.Provider = "oidc"
cfg.Options.ProviderURL = i.url.Value() cfg.Options.ProviderURL = idp.url.Value()
cfg.Options.ClientID = "CLIENT_ID" cfg.Options.ClientID = "CLIENT_ID"
cfg.Options.ClientSecret = "CLIENT_SECRET" cfg.Options.ClientSecret = "CLIENT_SECRET"
cfg.Options.Scopes = []string{"openid", "email", "profile"} cfg.Options.Scopes = []string{"openid", "email", "profile"}
@ -254,15 +253,17 @@ func (idp *IDP) HandleUserInfo(w http.ResponseWriter, r *http.Request) {
serveJSON(w, state.GetUserInfo(idp.userLookup)) serveJSON(w, state.GetUserInfo(idp.userLookup))
} }
var RootURLKey = struct{}{} type RootURLKey struct{}
var rootURLKey RootURLKey
// WithRootURL sets the Root URL in a context. // WithRootURL sets the Root URL in a context.
func WithRootURL(ctx context.Context, rootURL *url.URL) context.Context { func WithRootURL(ctx context.Context, rootURL *url.URL) context.Context {
return context.WithValue(ctx, RootURLKey, rootURL) return context.WithValue(ctx, rootURLKey, rootURL)
} }
func getRootURL(r *http.Request) *url.URL { func getRootURL(r *http.Request) *url.URL {
if u, ok := r.Context().Value(RootURLKey).(*url.URL); ok { if u, ok := r.Context().Value(rootURLKey).(*url.URL); ok {
return u return u
} }

View file

@ -26,7 +26,7 @@ type PolicyTemplate struct {
} }
func TemplateRoutes(n int, tmpl PolicyTemplate) testenv.Modifier { func TemplateRoutes(n int, tmpl PolicyTemplate) testenv.Modifier {
return testenv.ModifierFunc(func(ctx context.Context, cfg *config.Config) { return testenv.ModifierFunc(func(_ context.Context, cfg *config.Config) {
for i := range n { for i := range n {
cfg.Options.Policies = append(cfg.Options.Policies, newPolicyFromTemplate(i, tmpl)) cfg.Options.Policies = append(cfg.Options.Policies, newPolicyFromTemplate(i, tmpl))
} }

View file

@ -2,7 +2,6 @@ package snippets
import ( import (
"context" "context"
"testing"
"time" "time"
"github.com/pomerium/pomerium/internal/testenv" "github.com/pomerium/pomerium/internal/testenv"
@ -12,7 +11,7 @@ import (
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
) )
func WaitStartupComplete(t testing.TB, env testenv.Environment, timeout ...time.Duration) time.Duration { func WaitStartupComplete(env testenv.Environment, timeout ...time.Duration) time.Duration {
start := time.Now() start := time.Now()
recorder := env.NewLogRecorder() recorder := env.NewLogRecorder()
if len(timeout) == 0 { if len(timeout) == 0 {

View file

@ -192,7 +192,7 @@ type Upstream interface {
type Route interface { type Route interface {
Modifier Modifier
URL() values.Value[string] URL() values.Value[string]
To(toUrl values.Value[string]) Route To(toURL values.Value[string]) Route
Policy(edit func(*config.Policy)) Route Policy(edit func(*config.Policy)) Route
PPL(ppl string) Route PPL(ppl string) Route
// add more methods here as they become needed // add more methods here as they become needed
@ -202,5 +202,5 @@ type Route interface {
// From() method will return a [Route], from which further configuration can // From() method will return a [Route], from which further configuration can
// be made. // be made.
type RouteStub interface { type RouteStub interface {
From(fromUrl values.Value[string]) Route From(fromURL values.Value[string]) Route
} }

View file

@ -276,9 +276,9 @@ func (h *httpUpstream) Do(method string, r testenv.Route, opts ...RequestOption)
if err := retry.Retry(h.Env().Context(), "http", func(ctx context.Context) error { if err := retry.Retry(h.Env().Context(), "http", func(ctx context.Context) error {
var err error var err error
if options.authenticateAs != "" { if options.authenticateAs != "" {
resp, err = authenticateFlow(ctx, client, req, options.authenticateAs) resp, err = authenticateFlow(ctx, client, req, options.authenticateAs) //nolint:bodyclose
} else { } else {
resp, err = client.Do(req) resp, err = client.Do(req) //nolint:bodyclose
} }
// retry on connection refused // retry on connection refused
if err != nil { if err != nil {
@ -288,8 +288,8 @@ func (h *httpUpstream) Do(method string, r testenv.Route, opts ...RequestOption)
} }
return retry.NewTerminalError(err) return retry.NewTerminalError(err)
} }
if resp.StatusCode == 500 { if resp.StatusCode == http.StatusInternalServerError {
return errors.New("Internal Server Error") return errors.New(http.StatusText(resp.StatusCode))
} }
return nil return nil
}, retry.WithMaxInterval(100*time.Millisecond)); err != nil { }, retry.WithMaxInterval(100*time.Millisecond)); err != nil {
@ -322,7 +322,6 @@ func authenticateFlow(ctx context.Context, client *http.Client, req *http.Reques
return nil, err return nil, err
} }
return client.Do(formReq) return client.Do(formReq)
} else {
return nil, fmt.Errorf("test bug: expected IDP login form")
} }
return nil, fmt.Errorf("test bug: expected IDP login form")
} }

View file

@ -92,7 +92,7 @@ func Bind[T any, U any](dt Value[T], callback func(value T) U) Value[U] {
func Bind2[T any, U any, V any](dt Value[T], du Value[U], callback func(value1 T, value2 U) V) Value[V] { func Bind2[T any, U any, V any](dt Value[T], du Value[U], callback func(value1 T, value2 U) V) Value[V] {
dv := Deferred[V]() dv := Deferred[V]()
dv.ResolveFunc(func() V { dv.ResolveFunc(func() V {
if rand.IntN(2) == 0 { if rand.IntN(2) == 0 { //nolint:gosec
return callback(dt.Value(), du.Value()) return callback(dt.Value(), du.Value())
} }
u := du.Value() u := du.Value()