Skip to content

Commit

Permalink
Simplify LockTarget.IsEmpty implementation (#32607)
Browse files Browse the repository at this point in the history
  • Loading branch information
espadolini authored Sep 27, 2023
1 parent 9feb2ed commit 8ad4b1b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
18 changes: 13 additions & 5 deletions api/types/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,6 @@ func (c *LockV2) CheckAndSetDefaults() error {
return nil
}

// IsEmpty returns true if none of the target's fields is set.
func (t LockTarget) IsEmpty() bool {
return protoKnownFieldsEqual(&t, &LockTarget{})
}

// IntoMap returns the target attributes in the form of a map.
func (t LockTarget) IntoMap() (map[string]string, error) {
m := map[string]string{}
Expand All @@ -237,6 +232,19 @@ func (t *LockTarget) FromMap(m map[string]string) error {
return trace.Wrap(utils.ObjectToStruct(m, t))
}

// IsEmpty returns true if none of the target's fields is set.
func (t LockTarget) IsEmpty() bool {
return t.User == "" &&
t.Role == "" &&
t.Login == "" &&
t.Node == "" &&
t.MFADevice == "" &&
t.WindowsDesktop == "" &&
t.AccessRequest == "" &&
t.Device == "" &&
t.ServerID == ""
}

// Match returns true if the lock's target is matched by this target.
func (t LockTarget) Match(lock Lock) bool {
if t.IsEmpty() {
Expand Down
21 changes: 21 additions & 0 deletions api/types/lock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ limitations under the License.
package types

import (
"reflect"
"strings"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -112,3 +114,22 @@ func TestLockTargetMatch(t *testing.T) {
// Test that a lock with ServerID field set matches any target with ServerID.
require.True(t, targetServerID.Match(lockServerID))
}

// TestLockTargetIsEmpty checks that the implementation of [LockTarget.IsEmpty]
// is correct by filling one field at a time and expecting IsEmpty to return
// false. Only the public fields that don't start with `XXX_` are checked (as
// those are gogoproto-internal fields).
func TestLockTargetIsEmpty(t *testing.T) {
require.True(t, (LockTarget{}).IsEmpty())

for i, field := range reflect.VisibleFields(reflect.TypeOf(LockTarget{})) {
if strings.HasPrefix(field.Name, "XXX_") {
continue
}

var lt LockTarget
// if we add non-string fields to LockTarget we need a type switch here
reflect.ValueOf(&lt).Elem().Field(i).SetString("nonempty")
require.False(t, lt.IsEmpty(), "field name: %v", field.Name)
}
}

0 comments on commit 8ad4b1b

Please sign in to comment.