From 63c161224a580d5ac07f5bd0fda1baf2137be11f Mon Sep 17 00:00:00 2001 From: Paul Lorenz Date: Mon, 10 Oct 2022 16:49:46 -0400 Subject: [PATCH] Add linter and fix issues found by linter --- .github/workflows/golangci-lint.yml | 41 +++++++++ controller/config/config.go | 6 +- controller/env/appenv.go | 35 ++++---- controller/env/broker.go | 2 - controller/env/context.go | 6 +- controller/env/producers.go | 4 +- controller/handler_edge_ctrl/common.go | 4 +- controller/handler_edge_ctrl/common_tunnel.go | 2 +- .../current_identity_authenticator_router.go | 5 ++ controller/internal/routes/database_router.go | 2 +- .../internal/routes/identity_api_model.go | 4 +- .../routes/posture_check_api_model.go | 24 ++---- .../routes/posture_response_router.go | 13 +-- controller/model/api_session_heartbeats.go | 2 +- controller/model/auth_policy_manager.go | 9 -- controller/model/authenticator_manager.go | 8 +- controller/model/authenticator_mod_cert.go | 9 +- controller/model/authenticator_mod_ext_jwt.go | 30 +++---- controller/model/create_terminator_cmd.go | 4 + controller/model/enrollment.go | 4 +- controller/model/identity_manager.go | 23 +++-- controller/model/mfa_manager.go | 20 +++-- controller/model/posture_check_model_mac.go | 2 +- controller/model/posture_check_model_os.go | 28 +------ .../model/posture_check_model_process.go | 2 +- .../posture_check_model_process_multi.go | 2 +- .../posture_check_model_windows_domain.go | 2 +- controller/model/posture_response_manager.go | 7 +- controller/model/posture_response_model.go | 6 +- .../model/posture_response_model_process.go | 2 +- controller/persistence/api_session_store.go | 9 +- controller/persistence/auth_policy_store.go | 1 - .../persistence/eventual_event_store.go | 2 - controller/persistence/eventual_eventer.go | 2 +- .../persistence/external_jwt_signer_store.go | 1 - controller/persistence/migration_v15.go | 9 -- controller/persistence/migration_v16.go | 3 +- controller/persistence/migration_v18.go | 4 +- controller/persistence/posture_check_os.go | 7 +- .../persistence/posture_check_type_store.go | 4 +- controller/server/client-api.go | 4 +- controller/server/controller.go | 4 +- controller/sync_strats/rtx.go | 2 +- controller/sync_strats/sync_instant.go | 2 +- internal/cert/fingerprint.go | 13 --- internal/pem/pem.go | 10 +-- rest_util/capool.go | 4 +- rest_util/clients.go | 6 ++ router/enroll/enroll.go | 8 +- router/handler_edge_ctrl/apiSessionAdded.go | 16 ++-- router/internal/edgerouter/config.go | 4 - router/xgress_edge/certchecker.go | 2 +- router/xgress_edge/certchecker_test.go | 35 ++++---- router/xgress_edge/factory.go | 6 +- router/xgress_edge/listener.go | 2 +- router/xgress_edge/perf_test.go | 21 ++--- router/xgress_edge_transport/factory.go | 4 +- runner/runner.go | 1 + tests/api_session_certificates_test.go | 4 +- tests/auth_cert_test.go | 1 + tests/authenticate.go | 64 -------------- tests/authenticator_test.go | 2 + tests/config_test.go | 5 -- tests/context.go | 21 +---- tests/enrollment_create_test.go | 5 +- tests/enrollment_identity_extend_test.go | 22 ++++- tests/enrollment_updb_test.go | 15 ++-- tests/entities.go | 84 ++++++------------- tests/posture_check_mfa_test.go | 3 +- tunnel/dns/file.go | 5 +- tunnel/entities/service.go | 3 + tunnel/intercept/hosting.go | 4 +- tunnel/intercept/hosting_resolv.go | 5 +- tunnel/intercept/svcpoll.go | 4 +- tunnel/intercept/tproxy/tproxy_linux.go | 6 -- tunnel/router/router_linux.go | 15 +--- tunnel/utils/ifaddrs_linux.go | 6 +- 77 files changed, 311 insertions(+), 457 deletions(-) create mode 100644 .github/workflows/golangci-lint.yml delete mode 100644 controller/persistence/migration_v15.go diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 000000000..3a95834ad --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,41 @@ +name: golangci-lint +on: + pull_request: +permissions: + contents: read + # Optional: allow read access to pull request. Use with `only-new-issues` option. + # pull-requests: read + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + with: + go-version: 1.19 + - uses: actions/checkout@v3 + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version + version: v1.49 + + # Optional: working directory, useful for monorepos + # working-directory: somedir + + # Optional: golangci-lint command line arguments. + args: --build-tags apitests + + # Optional: show only new issues if it's a pull request. The default value is `false`. + # only-new-issues: true + + # Optional: if set to true then the all caching functionality will be complete disabled, + # takes precedence over all other caching options. + # skip-cache: true + + # Optional: if set to true then the action don't cache or restore ~/go/pkg. + # skip-pkg-cache: true + + # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. + # skip-build-cache: true diff --git a/controller/config/config.go b/controller/config/config.go index 2d7fb0ef2..25a72ba2d 100644 --- a/controller/config/config.go +++ b/controller/config/config.go @@ -24,8 +24,8 @@ import ( "github.com/michaelquigley/pfxlog" "github.com/openziti/identity" "github.com/pkg/errors" - "io/ioutil" "net" + "os" "reflect" "strconv" "strings" @@ -250,7 +250,7 @@ func (c *Config) loadEnrollmentSection(edgeConfigMap map[interface{}]interface{} if value, found := signingCertSubMap["cert"]; found { c.Enrollment.SigningCertConfig.Cert = value.(string) - certPem, err := ioutil.ReadFile(c.Enrollment.SigningCertConfig.Cert) + certPem, err := os.ReadFile(c.Enrollment.SigningCertConfig.Cert) if err != nil { pfxlog.Logger().WithError(err).Panic("unable to read [edge.enrollment.cert]") } @@ -271,7 +271,7 @@ func (c *Config) loadEnrollmentSection(edgeConfigMap map[interface{}]interface{} if value, found := signingCertSubMap["ca"]; found { c.Enrollment.SigningCertConfig.CA = value.(string) - if c.Enrollment.SigningCertCaPem, err = ioutil.ReadFile(c.Enrollment.SigningCertConfig.CA); err != nil { + if c.Enrollment.SigningCertCaPem, err = os.ReadFile(c.Enrollment.SigningCertConfig.CA); err != nil { return fmt.Errorf("could not read file CA file from [edge.enrollment.signingCert.ca]") } diff --git a/controller/env/appenv.go b/controller/env/appenv.go index e34f0e1ea..34a504d26 100644 --- a/controller/env/appenv.go +++ b/controller/env/appenv.go @@ -57,10 +57,8 @@ import ( cmap "github.com/orcaman/concurrent-map/v2" "github.com/xeipuuv/gojsonschema" "io" - "io/ioutil" "net/http" "strings" - "sync" "time" ) @@ -77,21 +75,20 @@ type AppEnv struct { ApiClientCsrSigner cert.Signer ControlClientCsrSigner cert.Signer - FingerprintGenerator cert.FingerprintGenerator - AuthRegistry model.AuthRegistry - EnrollRegistry model.EnrollmentRegistry - Broker *Broker - HostController HostController - ManagementApi *managementOperations.ZitiEdgeManagementAPI - ClientApi *clientOperations.ZitiEdgeClientAPI - IdentityRefreshMap cmap.ConcurrentMap[time.Time] - identityRefreshMeter metrics.Meter - StartupTime time.Time - InstanceId string - findEnrollmentSignerOnce sync.Once - enrollmentSigner jwtsigner.Signer - TraceManager *TraceManager - EventDispatcher *events.Dispatcher + FingerprintGenerator cert.FingerprintGenerator + AuthRegistry model.AuthRegistry + EnrollRegistry model.EnrollmentRegistry + Broker *Broker + HostController HostController + ManagementApi *managementOperations.ZitiEdgeManagementAPI + ClientApi *clientOperations.ZitiEdgeClientAPI + IdentityRefreshMap cmap.ConcurrentMap[time.Time] + identityRefreshMeter metrics.Meter + StartupTime time.Time + InstanceId string + enrollmentSigner jwtsigner.Signer + TraceManager *TraceManager + EventDispatcher *events.Dispatcher } func (ae *AppEnv) GetApiServerCsrSigner() cert.Signer { @@ -514,8 +511,8 @@ func (ae *AppEnv) GetSessionTokenFromRequest(r *http.Request) string { func (ae *AppEnv) CreateRequestContext(rw http.ResponseWriter, r *http.Request) *response.RequestContext { rid := eid.New() - body, _ := ioutil.ReadAll(r.Body) - r.Body = ioutil.NopCloser(bytes.NewReader(body)) + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) requestContext := &response.RequestContext{ Id: rid, diff --git a/controller/env/broker.go b/controller/env/broker.go index b2f142e38..0140c5f26 100644 --- a/controller/env/broker.go +++ b/controller/env/broker.go @@ -17,7 +17,6 @@ package env import ( - "github.com/kataras/go-events" "github.com/michaelquigley/pfxlog" "github.com/openziti/channel/v2" "github.com/openziti/edge/controller/persistence" @@ -48,7 +47,6 @@ const ( // and dealing with casting arguments to their proper concrete types. type Broker struct { ae *AppEnv - events map[events.EventEmmiter]map[events.EventName][]events.Listener sessionChunkSize int apiSessionChunkSize int routerMsgBufferSize int diff --git a/controller/env/context.go b/controller/env/context.go index 4bf387952..2cf32584f 100644 --- a/controller/env/context.go +++ b/controller/env/context.go @@ -4,15 +4,15 @@ import ( "bytes" "github.com/openziti/edge/controller/response" "github.com/openziti/edge/eid" - "io/ioutil" + "io" "net/http" ) func NewRequestContext(rw http.ResponseWriter, r *http.Request) *response.RequestContext { rid := eid.New() - body, _ := ioutil.ReadAll(r.Body) - r.Body = ioutil.NopCloser(bytes.NewReader(body)) + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) requestContext := &response.RequestContext{ Id: rid, diff --git a/controller/env/producers.go b/controller/env/producers.go index b9f75ac64..e0c1cc6b7 100644 --- a/controller/env/producers.go +++ b/controller/env/producers.go @@ -20,7 +20,6 @@ import ( "fmt" "gopkg.in/yaml.v3" "io" - "io/ioutil" ) type PemProducer struct{} @@ -30,7 +29,7 @@ func (p PemProducer) Produce(writer io.Writer, i interface{}) error { _, err := writer.Write(buffer) return err } else if reader, ok := i.(io.Reader); ok { - buffer, err := ioutil.ReadAll(reader) + buffer, err := io.ReadAll(reader) if err != nil { return err } @@ -43,7 +42,6 @@ func (p PemProducer) Produce(writer io.Writer, i interface{}) error { return fmt.Errorf("unsupported type for PEM producer: %T", i) } - type YamlProducer struct{} func (p YamlProducer) Produce(writer io.Writer, i interface{}) error { diff --git a/controller/handler_edge_ctrl/common.go b/controller/handler_edge_ctrl/common.go index 383ab7399..e28818fc2 100644 --- a/controller/handler_edge_ctrl/common.go +++ b/controller/handler_edge_ctrl/common.go @@ -282,9 +282,9 @@ func (self *baseSessionRequestContext) loadService() { if err != nil { if boltz.IsErrNotFoundErr(err) { - err = InvalidServiceError{} + self.err = InvalidServiceError{} } else { - err = internalError(err) + self.err = internalError(err) } logrus. WithField("sessionId", self.session.Id). diff --git a/controller/handler_edge_ctrl/common_tunnel.go b/controller/handler_edge_ctrl/common_tunnel.go index d8278ab86..0658574d3 100644 --- a/controller/handler_edge_ctrl/common_tunnel.go +++ b/controller/handler_edge_ctrl/common_tunnel.go @@ -259,7 +259,7 @@ func (self *baseTunnelRequestContext) ensureSessionForService(sessionId, session self.session, err = self.handler.getAppEnv().Managers.Session.Read(id) if err != nil { - err = internalError(err) + self.err = internalError(err) return } self.newSession = true diff --git a/controller/internal/routes/current_identity_authenticator_router.go b/controller/internal/routes/current_identity_authenticator_router.go index 9d5a5378a..cdfe28b81 100644 --- a/controller/internal/routes/current_identity_authenticator_router.go +++ b/controller/internal/routes/current_identity_authenticator_router.go @@ -225,6 +225,11 @@ func (r *CurrentIdentityAuthenticatorRouter) Extend(ae *env.AppEnv, rc *response func (r *CurrentIdentityAuthenticatorRouter) ExtendVerify(ae *env.AppEnv, rc *response.RequestContext, extend *rest_model.IdentityExtendValidateEnrollmentRequest) { authId, err := rc.GetEntityId() + if err != nil { + rc.RespondWithError(err) + return + } + err = ae.Managers.Authenticator.VerifyExtendCertForIdentity(rc.Identity.Id, authId, *extend.ClientCert) if err != nil { diff --git a/controller/internal/routes/database_router.go b/controller/internal/routes/database_router.go index bcb7b1484..491178cad 100644 --- a/controller/internal/routes/database_router.go +++ b/controller/internal/routes/database_router.go @@ -99,7 +99,7 @@ func (r *DatabaseRouter) CheckDatastoreIntegrity(ae *env.AppEnv, rc *response.Re } func (r *DatabaseRouter) GetCheckProgress(rc *response.RequestContext) { - integrityCheck := r.integrityCheck + integrityCheck := &r.integrityCheck integrityCheck.lock.Lock() defer integrityCheck.lock.Unlock() diff --git a/controller/internal/routes/identity_api_model.go b/controller/internal/routes/identity_api_model.go index d5fb5ca65..a35ea8453 100644 --- a/controller/internal/routes/identity_api_model.go +++ b/controller/internal/routes/identity_api_model.go @@ -223,7 +223,6 @@ func MapIdentityToRestEntity(ae *env.AppEnv, _ *response.RequestContext, e model } func MapIdentityToRestModel(ae *env.AppEnv, identity *model.Identity) (*rest_model.IdentityDetail, error) { - identityType, err := ae.Managers.IdentityType.ReadByIdOrName(identity.IdentityTypeId) if err != nil { @@ -231,6 +230,9 @@ func MapIdentityToRestModel(ae *env.AppEnv, identity *model.Identity) (*rest_mod } mfa, err := ae.Managers.Mfa.ReadByIdentityId(identity.Id) + if err != nil { + return nil, err + } isMfaEnabled := mfa != nil && mfa.IsVerified diff --git a/controller/internal/routes/posture_check_api_model.go b/controller/internal/routes/posture_check_api_model.go index 750f794aa..848e2c576 100644 --- a/controller/internal/routes/posture_check_api_model.go +++ b/controller/internal/routes/posture_check_api_model.go @@ -129,19 +129,16 @@ func MapUpdatePostureCheckToModel(id string, postureCheck rest_model.PostureChec RoleAttributes: AttributesOrDefault(postureCheck.RoleAttributes()), } - switch postureCheck.(type) { + switch check := postureCheck.(type) { case *rest_model.PostureCheckDomainUpdate: - check := postureCheck.(*rest_model.PostureCheckDomainUpdate) ret.SubType = &model.PostureCheckDomains{ Domains: check.Domains, } case *rest_model.PostureCheckMacAddressUpdate: - check := postureCheck.(*rest_model.PostureCheckMacAddressUpdate) ret.SubType = &model.PostureCheckMacAddresses{ MacAddresses: check.MacAddresses, } case *rest_model.PostureCheckProcessUpdate: - check := postureCheck.(*rest_model.PostureCheckProcessUpdate) ret.SubType = &model.PostureCheckProcess{ OsType: string(*check.Process.OsType), Path: stringz.OrEmpty(check.Process.Path), @@ -149,7 +146,6 @@ func MapUpdatePostureCheckToModel(id string, postureCheck rest_model.PostureChec Fingerprint: check.Process.SignerFingerprint, } case *rest_model.PostureCheckOperatingSystemUpdate: - check := postureCheck.(*rest_model.PostureCheckOperatingSystemUpdate) osCheck := &model.PostureCheckOperatingSystem{} ret.SubType = osCheck @@ -161,7 +157,6 @@ func MapUpdatePostureCheckToModel(id string, postureCheck rest_model.PostureChec osCheck.OperatingSystems = append(osCheck.OperatingSystems, modelOs) } case *rest_model.PostureCheckMfaUpdate: - check := postureCheck.(*rest_model.PostureCheckMfaUpdate) ret.SubType = &model.PostureCheckMfa{ TimeoutSeconds: check.TimeoutSeconds, PromptOnWake: check.PromptOnWake, @@ -169,12 +164,11 @@ func MapUpdatePostureCheckToModel(id string, postureCheck rest_model.PostureChec IgnoreLegacyEndpoints: check.IgnoreLegacyEndpoints, } case *rest_model.PostureCheckProcessMultiUpdate: - apiCheck := postureCheck.(*rest_model.PostureCheckProcessMultiUpdate) modelCheck := &model.PostureCheckProcessMulti{ - Semantic: string(*apiCheck.Semantic), + Semantic: string(*check.Semantic), } - for _, process := range apiCheck.Processes { + for _, process := range check.Processes { newProc := &model.ProcessMulti{ Hashes: process.Hashes, OsType: string(*process.OsType), @@ -203,23 +197,20 @@ func MapPatchPostureCheckToModel(id string, postureCheck rest_model.PostureCheck RoleAttributes: AttributesOrDefault(postureCheck.RoleAttributes()), } - switch postureCheck.(type) { + switch check := postureCheck.(type) { case *rest_model.PostureCheckDomainPatch: - check := postureCheck.(*rest_model.PostureCheckDomainPatch) ret.SubType = &model.PostureCheckDomains{ Domains: check.Domains, } ret.TypeId = model.PostureCheckTypeDomain case *rest_model.PostureCheckMacAddressPatch: - check := postureCheck.(*rest_model.PostureCheckMacAddressPatch) ret.SubType = &model.PostureCheckMacAddresses{ MacAddresses: check.MacAddresses, } ret.TypeId = model.PostureCheckTypeMAC case *rest_model.PostureCheckProcessPatch: - check := postureCheck.(*rest_model.PostureCheckProcessPatch) subType := &model.PostureCheckProcess{} ret.SubType = subType @@ -232,7 +223,6 @@ func MapPatchPostureCheckToModel(id string, postureCheck rest_model.PostureCheck ret.TypeId = model.PostureCheckTypeProcess case *rest_model.PostureCheckOperatingSystemPatch: - check := postureCheck.(*rest_model.PostureCheckOperatingSystemPatch) osCheck := &model.PostureCheckOperatingSystem{} ret.SubType = osCheck @@ -246,7 +236,6 @@ func MapPatchPostureCheckToModel(id string, postureCheck rest_model.PostureCheck ret.TypeId = model.PostureCheckTypeOs case *rest_model.PostureCheckMfaPatch: - check := postureCheck.(*rest_model.PostureCheckMfaPatch) ret.SubType = &model.PostureCheckMfa{ TimeoutSeconds: Int64OrDefault(check.TimeoutSeconds), PromptOnWake: BoolOrDefault(check.PromptOnWake), @@ -255,12 +244,11 @@ func MapPatchPostureCheckToModel(id string, postureCheck rest_model.PostureCheck } ret.TypeId = model.PostureCheckTypeMFA case *rest_model.PostureCheckProcessMultiPatch: - apiCheck := postureCheck.(*rest_model.PostureCheckProcessMultiPatch) modelCheck := &model.PostureCheckProcessMulti{ - Semantic: string(apiCheck.Semantic), + Semantic: string(check.Semantic), } - for _, process := range apiCheck.Processes { + for _, process := range check.Processes { newProc := &model.ProcessMulti{ Hashes: process.Hashes, OsType: string(*process.OsType), diff --git a/controller/internal/routes/posture_response_router.go b/controller/internal/routes/posture_response_router.go index ab9c4f46c..6adf0276b 100644 --- a/controller/internal/routes/posture_response_router.go +++ b/controller/internal/routes/posture_response_router.go @@ -94,7 +94,7 @@ func (r *PostureResponseRouter) CreateBulk(ae *env.AppEnv, rc *response.RequestC apiPostureData := postureData.ApiSessions[rc.ApiSession.Id] if passedMfaAt := apiPostureData.GetPassedMfaAt(); passedMfaAt != nil { //if the last time Mfa was passed at is outside of the grace period, send timeout update - durationSinceLastMfa := time.Now().Sub(*passedMfaAt) + durationSinceLastMfa := time.Since(*passedMfaAt) modelServicesWithTimeouts := ae.Managers.PostureResponse.GetEndpointStateChangeAffectedServices(durationSinceLastMfa, gracePeriod, onWake, onUnlock) @@ -119,10 +119,8 @@ func (r *PostureResponseRouter) CreateBulk(ae *env.AppEnv, rc *response.RequestC } func (r *PostureResponseRouter) handlePostureResponse(ae *env.AppEnv, rc *response.RequestContext, apiPostureResponse rest_model.PostureResponseCreate) { - switch apiPostureResponse.(type) { + switch apiPostureResponse := apiPostureResponse.(type) { case *rest_model.PostureResponseDomainCreate: - apiPostureResponse := apiPostureResponse.(*rest_model.PostureResponseDomainCreate) - postureResponse := &model.PostureResponse{ PostureCheckId: *apiPostureResponse.ID(), TypeId: string(apiPostureResponse.TypeID()), @@ -140,7 +138,6 @@ func (r *PostureResponseRouter) handlePostureResponse(ae *env.AppEnv, rc *respon ae.Managers.PostureResponse.Create(rc.Identity.Id, []*model.PostureResponse{postureResponse}) case *rest_model.PostureResponseMacAddressCreate: - apiPostureResponse := apiPostureResponse.(*rest_model.PostureResponseMacAddressCreate) postureResponse := &model.PostureResponse{ PostureCheckId: *apiPostureResponse.ID(), TypeId: string(apiPostureResponse.TypeID()), @@ -158,8 +155,6 @@ func (r *PostureResponseRouter) handlePostureResponse(ae *env.AppEnv, rc *respon ae.Managers.PostureResponse.Create(rc.Identity.Id, []*model.PostureResponse{postureResponse}) case *rest_model.PostureResponseProcessCreate: - apiPostureResponse := apiPostureResponse.(*rest_model.PostureResponseProcessCreate) - postureResponse := &model.PostureResponse{ PostureCheckId: *apiPostureResponse.ID(), TypeId: string(apiPostureResponse.TypeID()), @@ -179,8 +174,6 @@ func (r *PostureResponseRouter) handlePostureResponse(ae *env.AppEnv, rc *respon ae.Managers.PostureResponse.Create(rc.Identity.Id, []*model.PostureResponse{postureResponse}) case *rest_model.PostureResponseOperatingSystemCreate: - apiPostureResponse := apiPostureResponse.(*rest_model.PostureResponseOperatingSystemCreate) - postureResponse := &model.PostureResponse{ PostureCheckId: *apiPostureResponse.ID(), TypeId: string(apiPostureResponse.TypeID()), @@ -199,8 +192,6 @@ func (r *PostureResponseRouter) handlePostureResponse(ae *env.AppEnv, rc *respon ae.Managers.PostureResponse.Create(rc.Identity.Id, []*model.PostureResponse{postureResponse}) case *rest_model.PostureResponseEndpointStateCreate: - apiPostureResponse := apiPostureResponse.(*rest_model.PostureResponseEndpointStateCreate) - postureResponse := &model.PostureResponse{ PostureCheckId: *apiPostureResponse.ID(), TypeId: string(apiPostureResponse.TypeID()), diff --git a/controller/model/api_session_heartbeats.go b/controller/model/api_session_heartbeats.go index c429c8ef6..cd8cd9196 100644 --- a/controller/model/api_session_heartbeats.go +++ b/controller/model/api_session_heartbeats.go @@ -49,7 +49,7 @@ func NewHeartbeatCollector(env Env, batchSize int, updateInterval time.Duration, updateInterval: updateInterval, batchSize: batchSize, flushAction: action, - closeNotify: make(chan struct{}, 0), + closeNotify: make(chan struct{}), } env.GetStores().ApiSession.AddListener(boltz.EventDelete, collector.onApiSessionDelete) diff --git a/controller/model/auth_policy_manager.go b/controller/model/auth_policy_manager.go index d7d2f83e9..822ca1f2c 100644 --- a/controller/model/auth_policy_manager.go +++ b/controller/model/auth_policy_manager.go @@ -26,7 +26,6 @@ import ( "github.com/openziti/foundation/v2/errorz" "github.com/openziti/storage/boltz" "github.com/pkg/errors" - "go.etcd.io/bbolt" "google.golang.org/protobuf/proto" ) @@ -104,14 +103,6 @@ func (self *AuthPolicyManager) Read(id string) (*AuthPolicy, error) { return modelEntity, nil } -func (self *AuthPolicyManager) readInTx(tx *bbolt.Tx, id string) (*AuthPolicy, error) { - modelEntity := &AuthPolicy{} - if err := self.readEntityInTx(tx, id, modelEntity); err != nil { - return nil, err - } - return modelEntity, nil -} - func (self *AuthPolicyManager) Marshall(entity *AuthPolicy) ([]byte, error) { tags, err := edge_cmd_pb.EncodeTags(entity.Tags) if err != nil { diff --git a/controller/model/authenticator_manager.go b/controller/model/authenticator_manager.go index f2c19c307..ae6babeab 100644 --- a/controller/model/authenticator_manager.go +++ b/controller/model/authenticator_manager.go @@ -593,6 +593,9 @@ func (self *AuthenticatorManager) VerifyExtendCertForIdentity(identityId, authen // or an error. func (self *AuthenticatorManager) ReEnroll(id string, expiresAt time.Time) (string, error) { authenticator, err := self.Read(id) + if err != nil { + return "", err + } enrollment := &Enrollment{ IdentityId: &authenticator.IdentityId, @@ -648,7 +651,7 @@ func getCaId(env Env, auth *AuthenticatorCert) string { cert := certs[0] caId := "" - env.GetDbProvider().GetDb().View(func(tx *bbolt.Tx) error { + err := env.GetDbProvider().GetDb().View(func(tx *bbolt.Tx) error { for cursor := env.GetStores().Ca.IterateIds(tx, ast.BoolNodeTrue); cursor.IsValid(); cursor.Next() { ca, err := env.GetStores().Ca.LoadOneById(tx, string(cursor.Current())) if err != nil { @@ -672,6 +675,9 @@ func getCaId(env Env, auth *AuthenticatorCert) string { } return nil }) + if err != nil { + pfxlog.Logger().WithError(err).Error("error while getting CaId") + } return caId } diff --git a/controller/model/authenticator_mod_cert.go b/controller/model/authenticator_mod_cert.go index da28de9cb..4eb8de5e9 100644 --- a/controller/model/authenticator_mod_cert.go +++ b/controller/model/authenticator_mod_cert.go @@ -44,7 +44,6 @@ type AuthModuleCert struct { env Env method string fingerprintGenerator cert.FingerprintGenerator - caChain []byte staticCaCerts []*x509.Certificate dynamicCaCache cmap.ConcurrentMap[[]*x509.Certificate] } @@ -160,7 +159,7 @@ func (module *AuthModuleCert) Process(context AuthContext) (AuthResult, error) { if externalId != "" { logger = logger.WithField("externalId", externalId) - identity, err = module.env.GetManagers().Identity.ReadByExternalId(externalId) + identity, _ = module.env.GetManagers().Identity.ReadByExternalId(externalId) if identity == nil { logger.Error("failed to find identity by externalId") @@ -173,14 +172,14 @@ func (module *AuthModuleCert) Process(context AuthContext) (AuthResult, error) { fingerprint := module.env.GetFingerprintGenerator().FromCert(clientCert) logger = logger.WithField("fingerprint", fingerprint) - authenticator, err = module.env.GetManagers().Authenticator.ReadByFingerprint(fingerprint) + authenticator, _ = module.env.GetManagers().Authenticator.ReadByFingerprint(fingerprint) if authenticator == nil { logger.Error("failed to find authenticator by fingerprint") return nil, apierror.NewInvalidAuth() } - identity, err = module.env.GetManagers().Identity.Read(authenticator.IdentityId) + identity, _ = module.env.GetManagers().Identity.Read(authenticator.IdentityId) } if identity == nil { @@ -201,7 +200,7 @@ func (module *AuthModuleCert) Process(context AuthContext) (AuthResult, error) { return nil, apierror.NewInvalidAuth() } - authPolicy, err := module.env.GetManagers().AuthPolicy.Read(identity.AuthPolicyId) + authPolicy, _ := module.env.GetManagers().AuthPolicy.Read(identity.AuthPolicyId) if authPolicy == nil { logger.Error("failed to obtain authPolicy by id") diff --git a/controller/model/authenticator_mod_ext_jwt.go b/controller/model/authenticator_mod_ext_jwt.go index f1e6b30e4..207bb1232 100644 --- a/controller/model/authenticator_mod_ext_jwt.go +++ b/controller/model/authenticator_mod_ext_jwt.go @@ -1,17 +1,17 @@ /* - Copyright NetFoundry Inc. +Copyright NetFoundry Inc. - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - https://www.apache.org/licenses/LICENSE-2.0 +https://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. */ package model @@ -102,7 +102,7 @@ func (r *signerRecord) Resolve(force bool) error { return nil } - if !r.jwksLastRequest.IsZero() && time.Now().Sub(r.jwksLastRequest) < time.Second*5 { + if !r.jwksLastRequest.IsZero() && time.Since(r.jwksLastRequest) < time.Second*5 { return nil } @@ -209,12 +209,12 @@ func (a *AuthModuleExtJwt) pubKeyLookup(token *jwt.Token) (interface{}, error) { if err := signerRecord.Resolve(false); err != nil { logger.WithError(err).Error("error attempting to resolve extJwtSigner certificate used for signing") } - } - cert, ok = signerRecord.kidToCertificate[kid] + cert, ok = signerRecord.kidToCertificate[kid] - if !ok { - return nil, fmt.Errorf("kid [%s] not found for issuer [%s]", kid, issuer) + if !ok { + return nil, fmt.Errorf("kid [%s] not found for issuer [%s]", kid, issuer) + } } claims[ExtJwtInternalClaim] = signerRecord.externalJwtSigner diff --git a/controller/model/create_terminator_cmd.go b/controller/model/create_terminator_cmd.go index d07b00b2b..12626f351 100644 --- a/controller/model/create_terminator_cmd.go +++ b/controller/model/create_terminator_cmd.go @@ -38,6 +38,10 @@ func (self *CreateEdgeTerminatorCmd) validateTerminatorIdentity(tx *bbolt.Tx, te } identityTerminators, err := self.Env.GetStores().Terminator.GetTerminatorsInIdentityGroup(tx, terminator.GetId()) + if err != nil { + return err + } + for _, otherTerminator := range identityTerminators { otherSession, err := self.getTerminatorSession(tx, otherTerminator, "sibling ") if err != nil { diff --git a/controller/model/enrollment.go b/controller/model/enrollment.go index 5c37543df..1b8084f4b 100644 --- a/controller/model/enrollment.go +++ b/controller/model/enrollment.go @@ -22,7 +22,7 @@ import ( "github.com/go-openapi/runtime" "github.com/openziti/edge/controller/apierror" fabricApiError "github.com/openziti/fabric/controller/apierror" - "io/ioutil" + "io" "net/http" "strings" ) @@ -142,7 +142,7 @@ func (context *EnrollmentContextHttp) FillFromHttpRequest(request *http.Request) } var enrollData interface{} - body, _ := ioutil.ReadAll(request.Body) + body, _ := io.ReadAll(request.Body) contentType := strings.Split(request.Header.Get("content-type"), ";") diff --git a/controller/model/identity_manager.go b/controller/model/identity_manager.go index 5469c59d9..7b351d628 100644 --- a/controller/model/identity_manager.go +++ b/controller/model/identity_manager.go @@ -779,20 +779,17 @@ func (statusMap *identityStatusMap) IsActive(identityId string) bool { func (statusMap *identityStatusMap) start() { ticker := time.NewTicker(30 * time.Second) go func() { - for { - select { - case <-ticker.C: - var toRemove []string - now := time.Now() - statusMap.identityIdToStatus.IterCb(func(key string, stat *status) { - if stat.expiresAt.Before(now) { - toRemove = append(toRemove, key) - } - }) - - for _, identityId := range toRemove { - statusMap.identityIdToStatus.Remove(identityId) + for range ticker.C { + var toRemove []string + now := time.Now() + statusMap.identityIdToStatus.IterCb(func(key string, stat *status) { + if stat.expiresAt.Before(now) { + toRemove = append(toRemove, key) } + }) + + for _, identityId := range toRemove { + statusMap.identityIdToStatus.Remove(identityId) } } }() diff --git a/controller/model/mfa_manager.go b/controller/model/mfa_manager.go index b95166eb6..9de525bc3 100644 --- a/controller/model/mfa_manager.go +++ b/controller/model/mfa_manager.go @@ -65,7 +65,10 @@ func (self *MfaManager) CreateForIdentity(identity *Identity) (string, error) { _, _ = rand.Read(secretBytes) secret := base32.StdEncoding.EncodeToString(secretBytes) - recoveryCodes := self.generateRecoveryCodes() + recoveryCodes, err := self.generateRecoveryCodes() + if err != nil { + return "", err + } mfa := &Mfa{ BaseEntity: models.BaseEntity{}, @@ -76,7 +79,7 @@ func (self *MfaManager) CreateForIdentity(identity *Identity) (string, error) { RecoveryCodes: recoveryCodes, } - err := self.Create(mfa) + err = self.Create(mfa) if err != nil { return "", err } @@ -226,25 +229,30 @@ func (self *MfaManager) GetProvisioningUrl(mfa *Mfa) string { } func (self *MfaManager) RecreateRecoveryCodes(mfa *Mfa) error { - newCodes := self.generateRecoveryCodes() + newCodes, err := self.generateRecoveryCodes() + if err != nil { + return err + } mfa.RecoveryCodes = newCodes return self.Update(mfa, nil) } -func (self *MfaManager) generateRecoveryCodes() []string { +func (self *MfaManager) generateRecoveryCodes() ([]string, error) { recoveryCodes := []string{} for i := 0; i < 20; i++ { backupBytes := make([]byte, 8) - rand.Read(backupBytes) + if _, err := rand.Read(backupBytes); err != nil { + return nil, err + } backupStr := base32.StdEncoding.EncodeToString(backupBytes) backupCode := strings.Replace(backupStr, "=", "", -1)[:6] recoveryCodes = append(recoveryCodes, backupCode) } - return recoveryCodes + return recoveryCodes, nil } func (self *MfaManager) Marshall(entity *Mfa) ([]byte, error) { diff --git a/controller/model/posture_check_model_mac.go b/controller/model/posture_check_model_mac.go index 5aa2a96d2..b4ffd3534 100644 --- a/controller/model/posture_check_model_mac.go +++ b/controller/model/posture_check_model_mac.go @@ -119,7 +119,7 @@ type PostureCheckFailureValuesMac struct { } func (p PostureCheckFailureValuesMac) Expected() interface{} { - return p.Expected() + return p.ExpectedValue } func (p PostureCheckFailureValuesMac) Actual() interface{} { diff --git a/controller/model/posture_check_model_os.go b/controller/model/posture_check_model_os.go index 63629639b..57aecdc06 100644 --- a/controller/model/posture_check_model_os.go +++ b/controller/model/posture_check_model_os.go @@ -55,7 +55,7 @@ func (p *PostureCheckOperatingSystem) fillProtobuf(msg *edge_cmd_pb.PostureCheck func (p *PostureCheckOperatingSystem) fillFromProtobuf(msg *edge_cmd_pb.PostureCheck) error { if osList_, ok := msg.Subtype.(*edge_cmd_pb.PostureCheck_OsList_); ok { - if osList := osList_.OsList; osList_ != nil { + if osList := osList_.OsList; osList != nil { for _, os := range osList.OsList { p.OperatingSystems = append(p.OperatingSystems, OperatingSystem{ OsType: os.OsType, @@ -119,32 +119,6 @@ func (p *PostureCheckOperatingSystem) Evaluate(_ string, pd *PostureData) bool { return false } -type version struct { - value int64 - orHigher bool - subVersions map[int64]*version -} - -func (version *version) isValid(checkVersions []int64) bool { - if len(checkVersions) == 0 { - return false //not enough versions to check - } - - if checkVersions[0] == version.value { - if len(version.subVersions) == 0 { - return true - } - - for _, subVersion := range version.subVersions { - return subVersion.isValid(checkVersions[1:]) - } - } else if version.orHigher && checkVersions[0] > version.value { - return true - } - - return false -} - func getValidOses(oses []OperatingSystem) map[string][]*semver.Range { validOses := map[string][]*semver.Range{} diff --git a/controller/model/posture_check_model_process.go b/controller/model/posture_check_model_process.go index 3fd45949f..0254f5c19 100644 --- a/controller/model/posture_check_model_process.go +++ b/controller/model/posture_check_model_process.go @@ -96,8 +96,8 @@ func (p *PostureCheckProcess) FailureValues(_ string, pd *PostureData) PostureCh for _, processData := range pd.Processes { if processData.PostureCheckId == p.PostureCheckId { ret.ActualValue = *processData + break } - break } return ret diff --git a/controller/model/posture_check_model_process_multi.go b/controller/model/posture_check_model_process_multi.go index 02ea3691c..f5eca9899 100644 --- a/controller/model/posture_check_model_process_multi.go +++ b/controller/model/posture_check_model_process_multi.go @@ -105,8 +105,8 @@ func (p *PostureCheckProcessMulti) FailureValues(_ string, pd *PostureData) Post for _, processData := range pd.Processes { if processData.PostureCheckId == p.PostureCheckId { ret.ActualValue = []PostureResponseProcess{*processData} + break } - break } return ret diff --git a/controller/model/posture_check_model_windows_domain.go b/controller/model/posture_check_model_windows_domain.go index e164ced78..d88fb7893 100644 --- a/controller/model/posture_check_model_windows_domain.go +++ b/controller/model/posture_check_model_windows_domain.go @@ -90,7 +90,7 @@ func (p *PostureCheckDomains) Evaluate(_ string, pd *PostureData) bool { } for _, domain := range p.Domains { - if strings.ToLower(domain) == strings.ToLower(pd.Domain.Name) { + if strings.EqualFold(domain, pd.Domain.Name) { return true } } diff --git a/controller/model/posture_response_manager.go b/controller/model/posture_response_manager.go index 6a22dde1a..6328d463e 100644 --- a/controller/model/posture_response_manager.go +++ b/controller/model/posture_response_manager.go @@ -101,7 +101,7 @@ func (self *PostureResponseManager) SetMfaPostureForIdentity(identityId string, pd = newPostureData() } - for apiSessionId, _ := range pd.ApiSessions { + for apiSessionId := range pd.ApiSessions { postureSubType := &PostureResponseMfa{ ApiSessionId: apiSessionId, PassedMfaAt: passedAt, @@ -282,7 +282,7 @@ func (self *PostureResponseManager) GetEndpointStateChangeAffectedServices(timeS if err != nil { pfxlog.Logger().Errorf("error querying for onWake/onUnlock posture checks: %v", err) } else { - self.env.GetDbProvider().GetDb().View(func(tx *bbolt.Tx) error { + err = self.env.GetDbProvider().GetDb().View(func(tx *bbolt.Tx) error { cursor := self.env.GetStores().PostureCheck.IterateIds(tx, query) for cursor.IsValid() { @@ -300,6 +300,9 @@ func (self *PostureResponseManager) GetEndpointStateChangeAffectedServices(timeS } return nil }) + if err != nil { + pfxlog.Logger().WithError(err).Error("error querying for onWake/onUnlock posture by id") + } } } diff --git a/controller/model/posture_response_model.go b/controller/model/posture_response_model.go index a5ce3d196..6acc44bb2 100644 --- a/controller/model/posture_response_model.go +++ b/controller/model/posture_response_model.go @@ -115,7 +115,7 @@ func (pc *PostureCache) evaluate() { cursor.Seek(lastId) if cursor.IsValid() { - if bytes.Compare(cursor.Current(), lastId) == 0 { + if bytes.Equal(cursor.Current(), lastId) { cursor.Next() } } @@ -403,7 +403,7 @@ type PostureCheckFailureSubType interface { } type PostureCheckFailure struct { - PostureCheckId string `json:"postureCheckId'"` + PostureCheckId string `json:"postureCheckId"` PostureCheckName string `json:"postureCheckName"` PostureCheckType string `json:"postureCheckType"` PostureCheckFailureValues @@ -501,7 +501,7 @@ type PostureResponseSubType interface { Apply(postureData *PostureData) } -var macClean = regexp.MustCompile("[^a-f\\d]+") +var macClean = regexp.MustCompile(`[^a-f\d]+`) func CleanHexString(hexString string) string { return macClean.ReplaceAllString(strings.ToLower(hexString), "") diff --git a/controller/model/posture_response_model_process.go b/controller/model/posture_response_model_process.go index 5a8687c0b..bf70978ec 100644 --- a/controller/model/posture_response_model_process.go +++ b/controller/model/posture_response_model_process.go @@ -72,7 +72,7 @@ func (pr *PostureResponseProcess) VerifyMultiCriteria(process *ProcessMulti) boo foundValidHash = true //no hash to check for } else { for _, validHash := range process.Hashes { - if strings.ToLower(validHash) == strings.ToLower(pr.BinaryHash) { + if strings.EqualFold(validHash, pr.BinaryHash) { foundValidHash = true break } diff --git a/controller/persistence/api_session_store.go b/controller/persistence/api_session_store.go index 9a3aff883..017d88a21 100644 --- a/controller/persistence/api_session_store.go +++ b/controller/persistence/api_session_store.go @@ -37,8 +37,9 @@ const ( FieldApiSessionLastActivityAt = "lastActivityAt" FieldApiSessionAuthenticator = "authenticator" - EventFullyAuthenticated events.EventName = "FULLY_AUTHENTICATED" - EventualEventApiSessionDelete = "ApiSessionDelete" + EventFullyAuthenticated events.EventName = "FULLY_AUTHENTICATED" + + EventualEventApiSessionDelete = "ApiSessionDelete" ) type ApiSession struct { @@ -157,7 +158,7 @@ func (store *apiSessionStoreImpl) Create(ctx boltz.MutateContext, entity boltz.E if err == nil { if apiSession, ok := entity.(*ApiSession); ok && apiSession != nil { - if apiSession.MfaRequired == false || apiSession.MfaComplete == true { + if !apiSession.MfaRequired || apiSession.MfaComplete { store.Emit(EventFullyAuthenticated, apiSession) } } @@ -170,7 +171,7 @@ func (store *apiSessionStoreImpl) Update(ctx boltz.MutateContext, entity boltz.E if err == nil { if apiSession, ok := entity.(*ApiSession); ok && apiSession != nil { - if (checker == nil || checker.IsUpdated(FieldApiSessionMfaComplete)) && apiSession.MfaComplete == true { + if (checker == nil || checker.IsUpdated(FieldApiSessionMfaComplete)) && apiSession.MfaComplete { store.Emit(EventFullyAuthenticated, apiSession) } } diff --git a/controller/persistence/auth_policy_store.go b/controller/persistence/auth_policy_store.go index aebbaae12..2acd07dfc 100644 --- a/controller/persistence/auth_policy_store.go +++ b/controller/persistence/auth_policy_store.go @@ -169,7 +169,6 @@ func newAuthPolicyStore(stores *stores) *AuthPolicyStoreImpl { type AuthPolicyStoreImpl struct { *baseStore indexName boltz.ReadIndex - symbolExtJwtSignerId boltz.EntitySymbol symbolPrimaryAllowedExtJwtSigners boltz.EntitySetSymbol symbolSecondaryRequiredExtJwtSignerId boltz.EntitySymbol } diff --git a/controller/persistence/eventual_event_store.go b/controller/persistence/eventual_event_store.go index c159bd96d..35ab639dc 100644 --- a/controller/persistence/eventual_event_store.go +++ b/controller/persistence/eventual_event_store.go @@ -66,8 +66,6 @@ func newEventualEventStore(stores *stores) *eventualEventStoreImpl { type eventualEventStoreImpl struct { *baseStore - indexName boltz.ReadIndex - symbolEnrollments boltz.EntitySetSymbol } func (store *eventualEventStoreImpl) LoadOneById(tx *bbolt.Tx, id string) (*EventualEvent, error) { diff --git a/controller/persistence/eventual_eventer.go b/controller/persistence/eventual_eventer.go index be67dc9ba..9b96898cd 100644 --- a/controller/persistence/eventual_eventer.go +++ b/controller/persistence/eventual_eventer.go @@ -364,7 +364,7 @@ func (a *EventualEventerBbolt) Start(closeNotify <-chan struct{}) error { if !a.running.CompareAndSwap(false, true) { return errors.New("already started") } - a.stopNotify = make(chan struct{}, 0) + a.stopNotify = make(chan struct{}) a.closeNotify = closeNotify go a.run() diff --git a/controller/persistence/external_jwt_signer_store.go b/controller/persistence/external_jwt_signer_store.go index e0dd900f5..1b1e6d7a7 100644 --- a/controller/persistence/external_jwt_signer_store.go +++ b/controller/persistence/external_jwt_signer_store.go @@ -161,7 +161,6 @@ type externalJwtSignerStoreImpl struct { *baseStore indexName boltz.ReadIndex symbolFingerprint boltz.EntitySymbol - symbolEnrollments boltz.EntitySetSymbol symbolAuthPolicies boltz.EntitySetSymbol fingerprintIndex boltz.ReadIndex symbolKid boltz.EntitySymbol diff --git a/controller/persistence/migration_v15.go b/controller/persistence/migration_v15.go deleted file mode 100644 index 5aa2d035d..000000000 --- a/controller/persistence/migration_v15.go +++ /dev/null @@ -1,9 +0,0 @@ -package persistence - -import ( - "github.com/openziti/storage/boltz" -) - -func (m *Migrations) updateServerV1Config(step *boltz.MigrationStep) { - step.SetError(m.stores.ConfigType.Update(step.Ctx, serverConfigTypeV1, nil)) -} diff --git a/controller/persistence/migration_v16.go b/controller/persistence/migration_v16.go index 053867195..201968cf2 100644 --- a/controller/persistence/migration_v16.go +++ b/controller/persistence/migration_v16.go @@ -31,11 +31,12 @@ func (m *Migrations) removeOrphanedOttCaEnrollments(step *boltz.MigrationStep) { } //clear caIds that are invalid via CheckIntegrity - m.stores.Enrollment.CheckIntegrity(step.Ctx.Tx(), true, func(err error, fixed bool) { + err := m.stores.Enrollment.CheckIntegrity(step.Ctx.Tx(), true, func(err error, fixed bool) { if !fixed { pfxlog.Logger().Errorf("unfixable error during orphaned ottca enrollment integrity check: %v", err) } }) + step.SetError(err) for _, enrollmentId := range enrollmentsToDelete { pfxlog.Logger().Infof("removing invalid ottca enrollment [%s]", enrollmentId) diff --git a/controller/persistence/migration_v18.go b/controller/persistence/migration_v18.go index 4bce0da41..98f191451 100644 --- a/controller/persistence/migration_v18.go +++ b/controller/persistence/migration_v18.go @@ -5,12 +5,12 @@ import ( "github.com/openziti/storage/boltz" ) -//Primes API Session's lastActivityAt proper to their previous updatedAt value +// Primes API Session's lastActivityAt proper to their previous updatedAt value func (m *Migrations) setLastActivityAt(step *boltz.MigrationStep) { for cursor := m.stores.ApiSession.IterateIds(step.Ctx.Tx(), ast.BoolNodeTrue); cursor.IsValid(); cursor.Next() { if apiSession, err := m.stores.ApiSession.LoadOneById(step.Ctx.Tx(), string(cursor.Current())); err == nil { apiSession.LastActivityAt = apiSession.UpdatedAt - m.stores.ApiSession.Update(step.Ctx, apiSession, UpdateLastActivityAtChecker{}) + step.SetError(m.stores.ApiSession.Update(step.Ctx, apiSession, UpdateLastActivityAtChecker{})) } else { step.SetError(err) return diff --git a/controller/persistence/posture_check_os.go b/controller/persistence/posture_check_os.go index e95cee9b8..c79e0a17d 100644 --- a/controller/persistence/posture_check_os.go +++ b/controller/persistence/posture_check_os.go @@ -51,9 +51,7 @@ func (entity *PostureCheckOperatingSystem) LoadValues(_ boltz.CrudStore, bucket OsType: osBucket.GetStringOrError(FieldPostureCheckOsType), } - for _, osVersion := range osBucket.GetStringList(FieldPostureCheckOsVersions) { - newOsMatch.OsVersions = append(newOsMatch.OsVersions, osVersion) - } + newOsMatch.OsVersions = append(newOsMatch.OsVersions, osBucket.GetStringList(FieldPostureCheckOsVersions)...) entity.OperatingSystems = append(entity.OperatingSystems, newOsMatch) } @@ -70,8 +68,7 @@ func (entity *PostureCheckOperatingSystem) SetValues(ctx *boltz.PersistContext, cursor := bucket.Cursor() for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() { - osType := string(key) - if _, found := osMap[osType]; !found { + if _, found := osMap[string(key)]; !found { err := bucket.DeleteBucket(key) if err != nil { pfxlog.Logger().Errorf(err.Error()) diff --git a/controller/persistence/posture_check_type_store.go b/controller/persistence/posture_check_type_store.go index 75de1439d..317ef9444 100644 --- a/controller/persistence/posture_check_type_store.go +++ b/controller/persistence/posture_check_type_store.go @@ -53,9 +53,7 @@ func (entity *PostureCheckOs) LoadValues(_ boltz.CrudStore, bucket *boltz.TypedB OsType: curOs.GetStringOrError(FieldPostureCheckOsType), } - for _, osVersion := range curOs.GetStringList(FieldPostureCheckOsVersions) { - newOsMatch.OsVersions = append(newOsMatch.OsVersions, osVersion) - } + newOsMatch.OsVersions = append(newOsMatch.OsVersions, curOs.GetStringList(FieldPostureCheckOsVersions)...) entity.OperatingSystems = append(entity.OperatingSystems, newOsMatch) } } diff --git a/controller/server/client-api.go b/controller/server/client-api.go index 061b9da4f..8ad6eb145 100644 --- a/controller/server/client-api.go +++ b/controller/server/client-api.go @@ -28,8 +28,8 @@ import ( "github.com/openziti/fabric/controller/api" "github.com/openziti/xweb/v2" "github.com/pkg/errors" - "io/ioutil" "net/http" + "os" "strings" "time" ) @@ -47,7 +47,7 @@ func (factory ClientApiFactory) Validate(config *xweb.InstanceConfig) error { for _, api := range webListener.APIs { if webListener.Identity != nil && (api.Binding() == controller.ClientApiBinding || api.Binding() == controller.ManagementApiBinding) { - caBytes, err := ioutil.ReadFile(webListener.Identity.GetConfig().CA) + caBytes, err := os.ReadFile(webListener.Identity.GetConfig().CA) if err != nil { return errors.Errorf("could not read xweb web listener [%s]'s CA file [%s] to retrieve CA PEMs: %v", webListener.Name, webListener.Identity.GetConfig().CA, err) diff --git a/controller/server/controller.go b/controller/server/controller.go index 387dba0de..b5a77e675 100644 --- a/controller/server/controller.go +++ b/controller/server/controller.go @@ -24,7 +24,7 @@ import ( sync2 "github.com/openziti/edge/controller/sync_strats" "github.com/openziti/edge/pb/edge_ctrl_pb" "github.com/openziti/fabric/controller/api_impl" - "io/ioutil" + "os" "sync" "time" @@ -102,7 +102,7 @@ func NewController(cfg config.Configurable, host env.HostController) (*Controlle } // Add the root host controller's identity's CAs to the ca's served by well-known urls - if caCerts, err := ioutil.ReadFile(c.AppEnv.HostController.Identity().GetConfig().CA); err == nil { + if caCerts, err := os.ReadFile(c.AppEnv.HostController.Identity().GetConfig().CA); err == nil { c.config.AddCaPems(caCerts) } else { pfxlog.Logger().Fatalf("could not read controller identity CA file: %s: %v", c.AppEnv.HostController.Identity().GetConfig().CA, err) diff --git a/controller/sync_strats/rtx.go b/controller/sync_strats/rtx.go index a8c14eee2..ab2665f68 100644 --- a/controller/sync_strats/rtx.go +++ b/controller/sync_strats/rtx.go @@ -49,7 +49,7 @@ func newRouterSender(edgeRouter *model.EdgeRouter, router *network.Router, sendB EdgeRouter: edgeRouter, Router: router, send: make(chan *channel.Message, sendBufferSize), - closeNotify: make(chan struct{}, 0), + closeNotify: make(chan struct{}), RouterState: env.NewLockingRouterStatus(), } rtx.running.Store(true) diff --git a/controller/sync_strats/sync_instant.go b/controller/sync_strats/sync_instant.go index 87e3b94bc..a366b5aa4 100644 --- a/controller/sync_strats/sync_instant.go +++ b/controller/sync_strats/sync_instant.go @@ -126,7 +126,7 @@ func NewInstantStrategy(ae *env.AppEnv, options InstantStrategyOptions) *Instant routerConnectedQueue: make(chan *RouterSender, options.MaxQueuedRouterConnects), receivedClientHelloQueue: make(chan *RouterSender, options.MaxQueuedClientHellos), - stopNotify: make(chan struct{}, 0), + stopNotify: make(chan struct{}), } strategy.helloHandler = handler_edge_ctrl.NewHelloHandler(ae, strategy.ReceiveClientHello) diff --git a/internal/cert/fingerprint.go b/internal/cert/fingerprint.go index ca79e46c7..c038510a0 100644 --- a/internal/cert/fingerprint.go +++ b/internal/cert/fingerprint.go @@ -17,12 +17,10 @@ package cert import ( - "bytes" "crypto/sha1" "crypto/x509" "encoding/pem" "fmt" - "strings" ) type Fingerprints map[string]*x509.Certificate @@ -122,14 +120,3 @@ func (fpg *defaultFingerprintGenerator) FromRaw(raw []byte) string { // #nosec return fmt.Sprintf("%x", sha1.Sum(raw)) } - -func (fpg *defaultFingerprintGenerator) toHex(f []byte) string { - var buf bytes.Buffer - for i, b := range f { - if i > 0 { - fmt.Fprintf(&buf, ":") - } - fmt.Fprintf(&buf, "%02x", b) - } - return strings.ToUpper(buf.String()) -} diff --git a/internal/pem/pem.go b/internal/pem/pem.go index a0998cbb3..a6cda664e 100644 --- a/internal/pem/pem.go +++ b/internal/pem/pem.go @@ -22,7 +22,7 @@ import ( "crypto/x509" "encoding/pem" "fmt" - "io/ioutil" + "os" "strings" ) @@ -61,7 +61,7 @@ func NewKeyPair(privPath, pubPath, password string) (*KeyPair, error) { } func (kp *KeyPair) loadKey(privPath, password string) error { - pemBytes, err := ioutil.ReadFile(privPath) + pemBytes, err := os.ReadFile(privPath) kp.KeyPem = pemBytes if err != nil { return err @@ -74,8 +74,8 @@ func (kp *KeyPair) loadKey(privPath, password string) error { derBytes := block.Bytes - if x509.IsEncryptedPEMBlock(block) { - derBytes, err = x509.DecryptPEMBlock(block, []byte(password)) + if x509.IsEncryptedPEMBlock(block) { //nolint:staticcheck + derBytes, err = x509.DecryptPEMBlock(block, []byte(password)) //nolint:staticcheck if err != nil { return err } @@ -119,7 +119,7 @@ func (kp *KeyPair) loadKey(privPath, password string) error { } func (kp *KeyPair) loadCertificate(pubPath string) error { - pemBytes, err := ioutil.ReadFile(pubPath) + pemBytes, err := os.ReadFile(pubPath) kp.CertPem = pemBytes if err != nil { diff --git a/rest_util/capool.go b/rest_util/capool.go index 3a8ae1602..6fe4b06e0 100644 --- a/rest_util/capool.go +++ b/rest_util/capool.go @@ -21,7 +21,7 @@ import ( "encoding/base64" "fmt" "github.com/fullsailor/pkcs7" - "io/ioutil" + "io" ) // VerifyController will attempt to use the provided x509.CertPool to connect to the provided controller. @@ -71,7 +71,7 @@ func GetControllerWellKnownCas(controllerAddr string) ([]*x509.Certificate, erro return nil, err } defer func() { _ = resp.Body.Close() }() - encoded, err := ioutil.ReadAll(resp.Body) + encoded, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/rest_util/clients.go b/rest_util/clients.go index 023a4d3bc..c7474e98f 100644 --- a/rest_util/clients.go +++ b/rest_util/clients.go @@ -101,6 +101,9 @@ func NewEdgeManagementClientWithAuthenticator(authenticator Authenticator, apiAd } httpClient, err := authenticator.BuildHttpClient() + if err != nil { + return nil, err + } return NewEdgeManagementClientWithToken(httpClient, apiAddress, *apiSession.Token) } @@ -162,6 +165,9 @@ func NewEdgeClientClientWithAuthenticator(authenticator Authenticator, apiAddres } httpClient, err := authenticator.BuildHttpClient() + if err != nil { + return nil, err + } return NewEdgeClientClientWithToken(httpClient, apiAddress, *apiSession.Token) } diff --git a/router/enroll/enroll.go b/router/enroll/enroll.go index 6e1a61221..33bf214cb 100644 --- a/router/enroll/enroll.go +++ b/router/enroll/enroll.go @@ -32,9 +32,9 @@ import ( "github.com/openziti/sdk-golang/ziti/config" "github.com/openziti/sdk-golang/ziti/enroll" "gopkg.in/resty.v1" - "io/ioutil" "net/http" "net/url" + "os" "strings" ) @@ -190,15 +190,15 @@ func (re *RestEnroller) Enroll(jwtBuf []byte, silent bool, engine string, keyAlg return fmt.Errorf("enrollment response did not contain a CA chain") } - if err = ioutil.WriteFile(identityConfig.Cert, []byte(resp.Cert), 0600); err != nil { + if err = os.WriteFile(identityConfig.Cert, []byte(resp.Cert), 0600); err != nil { return fmt.Errorf("unable to write client cert to [%s]: %s", identityConfig.Cert, err) } - if err = ioutil.WriteFile(identityConfig.ServerCert, []byte(resp.ServerCert), 0600); err != nil { + if err = os.WriteFile(identityConfig.ServerCert, []byte(resp.ServerCert), 0600); err != nil { return fmt.Errorf("unable to write server cert to [%s]: %s", identityConfig.ServerCert, err) } - if err = ioutil.WriteFile(identityConfig.CA, []byte(resp.Ca), 0600); err != nil { + if err = os.WriteFile(identityConfig.CA, []byte(resp.Ca), 0600); err != nil { return fmt.Errorf("unable to write CA certs to [%s]: %s", identityConfig.CA, err) } diff --git a/router/handler_edge_ctrl/apiSessionAdded.go b/router/handler_edge_ctrl/apiSessionAdded.go index b87be33ea..7fb307ce3 100644 --- a/router/handler_edge_ctrl/apiSessionAdded.go +++ b/router/handler_edge_ctrl/apiSessionAdded.go @@ -51,7 +51,7 @@ func NewApiSessionAddedHandler(sm fabric.StateManager, binding channel.Binding) control: binding.GetChannel(), sm: sm, reqChan: make(chan *apiSessionAddedWithState, 100), - stop: make(chan struct{}, 0), + stop: make(chan struct{}), } go handler.startReceiveSync() @@ -238,7 +238,7 @@ func newApiSessionSyncTracker(id string) *apiSessionSyncTracker { return &apiSessionSyncTracker{ syncId: id, reqsWithState: map[int]*apiSessionAddedWithState{}, - stop: make(chan struct{}, 0), + stop: make(chan struct{}), startTime: time.Now(), } } @@ -256,9 +256,7 @@ func (tracker *apiSessionSyncTracker) Add(reqWithState *apiSessionAddedWithState if reqWithState.isPostSyncData { current := tracker.reqsWithState[-1] if current != nil { - for _, session := range reqWithState.ApiSessions { - current.ApiSessions = append(current.ApiSessions, session) - } + current.ApiSessions = append(current.ApiSessions, reqWithState.ApiSessions...) } else { tracker.reqsWithState[-1] = reqWithState } @@ -329,18 +327,14 @@ func (tracker *apiSessionSyncTracker) all() []*edge_ctrl_pb.ApiSession { var result []*edge_ctrl_pb.ApiSession for i := 0; i <= tracker.lastSeq; i++ { if req, ok := tracker.reqsWithState[i]; ok { - for _, apiSession := range req.ApiSessions { - result = append(result, apiSession) - } + result = append(result, req.ApiSessions...) } else { pfxlog.Logger().WithField("strategy", sync_strats.RouterSyncStrategyInstant).Error("all failed to have all update sequences") } } if req, ok := tracker.reqsWithState[-1]; ok { - for _, apiSession := range req.ApiSessions { - result = append(result, apiSession) - } + result = append(result, req.ApiSessions...) } return result diff --git a/router/internal/edgerouter/config.go b/router/internal/edgerouter/config.go index d8f7e727e..03a5ede29 100644 --- a/router/internal/edgerouter/config.go +++ b/router/internal/edgerouter/config.go @@ -184,10 +184,6 @@ func (config *Config) LoadConfigFromMap(configMap map[interface{}]interface{}) e return nil } -func (config *Config) LoadIdentity() (identity.Identity, error) { - return config.LoadIdentity() -} - func (config *Config) loadApiProxy(edgeConfigMap map[interface{}]interface{}) error { config.ApiProxy = ApiProxy{} diff --git a/router/xgress_edge/certchecker.go b/router/xgress_edge/certchecker.go index 595d918ad..50771c184 100644 --- a/router/xgress_edge/certchecker.go +++ b/router/xgress_edge/certchecker.go @@ -180,7 +180,7 @@ func (self *CertExpirationChecker) ExtendEnrollment() error { } func (self *CertExpirationChecker) getWaitTime() (time.Duration, error) { - var durationToWait time.Duration = 0 + var durationToWait time.Duration if self.edgeConfig.ExtendEnrollment { self.edgeConfig.ExtendEnrollment = false diff --git a/router/xgress_edge/certchecker_test.go b/router/xgress_edge/certchecker_test.go index 598f3f9d1..911d7b74c 100644 --- a/router/xgress_edge/certchecker_test.go +++ b/router/xgress_edge/certchecker_test.go @@ -362,10 +362,7 @@ func Test_CertExpirationChecker(t *testing.T) { certChecker.id.Cert().Leaf.NotAfter = time.Now().AddDate(0, 0, -1) - var err error - - err = certChecker.Run() - req.Error(err) + req.Error(certChecker.Run()) }) }) @@ -409,27 +406,27 @@ type SimpleTestIdentity struct { setServerCertCalled bool } -func (s SimpleTestIdentity) WatchFiles() error { +func (s *SimpleTestIdentity) WatchFiles() error { panic("implement me") } -func (s SimpleTestIdentity) StopWatchingFiles() { +func (s *SimpleTestIdentity) StopWatchingFiles() { panic("implement me") } -func (s SimpleTestIdentity) Cert() *tls.Certificate { +func (s *SimpleTestIdentity) Cert() *tls.Certificate { return s.TlsCert } -func (s SimpleTestIdentity) ServerCert() []*tls.Certificate { +func (s *SimpleTestIdentity) ServerCert() []*tls.Certificate { return s.TlsServerCert } -func (s SimpleTestIdentity) CA() *x509.CertPool { +func (s *SimpleTestIdentity) CA() *x509.CertPool { return s.CaPool } -func (s SimpleTestIdentity) ServerTLSConfig() *tls.Config { +func (s *SimpleTestIdentity) ServerTLSConfig() *tls.Config { var certs []tls.Certificate for _, cert := range s.TlsServerCert { @@ -445,29 +442,29 @@ func (s SimpleTestIdentity) ServerTLSConfig() *tls.Config { } } -func (s SimpleTestIdentity) ClientTLSConfig() *tls.Config { +func (s *SimpleTestIdentity) ClientTLSConfig() *tls.Config { return &tls.Config{ RootCAs: s.CaPool, Certificates: []tls.Certificate{*s.TlsCert}, } } -func (s SimpleTestIdentity) Reload() error { +func (s *SimpleTestIdentity) Reload() error { s.reloadCalled = true return nil } -func (s SimpleTestIdentity) SetCert(string) error { +func (s *SimpleTestIdentity) SetCert(string) error { s.setCertCalled = true return nil } -func (s SimpleTestIdentity) SetServerCert(string) error { +func (s *SimpleTestIdentity) SetServerCert(string) error { s.setServerCertCalled = true return nil } -func (s SimpleTestIdentity) GetConfig() *identity.Config { +func (s *SimpleTestIdentity) GetConfig() *identity.Config { return nil } @@ -612,15 +609,15 @@ type stubExtender struct { done func() error } -func (s stubExtender) IsRequestingCompareAndSwap(expected bool, value bool) bool { +func (s *stubExtender) IsRequestingCompareAndSwap(expected bool, value bool) bool { return s.isRequesting.CompareAndSwap(expected, value) } -func (s stubExtender) SetIsRequesting(value bool) { +func (s *stubExtender) SetIsRequesting(value bool) { s.isRequesting.Store(value) } -func (s stubExtender) ExtendEnrollment() error { +func (s *stubExtender) ExtendEnrollment() error { s.SetIsRequesting(true) if s.done != nil { @@ -630,6 +627,6 @@ func (s stubExtender) ExtendEnrollment() error { return nil } -func (s stubExtender) IsRequesting() bool { +func (s *stubExtender) IsRequesting() bool { return s.isRequesting.Load() } diff --git a/router/xgress_edge/factory.go b/router/xgress_edge/factory.go index 78891cb87..f65ba5751 100644 --- a/router/xgress_edge/factory.go +++ b/router/xgress_edge/factory.go @@ -93,7 +93,11 @@ func (factory *Factory) Run(env env.RouterEnv) error { factory.certChecker = NewCertExpirationChecker(factory.routerConfig.Id, factory.edgeRouterConfig, env.GetNetworkControllers(), env.GetCloseNotify()) - go factory.certChecker.Run() + go func() { + if err := factory.certChecker.Run(); err != nil { + pfxlog.Logger().WithError(err).Error("error while running certchecker") + } + }() return nil } diff --git a/router/xgress_edge/listener.go b/router/xgress_edge/listener.go index d88f607c6..5af871ec5 100644 --- a/router/xgress_edge/listener.go +++ b/router/xgress_edge/listener.go @@ -263,7 +263,7 @@ func (self *edgeClientConn) processBind(req *channel.Message, ch channel.Channel terminatorIdentity, _ := req.GetStringHeader(edge.TerminatorIdentityHeader) var terminatorIdentitySecret []byte if terminatorIdentity != "" { - terminatorIdentitySecret, _ = req.Headers[edge.TerminatorIdentitySecretHeader] + terminatorIdentitySecret = req.Headers[edge.TerminatorIdentitySecretHeader] } request := &edge_ctrl_pb.CreateTerminatorRequest{ diff --git a/router/xgress_edge/perf_test.go b/router/xgress_edge/perf_test.go index 852db4d7b..c3bd75932 100644 --- a/router/xgress_edge/perf_test.go +++ b/router/xgress_edge/perf_test.go @@ -11,18 +11,13 @@ import ( metrics2 "github.com/openziti/fabric/router/metrics" "github.com/openziti/fabric/router/xgress" "github.com/openziti/metrics" - "github.com/openziti/metrics/metrics_pb" "github.com/openziti/sdk-golang/ziti/edge" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "testing" "time" ) -type noopMetricsHandler struct{} - -func (n noopMetricsHandler) AcceptMetrics(*metrics_pb.MetricsMessage) { -} - func newMirrorLink(fwd *forwarder.Forwarder) *mirrorLink { result := &mirrorLink{ fwd: fwd, @@ -148,8 +143,10 @@ func writePerf(b *testing.B, mux edge.MsgMux) { link := newMirrorLink(fwd) - fwd.RegisterLink(link) - fwd.Route("test", &ctrl_pb.Route{ + err := fwd.RegisterLink(link) + assert.NoError(b, err) + + err = fwd.Route("test", &ctrl_pb.Route{ CircuitId: "test", Egress: nil, Forwards: []*ctrl_pb.Route_Forward{ @@ -157,6 +154,7 @@ func writePerf(b *testing.B, mux edge.MsgMux) { {SrcAddress: "router1", DstAddress: "test"}, }, }) + assert.NoError(b, err) x := xgress.NewXgress("test", "test", "test", conn, xgress.Initiator, xgress.DefaultOptions(), nil) x.SetReceiveHandler(handler_xgress.NewReceiveHandler(fwd)) @@ -222,8 +220,10 @@ func Benchmark_BaselinePerf(b *testing.B) { link := newMirrorLink(fwd) - fwd.RegisterLink(link) - fwd.Route("test", &ctrl_pb.Route{ + err := fwd.RegisterLink(link) + assert.NoError(b, err) + + err = fwd.Route("test", &ctrl_pb.Route{ CircuitId: "test", Egress: nil, Forwards: []*ctrl_pb.Route_Forward{ @@ -231,6 +231,7 @@ func Benchmark_BaselinePerf(b *testing.B) { {SrcAddress: "router1", DstAddress: "test"}, }, }) + assert.NoError(b, err) x := xgress.NewXgress("test", "test", "test", conn, xgress.Initiator, xgOptions, nil) x.SetReceiveHandler(handler_xgress.NewReceiveHandler(fwd)) diff --git a/router/xgress_edge_transport/factory.go b/router/xgress_edge_transport/factory.go index f65e7eca7..e6f21f794 100644 --- a/router/xgress_edge_transport/factory.go +++ b/router/xgress_edge_transport/factory.go @@ -23,9 +23,7 @@ import ( const BindingName = "edge_transport" -type factory struct { - options *xgress.Options -} +type factory struct{} // NewFactory returns a new Transport Xgress factory func NewFactory() xgress.Factory { diff --git a/runner/runner.go b/runner/runner.go index 29589a5f7..65b172752 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -104,6 +104,7 @@ func (r *LimitedRunner) Start(closeNotify <-chan struct{}) error { r.isRunning = true for _, te := range r.tickerEnforcers { + te := te // ensure te isn't changed during loop evaluation in gorutine capture below if te.Ticker != nil { return errors.New("dirty ticker encountered") } diff --git a/tests/api_session_certificates_test.go b/tests/api_session_certificates_test.go index 42e64f4e9..bedc309cb 100644 --- a/tests/api_session_certificates_test.go +++ b/tests/api_session_certificates_test.go @@ -1,5 +1,4 @@ //go:build apitests -// +build apitests /* Copyright NetFoundry Inc. @@ -56,7 +55,8 @@ func Test_Api_Session_Certs(t *testing.T) { request := ctx.AdminClientSession.newAuthenticatedRequest() body := gabs.New() - body.Set(string(csrPem), "csr") + _, err = body.Set(string(csrPem), "csr") + ctx.Req.NoError(err) bodyStr := body.String() request.SetBody(bodyStr) diff --git a/tests/auth_cert_test.go b/tests/auth_cert_test.go index 2438d2502..938f4e534 100644 --- a/tests/auth_cert_test.go +++ b/tests/auth_cert_test.go @@ -115,6 +115,7 @@ func (test *authCertTests) testAuthenticateCertStoresAndFillsFullCert(t *testing resp, err := testClient.NewRequest(). SetHeader("content-type", "application/json"). Post("/authenticate?method=cert") + r.NoError(err) standardJsonResponseTests(resp, http.StatusOK, t) diff --git a/tests/authenticate.go b/tests/authenticate.go index faab706a5..7fc745b4f 100644 --- a/tests/authenticate.go +++ b/tests/authenticate.go @@ -553,12 +553,6 @@ func (request *authenticatedRequests) requireNewPostureCheckDomain(domains []str return postureCheck } -func (request *authenticatedRequests) requireNewPostureCheckMFA(roleAttributes []string) *postureCheck { - postureCheck := request.testContext.newPostureCheckMFA(roleAttributes) - request.requireCreateEntity(postureCheck) - return postureCheck -} - func (request *authenticatedRequests) requireNewPostureCheckProcessMulti(semantic rest_model.Semantic, processes []*rest_model.ProcessMulti, roleAttributes []string) *rest_model.PostureCheckProcessMultiDetail { postureCheck := request.testContext.newPostureCheckProcessMulti(semantic, processes, roleAttributes) id := request.requireCreateRestModelEntity("posture-checks", postureCheck) @@ -583,12 +577,6 @@ func (request *authenticatedRequests) requireNewService(roleAttributes, configs return service } -func (request *authenticatedRequests) newServiceBulk(roleAttributes, configs []string) *service { - service := request.testContext.newService(roleAttributes, configs) - request.requireCreateEntity(service) - return service -} - func (request *authenticatedRequests) RequireNewServiceAccessibleToAll(terminatorStrategy string) *service { request.requireNewServicePolicy("Dial", s("#all"), s("#all"), nil) request.requireNewServicePolicy("Bind", s("#all"), s("#all"), nil) @@ -719,16 +707,6 @@ func (request *authenticatedRequests) requireCreateRestModelPostureResponse(enti standardJsonResponseTests(resp, http.StatusCreated, request.testContext.testing) } -func (request *authenticatedRequests) createEntityBulk(entity entity) string { - resp := request.createEntity(entity) - if http.StatusCreated != resp.StatusCode() { - panic(errors.Errorf("expected error code %v", resp.StatusCode())) - } - id := request.testContext.getEntityId(resp.Body()) - entity.setId(id) - return id -} - func (request *authenticatedRequests) requireDeleteEntity(entity entity) { resp := request.deleteEntityOfType(entity.getEntityType(), entity.getId()) standardJsonResponseTests(resp, http.StatusOK, request.testContext.testing) @@ -764,16 +742,6 @@ func (request *authenticatedRequests) requireQuery(url string) *gabs.Container { return request.testContext.parseJson(body) } -func (request *authenticatedRequests) requireAddAssociation(url string, ids ...string) { - httpStatus, _ := request.addAssociation(url, ids...) - request.testContext.Req.Equal(http.StatusOK, httpStatus) -} - -func (request *authenticatedRequests) requireRemoveAssociation(url string, ids ...string) { - httpStatus, _ := request.removeAssociation(url, ids...) - request.testContext.Req.Equal(http.StatusOK, httpStatus) -} - func (request *authenticatedRequests) createEntityOfType(entityType string, body interface{}) *resty.Response { resp, err := request.newAuthenticatedRequest(). SetBody(body). @@ -902,14 +870,6 @@ func (request *authenticatedRequests) query(url string) (int, []byte) { return resp.StatusCode(), resp.Body() } -func (request *authenticatedRequests) addAssociation(url string, ids ...string) (int, []byte) { - return request.updateAssociation(http.MethodPut, url, ids...) -} - -func (request *authenticatedRequests) removeAssociation(url string, ids ...string) (int, []byte) { - return request.updateAssociation(http.MethodDelete, url, ids...) -} - func (request *authenticatedRequests) validateAssociations(entity entity, childType string, children ...entity) { var ids []string for _, child := range children { @@ -958,16 +918,6 @@ func (request *authenticatedRequests) validateAssociationsAtContains(url string, } } -func (request *authenticatedRequests) updateAssociation(method, url string, ids ...string) (int, []byte) { - - resp, err := request.newAuthenticatedRequest(). - SetBody(request.testContext.idsJson(ids...).String()). - Execute(method, url) - request.testContext.Req.NoError(err) - request.testContext.logJson(resp.Body()) - return resp.StatusCode(), resp.Body() -} - func (request *authenticatedRequests) isServiceVisibleToUser(serviceId string) bool { query := url.QueryEscape(fmt.Sprintf(`id = "%v"`, serviceId)) result := request.requireQuery("services?filter=" + query) @@ -984,20 +934,6 @@ func (request *authenticatedRequests) createUserAndLoginClientApi(isAdmin bool, return session } -func (request *authenticatedRequests) createUserAndLoginManagementApi(isAdmin bool, roleAttributes, configTypes []string) *session { - _, userAuth := request.requireCreateIdentityWithUpdbEnrollment(eid.New(), eid.New(), isAdmin, roleAttributes...) - userAuth.ConfigTypes = configTypes - - session, _ := userAuth.AuthenticateManagementApi(request.testContext) - - return session -} - -func (request *authenticatedRequests) refreshServiceUpdateTime() { - lastUpdated := request.getServiceUpdateTime() - request.session.lastServiceUpdate = lastUpdated -} - func (request *authenticatedRequests) requireServiceUpdateTimeUnchanged() { time.Sleep(5 * time.Millisecond) lastUpdated := request.getServiceUpdateTime() diff --git a/tests/authenticator_test.go b/tests/authenticator_test.go index d29d37e1b..4fd2654bc 100644 --- a/tests/authenticator_test.go +++ b/tests/authenticator_test.go @@ -51,6 +51,7 @@ func Test_Authenticators_AdminUsingAdminEndpoints(t *testing.T) { standardJsonResponseTests(resp, http.StatusOK, t) authenticatorsBody, err := gabs.ParseJSON(resp.Body()) + req.NoError(err) t.Run("can see three authenticators", func(t *testing.T) { req := require.New(t) @@ -77,6 +78,7 @@ func Test_Authenticators_AdminUsingAdminEndpoints(t *testing.T) { req.NotEmpty(authenticatorId) detailResp, err := ctx.AdminManagementSession.newAuthenticatedRequest().Get("/authenticators/" + authenticatorId) + req.NoError(err) standardJsonResponseTests(detailResp, http.StatusOK, t) }) diff --git a/tests/config_test.go b/tests/config_test.go index bf773c110..5fd778105 100644 --- a/tests/config_test.go +++ b/tests/config_test.go @@ -1,5 +1,4 @@ //go:build apitests -// +build apitests /* Copyright NetFoundry Inc. @@ -167,7 +166,6 @@ func Test_Configs(t *testing.T) { createdAt := ctx.validateDateFieldsForCreate(now, entityJson) time.Sleep(time.Millisecond * 10) - now = time.Now() newName := eid.New() config.Name = newName config.Data = map[string]interface{}{"foo": "bar"} @@ -180,7 +178,6 @@ func Test_Configs(t *testing.T) { ctx.validateDateFieldsForUpdate(now, createdAt, jsonConfig) time.Sleep(time.Millisecond * 10) - now = time.Now() config.Name = eid.New() config.Data = map[string]interface{}{"foo": "bar"} config.Tags = map[string]interface{}{"baz": "bam"} @@ -191,7 +188,6 @@ func Test_Configs(t *testing.T) { ctx.AdminManagementSession.validateUpdate(config) time.Sleep(time.Millisecond * 10) - now = time.Now() config.Name = eid.New() config.Data = map[string]interface{}{"bim": "bam"} config.Tags = map[string]interface{}{"enlightened": false} @@ -202,7 +198,6 @@ func Test_Configs(t *testing.T) { ctx.AdminManagementSession.validateUpdate(config) time.Sleep(time.Millisecond * 10) - now = time.Now() config.Name = eid.New() config.Data = map[string]interface{}{"bim": "bom"} config.Tags = map[string]interface{}{"enlightened": true} diff --git a/tests/context.go b/tests/context.go index 85c7ce82b..45c082897 100644 --- a/tests/context.go +++ b/tests/context.go @@ -538,11 +538,6 @@ func (ctx *TestContext) newAnonymousClientApiRequest() *resty.Request { SetHeader("content-type", "application/json") } -func (ctx *TestContext) newAnonymousManagementApiRequest() *resty.Request { - return ctx.DefaultClientApiClient().R(). - SetHeader("content-type", "application/json") -} - func (ctx *TestContext) newRequestWithClientCert(cert *x509.Certificate, privateKey crypto.PrivateKey) *resty.Request { client, _, _ := ctx.NewClientComponentsWithClientCert(cert, privateKey) @@ -626,6 +621,7 @@ func (ctx *TestContext) completeOttEnrollment(identityId string) *certAuthentica request, err := certtools.NewCertRequest(map[string]string{ "C": "US", "O": "NetFoundry-API-Test", "CN": identityId, }, nil) + ctx.Req.NoError(err) csr, err := x509.CreateCertificateRequest(rand.Reader, request, privateKey) ctx.Req.NoError(err) @@ -670,15 +666,6 @@ func (ctx *TestContext) validateDateFieldsForCreate(start time.Time, jsonEntity return createdAt } -func (ctx *TestContext) newPostureCheckMFA(roleAttributes []string) *postureCheck { - return &postureCheck{ - name: eid.New(), - typeId: "MFA", - roleAttributes: roleAttributes, - tags: nil, - } -} - func (ctx *TestContext) newPostureCheckProcessMulti(semantic rest_model.Semantic, processes []*rest_model.ProcessMulti, roleAttributes []string) *rest_model.PostureCheckProcessMultiCreate { check := &rest_model.PostureCheckProcessMultiCreate{ Processes: processes, @@ -781,12 +768,6 @@ func (ctx *TestContext) validateEntity(entity entity, jsonEntity *gabs.Container return jsonEntity } -func (ctx *TestContext) idsJson(ids ...string) *gabs.Container { - entityData := gabs.New() - ctx.setJsonValue(entityData, ids, "ids") - return entityData -} - func (ctx *TestContext) requireEntityNotEnrolled(name string, entity *gabs.Container) { fingerprint := entity.Path("fingerprint").Data() ctx.Req.Nil(fingerprint, "expected "+name+" with isVerified=false to have an empty fingerprint") diff --git a/tests/enrollment_create_test.go b/tests/enrollment_create_test.go index fbe1d6c6b..85a0bb109 100644 --- a/tests/enrollment_create_test.go +++ b/tests/enrollment_create_test.go @@ -1,5 +1,4 @@ //go:build apitests -// +build apitests /* Copyright NetFoundry Inc. @@ -199,6 +198,8 @@ func Test_EnrollmentCreate(t *testing.T) { caCreateResp := &rest_model.CreateEnvelope{} resp, err := ctx.AdminManagementSession.newAuthenticatedRequest().SetBody(caCreate).SetResult(caCreateResp).Post("cas/") + ctx.NoError(err) + ctx.Equal(http.StatusCreated, resp.StatusCode(), string(resp.Body())) ctx.NotNil(caCreateResp) ctx.NotNil(caCreateResp.Data) ctx.NotEmpty(caCreateResp.Data.ID) @@ -294,6 +295,8 @@ func Test_EnrollmentCreate(t *testing.T) { caCreateResp := &rest_model.CreateEnvelope{} resp, err := ctx.AdminManagementSession.newAuthenticatedRequest().SetBody(caCreate).SetResult(caCreateResp).Post("cas/") + ctx.NoError(err) + ctx.Equal(http.StatusCreated, resp.StatusCode(), string(resp.Body())) ctx.NotNil(caCreateResp) ctx.NotNil(caCreateResp.Data) ctx.NotEmpty(caCreateResp.Data.ID) diff --git a/tests/enrollment_identity_extend_test.go b/tests/enrollment_identity_extend_test.go index af04da5fa..a39a026e4 100644 --- a/tests/enrollment_identity_extend_test.go +++ b/tests/enrollment_identity_extend_test.go @@ -30,8 +30,8 @@ import ( "fmt" "github.com/openziti/edge/eid" "github.com/openziti/edge/rest_model" - "github.com/openziti/identity/certtools" nfpem "github.com/openziti/foundation/v2/pem" + "github.com/openziti/identity/certtools" "github.com/openziti/sdk-golang/ziti/constants" "gopkg.in/resty.v1" "net/http" @@ -54,9 +54,12 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { ctx.Req.NoError(err) newPrivateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + ctx.NoError(err) + request, err := certtools.NewCertRequest(map[string]string{ "C": "US", "O": "NetFoundry-API-Test", "CN": identityAuth.cert.Subject.CommonName, }, nil) + ctx.NoError(err) csr, err := x509.CreateCertificateRequest(rand.Reader, request, newPrivateKey) ctx.Req.NoError(err) @@ -181,9 +184,12 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { ctx.Req.NoError(err) newPrivateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + ctx.Req.NoError(err) + request, err := certtools.NewCertRequest(map[string]string{ "C": "US", "O": "NetFoundry-API-Test", "CN": identityAuth.cert.Subject.CommonName, }, nil) + ctx.Req.NoError(err) csr, err := x509.CreateCertificateRequest(rand.Reader, request, newPrivateKey) ctx.Req.NoError(err) @@ -205,6 +211,8 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { path := fmt.Sprintf("/edge/client/v1/current-identity/authenticators/%s/extend", *currentAuthenticator.ID) resolvedUrl, err := identityApiSession.resolveApiUrl(ctx.ApiHost, path) + ctx.Req.NoError(err) + client := resty.New().SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true, }) @@ -226,9 +234,12 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { ctx.Req.NoError(err) newPrivateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + ctx.Req.NoError(err) + request, err := certtools.NewCertRequest(map[string]string{ "C": "US", "O": "NetFoundry-API-Test", "CN": identityAuth.cert.Subject.CommonName, }, nil) + ctx.Req.NoError(err) csr, err := x509.CreateCertificateRequest(rand.Reader, request, newPrivateKey) ctx.Req.NoError(err) @@ -294,13 +305,15 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { name := eid.New() _, identityAuth := ctx.AdminManagementSession.requireCreateIdentityOttEnrollment(name, false) identityApiSession, err := identityAuth.AuthenticateClientApi(ctx) - ctx.Req.NoError(err) newPrivateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + ctx.Req.NoError(err) + request, err := certtools.NewCertRequest(map[string]string{ "C": "US", "O": "NetFoundry-API-Test", "CN": identityAuth.cert.Subject.CommonName, }, nil) + ctx.Req.NoError(err) csr, err := x509.CreateCertificateRequest(rand.Reader, request, newPrivateKey) ctx.Req.NoError(err) @@ -313,6 +326,7 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { path := fmt.Sprintf("/current-identity/authenticators/%s/extend", "fake") resolvedUrl, err := identityApiSession.resolveApiUrl(ctx.ApiHost, path) + ctx.Req.NoError(err) extendResp, err := identityApiSession.NewRequest().SetBody(csrRequest).Post(resolvedUrl) ctx.Req.NoError(err) @@ -332,9 +346,12 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { ctx.Req.NoError(err) newPrivateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + ctx.Req.NoError(err) + request, err := certtools.NewCertRequest(map[string]string{ "C": "US", "O": "NetFoundry-API-Test", "CN": identityAuth.cert.Subject.CommonName, }, nil) + ctx.Req.NoError(err) csr, err := x509.CreateCertificateRequest(rand.Reader, request, newPrivateKey) ctx.Req.NoError(err) @@ -360,5 +377,4 @@ func Test_EnrollmentIdentityExtend(t *testing.T) { ctx.Req.NoError(err) ctx.Req.Equal(401, extendResp.StatusCode()) }) - } diff --git a/tests/enrollment_updb_test.go b/tests/enrollment_updb_test.go index c82f44866..f1f81bb5f 100644 --- a/tests/enrollment_updb_test.go +++ b/tests/enrollment_updb_test.go @@ -42,12 +42,16 @@ func Test_EnrollmentUpdb(t *testing.T) { updbPassword := uuid.New().String() updbType := "User" - updbCreate.Set(updbName, "name") - updbCreate.Set(updbType, "type") - updbCreate.Set(map[string]string{ + _, err := updbCreate.Set(updbName, "name") + ctx.Req.NoError(err) + _, err = updbCreate.Set(updbType, "type") + ctx.Req.NoError(err) + _, err = updbCreate.Set(map[string]string{ "updb": updbUsername, }, "enrollment") - updbCreate.Set(false, "isAdmin") + ctx.Req.NoError(err) + _, err = updbCreate.Set(false, "isAdmin") + ctx.Req.NoError(err) resp, err := ctx.AdminManagementSession.newAuthenticatedRequest().SetBody(updbCreate.String()).Post("identities") ctx.Req.NoError(err) @@ -93,7 +97,8 @@ func Test_EnrollmentUpdb(t *testing.T) { enrollmentBody := gabs.New() - enrollmentBody.Set(updbPassword, "password") + _, err = enrollmentBody.Set(updbPassword, "password") + ctx.Req.NoError(err) resp, err := ctx.newAnonymousClientApiRequest().SetBody(enrollmentBody.String()).Post("enroll?method=updb&token=" + updbEnrollmentToken) ctx.Req.NoError(err) diff --git a/tests/entities.go b/tests/entities.go index b4e1b39ce..210ecf47d 100644 --- a/tests/entities.go +++ b/tests/entities.go @@ -662,41 +662,6 @@ func (entity *configType) validate(ctx *TestContext, c *gabs.Container) { ctx.pathEquals(c, entity.Tags, path("tags")) } -type apiSession struct { - id string - token string - identityId string - configTypes []string - tags map[string]interface{} -} - -func (entity *apiSession) getId() string { - return entity.id -} - -func (entity *apiSession) setId(id string) { - entity.id = id -} - -func (entity *apiSession) getEntityType() string { - return "apiSessions" -} - -func (entity *apiSession) toJson(_ bool, ctx *TestContext, _ ...string) string { - ctx.Req.FailNow("should not be called") - return "" -} - -func (entity *apiSession) validate(ctx *TestContext, c *gabs.Container) { - if entity.tags == nil { - entity.tags = map[string]interface{}{} - } - ctx.pathEquals(c, entity.token, path("token")) - ctx.pathEquals(c, entity.identityId, path("identity", "id")) - ctx.pathEquals(c, entity.configTypes, path("configTypes")) - ctx.pathEquals(c, entity.tags, path("tags")) -} - type configValidatingService struct { *service configs map[string]*Config @@ -758,27 +723,27 @@ func (entity *transitRouter) validate(ctx *TestContext, c *gabs.Container) { type ca struct { id string - name string `json:"name"` - isAutoCaEnrollmentEnabled bool `json:"isAutoCaEnrollmentEnabled"` - isAuthEnabled bool `json:"isAuthEnabled"` - isOttCaEnrollmentEnabled bool `json:"isOttCaEnrollmentEnabled"` - certPem string `json:"certPem"` - identityRoles []string `json:"identityRoles"` - identityNameFormat string `json:"identityNameFormat"` - tags map[string]interface{} `json:"tags"` - externalIdClaim *externalIdClaim `json:"externalIdClaim"` + name string + isAutoCaEnrollmentEnabled bool + isAuthEnabled bool + isOttCaEnrollmentEnabled bool + certPem string + identityRoles []string + identityNameFormat string + tags map[string]interface{} + externalIdClaim *externalIdClaim - privateKey crypto.Signer `json:"-"` //utility property, not used in API calls - publicCert *x509.Certificate `json:"-"` //utility property, not used in API calls + privateKey crypto.Signer //utility property, not used in API calls + publicCert *x509.Certificate //utility property, not used in API calls } type externalIdClaim struct { - location string `json:"location"` - matcher string `json:"matcher"` - matcherCriteria string `json:"matcherCriteria"` - parser string `json:"parser"` - parserCriteria string `json:"parserCriteria"` - index int64 `json:"index"` + location string + matcher string + matcherCriteria string + parser string + parserCriteria string + index int64 } func newTestCaCert() (*x509.Certificate, *ecdsa.PrivateKey, *bytes.Buffer) { @@ -809,6 +774,9 @@ func newTestCaCert() (*x509.Certificate, *ecdsa.PrivateKey, *bytes.Buffer) { } caCert, err = x509.ParseCertificate(caBytes) + if err != nil { + panic(err) + } caPEM := new(bytes.Buffer) _ = pem.Encode(caPEM, &pem.Block{ @@ -840,19 +808,19 @@ func newTestCa(identityRoles ...string) *ca { } } -func (entity ca) getId() string { +func (entity *ca) getId() string { return entity.id } -func (entity ca) setId(id string) { +func (entity *ca) setId(id string) { entity.id = id } -func (entity ca) getEntityType() string { +func (entity *ca) getEntityType() string { return "cas" } -func (entity ca) toJson(create bool, ctx *TestContext, fields ...string) string { +func (entity *ca) toJson(create bool, ctx *TestContext, fields ...string) string { entityData := gabs.New() ctx.setValue(entityData, entity.name, fields, "name") ctx.setValue(entityData, entity.isOttCaEnrollmentEnabled, fields, "isOttCaEnrollmentEnabled") @@ -878,7 +846,7 @@ func (entity ca) toJson(create bool, ctx *TestContext, fields ...string) string return entityData.String() } -func (entity ca) validate(ctx *TestContext, c *gabs.Container) { +func (entity *ca) validate(ctx *TestContext, c *gabs.Container) { if entity.tags == nil { entity.tags = map[string]interface{}{} } @@ -893,7 +861,7 @@ func (entity ca) validate(ctx *TestContext, c *gabs.Container) { ctx.pathEquals(c, entity.tags, path("tags")) } -func (entity ca) CreateSignedCert(name string) *certAuthenticator { +func (entity *ca) CreateSignedCert(name string) *certAuthenticator { clientKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(err) diff --git a/tests/posture_check_mfa_test.go b/tests/posture_check_mfa_test.go index 4d18abe73..928598887 100644 --- a/tests/posture_check_mfa_test.go +++ b/tests/posture_check_mfa_test.go @@ -1,5 +1,4 @@ //go:build apitests -// +build apitests /* Copyright NetFoundry Inc. @@ -909,7 +908,7 @@ func Test_PostureChecks_MFA(t *testing.T) { t.Run("after the MFA posture check timeout", func(t *testing.T) { ctx.testContextChanged(t) - durationTillTimeout := timeoutAt.Sub(time.Now()) + durationTillTimeout := time.Until(timeoutAt) if durationTillTimeout > 0 { time.Sleep(durationTillTimeout) } diff --git a/tunnel/dns/file.go b/tunnel/dns/file.go index 44c528a3a..04584699e 100644 --- a/tunnel/dns/file.go +++ b/tunnel/dns/file.go @@ -28,9 +28,8 @@ import ( const hostFormat = "%s\t%s\t# NetFoundry" type hostFile struct { - path string - mutex sync.Mutex - domains map[string]*domainEntry + path string + mutex sync.Mutex } func NewHostFile(path string) Resolver { diff --git a/tunnel/entities/service.go b/tunnel/entities/service.go index aff3c9fec..25e17274f 100644 --- a/tunnel/entities/service.go +++ b/tunnel/entities/service.go @@ -306,6 +306,9 @@ func (self *HostV2Terminator) GetPort(options map[string]interface{}) (string, e return portStr, err } port, err := strconv.Atoi(portStr) + if err != nil { + return "", errors.Wrapf(err, "invalid destination port %v", portStr) + } for _, portRange := range self.AllowedPortRanges { if uint16(port) >= portRange.Low && uint16(port) <= portRange.High { return portStr, nil diff --git a/tunnel/intercept/hosting.go b/tunnel/intercept/hosting.go index 57716d425..01860f640 100644 --- a/tunnel/intercept/hosting.go +++ b/tunnel/intercept/hosting.go @@ -173,7 +173,9 @@ func (self *hostingContext) OnClose() { if err != nil { log.WithError(err).Error("failed to get dial IP") } else if self.addrTracker.RemoveAddress(ipNet.String()) { - err = router.RemoveLocalAddress(ipNet, "lo") + if err = router.RemoveLocalAddress(ipNet, "lo"); err != nil { + log.WithError(err).Error("failed to remove local address") + } } } diff --git a/tunnel/intercept/hosting_resolv.go b/tunnel/intercept/hosting_resolv.go index 4a8b1d1e0..5827a9161 100644 --- a/tunnel/intercept/hosting_resolv.go +++ b/tunnel/intercept/hosting_resolv.go @@ -130,10 +130,7 @@ func (r *resolvConn) Write(b []byte) (int, error) { q = dnsMessage.Question[0] - matchName = q.Name - if strings.HasSuffix(matchName, ".") { - matchName = matchName[0 : len(matchName)-1] - } + matchName = strings.TrimSuffix(q.Name, ".") log.WithField("name", matchName).WithField("type", q.Type).Info("resolving") for _, allowed := range r.ctx.config.GetAllowedAddresses() { if allowed.Allows(matchName) { diff --git a/tunnel/intercept/svcpoll.go b/tunnel/intercept/svcpoll.go index 42b63728e..375eeaf7f 100644 --- a/tunnel/intercept/svcpoll.go +++ b/tunnel/intercept/svcpoll.go @@ -76,7 +76,7 @@ func (self *ServiceListenerGroup) NewServiceListener() *ServiceListener { func (self *ServiceListenerGroup) WaitForShutdown() { sig := make(chan os.Signal, 1) //signal.Notify expects a buffered chan of at least 1 - signal.Notify(sig, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) for s := range sig { logrus.Debugf("caught signal %v", s) @@ -115,7 +115,7 @@ type ServiceListener struct { func (self *ServiceListener) WaitForShutdown() { sig := make(chan os.Signal, 1) //signal.Notify expects a buffered chan of at least 1 - signal.Notify(sig, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) for s := range sig { logrus.Debugf("caught signal %v", s) diff --git a/tunnel/intercept/tproxy/tproxy_linux.go b/tunnel/intercept/tproxy/tproxy_linux.go index cb28853c1..2dfbf3c7d 100644 --- a/tunnel/intercept/tproxy/tproxy_linux.go +++ b/tunnel/intercept/tproxy/tproxy_linux.go @@ -544,12 +544,6 @@ func (self *tProxy) StopIntercepting(tracker intercept.AddressTracker) error { return impl.MultipleErrors(errorList) } -func (self *tProxy) logAddresses() { - for idx, addr := range self.addresses { - fmt.Printf("%v: (%p) %v\n", idx, addr, addr) - } -} - type IPPortAddr interface { GetIP() net.IP GetPort() int diff --git a/tunnel/router/router_linux.go b/tunnel/router/router_linux.go index d585a7f15..60875e068 100644 --- a/tunnel/router/router_linux.go +++ b/tunnel/router/router_linux.go @@ -28,7 +28,7 @@ import ( "os" ) -// Add an address (or prefix) to the specified network interface. +// AddLocalAddress adds an address (or prefix) to the specified network interface. func AddLocalAddress(prefix *net.IPNet, ifName string) error { logrus.Debugf("adding local address '%v' to interface %v", prefix.String(), ifName) return nlAddrReq(prefix, nil, ifName, unix.RTM_NEWADDR) @@ -148,19 +148,6 @@ func marshalIfAddrmsg(m *unix.IfAddrmsg) []byte { return b } -func marshalIfInfomsg(m *unix.IfInfomsg) []byte { - b := make([]byte, unix.SizeofIfInfomsg) - - b[0] = m.Family - b[1] = 0 // pad - nlenc.PutUint16(b[2:4], m.Type) - nlenc.PutInt32(b[4:8], m.Index) - nlenc.PutUint32(b[8:12], m.Flags) - nlenc.PutUint32(b[12:16], m.Change) - - return b -} - func closeNetlink(conn *netlink.Conn) { err := conn.Close() if err != nil { diff --git a/tunnel/utils/ifaddrs_linux.go b/tunnel/utils/ifaddrs_linux.go index d5be31bfc..718c9717a 100644 --- a/tunnel/utils/ifaddrs_linux.go +++ b/tunnel/utils/ifaddrs_linux.go @@ -51,11 +51,7 @@ loop: return nil, os.NewSyscallError("parsenetlinkrouteattr", err) } ifa := newAddr(ifam, attrs) - if ifa != nil { - for _, a := range ifa { - ifat = append(ifat, a) - } - } + ifat = append(ifat, ifa...) } } return ifat, nil