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

Replace all remaining time.ParseDurations with parseutil.ParseDurationSeconds #21357

Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion builtin/credential/aws/path_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
"strings"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be good to remove this extra line?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, it was added by my IDE but it definitely doesn't look correct there, looking at the full file. I'll fix these!

"github.com/aws/aws-sdk-go/aws"
awsClient "github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/service/ec2"
Expand Down Expand Up @@ -1291,7 +1293,7 @@ func (b *backend) pathLoginRenewEc2(ctx context.Context, req *logical.Request, _
// If the login was made using the role tag, then max_ttl from tag
// is cached in internal data during login and used here to cap the
// max_ttl of renewal.
rTagMaxTTL, err := time.ParseDuration(req.Auth.Metadata["role_tag_max_ttl"])
rTagMaxTTL, err := parseutil.ParseDurationSecond(req.Auth.Metadata["role_tag_max_ttl"])
if err != nil {
return nil, err
}
Expand Down
4 changes: 3 additions & 1 deletion builtin/credential/aws/path_role_tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"strings"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/go-secure-stdlib/strutil"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/sdk/framework"
Expand Down Expand Up @@ -347,7 +349,7 @@ func (b *backend) parseAndVerifyRoleTagValue(ctx context.Context, s logical.Stor
return nil, err
}
case strings.HasPrefix(tagItem, "t="):
rTag.MaxTTL, err = time.ParseDuration(fmt.Sprintf("%ss", strings.TrimPrefix(tagItem, "t=")))
rTag.MaxTTL, err = parseutil.ParseDurationSecond(fmt.Sprintf("%ss", strings.TrimPrefix(tagItem, "t=")))
if err != nil {
return nil, err
}
Expand Down
6 changes: 4 additions & 2 deletions builtin/logical/aws/path_config_lease.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"fmt"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
Expand Down Expand Up @@ -82,12 +84,12 @@ func (b *backend) pathLeaseWrite(ctx context.Context, req *logical.Request, d *f
return logical.ErrorResponse("'lease_max' is a required parameter"), nil
}

lease, err := time.ParseDuration(leaseRaw)
lease, err := parseutil.ParseDurationSecond(leaseRaw)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Invalid lease: %s", err)), nil
}
leaseMax, err := time.ParseDuration(leaseMaxRaw)
leaseMax, err := parseutil.ParseDurationSecond(leaseMaxRaw)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Invalid lease_max: %s", err)), nil
Expand Down
4 changes: 3 additions & 1 deletion builtin/logical/pki/crl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"testing"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/vault/sdk/helper/testhelpers/schema"

"github.com/hashicorp/vault/api"
Expand Down Expand Up @@ -1068,7 +1070,7 @@ func TestAutoRebuild(t *testing.T) {
thisCRLNumber := getCRLNumber(t, crl)
requireSerialNumberInCRL(t, crl, leafSerial) // But the old one should.
now := time.Now()
graceInterval, _ := time.ParseDuration(gracePeriod)
graceInterval, _ := parseutil.ParseDurationSecond(gracePeriod)
expectedUpdate := lastCRLExpiry.Add(-1 * graceInterval)
if requireSerialNumberInCRL(nil, crl, newLeafSerial) {
// If we somehow lagged and we ended up needing to rebuild
Expand Down
10 changes: 6 additions & 4 deletions builtin/logical/pki/crl_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"sync"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

atomic2 "go.uber.org/atomic"

"github.com/hashicorp/vault/sdk/helper/certutil"
Expand Down Expand Up @@ -248,12 +250,12 @@ func (cb *crlBuilder) checkForAutoRebuild(sc *storageContext) error {
// the grace period and act accordingly.
now := time.Now()

period, err := time.ParseDuration(cfg.AutoRebuildGracePeriod)
period, err := parseutil.ParseDurationSecond(cfg.AutoRebuildGracePeriod)
if err != nil {
// This may occur if the duration is empty; in that case
// assume the default. The default should be valid and shouldn't
// error.
defaultPeriod, defaultErr := time.ParseDuration(defaultCrlConfig.AutoRebuildGracePeriod)
defaultPeriod, defaultErr := parseutil.ParseDurationSecond(defaultCrlConfig.AutoRebuildGracePeriod)
if defaultErr != nil {
return fmt.Errorf("error checking for auto-rebuild status: unable to parse duration from both config's grace period (%v) and default grace period (%v):\n- config: %v\n- default: %w\n", cfg.AutoRebuildGracePeriod, defaultCrlConfig.AutoRebuildGracePeriod, err, defaultErr)
}
Expand Down Expand Up @@ -436,7 +438,7 @@ func (cb *crlBuilder) rebuildDeltaCRLsIfForced(sc *storageContext, override bool
return nil, nil
}

deltaRebuildDuration, err := time.ParseDuration(cfg.DeltaRebuildInterval)
deltaRebuildDuration, err := parseutil.ParseDurationSecond(cfg.DeltaRebuildInterval)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -2118,7 +2120,7 @@ func augmentWithRevokedIssuers(issuerIDEntryMap map[issuerID]*issuerEntry, issue
func buildCRL(sc *storageContext, crlInfo *crlConfig, forceNew bool, thisIssuerId issuerID, revoked []pkix.RevokedCertificate, identifier crlID, crlNumber int64, isUnified bool, isDelta bool, lastCompleteNumber int64) (*time.Time, error) {
var revokedCerts []pkix.RevokedCertificate

crlLifetime, err := time.ParseDuration(crlInfo.Expiry)
crlLifetime, err := parseutil.ParseDurationSecond(crlInfo.Expiry)
if err != nil {
return nil, errutil.InternalError{Err: fmt.Sprintf("error parsing CRL duration of %s", crlInfo.Expiry)}
}
Expand Down
17 changes: 9 additions & 8 deletions builtin/logical/pki/path_config_crl.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import (
"context"
"fmt"
"net/http"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/vault/helper/constants"
"github.com/hashicorp/vault/sdk/framework"
Expand Down Expand Up @@ -291,7 +292,7 @@ func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *fra

if expiryRaw, ok := d.GetOk("expiry"); ok {
expiry := expiryRaw.(string)
_, err := time.ParseDuration(expiry)
_, err := parseutil.ParseDurationSecond(expiry)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("given expiry could not be decoded: %s", err)), nil
}
Expand All @@ -309,7 +310,7 @@ func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *fra

if expiryRaw, ok := d.GetOk("ocsp_expiry"); ok {
expiry := expiryRaw.(string)
duration, err := time.ParseDuration(expiry)
duration, err := parseutil.ParseDurationSecond(expiry)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("given ocsp_expiry could not be decoded: %s", err)), nil
}
Expand All @@ -326,7 +327,7 @@ func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *fra

if autoRebuildGracePeriodRaw, ok := d.GetOk("auto_rebuild_grace_period"); ok {
autoRebuildGracePeriod := autoRebuildGracePeriodRaw.(string)
if _, err := time.ParseDuration(autoRebuildGracePeriod); err != nil {
if _, err := parseutil.ParseDurationSecond(autoRebuildGracePeriod); err != nil {
return logical.ErrorResponse(fmt.Sprintf("given auto_rebuild_grace_period could not be decoded: %s", err)), nil
}
config.AutoRebuildGracePeriod = autoRebuildGracePeriod
Expand All @@ -339,7 +340,7 @@ func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *fra

if deltaRebuildIntervalRaw, ok := d.GetOk("delta_rebuild_interval"); ok {
deltaRebuildInterval := deltaRebuildIntervalRaw.(string)
if _, err := time.ParseDuration(deltaRebuildInterval); err != nil {
if _, err := parseutil.ParseDurationSecond(deltaRebuildInterval); err != nil {
return logical.ErrorResponse(fmt.Sprintf("given delta_rebuild_interval could not be decoded: %s", err)), nil
}
config.DeltaRebuildInterval = deltaRebuildInterval
Expand All @@ -362,16 +363,16 @@ func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *fra
return logical.ErrorResponse("unified_crl_on_existing_paths cannot be enabled if unified_crl is disabled"), nil
}

expiry, _ := time.ParseDuration(config.Expiry)
expiry, _ := parseutil.ParseDurationSecond(config.Expiry)
if config.AutoRebuild {
gracePeriod, _ := time.ParseDuration(config.AutoRebuildGracePeriod)
gracePeriod, _ := parseutil.ParseDurationSecond(config.AutoRebuildGracePeriod)
if gracePeriod >= expiry {
return logical.ErrorResponse(fmt.Sprintf("CRL auto-rebuilding grace period (%v) must be strictly shorter than CRL expiry (%v) value when auto-rebuilding of CRLs is enabled", config.AutoRebuildGracePeriod, config.Expiry)), nil
}
}

if config.EnableDelta {
deltaRebuildInterval, _ := time.ParseDuration(config.DeltaRebuildInterval)
deltaRebuildInterval, _ := parseutil.ParseDurationSecond(config.DeltaRebuildInterval)
if deltaRebuildInterval >= expiry {
return logical.ErrorResponse(fmt.Sprintf("CRL delta rebuild window (%v) must be strictly shorter than CRL expiry (%v) value when delta CRLs are enabled", config.DeltaRebuildInterval, config.Expiry)), nil
}
Expand Down
4 changes: 3 additions & 1 deletion builtin/logical/pki/path_ocsp.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
"strings"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/vault/sdk/helper/errutil"

"golang.org/x/crypto/ocsp"
Expand Down Expand Up @@ -476,7 +478,7 @@ func doesRequestMatchIssuer(parsedBundle *certutil.ParsedCertBundle, req *ocsp.R

func genResponse(cfg *crlConfig, caBundle *certutil.ParsedCertBundle, info *ocspRespInfo, reqHash crypto.Hash, revSigAlg x509.SignatureAlgorithm) ([]byte, error) {
curTime := time.Now()
duration, err := time.ParseDuration(cfg.OcspExpiry)
duration, err := parseutil.ParseDurationSecond(cfg.OcspExpiry)
if err != nil {
return nil, err
}
Expand Down
5 changes: 3 additions & 2 deletions builtin/logical/pki/path_ocsp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
"strconv"
"strings"
"testing"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/vault/sdk/helper/testhelpers/schema"

Expand Down Expand Up @@ -581,7 +582,7 @@ func runOcspRequestTest(t *testing.T, requestType string, caKeyType string, caKe
require.True(t, thisUpdate.Before(nextUpdate),
fmt.Sprintf("thisUpdate %s, should have been before nextUpdate: %s", thisUpdate, nextUpdate))
nextUpdateDiff := nextUpdate.Sub(thisUpdate)
expectedDiff, err := time.ParseDuration(defaultCrlConfig.OcspExpiry)
expectedDiff, err := parseutil.ParseDurationSecond(defaultCrlConfig.OcspExpiry)
require.NoError(t, err, "failed to parse default ocsp expiry value")
require.Equal(t, expectedDiff, nextUpdateDiff,
fmt.Sprintf("the delta between thisUpdate %s and nextUpdate: %s should have been around: %s but was %s",
Expand Down
6 changes: 4 additions & 2 deletions builtin/logical/pki/path_tidy.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"sync/atomic"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"

Expand Down Expand Up @@ -768,7 +770,7 @@ func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *fr

if pauseDurationStr != "" {
var err error
pauseDuration, err = time.ParseDuration(pauseDurationStr)
pauseDuration, err = parseutil.ParseDurationSecond(pauseDurationStr)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("Error parsing pause_duration: %v", err)), nil
}
Expand Down Expand Up @@ -1792,7 +1794,7 @@ func (b *backend) pathConfigAutoTidyWrite(ctx context.Context, req *logical.Requ
}

if pauseDurationRaw, ok := d.GetOk("pause_duration"); ok {
config.PauseDuration, err = time.ParseDuration(pauseDurationRaw.(string))
config.PauseDuration, err = parseutil.ParseDurationSecond(pauseDurationRaw.(string))
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("unable to parse given pause_duration: %v", err)), nil
}
Expand Down
3 changes: 3 additions & 0 deletions changelog/21357.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:bug
core: Fixed issue with some durations not being properly parsed to include days.
```
30 changes: 0 additions & 30 deletions command/base_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -989,33 +989,3 @@ func (d *timeValue) Get() interface{} { return *d.target }
func (d *timeValue) String() string { return (*d.target).String() }
func (d *timeValue) Example() string { return "time" }
func (d *timeValue) Hidden() bool { return d.hidden }

// -- helpers
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These three functions were unused. I found them as part of my search for time.ParseDuration, and thought it better to remove them.

func envDefault(key, def string) string {
if v, exist := os.LookupEnv(key); exist {
return v
}
return def
}

func envBoolDefault(key string, def bool) bool {
if v, exist := os.LookupEnv(key); exist {
b, err := strconv.ParseBool(v)
if err != nil {
panic(err)
}
return b
}
return def
}

func envDurationDefault(key string, def time.Duration) time.Duration {
if v, exist := os.LookupEnv(key); exist {
d, err := time.ParseDuration(v)
if err != nil {
panic(err)
}
return d
}
return def
}
12 changes: 7 additions & 5 deletions physical/raft/raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"sync/atomic"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/armon/go-metrics"
"github.com/golang/protobuf/proto"
log "github.com/hashicorp/go-hclog"
Expand Down Expand Up @@ -371,7 +373,7 @@ func NewRaftBackend(conf map[string]string, logger log.Logger) (physical.Backend
}

if delayRaw, ok := conf["apply_delay"]; ok {
delay, err := time.ParseDuration(delayRaw)
delay, err := parseutil.ParseDurationSecond(delayRaw)
if err != nil {
return nil, fmt.Errorf("apply_delay does not parse as a duration: %w", err)
}
Expand Down Expand Up @@ -428,7 +430,7 @@ func NewRaftBackend(conf map[string]string, logger log.Logger) (physical.Backend
}

if delayRaw, ok := conf["snapshot_delay"]; ok {
delay, err := time.ParseDuration(delayRaw)
delay, err := parseutil.ParseDurationSecond(delayRaw)
if err != nil {
return nil, fmt.Errorf("snapshot_delay does not parse as a duration: %w", err)
}
Expand All @@ -447,7 +449,7 @@ func NewRaftBackend(conf map[string]string, logger log.Logger) (physical.Backend

var reconcileInterval time.Duration
if interval := conf["autopilot_reconcile_interval"]; interval != "" {
interval, err := time.ParseDuration(interval)
interval, err := parseutil.ParseDurationSecond(interval)
if err != nil {
return nil, fmt.Errorf("autopilot_reconcile_interval does not parse as a duration: %w", err)
}
Expand All @@ -456,7 +458,7 @@ func NewRaftBackend(conf map[string]string, logger log.Logger) (physical.Backend

var updateInterval time.Duration
if interval := conf["autopilot_update_interval"]; interval != "" {
interval, err := time.ParseDuration(interval)
interval, err := parseutil.ParseDurationSecond(interval)
if err != nil {
return nil, fmt.Errorf("autopilot_update_interval does not parse as a duration: %w", err)
}
Expand Down Expand Up @@ -817,7 +819,7 @@ func (b *RaftBackend) applyConfigSettings(config *raft.Config) error {
snapshotIntervalRaw, ok := b.conf["snapshot_interval"]
if ok {
var err error
snapshotInterval, err := time.ParseDuration(snapshotIntervalRaw)
snapshotInterval, err := parseutil.ParseDurationSecond(snapshotIntervalRaw)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion physical/raft/raft_autopilot.go
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,7 @@ func (d *ReadableDuration) UnmarshalJSON(raw []byte) (err error) {
str := string(raw)
if len(str) >= 2 && str[0] == '"' && str[len(str)-1] == '"' {
// quoted string
dur, err = time.ParseDuration(str[1 : len(str)-1])
dur, err = parseutil.ParseDurationSecond(str[1 : len(str)-1])
if err != nil {
return err
}
Expand Down
4 changes: 3 additions & 1 deletion sdk/database/dbplugin/v5/testing/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"testing"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/vault/sdk/database/dbplugin/v5"
)

Expand All @@ -22,7 +24,7 @@ func getRequestTimeout(t *testing.T) time.Duration {
return 10 * time.Second
}

dur, err := time.ParseDuration(rawDur)
dur, err := parseutil.ParseDurationSecond(rawDur)
if err != nil {
t.Fatalf("Failed to parse custom request timeout %q: %s", rawDur, err)
}
Expand Down
4 changes: 3 additions & 1 deletion sdk/helper/identitytpl/templating.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"strings"
"time"

"github.com/hashicorp/go-secure-stdlib/parseutil"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/sdk/logical"
)
Expand Down Expand Up @@ -330,7 +332,7 @@ func performTemplating(input string, p *PopulateStringInput) (string, error) {
return "", errors.New("missing time operand")

case 3:
duration, err := time.ParseDuration(opsSplit[2])
duration, err := parseutil.ParseDurationSecond(opsSplit[2])
if err != nil {
return "", errwrap.Wrapf("invalid duration: {{err}}", err)
}
Expand Down
Loading