Merge pull request #1204 from openziti/add-linter

Add linter and fix issues found by linter
This commit is contained in:
Paul Lorenz
2022-10-12 09:50:38 -04:00
committed by GitHub
77 changed files with 311 additions and 457 deletions
+41
View File
@@ -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
+3 -3
View File
@@ -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]")
}
+16 -19
View File
@@ -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,
-2
View File
@@ -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
+3 -3
View File
@@ -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,
+1 -3
View File
@@ -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 {
+2 -2
View File
@@ -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).
@@ -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
@@ -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 {
@@ -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()
@@ -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
@@ -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),
@@ -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()),
+1 -1
View File
@@ -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)
-9
View File
@@ -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 {
+7 -1
View File
@@ -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
}
+4 -5
View File
@@ -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")
+15 -15
View File
@@ -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
@@ -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 {
+2 -2
View File
@@ -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"), ";")
+10 -13
View File
@@ -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)
}
}
}()
+14 -6
View File
@@ -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) {
+1 -1
View File
@@ -119,7 +119,7 @@ type PostureCheckFailureValuesMac struct {
}
func (p PostureCheckFailureValuesMac) Expected() interface{} {
return p.Expected()
return p.ExpectedValue
}
func (p PostureCheckFailureValuesMac) Actual() interface{} {
+1 -27
View File
@@ -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{}
@@ -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
@@ -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
@@ -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
}
}
+5 -2
View File
@@ -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")
}
}
}
+3 -3
View File
@@ -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), "")
@@ -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
}
+5 -4
View File
@@ -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)
}
}
@@ -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
}
@@ -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) {
+1 -1
View File
@@ -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()
@@ -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
-9
View File
@@ -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))
}
+2 -1
View File
@@ -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)
+2 -2
View File
@@ -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
+2 -5
View File
@@ -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())
@@ -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)
}
}
+2 -2
View File
@@ -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)
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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)
-13
View File
@@ -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())
}
+5 -5
View File
@@ -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 {
+2 -2
View File
@@ -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
}
+6
View File
@@ -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)
}
+4 -4
View File
@@ -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)
}
+5 -11
View File
@@ -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
-4
View File
@@ -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{}
+1 -1
View File
@@ -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
+16 -19
View File
@@ -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()
}
+5 -1
View File
@@ -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
}
+1 -1
View File
@@ -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{
+11 -10
View File
@@ -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))
+1 -3
View File
@@ -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 {
+1
View File
@@ -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")
}
+2 -2
View File
@@ -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)
+1
View File
@@ -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)
-64
View File
@@ -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()
+2
View File
@@ -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)
})
-5
View File
@@ -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}
+1 -20
View File
@@ -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")
+4 -1
View File
@@ -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)
+19 -3
View File
@@ -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())
})
}
+10 -5
View File
@@ -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)
+26 -58
View File
@@ -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)
+1 -2
View File
@@ -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)
}
+2 -3
View File
@@ -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 {
+3
View File
@@ -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
+3 -1
View File
@@ -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")
}
}
}
+1 -4
View File
@@ -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) {
+2 -2
View File
@@ -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)
-6
View File
@@ -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
+1 -14
View File
@@ -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 {
+1 -5
View File
@@ -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