Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a tag to accept missing struct field secrets #88

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions client/setec/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"reflect"
"strings"

"github.com/tailscale/setec/types/api"
"golang.org/x/exp/slices"
)

Expand All @@ -36,10 +37,13 @@ func ParseFields(v any, namePrefix string) (*Fields, error) {
// Fields is a helper for plumbing secrets to the fields of struct values. The
// [ParseFields] function recognizes fields of a struct with a tag like:
//
// setec:"base-secret-name[,json]"
// setec:"base-secret-name[,json][,allowmissing]"
//
// The resulting Fields value fetches the secrets identified by these tags from
// a setec.Store, and injects their values into the fields.
// a setec.Store, and injects their values into the fields. By default, an
// error is reported if a tagged secret is not found in the store; adding the
// optional "allowmissing" verb causes missing or inaccessible secrets to be
// silently replaced with a static empty value.
//
// # Background
//
Expand Down Expand Up @@ -149,6 +153,7 @@ type fieldInfo struct {
unmarshal func([]byte) error // if non-nil, call to unmarshal the value
isJSON bool // if true, secret must be JSON encoded
vtype reflect.Type // type of field pointed to by value
missingOK bool // treat missing secret values as empty without error
}

// apply sets the target of fi.value to the secret named. It reports an error
Expand All @@ -160,23 +165,32 @@ func (f fieldInfo) apply(ctx context.Context, s *Store, fullName string) error {
if f.isJSON {
v, err := s.LookupSecret(ctx, fullName)
if err != nil {
return err
if !f.missingOK || !isMissingErr(err) {
return err
}
v = StaticSecret("")
}
return json.Unmarshal(v.Get(), f.value.Interface())
}

if f.vtype == watcherType {
w, err := s.LookupWatcher(ctx, fullName)
if err != nil {
return err
if !f.missingOK || !isMissingErr(err) {
return err
}
w = Watcher{secret: StaticSecret("")} // never ready
}
f.value.Elem().Set(reflect.ValueOf(w))
return nil
}

v, err := s.LookupSecret(ctx, fullName)
if err != nil {
return err
if !f.missingOK || !isMissingErr(err) {
return err
}
v = StaticSecret("")
}
if f.unmarshal != nil {
return f.unmarshal(v.Get())
Expand All @@ -194,6 +208,10 @@ func (f fieldInfo) apply(ctx context.Context, s *Store, fullName string) error {
return nil
}

func isMissingErr(err error) bool {
return errors.Is(err, api.ErrNotFound) || errors.Is(err, api.ErrAccessDenied)
}

var (
bytesType = reflect.TypeOf([]byte(nil))
secretType = reflect.TypeOf(Secret(nil))
Expand Down Expand Up @@ -229,6 +247,7 @@ func parseFields(obj any) ([]fieldInfo, error) {
value: v.Elem().FieldByIndex(ft.Index).Addr(),
isJSON: slices.Contains(parts[1:], "json"),
vtype: ft.Type,
missingOK: slices.Contains(parts[1:], "allowmissing"),
}
if !fi.isJSON {
if u := checkUnmarshal(fi.value); u != nil {
Expand Down
40 changes: 40 additions & 0 deletions client/setec/fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,46 @@ func TestFields(t *testing.T) {
}
}

func TestMissingFields(t *testing.T) {
db := setectest.NewDB(t, nil)
db.MustPut(db.Superuser, "int-val", "12345")

ss := setectest.NewServer(t, db, nil)
hs := httptest.NewServer(ss.Mux)
defer hs.Close()

st, err := setec.NewStore(context.Background(), setec.StoreConfig{
Client: setec.Client{Server: hs.URL, DoHTTP: hs.Client().Do},
AllowLookup: true,
Logf: logger.Discard,
})
if err != nil {
t.Fatalf("NewStore: %v", err)
}
defer st.Close()

type testStruct struct {
S setec.Secret `setec:"string-val,allowmissing"`
Z int `setec:"int-val,json"`
}

tf := testStruct{S: setec.StaticSecret("you do not see me"), Z: 9}
f, err := setec.ParseFields(&tf, "")
if err != nil {
t.Fatalf("ParseFields: unexpected error: %v", err)
}

if err := f.Apply(context.Background(), st); err != nil {
t.Errorf("Apply failed: %v", err)
}
if tf.Z != 12345 {
t.Errorf("Field Z: got %d, want 12345", tf.Z)
}
if got := string(tf.S.Get()); got != "" {
t.Errorf(`Field S: got %q, want ""`, got)
}
}

func TestParseErrors(t *testing.T) {
checkFail := func(input any, wantErr string) func(t *testing.T) {
return func(t *testing.T) {
Expand Down