Fix some staticcheck findings (#1962)
Some checks failed
CI / Setup (push) Has been cancelled
CI / Verify doc-ui only PRs (push) Has been cancelled
CI / Run Go tests (push) Has been cancelled
CI / Run Go tests tagged with testonly (push) Has been cancelled
CI / Run Go tests with data race detection (push) Has been cancelled
CI / Test UI (push) Has been cancelled
CI / tests-completed (push) Has been cancelled
Run linters / Vulnerable dependencies (push) Has been cancelled
Run linters / Code checks (push) Has been cancelled
Run linters / Semgrep (push) Has been cancelled
Run linters / Go mod checks (push) Has been cancelled
Run linters / EL8 Go build checks (push) Has been cancelled
Run linters / Protobuf checks (push) Has been cancelled
CodeQL Advanced / Analyze (go) (push) Has been cancelled
Go Dependency Submission / go-dependency-submission (push) Has been cancelled
Mirror Repo / mirror (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled

* Remove long deprecated role statements fields

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Use tagged switches

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Remove embedded field access

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Simplify loops

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Fix yoda conditions

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Remove empty branches

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Use time.Since and time.Until instead of Add and Sub

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Apply De Morgan's laws to simplify conditions

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Simplify boolean expressions

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Remove dot import

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Remove duplicate imports

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Rely on type inference instead of explicit types

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Simplify various overly complicated string operations

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Various error improvements

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Various small improvements

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Fix copied lock

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Handle unhandled errors where necessary

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

* Output all lint findings

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>

---------

Signed-off-by: Tom Gehrke <tom.gehrke@sap.com>
This commit is contained in:
Tom Gehrke
2025-10-24 04:25:01 +02:00
committed by GitHub
parent 418ed1032a
commit 3dc698b37f
196 changed files with 820 additions and 1064 deletions

View File

@@ -9,3 +9,4 @@ linters:
- SA1019
issues:
max-issues-per-linter: 0
max-same-issues: 0

View File

@@ -10,3 +10,4 @@ formatters:
module-path: github.com/openbao/openbao
issues:
max-issues-per-linter: 0
max-same-issues: 0

View File

@@ -12,3 +12,4 @@ formatters:
module-path: github.com/openbao/openbao
issues:
max-issues-per-linter: 0
max-same-issues: 0

View File

@@ -15,6 +15,7 @@ import (
"net/http"
"net/url"
"path"
"slices"
"strconv"
"strings"
"sync"
@@ -1038,9 +1039,7 @@ func (c *Client) Headers() http.Header {
ret := make(http.Header)
for k, v := range c.headers {
for _, val := range v {
ret[k] = append(ret[k], val)
}
ret[k] = slices.Clone(v)
}
return ret

View File

@@ -281,7 +281,7 @@ func (r *LifetimeWatcher) doRenewWithOptions(tokenMode bool, nonRenewable bool,
}
var remainingLeaseDuration time.Duration
fallbackLeaseDuration := initialTime.Add(priorDuration).Sub(time.Now())
fallbackLeaseDuration := time.Until(initialTime.Add(priorDuration))
var renewal *Secret
var err error
@@ -305,7 +305,7 @@ func (r *LifetimeWatcher) doRenewWithOptions(tokenMode bool, nonRenewable bool,
}
// Calculate remaining duration until initial token lease expires
remainingLeaseDuration = initialTime.Add(time.Duration(initLeaseDuration) * time.Second).Sub(time.Now())
remainingLeaseDuration = time.Until(initialTime.Add(time.Duration(initLeaseDuration) * time.Second))
if errorBackoff == nil {
errorBackoff = &backoff.ExponentialBackOff{
MaxElapsedTime: remainingLeaseDuration,

View File

@@ -50,7 +50,7 @@ func (d *OutputStringError) CurlString() (string, error) {
}
func (d *OutputStringError) buildCurlString() (string, error) {
body, err := d.Request.BodyBytes()
body, err := d.BodyBytes()
if err != nil {
return "", err
}
@@ -60,8 +60,8 @@ func (d *OutputStringError) buildCurlString() (string, error) {
if d.TLSSkipVerify {
finalCurlString += "--insecure "
}
if d.Request.Method != http.MethodGet {
finalCurlString = fmt.Sprintf("%s-X %s ", finalCurlString, d.Request.Method)
if d.Method != http.MethodGet {
finalCurlString = fmt.Sprintf("%s-X %s ", finalCurlString, d.Method)
}
if d.ClientCACert != "" {
clientCACert := strings.ReplaceAll(d.ClientCACert, "'", "'\"'\"'")
@@ -79,7 +79,7 @@ func (d *OutputStringError) buildCurlString() (string, error) {
clientKey := strings.ReplaceAll(d.ClientKey, "'", "'\"'\"'")
finalCurlString = fmt.Sprintf("%s--key '%s' ", finalCurlString, clientKey)
}
for k, v := range d.Request.Header {
for k, v := range d.Header {
for _, h := range v {
if strings.ToLower(k) == "x-vault-token" {
h = `$(bao print token)`
@@ -95,5 +95,5 @@ func (d *OutputStringError) buildCurlString() (string, error) {
finalCurlString = fmt.Sprintf("%s-d '%s' ", finalCurlString, escapedBody)
}
return fmt.Sprintf("%s%s", finalCurlString, strconv.Quote(d.Request.URL.String())), nil
return fmt.Sprintf("%s%s", finalCurlString, strconv.Quote(d.URL.String())), nil
}

View File

@@ -77,13 +77,13 @@ func (r *Request) ToHTTP() (*http.Request, error) {
// No body
case r.BodyBytes != nil:
req.Request.Body = io.NopCloser(bytes.NewReader(r.BodyBytes))
req.Body = io.NopCloser(bytes.NewReader(r.BodyBytes))
default:
if c, ok := r.Body.(io.ReadCloser); ok {
req.Request.Body = c
req.Body = c
} else {
req.Request.Body = io.NopCloser(r.Body)
req.Body = io.NopCloser(r.Body)
}
}

View File

@@ -168,7 +168,7 @@ func (f *AuditFormatter) FormatRequest(ctx context.Context, w io.Writer, config
reqEntry.Time = time.Now().UTC().Format(time.RFC3339Nano)
}
return f.AuditFormatWriter.WriteRequest(w, reqEntry)
return f.WriteRequest(w, reqEntry)
}
func (f *AuditFormatter) FormatResponse(ctx context.Context, w io.Writer, config FormatterConfig, in *logical.LogInput) error {
@@ -390,7 +390,7 @@ func (f *AuditFormatter) FormatResponse(ctx context.Context, w io.Writer, config
respEntry.Time = time.Now().UTC().Format(time.RFC3339Nano)
}
return f.AuditFormatWriter.WriteResponse(w, respEntry)
return f.WriteResponse(w, respEntry)
}
// AuditRequestEntry is the structure of a request audit log entry in Audit.

View File

@@ -134,7 +134,7 @@ func TestFormatJSON_formatRequest(t *testing.T) {
expectedjson.Request.Namespace = &AuditNamespace{ID: "root"}
actualjson := new(AuditRequestEntry)
if err := jsonutil.DecodeJSON([]byte(buf.String())[len(tc.Prefix):], &actualjson); err != nil {
if err := jsonutil.DecodeJSON(buf.Bytes()[len(tc.Prefix):], &actualjson); err != nil {
t.Fatalf("bad json: %s", err)
}

View File

@@ -25,7 +25,7 @@ func createBackendWithStorage(t *testing.T) (*backend, logical.Storage) {
if b == nil {
t.Fatal("failed to create backend")
}
err = b.Backend.Setup(context.Background(), config)
err = b.Setup(context.Background(), config)
if err != nil {
t.Fatal(err)
}

View File

@@ -237,8 +237,8 @@ func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, dat
return logical.ErrorResponse("invalid role or secret ID"), nil
}
switch {
case entry.SecretIDNumUses == 0:
switch entry.SecretIDNumUses {
case 0:
//
// SecretIDNumUses will be zero only if the usage limit was not set at all,
// in which case, the SecretID will remain to be valid as long as it is not

View File

@@ -1660,8 +1660,8 @@ func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request
localSecretIDsRaw, ok := data.GetOk("local_secret_ids")
if ok {
switch {
case req.Operation == logical.CreateOperation:
switch req.Operation {
case logical.CreateOperation:
localSecretIDs := localSecretIDsRaw.(bool)
if localSecretIDs {
role.SecretIDPrefix = secretIDLocalPrefix
@@ -2524,10 +2524,7 @@ func (b *backend) pathRoleLocalSecretIDsRead(ctx context.Context, req *logical.R
return nil, nil
}
localSecretIDs := false
if role.SecretIDPrefix == secretIDLocalPrefix {
localSecretIDs = true
}
localSecretIDs := role.SecretIDPrefix == secretIDLocalPrefix
return &logical.Response{
Data: map[string]interface{}{

View File

@@ -715,7 +715,7 @@ func TestAppRole_RoleIDUniqueness(t *testing.T) {
roleReq.Path = "role/testrole2"
resp, err = b.HandleRequest(context.Background(), roleReq)
if err == nil && !(resp != nil && resp.IsError()) {
if err == nil && (resp == nil || !resp.IsError()) {
t.Fatalf("expected an error: got resp:%#v", resp)
}
@@ -725,14 +725,14 @@ func TestAppRole_RoleIDUniqueness(t *testing.T) {
roleReq.Operation = logical.UpdateOperation
roleData["role_id"] = "role-id-123"
resp, err = b.HandleRequest(context.Background(), roleReq)
if err == nil && !(resp != nil && resp.IsError()) {
if err == nil && (resp == nil || !resp.IsError()) {
t.Fatalf("expected an error: got resp:%#v", resp)
}
roleReq.Path = "role/testrole1"
roleData["role_id"] = "role-id-456"
resp, err = b.HandleRequest(context.Background(), roleReq)
if err == nil && !(resp != nil && resp.IsError()) {
if err == nil && (resp == nil || !resp.IsError()) {
t.Fatalf("expected an error: got resp:%#v", resp)
}
@@ -746,14 +746,14 @@ func TestAppRole_RoleIDUniqueness(t *testing.T) {
Data: roleIDData,
}
resp, err = b.HandleRequest(context.Background(), roleIDReq)
if err == nil && !(resp != nil && resp.IsError()) {
if err == nil && (resp == nil || !resp.IsError()) {
t.Fatalf("expected an error: got resp:%#v", resp)
}
roleIDData["role_id"] = "role-id-123"
roleIDReq.Path = "role/testrole2/role-id"
resp, err = b.HandleRequest(context.Background(), roleIDReq)
if err == nil && !(resp != nil && resp.IsError()) {
if err == nil && (resp == nil || !resp.IsError()) {
t.Fatalf("expected an error: got resp:%#v", resp)
}
@@ -1794,7 +1794,7 @@ func TestAppRole_RoleWithTokenTypeCRUD(t *testing.T) {
resp = b.requestNoErr(t, roleReq)
if 0 == len(resp.Warnings) {
if len(resp.Warnings) == 0 {
t.Fatalf("bad:\nexpected warning in resp:%#v\n", resp.Warnings)
}
@@ -1843,7 +1843,7 @@ func TestAppRole_RoleWithTokenTypeCRUD(t *testing.T) {
resp = b.requestNoErr(t, roleReq)
if 0 == len(resp.Warnings) {
if len(resp.Warnings) == 0 {
t.Fatalf("bad:\nexpected a warning in resp:%#v\n", resp.Warnings)
}

View File

@@ -115,8 +115,8 @@ func TestAppRole_TidyDanglingAccessors_RaceTest(t *testing.T) {
wg := &sync.WaitGroup{}
start := time.Now()
for time.Now().Sub(start) < 10*time.Second {
if time.Now().Sub(start) > 100*time.Millisecond && atomic.LoadUint32(b.tidySecretIDCASGuard) == 0 {
for time.Since(start) < 10*time.Second {
if time.Since(start) > 100*time.Millisecond && atomic.LoadUint32(b.tidySecretIDCASGuard) == 0 {
secret, err := b.tidySecretID(context.Background(), &logical.Request{
Storage: storage,
})

View File

@@ -331,7 +331,7 @@ func fetchAuthURL(c *api.Client, role, mount, callbackPort string, callbackMetho
}
if authURL == "" {
return "", "", nil, fmt.Errorf("Unable to authorize role %q with redirect_uri %q. Check OpenBao logs for more information.", role, redirectURI)
return "", "", nil, fmt.Errorf("Unable to authorize role %q with redirect_uri %q. Check OpenBao logs for more information.", role, redirectURI) //nolint:staticcheck // user-facing error
}
return authURL, clientNonce, secret, nil

View File

@@ -815,7 +815,7 @@ func TestConfig_CAContext_MismatchedHost(t *testing.T) {
for name, test := range tests {
t.Run(name, func(t *testing.T) {
config, err, caPEM := getCertificate(test.nameInCertificate)
config, caPEM, err := getCertificate(test.nameInCertificate)
require.NoError(t, err)
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello")
@@ -835,7 +835,7 @@ func TestConfig_CAContext_MismatchedHost(t *testing.T) {
rootCAString := ""
if test.addRootCA {
rootCAString = string(caPEM.Bytes())
rootCAString = caPEM.String()
}
caCtx, err := b.createCAContext(ctx, rootCAString, test.allowedServerNames)
@@ -859,7 +859,7 @@ func TestConfig_CAContext_MismatchedHost(t *testing.T) {
}
}
func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPEM *bytes.Buffer) {
func getCertificate(hostname string) (serverTLSConf *tls.Config, caPEM *bytes.Buffer, err error) {
ca := &x509.Certificate{
SerialNumber: big.NewInt(2019),
Subject: pkix.Name{
@@ -881,12 +881,12 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
caPrivKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &caPrivKey.PublicKey, caPrivKey)
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
caPEM = new(bytes.Buffer)
@@ -895,7 +895,7 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
Bytes: caBytes,
})
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
caPrivKeyPEM := new(bytes.Buffer)
@@ -904,7 +904,7 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
Bytes: x509.MarshalPKCS1PrivateKey(caPrivKey),
})
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
cert := &x509.Certificate{
@@ -927,12 +927,12 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
certPrivKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
certBytes, err := x509.CreateCertificate(rand.Reader, cert, ca, &certPrivKey.PublicKey, caPrivKey)
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
certPEM := new(bytes.Buffer)
@@ -941,7 +941,7 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
Bytes: certBytes,
})
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
certPrivKeyPEM := new(bytes.Buffer)
@@ -950,12 +950,12 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
Bytes: x509.MarshalPKCS1PrivateKey(certPrivKey),
})
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
serverCert, err := tls.X509KeyPair(certPEM.Bytes(), certPrivKeyPEM.Bytes())
if err != nil {
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
serverTLSConf = &tls.Config{
@@ -963,7 +963,7 @@ func getCertificate(hostname string) (serverTLSConf *tls.Config, err error, caPE
ServerName: hostname,
}
return serverTLSConf, err, caPEM
return serverTLSConf, caPEM, err
}
const (

View File

@@ -557,7 +557,7 @@ func (b *jwtAuthBackend) pathPoll(ctx context.Context, req *logical.Request, d *
// already been unmarshalled once, unlikely
return nil, err
}
oauth2Token := tokenOrError.Token.WithExtra(extra)
oauth2Token := tokenOrError.WithExtra(extra)
// idToken, ok := oauth2Token.Extra("id_token").(oidc.IDToken)
rawToken, ok := oauth2Token.Extra("id_token").(string)

View File

@@ -727,11 +727,12 @@ func TestOIDC_Callback(t *testing.T) {
var useBoundCIDRs bool
callbackMode := "client"
if i == 2 {
switch i {
case 2:
useBoundCIDRs = true
} else if i == 3 {
case 3:
callbackMode = "direct"
} else if i == 4 {
case 4:
callbackMode = "device"
}
@@ -1427,7 +1428,7 @@ func (o *oidcProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Write([]byte(strings.Replace(`
_, err := w.Write([]byte(strings.ReplaceAll(`
{
"issuer": "%s",
"authorization_endpoint": "%s/auth",
@@ -1435,14 +1436,23 @@ func (o *oidcProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
"token_endpoint": "%s/token",
"jwks_uri": "%s/certs",
"userinfo_endpoint": "%s/userinfo"
}`, "%s", o.server.URL, -1)))
}`, "%s", o.server.URL)))
if err != nil {
o.t.Fatal(err)
}
case "/certs":
a := getTestJWKS(o.t, ecdsaPubKey)
w.Write(a)
_, err := w.Write(a)
if err != nil {
o.t.Fatal(err)
}
case "/certs_missing":
w.WriteHeader(404)
case "/certs_invalid":
w.Write([]byte("It's not a keyset!"))
_, err := w.Write([]byte("It's not a keyset!"))
if err != nil {
o.t.Fatal(err)
}
case "/device":
values := map[string]interface{}{
"device_code": o.code,
@@ -1451,7 +1461,10 @@ func (o *oidcProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err != nil {
o.t.Fatal(err)
}
w.Write(data)
_, err = w.Write(data)
if err != nil {
o.t.Fatal(err)
}
case "/token":
var code string
grant_type := r.FormValue("grant_type")
@@ -1485,21 +1498,26 @@ func (o *oidcProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Audience: jwt.Audience{o.clientID},
}
jwtData, _ := getTestJWT(o.t, ecdsaPrivKey, stdClaims, o.customClaims)
w.Write([]byte(fmt.Sprintf(`
_, err := fmt.Fprintf(w, `
{
"access_token":"%s",
"id_token":"%s"
}`,
jwtData,
jwtData,
)))
jwtData)
if err != nil {
o.t.Fatal(err)
}
case "/userinfo":
w.Write([]byte(`
_, err := w.Write([]byte(`
{
"sub": "r3qXcK2bix9eFECzsU3Sbmh0K16fatW6@clients",
"color":"red",
"temperature":"76"
}`))
if err != nil {
o.t.Fatal(err)
}
default:
o.t.Fatalf("unexpected path: %q", r.URL.Path)

View File

@@ -119,10 +119,11 @@ func (a *AzureProvider) getClaimSource(logger log.Logger, allClaims map[string]i
// - https://developer.microsoft.com/en-us/office/blogs/microsoft-graph-or-azure-ad-graph/
// - https://docs.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0
// - https://docs.microsoft.com/en-us/graph/migrate-azure-ad-graph-request-differences
if urlParsed.Host == azureADGraphHost {
switch urlParsed.Host {
case azureADGraphHost:
urlParsed.Host = microsoftGraphHost
urlParsed.Path = microsoftGraphAPIVersion + urlParsed.Path
} else if urlParsed.Host == azureADGraphUShost {
case azureADGraphUShost:
urlParsed.Host = microsoftGraphUSHost
urlParsed.Path = microsoftGraphAPIVersion + urlParsed.Path
}

View File

@@ -38,20 +38,26 @@ func (a *azureServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Write([]byte(strings.Replace(`
_, err := w.Write([]byte(strings.ReplaceAll(`
{
"issuer": "%s",
"authorization_endpoint": "%s/auth",
"token_endpoint": "%s/oauth2/v2.0/token",
"jwks_uri": "%s/certs",
"userinfo_endpoint": "%s/userinfo"
}`, "%s", a.server.URL, -1)))
}`, "%s", a.server.URL)))
if err != nil {
a.t.Fatal(err)
}
case "/getMemberObjects":
groups := azureGroups{
Value: []interface{}{"group1", "group2"},
}
gBytes, _ := json.Marshal(groups)
w.Write(gBytes)
_, err := w.Write(gBytes)
if err != nil {
a.t.Fatal(err)
}
default:
a.t.Fatalf("unexpected path: %q", r.URL.Path)
}

View File

@@ -36,14 +36,17 @@ func (a *ibmisamServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Write([]byte(strings.Replace(`
_, err := w.Write([]byte(strings.ReplaceAll(`
{
"issuer": "%s",
"authorization_endpoint": "%s/auth",
"token_endpoint": "%s/oauth2/v2.0/token",
"jwks_uri": "%s/certs",
"userinfo_endpoint": "%s/userinfo"
}`, "%s", a.server.URL, -1)))
}`, "%s", a.server.URL)))
if err != nil {
a.t.Fatal(err)
}
default:
a.t.Fatalf("unexpected path: %q", r.URL.Path)
}

View File

@@ -36,14 +36,17 @@ func (a *secureauthServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Write([]byte(strings.Replace(`
_, err := w.Write([]byte(strings.ReplaceAll(`
{
"issuer": "%s",
"authorization_endpoint": "%s/auth",
"token_endpoint": "%s/oauth2/v2.0/token",
"jwks_uri": "%s/certs",
"userinfo_endpoint": "%s/userinfo"
}`, "%s", a.server.URL, -1)))
}`, "%s", a.server.URL)))
if err != nil {
a.t.Fatal(err)
}
default:
a.t.Fatalf("unexpected path: %q", r.URL.Path)
}

View File

@@ -140,7 +140,7 @@ func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, d *
identity, ok = raw.(goidentity.Identity)
if !ok {
w.WriteHeader(400)
_, _ = w.Write([]byte(fmt.Sprintf("identity credentials are malformed: %+v", raw)))
_, _ = fmt.Fprintf(w, "identity credentials are malformed: %+v", raw)
return
}
b.Logger().Debug(fmt.Sprintf("identity: %+v", identity))
@@ -160,9 +160,9 @@ func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, d *
// config's realm and the Kerberos realm. In such a case, it prevents a user from
// passing Kerberos authentication, and then extracting group membership, and
// therefore policies, from a separate directory.
if ldapCfg.ConfigEntry.UPNDomain != "" && identity.Domain() != ldapCfg.ConfigEntry.UPNDomain {
if ldapCfg.UPNDomain != "" && identity.Domain() != ldapCfg.UPNDomain {
w.WriteHeader(400)
_, _ = w.Write([]byte(fmt.Sprintf("identity domain of %q doesn't match LDAP upndomain of %q", identity.Domain(), ldapCfg.ConfigEntry.UPNDomain)))
_, _ = fmt.Fprintf(w, "identity domain of %q doesn't match LDAP upndomain of %q", identity.Domain(), ldapCfg.UPNDomain)
return
}
authenticated = true

View File

@@ -35,7 +35,7 @@ func createBackendWithStorage(t *testing.T) (*backend, logical.Storage) {
t.Fatal("failed to create backend")
}
err := b.Backend.Setup(context.Background(), config)
err := b.Setup(context.Background(), config)
if err != nil {
t.Fatal(err)
}

View File

@@ -13,7 +13,7 @@ import (
"time"
"layeh.com/radius"
. "layeh.com/radius/rfc2865"
"layeh.com/radius/rfc2865"
"github.com/openbao/openbao/sdk/v2/framework"
"github.com/openbao/openbao/sdk/v2/helper/cidrutil"
@@ -204,10 +204,19 @@ func (b *backend) RadiusLogin(ctx context.Context, req *logical.Request, usernam
hostport := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
packet := radius.New(radius.CodeAccessRequest, []byte(cfg.Secret))
UserName_SetString(packet, username)
UserPassword_SetString(packet, password)
err = rfc2865.UserName_SetString(packet, username)
if err != nil {
return nil, nil, err
}
err = rfc2865.UserPassword_SetString(packet, password)
if err != nil {
return nil, nil, err
}
if cfg.NasIdentifier != "" {
NASIdentifier_AddString(packet, cfg.NasIdentifier)
err = rfc2865.NASIdentifier_AddString(packet, cfg.NasIdentifier)
if err != nil {
return nil, nil, err
}
}
packet.Add(5, radius.NewInteger(uint32(cfg.NasPort)))

View File

@@ -29,7 +29,7 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string, nonInteractive boo
if x, ok := m["lookup"]; ok {
parsed, err := strconv.ParseBool(x)
if err != nil {
return nil, fmt.Errorf("Failed to parse \"lookup\" as boolean: %w", err)
return nil, fmt.Errorf("Failed to parse \"lookup\" as boolean: %w", err) //nolint:staticcheck // user-facing error
}
lookup = parsed
}
@@ -58,6 +58,7 @@ func (h *CLIHandler) Auth(c *api.Client, m map[string]string, nonInteractive boo
return nil, errors.New("user interrupted")
}
//nolint:staticcheck // user-facing error
return nil, fmt.Errorf("An error occurred attempting to "+
"ask for a token. The raw error message is shown below, but usually "+
"this is because you attempted to pipe a value into the command or "+

View File

@@ -11,7 +11,6 @@ import (
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/openbao/openbao/sdk/v2/database/dbplugin/v5"
v5 "github.com/openbao/openbao/sdk/v2/database/dbplugin/v5"
"github.com/openbao/openbao/sdk/v2/framework"
"github.com/openbao/openbao/sdk/v2/logical"
)
@@ -125,15 +124,15 @@ func (b *databaseBackend) pathCredsCreateRead() framework.OperationFunc {
// to ensure the database credential does not expire before the lease
expiration = expiration.Add(5 * time.Second)
newUserReq := v5.NewUserRequest{
UsernameConfig: v5.UsernameMetadata{
newUserReq := dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: req.DisplayName,
RoleName: name,
},
Statements: v5.Statements{
Statements: dbplugin.Statements{
Commands: role.Statements.Creation,
},
RollbackStatements: v5.Statements{
RollbackStatements: dbplugin.Statements{
Commands: role.Statements.Rollback,
},
Expiration: expiration,
@@ -143,7 +142,7 @@ func (b *databaseBackend) pathCredsCreateRead() framework.OperationFunc {
// Generate the credential based on the role's credential type
switch role.CredentialType {
case v5.CredentialTypePassword:
case dbplugin.CredentialTypePassword:
generator, err := newPasswordGenerator(role.CredentialConfig)
if err != nil {
return nil, fmt.Errorf("failed to construct credential generator: %s", err)
@@ -162,10 +161,10 @@ func (b *databaseBackend) pathCredsCreateRead() framework.OperationFunc {
}
// Set input credential
newUserReq.CredentialType = v5.CredentialTypePassword
newUserReq.CredentialType = dbplugin.CredentialTypePassword
newUserReq.Password = password
case v5.CredentialTypeRSAPrivateKey:
case dbplugin.CredentialTypeRSAPrivateKey:
generator, err := newRSAKeyGenerator(role.CredentialConfig)
if err != nil {
return nil, fmt.Errorf("failed to construct credential generator: %s", err)
@@ -178,12 +177,12 @@ func (b *databaseBackend) pathCredsCreateRead() framework.OperationFunc {
}
// Set input credential
newUserReq.CredentialType = v5.CredentialTypeRSAPrivateKey
newUserReq.CredentialType = dbplugin.CredentialTypeRSAPrivateKey
newUserReq.PublicKey = public
// Set output credential
respData["rsa_private_key"] = string(private)
case v5.CredentialTypeClientCertificate:
case dbplugin.CredentialTypeClientCertificate:
generator, err := newClientCertificateGenerator(role.CredentialConfig)
if err != nil {
return nil, fmt.Errorf("failed to construct credential generator: %s", err)
@@ -217,7 +216,7 @@ func (b *databaseBackend) pathCredsCreateRead() framework.OperationFunc {
// Database plugins using the v4 interface generate and return the password.
// Set the password response to what is returned by the NewUser request.
if role.CredentialType == v5.CredentialTypePassword {
if role.CredentialType == dbplugin.CredentialTypePassword {
respData["password"] = password
}
@@ -276,9 +275,9 @@ func (b *databaseBackend) pathStaticCredsRead() framework.OperationFunc {
}
switch role.CredentialType {
case v5.CredentialTypePassword:
case dbplugin.CredentialTypePassword:
respData["password"] = role.StaticAccount.Password
case v5.CredentialTypeRSAPrivateKey:
case dbplugin.CredentialTypeRSAPrivateKey:
respData["rsa_private_key"] = string(role.StaticAccount.PrivateKey)
}

View File

@@ -506,12 +506,6 @@ func (b *databaseBackend) pathRoleCreateUpdate(ctx context.Context, req *logical
} else if createOperation {
role.Statements.Renewal = data.Get("renew_statements").([]string)
}
// Do not persist deprecated statements that are populated on role read
role.Statements.CreationStatements = ""
role.Statements.RevocationStatements = ""
role.Statements.RenewStatements = ""
role.Statements.RollbackStatements = ""
}
role.Statements.Revocation = strutil.RemoveEmpty(role.Statements.Revocation)

View File

@@ -828,18 +828,18 @@ func testBackend_StaticRole_Rotations(t *testing.T, createUser userCreator, opts
if len(v) < 3 {
t.Fatalf("expected to find 3 passwords for (%s), only found (%d)", k, len(v))
}
switch {
case k == "plugin-static-role-10":
switch k {
case "plugin-static-role-10":
// expect all passwords to be different
if v[0] == v[1] || v[1] == v[2] || v[0] == v[2] {
pass = false
}
case k == "plugin-static-role-20":
case "plugin-static-role-20":
// expect the first two to be equal, but different from the third
if v[0] != v[1] || v[0] == v[2] {
pass = false
}
case k == "plugin-static-role-100":
case "plugin-static-role-100":
// expect all passwords to be equal
if v[0] != v[1] || v[1] != v[2] {
pass = false

View File

@@ -12,7 +12,6 @@ import (
authenticationv1 "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -40,7 +39,7 @@ func newClient(config *kubeConfig) (*client, error) {
BearerToken: config.ServiceAccountJwt,
}
if config.CACert != "" {
clientConfig.TLSClientConfig.CAData = []byte(config.CACert)
clientConfig.CAData = []byte(config.CACert)
}
k8sClient, err := kubernetes.NewForConfig(&clientConfig)
if err != nil {
@@ -65,7 +64,7 @@ func (c *client) createToken(ctx context.Context, namespace, name string, ttl ti
return &resp.Status, nil
}
func (c *client) createServiceAccount(ctx context.Context, namespace, name string, vaultRole *roleEntry, ownerRef metav1.OwnerReference) (*v1.ServiceAccount, error) {
func (c *client) createServiceAccount(ctx context.Context, namespace, name string, vaultRole *roleEntry, ownerRef metav1.OwnerReference) (*corev1.ServiceAccount, error) {
// Set standardLabels last so that users can't override them
labels := combineMaps(vaultRole.ExtraLabels, standardLabels)
serviceAccountConfig := &corev1.ServiceAccount{

View File

@@ -39,7 +39,7 @@ func newK8sClient(t *testing.T, token string) kubernetes.Interface {
Host: os.Getenv("KUBE_HOST"),
BearerToken: token,
}
config.TLSClientConfig.CAData = append(config.TLSClientConfig.CAData, []byte(os.Getenv("KUBERNETES_CA"))...)
config.CAData = append(config.CAData, []byte(os.Getenv("KUBERNETES_CA"))...)
client, err := kubernetes.NewForConfig(&config)
if err != nil {

View File

@@ -45,10 +45,7 @@ const (
// IsDeleteVersionAfterDisabled returns true if DeleteVersionAfter is
// disabled.
func (c *Configuration) IsDeleteVersionAfterDisabled() bool {
if deleteVersionAfter(c) == disabled {
return true
}
return false
return deleteVersionAfter(c) == disabled
}
// DisableDeleteVersionAfter disables DeleteVersionAfter.

View File

@@ -101,7 +101,7 @@ func TestPassthroughBackend_Read(t *testing.T) {
// What comes back if an int is passed in is a json.Number which is
// actually aliased as a string so to make the deep equal happy if it's
// actually a number we set it to an int64
var respTTL interface{} = resp.Data[ttlType]
respTTL := resp.Data[ttlType]
_, ok := respTTL.(json.Number)
if ok {
respTTL, err = respTTL.(json.Number).Int64()

View File

@@ -210,7 +210,7 @@ func TestVersionedKV_Data_Put_ZeroCas(t *testing.T) {
expectedSubStr := "check-and-set parameter did not match"
if errorMsg, ok := resp.Data["error"]; !(ok && strings.Contains(errorMsg.(string), expectedSubStr)) {
if errorMsg, ok := resp.Data["error"]; !ok || !strings.Contains(errorMsg.(string), expectedSubStr) {
t.Fatalf("expected check-and-set validation error, resp: %#v\n", resp)
}
}
@@ -745,7 +745,7 @@ func TestVersionedKV_Patch_CASValidation(t *testing.T) {
expectedSubStr := "check-and-set parameter required for this call"
if errorMsg, ok := resp.Data["error"]; !(ok && strings.Contains(errorMsg.(string), expectedSubStr)) {
if errorMsg, ok := resp.Data["error"]; !ok || !strings.Contains(errorMsg.(string), expectedSubStr) {
t.Fatalf("expected check-and-set validation error, resp: %#v\n", resp)
}
@@ -774,7 +774,7 @@ func TestVersionedKV_Patch_CASValidation(t *testing.T) {
expectedSubStr = "check-and-set parameter did not match"
if errorMsg, ok := resp.Data["error"]; !(ok && strings.Contains(errorMsg.(string), expectedSubStr)) {
if errorMsg, ok := resp.Data["error"]; !ok || !strings.Contains(errorMsg.(string), expectedSubStr) {
t.Fatalf("expected check-and-set validation error, resp: %#v\n", resp)
}
}

View File

@@ -395,7 +395,7 @@ func validateCustomMetadata(customMetadata map[string]string) error {
// Perform validation on each key and value and return ALL errors
for key, value := range customMetadata {
if keyLen := len(key); 0 == keyLen || keyLen > maxCustomMetadataKeyLength {
if keyLen := len(key); keyLen == 0 || keyLen > maxCustomMetadataKeyLength {
errs = multierror.Append(errs, fmt.Errorf("%s: length of key %q is %d but must be 0 < len(key) <= %d",
customMetadataValidationErrorPrefix,
key,
@@ -403,7 +403,7 @@ func validateCustomMetadata(customMetadata map[string]string) error {
maxCustomMetadataKeyLength))
}
if valueLen := len(value); 0 == valueLen || valueLen > maxCustomMetadataValueLength {
if valueLen := len(value); valueLen == 0 || valueLen > maxCustomMetadataValueLength {
errs = multierror.Append(errs, fmt.Errorf("%s: length of value for key %q is %d but must be 0 < len(value) <= %d",
customMetadataValidationErrorPrefix,
key,

View File

@@ -64,11 +64,7 @@ func TestVersionedKV_Upgrade(t *testing.T) {
}
// wait for upgrade to finish
for {
if atomic.LoadUint32(b.(*versionedKVBackend).upgrading) == 0 {
break
}
for atomic.LoadUint32(b.(*versionedKVBackend).upgrading) != 0 {
time.Sleep(time.Second)
}

View File

@@ -404,7 +404,7 @@ func ListSets(b logical.Backend, s logical.Storage) func(t *testing.T) {
if len(listedKeys) != 1 {
t.Fatalf("expected 1 key but received %s", listedKeys)
}
if "test-set" != listedKeys[0] {
if listedKeys[0] != "test-set" {
t.Fatal("expected test-set to be the only listed item")
}
}

View File

@@ -430,7 +430,7 @@ func (s *staticAccount) NextRotationTime() time.Time {
// be invalidated.
func (s *staticAccount) PasswordTTL() time.Duration {
next := s.NextRotationTime()
ttl := next.Sub(time.Now()).Round(time.Second)
ttl := time.Until(next).Round(time.Second)
if ttl < 0 {
ttl = time.Duration(0)
}

View File

@@ -392,7 +392,7 @@ func ValidateTLSALPN01Challenge(domain string, token string, thumbprint string,
// Remove the handled critical extension and validate that we
// have no additional critical extensions left unhandled.
var index int = -1
index := -1
for oidIndex, oid := range cert.UnhandledCriticalExtensions {
if oid.Equal(OIDACMEIdentifier) {
index = oidIndex

View File

@@ -126,7 +126,7 @@ func TestAcmeValidateHTTP01Challenge(t *testing.T) {
}
withRedirect := func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/.well-known/") {
http.Redirect(w, r, "/my-http-01-challenge-response", 301)
http.Redirect(w, r, "/my-http-01-challenge-response", http.StatusMovedPermanently)
return
}
@@ -165,10 +165,10 @@ func TestAcmeValidateHTTP01Challenge(t *testing.T) {
// Negative test cases for various HTTP-specific scenarios.
redirectLoop := func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/my-http-01-challenge-response", 301)
http.Redirect(w, r, "/my-http-01-challenge-response", http.StatusMovedPermanently)
}
publicRedirect := func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://hashicorp.com/", 301)
http.Redirect(w, r, "http://hashicorp.com/", http.StatusMovedPermanently)
}
noData := func(w http.ResponseWriter, r *http.Request) {}
noContent := func(w http.ResponseWriter, r *http.Request) {
@@ -254,10 +254,10 @@ func TestAcmeValidateTLSALPN01Challenge(t *testing.T) {
tlsCfg := &tls.Config{}
tlsCfg.GetConfigForClient = func(*tls.ClientHelloInfo) (*tls.Config, error) {
var retCfg tls.Config = *tlsCfg
retCfg := tlsCfg.Clone()
retCfg.NextProtos = returnedProtocols
log.Info(fmt.Sprintf("[alpn-server] returned protocol: %v", returnedProtocols))
return &retCfg, nil
return retCfg, nil
}
tlsCfg.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
var ret tls.Certificate
@@ -740,7 +740,7 @@ func TestAcmeValidateHttp01TLSRedirect(t *testing.T) {
// Set up a http server that will redirect to our TLS server
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, tlsTs.URL+r.URL.Path, 301)
http.Redirect(w, r, tlsTs.URL+r.URL.Path, http.StatusMovedPermanently)
}))
defer ts.Close()

View File

@@ -142,7 +142,7 @@ func (e *ErrorResponse) Marshal() (*logical.Response, error) {
return &resp, nil
}
func FindType(given error) (err error, id string, code int, found bool) {
func FindType(given error) (id string, code int, found bool, err error) {
matchedError := false
for err, id = range errIdMappings {
if errors.Is(given, err) {
@@ -160,7 +160,7 @@ func FindType(given error) (err error, id string, code int, found bool) {
code = errCodeMappings[err]
return err, id, code, found
return id, code, found, err
}
func TranslateError(given error) (*logical.Response, error) {
@@ -187,7 +187,7 @@ func TranslateErrorToErrorResponse(given error) ErrorResponse {
given = unwrapped.Errors[0]
}
_, id, code, found := FindType(given)
id, code, found, _ := FindType(given)
if !found && len(remaining) > 0 {
// Translate multierrors into a generic error code.
id = errIdMappings[ErrCompound]
@@ -200,7 +200,7 @@ func TranslateErrorToErrorResponse(given error) ErrorResponse {
body.StatusCode = code
for _, subgiven := range remaining {
_, subid, _, _ := FindType(subgiven)
subid, _, _, _ := FindType(subgiven)
var sub ErrorResponse
sub.Type = ErrorPrefix + subid

View File

@@ -460,12 +460,5 @@ func isAcmeDisabled(sc *storageContext, config *acmeConfigEntry, policy EabPolic
}
// The OS environment if true will override any configuration option.
if disableAcme {
if policy.OverrideEnvDisablingPublicAcme() {
return false
}
return true
}
return false
return disableAcme && !policy.OverrideEnvDisablingPublicAcme()
}

View File

@@ -6,7 +6,7 @@ package pki
import (
"context"
"fmt"
"sort"
"slices"
"strings"
"sync"
"sync/atomic"
@@ -227,9 +227,7 @@ func Backend(conf *logical.BackendConfig) *backend {
acmePaths = append(acmePaths, pathAcmeRevoke(&b)...)
acmePaths = append(acmePaths, pathAcmeNewEab(&b)...) // auth'd API that lives underneath the various /acme paths
for _, acmePath := range acmePaths {
b.Backend.Paths = append(b.Backend.Paths, acmePath)
}
b.Paths = append(b.Paths, acmePaths...)
// Add specific un-auth'd paths for ACME APIs
for _, acmePrefix := range []string{"", "issuer/+/", "roles/+/", "issuer/+/roles/+/"} {
@@ -632,11 +630,11 @@ func (b *backend) periodicFunc(ctx context.Context, request *logical.Request) er
var errors error
if crlErr != nil {
errors = multierror.Append(errors, fmt.Errorf("Error building CRLs:\n - %w\n", crlErr))
errors = multierror.Append(errors, fmt.Errorf("error building CRLs: %w", crlErr))
}
if tidyErr != nil {
errors = multierror.Append(errors, fmt.Errorf("Error running auto-tidy:\n - %w\n", tidyErr))
errors = multierror.Append(errors, fmt.Errorf("error running auto-tidy: %w", tidyErr))
}
if errors != nil {
@@ -669,7 +667,7 @@ func (b *backend) initializeStoredCertificateCounts(ctx context.Context) error {
b.certCountEnabled.Store(config.MaintainCount)
b.publishCertCountMetrics.Store(config.PublishMetrics)
if config.MaintainCount == false {
if !config.MaintainCount {
b.possibleDoubleCountedRevokedSerials = nil
b.possibleDoubleCountedSerials = nil
b.certsCounted.Store(true)
@@ -707,28 +705,16 @@ func (b *backend) initializeStoredCertificateCounts(ctx context.Context) error {
// there may be some delay here.
// Sort the listed-entries first, to accommodate that delay.
sort.Slice(entries, func(i, j int) bool {
return entries[i] < entries[j]
})
slices.Sort(entries)
sort.Slice(revokedEntries, func(i, j int) bool {
return revokedEntries[i] < revokedEntries[j]
})
slices.Sort(revokedEntries)
// We assume here that these lists are now complete.
sort.Slice(b.possibleDoubleCountedSerials, func(i, j int) bool {
return b.possibleDoubleCountedSerials[i] < b.possibleDoubleCountedSerials[j]
})
slices.Sort(b.possibleDoubleCountedSerials)
listEntriesIndex := 0
possibleDoubleCountIndex := 0
for {
if listEntriesIndex >= len(entries) {
break
}
if possibleDoubleCountIndex >= len(b.possibleDoubleCountedSerials) {
break
}
for listEntriesIndex < len(entries) && possibleDoubleCountIndex < len(b.possibleDoubleCountedSerials) {
if entries[listEntriesIndex] == b.possibleDoubleCountedSerials[possibleDoubleCountIndex] {
// This represents a double-counted entry
b.decrementTotalCertificatesCountNoReport()
@@ -746,19 +732,11 @@ func (b *backend) initializeStoredCertificateCounts(ctx context.Context) error {
}
}
sort.Slice(b.possibleDoubleCountedRevokedSerials, func(i, j int) bool {
return b.possibleDoubleCountedRevokedSerials[i] < b.possibleDoubleCountedRevokedSerials[j]
})
slices.Sort(b.possibleDoubleCountedRevokedSerials)
listRevokedEntriesIndex := 0
possibleRevokedDoubleCountIndex := 0
for {
if listRevokedEntriesIndex >= len(revokedEntries) {
break
}
if possibleRevokedDoubleCountIndex >= len(b.possibleDoubleCountedRevokedSerials) {
break
}
for listRevokedEntriesIndex < len(revokedEntries) && possibleRevokedDoubleCountIndex < len(b.possibleDoubleCountedRevokedSerials) {
if revokedEntries[listRevokedEntriesIndex] == b.possibleDoubleCountedRevokedSerials[possibleRevokedDoubleCountIndex] {
// This represents a double-counted revoked entry
b.decrementTotalRevokedCertificatesCountNoReport()
@@ -787,7 +765,7 @@ func (b *backend) initializeStoredCertificateCounts(ctx context.Context) error {
}
func (b *backend) emitCertStoreMetrics(config *tidyConfig) {
if config.PublishMetrics == true {
if config.PublishMetrics {
certCount := b.certCount.Load()
b.emitTotalCertCountMetric(certCount)
revokedCertCount := b.revokedCertCount.Load()

View File

@@ -1387,8 +1387,8 @@ func generateRoleSteps(t *testing.T, useCSRs bool) []logicaltest.TestStep {
var extUsage x509.ExtKeyUsage
i := mathRand.Int() % 4
switch {
case i == 0:
switch i {
case 0:
// Punt on this for now since I'm not clear the actual proper
// way to format these
if name != "daɪˈɛrɨsɨs" {
@@ -1397,10 +1397,10 @@ func generateRoleSteps(t *testing.T, useCSRs bool) []logicaltest.TestStep {
break
}
fallthrough
case i == 1:
case 1:
extUsage = x509.ExtKeyUsageServerAuth
roleVals.ServerFlag = true
case i == 2:
case 2:
extUsage = x509.ExtKeyUsageClientAuth
roleVals.ClientFlag = true
default:
@@ -5653,7 +5653,7 @@ func TestIssuanceTTLs(t *testing.T) {
func TestSealWrappedStorageConfigured(t *testing.T) {
t.Parallel()
b, _ := CreateBackendWithStorage(t)
wrappedEntries := b.Backend.PathsSpecial.SealWrapStorage
wrappedEntries := b.PathsSpecial.SealWrapStorage
// Make sure our legacy bundle is within the list
// NOTE: do not convert these test values to constants, we should always have these paths within seal wrap config
@@ -6274,7 +6274,7 @@ func TestBackend_InitializeCertificateCounts(t *testing.T) {
}
// Put certificates A, B, C, D, E in backend
var certificates []string = []string{"a", "b", "c", "d", "e"}
certificates := []string{"a", "b", "c", "d", "e"}
serials := make([]string, 5)
for i, cn := range certificates {
resp, err = CBWrite(b, s, "issue/example", map[string]interface{}{
@@ -7555,11 +7555,12 @@ func TestProperAuthing(t *testing.T) {
_, hasPost := openapi_data["post"]
_, hasDelete := openapi_data["delete"]
if handler == shouldBeUnauthedReadList {
switch handler {
case shouldBeUnauthedReadList:
if hasPost || hasDelete {
t.Fatalf("Unauthed read-only endpoints should not have POST/DELETE capabilities: %v->%v", openapi_path, raw_path)
}
} else if handler == shouldBeUnauthedWriteOnly {
case shouldBeUnauthedWriteOnly:
if hasGet || hasList {
t.Fatalf("Unauthed write-only endpoints should not have GET/LIST capabilities: %v->%v", openapi_path, raw_path)
}

View File

@@ -557,13 +557,14 @@ func runSteps(t *testing.T, rootB, intB *backend, client *api.Client, rootName,
}
var crlBytes []byte
if derPemOrJSON == 2 {
switch derPemOrJSON {
case 2:
// Old endpoint
crlBytes = []byte(resp.Data["certificate"].(string))
} else if derPemOrJSON == 3 {
case 3:
// New endpoint
crlBytes = []byte(resp.Data["crl"].(string))
} else {
default:
// DER or PEM
crlBytes = resp.Data["http_raw_body"].([]byte)
}

View File

@@ -1026,7 +1026,8 @@ func signCert(b *backend,
//
// This validation needs to occur regardless of the role's key type, so
// that we always validate both RSA and ECDSA key sizes.
if actualKeyType == "rsa" {
switch actualKeyType {
case "rsa":
if actualKeyBits < data.role.KeyBits {
return nil, nil, errutil.UserError{Err: fmt.Sprintf(
"role requires a minimum of a %d-bit key, but CSR's key is %d bits",
@@ -1038,7 +1039,7 @@ func signCert(b *backend,
"OpenBao requires a minimum of a 2048-bit key, but CSR's key is %d bits",
actualKeyBits)}
}
} else if actualKeyType == "ec" {
case "ec":
if actualKeyBits < data.role.KeyBits {
return nil, nil, errutil.UserError{Err: fmt.Sprintf(
"role requires a minimum of a %d-bit key, but CSR's key is %d bits",

View File

@@ -1020,7 +1020,7 @@ func TestAutoRebuild(t *testing.T) {
// Wait for the CRL to update based on the configuration change we just did
// so that it doesn't grab the revocation we are going to do afterwards.
crl = waitForUpdatedCrl(t, client, defaultCrlPath, lastCRLNumber, lastCRLExpiry.Sub(time.Now()))
crl = waitForUpdatedCrl(t, client, defaultCrlPath, lastCRLNumber, time.Until(lastCRLExpiry))
lastCRLNumber = getCRLNumber(t, crl)
lastCRLExpiry = crl.NextUpdate
@@ -1095,11 +1095,7 @@ func TestAutoRebuild(t *testing.T) {
haveUpdatedDeltaCRL := false
interruptChan := time.After(4*newPeriod + delta)
for {
if haveUpdatedDeltaCRL {
break
}
for !haveUpdatedDeltaCRL {
select {
case <-interruptChan:
t.Fatalf("expected to regenerate delta CRL within a couple of periodicFunc invocations (plus %v grace period)", delta)

View File

@@ -1054,7 +1054,7 @@ func (b *backend) acmeTidyOrder(sc *storageContext, accountId string, orderPath
}
orderExpiry = order.Expires
}
if shouldTidy == false {
if !shouldTidy {
return shouldTidy, orderExpiry, nil
}

View File

@@ -667,7 +667,7 @@ func TestAcmeDisabledWithEnvVar(t *testing.T) {
// Make sure that ACME is disabled now.
for _, method := range []string{http.MethodHead, http.MethodGet} {
t.Run(fmt.Sprintf("%s", method), func(t *testing.T) {
t.Run(method, func(t *testing.T) {
req := client.NewRequest(method, "/v1/pki/acme/new-nonce")
_, err := client.RawRequestWithContext(ctx, req)
require.Error(t, err, "should have received an error as ACME should have been disabled")
@@ -1024,10 +1024,11 @@ func TestIssuerRoleDirectoryAssociations(t *testing.T) {
// Path should override role.
directory := "/v1/pki/issuer/" + issuer + "/acme/"
issuerPath := "/pki/issuer/" + issuer
if issuer == "" {
switch issuer {
case "":
directory = "/v1/pki/acme/"
issuerPath = "/pki/issuer/int-ca"
} else if issuer == "default" {
case "default":
issuerPath = "/pki/issuer/int-ca"
}

View File

@@ -435,10 +435,11 @@ func (b *backend) pathFetchRead(ctx context.Context, req *logical.Request, data
serial = "ca"
contentType = "application/pkix-cert"
if req.Path == "ca/pem" || req.Path == "cert/ca/raw/pem" {
switch req.Path {
case "ca/pem", "cert/ca/raw/pem":
pemType = "CERTIFICATE"
contentType = "application/pem-certificate-chain"
} else if req.Path == "cert/ca" {
case "cert/ca":
pemType = "CERTIFICATE"
contentType = ""
}
@@ -507,7 +508,8 @@ func (b *backend) pathFetchRead(ctx context.Context, req *logical.Request, data
}
}
if serial == "ca_chain" {
switch serial {
case "ca_chain":
rawChain := caInfo.GetFullChain()
var chainStr string
for _, ca := range rawChain {
@@ -519,7 +521,7 @@ func (b *backend) pathFetchRead(ctx context.Context, req *logical.Request, data
}
fullChain = []byte(strings.TrimSpace(chainStr))
certificate = fullChain
} else if serial == "ca" {
case "ca":
certificate = caInfo.Certificate.Raw
if len(pemType) != 0 {

View File

@@ -112,11 +112,12 @@ func TestListCertificatesWithDetails(t *testing.T) {
// Determine if the certificate is root or leaf based on the common name
commonName := certData["common_name"].(string)
if commonName == RootCN {
switch commonName {
case RootCN:
checkCertificateDetails(t, certData, expectedRootCertDetails)
} else if commonName == leafCN {
case leafCN:
checkCertificateDetails(t, certData, expectedLeafCertDetails)
} else {
default:
t.Fatalf("Unexpected common name found: %s", commonName)
}
}

View File

@@ -137,7 +137,7 @@ func (b *backend) pathGenerateIntermediate(ctx context.Context, req *logical.Req
apiData: data,
}
parsedBundle, warnings, err := generateIntermediateCSR(sc, input, b.Backend.GetRandomReader())
parsedBundle, warnings, err := generateIntermediateCSR(sc, input, b.GetRandomReader())
if err != nil {
switch err.(type) {
case errutil.UserError:

View File

@@ -741,7 +741,7 @@ func (b *backend) pathIssueSignCert(ctx context.Context, req *logical.Request, d
map[string]interface{}{
"serial_number": cb.SerialNumber,
})
resp.Secret.TTL = parsedBundle.Certificate.NotAfter.Sub(time.Now())
resp.Secret.TTL = time.Until(parsedBundle.Certificate.NotAfter)
}
if data.Get("private_key_format").(string) == "pkcs8" {
@@ -1035,7 +1035,7 @@ func (b *backend) pathCelIssueSignCert(ctx context.Context, req *logical.Request
map[string]interface{}{
"serial_number": cb.SerialNumber,
})
resp.Secret.TTL = parsedBundle.Certificate.NotAfter.Sub(time.Now())
resp.Secret.TTL = time.Until(parsedBundle.Certificate.NotAfter)
} else {
// Non-Leased Certificate
resp = &logical.Response{

View File

@@ -522,7 +522,7 @@ func parseExtAsn1ObjectId(entry map[string]interface{}) (asn1.ObjectIdentifier,
// Parse out dot notation
oidParts := strings.Split(oidStr, ".")
oid := make(asn1.ObjectIdentifier, len(oidParts), len(oidParts))
oid := make(asn1.ObjectIdentifier, len(oidParts))
for i := range oidParts {
oidIntVal, err := strconv.Atoi(oidParts[i])
if err != nil {

View File

@@ -133,11 +133,7 @@ func TestResignCrls_ConflictingExpiry(t *testing.T) {
// Wait until at least we have rolled over to the next second to match sure the generated CRL time
// on backend 2 for the serial 1 will be different
for {
if time.Now().After(timeAfterMountSetup.Add(1 * time.Second)) {
break
}
}
time.Sleep(time.Until(timeAfterMountSetup.Add(1 * time.Second)))
// Use BYOC to revoke the same certificate on backend 2 now
resp, err = CBWrite(b2, s2, "revoke", map[string]interface{}{

View File

@@ -188,7 +188,7 @@ func (b *backend) pathCAGenerateRoot(ctx context.Context, req *logical.Request,
apiData: data,
role: role,
}
parsedBundle, warnings, err := generateCert(sc, input, nil, true, b.Backend.GetRandomReader())
parsedBundle, warnings, err := generateCert(sc, input, nil, true, b.GetRandomReader())
if err != nil {
switch err.(type) {
case errutil.UserError:

View File

@@ -20,7 +20,7 @@ import (
"github.com/openbao/openbao/sdk/v2/logical"
)
var tidyCancelledError = errors.New("tidy operation cancelled")
var errTidyCancelled = errors.New("tidy operation cancelled")
type tidyStatusState int
@@ -863,7 +863,7 @@ func (b *backend) startTidyOperation(req *logical.Request, config *tidyConfig) {
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
return errTidyCancelled
}
if config.RevokedCerts || config.IssuerAssocs || config.InvalidCerts {
@@ -876,7 +876,7 @@ func (b *backend) startTidyOperation(req *logical.Request, config *tidyConfig) {
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
return errTidyCancelled
}
if rebuildCRL {
@@ -887,7 +887,7 @@ func (b *backend) startTidyOperation(req *logical.Request, config *tidyConfig) {
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
return errTidyCancelled
}
if config.ExpiredIssuers {
@@ -898,7 +898,7 @@ func (b *backend) startTidyOperation(req *logical.Request, config *tidyConfig) {
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
return errTidyCancelled
}
if config.BackupBundle {
@@ -909,7 +909,7 @@ func (b *backend) startTidyOperation(req *logical.Request, config *tidyConfig) {
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
return errTidyCancelled
}
if config.TidyAcme {
@@ -956,7 +956,7 @@ func (b *backend) doTidyCertStore(ctx context.Context, req *logical.Request, log
// Check for cancel before continuing
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return false, tidyCancelledError
return false, errTidyCancelled
}
// Check for pause duration to reduce resource consumption
@@ -1091,9 +1091,9 @@ func (b *backend) doTidyRevocationStore(ctx context.Context, req *logical.Reques
// Number of certificates on current page. This value is <= PageSize.
var lenSerials int
// Total number of revoked certificates in storage
var totalRevokedSerialCount int = 0
totalRevokedSerialCount := 0
// Total number of deleted revoked certificates in this tidy call
var revokedDeletedCount int = 0
revokedDeletedCount := 0
var revInfo revocationInfo
haveWarned := false
@@ -1107,7 +1107,7 @@ func (b *backend) doTidyRevocationStore(ctx context.Context, req *logical.Reques
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return false, tidyCancelledError
return false, errTidyCancelled
}
// Check for pause duration to reduce resource consumption.
@@ -1183,7 +1183,7 @@ func (b *backend) doTidyRevocationStore(ctx context.Context, req *logical.Reques
// Tidy operations over revoked certs should execute prior to
// tidyRevokedCerts as that may remove the entry. If that happens,
// we won't persist the revInfo changes (as it was deleted instead).
var storeCert bool = false
storeCert := false
if config.IssuerAssocs {
if !isRevInfoIssuerValid(&revInfo, issuerIDCertMap) {
b.tidyStatusIncMissingIssuerCertCount()
@@ -1474,7 +1474,7 @@ func (b *backend) doTidyAcme(ctx context.Context, req *logical.Request, logger h
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return false, tidyCancelledError
return false, errTidyCancelled
}
// Check for pause duration to reduce resource consumption.
@@ -1541,7 +1541,7 @@ func (b *backend) doTidyAcme(ctx context.Context, req *logical.Request, logger h
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
return errTidyCancelled
}
// Check for pause duration to reduce resource consumption.
@@ -1848,11 +1848,12 @@ func (b *backend) tidyStatusStop(err error) {
b.tidyStatus.timeFinished = time.Now()
b.tidyStatus.err = err
if err == nil {
switch err {
case nil:
b.tidyStatus.state = tidyStatusFinished
} else if err == tidyCancelledError {
case errTidyCancelled:
b.tidyStatus.state = tidyStatusCancelled
} else {
default:
b.tidyStatus.state = tidyStatusError
}

View File

@@ -288,7 +288,7 @@ func TestAutoTidy(t *testing.T) {
require.NoError(t, err, "failed converting %s to int", resp.Data["revocation_time"])
revTime := time.Unix(revocationTime, 0)
now := time.Now()
if !(now.After(revTime) && now.Add(-10*time.Minute).Before(revTime)) {
if !now.After(revTime) || !now.Add(-10*time.Minute).Before(revTime) {
t.Fatalf("parsed revocation time not within the last 10 minutes current time: %s, revocation time: %s", now, revTime)
}
utcLoc, err := time.LoadLocation("UTC")
@@ -1261,7 +1261,7 @@ func waitForTidyToFinish(t *testing.T, client *api.Client, mount string) *api.Se
return errors.New("tidy status state is still running")
}
if errorOccurred, ok := statusResp.Data["error"]; !ok || !(errorOccurred == nil || errorOccurred == "") {
if errorOccurred, ok := statusResp.Data["error"]; !ok || (errorOccurred != nil && errorOccurred != "") {
return fmt.Errorf("tidy status returned an error: %s", errorOccurred)
}
@@ -1277,11 +1277,7 @@ func waitForAutoTidyToFinish(t *testing.T, client *api.Client) {
var foundTidyFinished bool
timeoutChan := time.After(120 * time.Second)
for {
if foundTidyRunning != "" && foundTidyFinished {
break
}
for foundTidyRunning == "" || !foundTidyFinished {
select {
case <-timeoutChan:
t.Fatalf("expected auto-tidy to run (%v) and finish (%v) before timeout", foundTidyRunning, foundTidyFinished)

View File

@@ -1411,7 +1411,7 @@ func (sc *storageContext) writeAutoTidyConfig(config *tidyConfig) error {
sc.Backend.publishCertCountMetrics.Store(config.PublishMetrics)
// To Potentially Disable Certificate Counting
if config.MaintainCount == false {
if !config.MaintainCount {
certCountWasEnabled := sc.Backend.certCountEnabled.Swap(config.MaintainCount)
if certCountWasEnabled {
sc.Backend.certsCounted.Store(true)
@@ -1422,7 +1422,7 @@ func (sc *storageContext) writeAutoTidyConfig(config *tidyConfig) error {
sc.Backend.revokedCertCount.Store(0)
}
} else { // To Potentially Enable Certificate Counting
if sc.Backend.certCountEnabled.Load() == false {
if !sc.Backend.certCountEnabled.Load() {
// We haven't written "re-enable certificate counts" outside the initialize function
// Any call derived call to do so is likely to time out on ~2 million certs
sc.Backend.certCountError = "Certificate Counting Has Not Been Initialized, re-initialize this mount"

View File

@@ -352,7 +352,7 @@ func waitForUpdatedCrlUntil(t *testing.T, client *api.Client, crlPath string, la
if time.Since(start) > maxWait {
t.Logf("Timed out waiting for new CRL on path %s after iteration %d, delay: %v",
crlPath, iteration, time.Now().Sub(start))
crlPath, iteration, time.Since(start))
return crl, true
}
@@ -360,7 +360,7 @@ func waitForUpdatedCrlUntil(t *testing.T, client *api.Client, crlPath string, la
newCrlRevision := getCRLNumber(t, crl)
if newCrlRevision > initialCrlRevision {
t.Logf("Got new revision of CRL %s from %d to %d after iteration %d, delay %v",
crlPath, initialCrlRevision, newCrlRevision, iteration, time.Now().Sub(start))
crlPath, initialCrlRevision, newCrlRevision, iteration, time.Since(start))
return crl, false
}

View File

@@ -2102,12 +2102,12 @@ func validateSSHCertificate(cert *ssh.Certificate, keyID string, certType int, v
return fmt.Errorf("incorrect Signature: %v", cert.Signature)
}
if !reflect.DeepEqual(cert.Permissions.Extensions, extensionPermissions) {
return fmt.Errorf("incorrect Permissions.Extensions: Expected: %v, Actual: %v", extensionPermissions, cert.Permissions.Extensions)
if !reflect.DeepEqual(cert.Extensions, extensionPermissions) {
return fmt.Errorf("incorrect Permissions.Extensions: Expected: %v, Actual: %v", extensionPermissions, cert.Extensions)
}
if !reflect.DeepEqual(cert.Permissions.CriticalOptions, criticalOptionPermissions) {
return fmt.Errorf("incorrect Permissions.CriticalOptions: %v", cert.Permissions.CriticalOptions)
if !reflect.DeepEqual(cert.CriticalOptions, criticalOptionPermissions) {
return fmt.Errorf("incorrect Permissions.CriticalOptions: %v", cert.CriticalOptions)
}
return nil

View File

@@ -131,7 +131,8 @@ func (b *backend) pathCredsCreateWrite(ctx context.Context, req *logical.Request
}
var result *logical.Response
if role.KeyType == KeyTypeOTP {
switch role.KeyType {
case KeyTypeOTP:
// Generate an OTP
otp, err := b.GenerateOTPCredential(ctx, req, &sshOTP{
Username: username,
@@ -155,9 +156,9 @@ func (b *backend) pathCredsCreateWrite(ctx context.Context, req *logical.Request
}, map[string]interface{}{
"otp": otp,
})
} else if role.KeyType == KeyTypeDynamic {
case KeyTypeDynamic:
return nil, errors.New("dynamic key types have been removed")
} else {
default:
return nil, errors.New("key type unknown")
}

View File

@@ -428,7 +428,7 @@ func (b *backend) validateSignedKeyRequirements(publickey ssh.PublicKey, role *s
keyBits = k.N.BitLen()
case *dsa.PublicKey:
keyType = "dsa"
keyBits = k.Parameters.P.BitLen()
keyBits = k.P.BitLen()
case *ecdsa.PublicKey:
keyType = "ecdsa"
keyBits = k.Curve.Params().BitSize

View File

@@ -464,7 +464,8 @@ func (b *backend) pathRoleWrite(ctx context.Context, req *logical.Request, d *fr
keyType = strings.ToLower(keyType)
var roleEntry sshRole
if keyType == KeyTypeOTP {
switch keyType {
case KeyTypeOTP:
defaultUser := d.Get("default_user").(string)
if defaultUser == "" {
return logical.ErrorResponse("missing default user"), nil
@@ -480,9 +481,9 @@ func (b *backend) pathRoleWrite(ctx context.Context, req *logical.Request, d *fr
AllowedUsers: allowedUsers,
Version: roleEntryVersion,
}
} else if keyType == KeyTypeDynamic {
case KeyTypeDynamic:
return logical.ErrorResponse("dynamic key type roles are no longer supported"), nil
} else if keyType == KeyTypeCA {
case KeyTypeCA:
algorithmSigner := DefaultAlgorithmSigner
algorithmSignerRaw, ok := d.GetOk("algorithm_signer")
if ok {
@@ -504,7 +505,7 @@ func (b *backend) pathRoleWrite(ctx context.Context, req *logical.Request, d *fr
return errorResponse, nil
}
roleEntry = *role
} else {
default:
return logical.ErrorResponse("invalid key type"), nil
}

View File

@@ -7,6 +7,7 @@ import (
"bytes"
"context"
"fmt"
"slices"
uuid "github.com/hashicorp/go-uuid"
"github.com/openbao/openbao/sdk/v2/helper/errutil"
@@ -139,12 +140,7 @@ func (sc *storageContext) listIssuersPage(after string, limit int) ([]string, er
return nil, err
}
issuerIds := make([]string, 0, len(strList))
for _, entry := range strList {
issuerIds = append(issuerIds, entry)
}
return issuerIds, nil
return slices.Clone(strList), nil
}
// fetchIssuerById returns an issuer entry based an identifier, if not found an error is returned

View File

@@ -169,7 +169,7 @@ func (b *backend) handleKeyGeneration(data *framework.FieldData) (publicKey stri
keyType := data.Get("key_type").(string)
keyBits := data.Get("key_bits").(int)
publicKey, privateKey, err = generateSSHKeyPair(b.Backend.GetRandomReader(), keyType, keyBits)
publicKey, privateKey, err = generateSSHKeyPair(b.GetRandomReader(), keyType, keyBits)
if err != nil {
err = errutil.InternalError{Err: err.Error()}
return publicKey, privateKey, generateSigningKey, err

View File

@@ -1448,7 +1448,7 @@ func testPolicyFuzzingCommon(t *testing.T, be *backend) {
// t.Errorf("Starting %d", id)
for {
// Stop after 10 seconds
if time.Now().Sub(startTime) > 10*time.Second {
if time.Since(startTime) > 10*time.Second {
return
}
@@ -1638,7 +1638,7 @@ func TestTransit_AutoRotateKeys(t *testing.T) {
t.Fatal("failed to create backend")
}
err := b.Backend.Setup(context.Background(), conf)
err := b.Setup(context.Background(), conf)
if err != nil {
t.Fatal(err)
}

View File

@@ -315,10 +315,11 @@ func encodeRSAPrivateKey(key *keysutil.KeyEntry, format string) (string, error)
var derBytes []byte
var blockType string
var err error
if format == "" {
switch format {
case "":
derBytes = x509.MarshalPKCS1PrivateKey(key.RSAKey)
blockType = "RSA PRIVATE KEY"
} else if format == "der" || format == "pem" {
case "der", "pem":
derBytes, err = x509.MarshalPKCS8PrivateKey(key.RSAKey)
blockType = "PRIVATE KEY"
}
@@ -408,10 +409,11 @@ func keyEntryToECPrivateKey(k *keysutil.KeyEntry, curve elliptic.Curve, format s
var blockType string
var derBytes []byte
var err error
if format == "" {
switch format {
case "":
derBytes, err = x509.MarshalECPrivateKey(privKey)
blockType = "EC PRIVATE KEY"
} else if format == "der" || format == "pem" {
case "der", "pem":
derBytes, err = x509.MarshalPKCS8PrivateKey(privKey)
blockType = "PRIVATE KEY"
}

View File

@@ -343,8 +343,8 @@ func TestTransit_Export_KeysDoesNotExist_ReturnsNotFound(t *testing.T) {
}
rsp, err := b.HandleRequest(context.Background(), req)
if !(rsp == nil && err == nil) {
t.Fatal("Key does not exist but does not return not found")
if rsp != nil || err != nil {
t.Fatal("Key does not exist: should return no response and no error.")
}
}
@@ -608,7 +608,7 @@ func TestTransit_Export_CertificateChain(t *testing.T) {
}
func testTransit_Export_CertificateChain(t *testing.T, apiClient *api.Client, keyType string) {
keyName := fmt.Sprintf("%s", keyType)
keyName := keyType
issuerName := fmt.Sprintf("%s-issuer", keyType)
// get key to be imported

View File

@@ -432,11 +432,8 @@ func checkKeyFieldsSet(d *framework.FieldData) (bool, error) {
func isFieldSet(fieldName string, d *framework.FieldData) bool {
_, fieldSet := d.Raw[fieldName]
if !fieldSet {
return false
}
return true
return fieldSet
}
const (

View File

@@ -12,7 +12,6 @@ import (
"github.com/openbao/openbao/sdk/v2/helper/consts"
"github.com/openbao/openbao/sdk/v2/logical"
"github.com/openbao/openbao/sdk/v2/plugin"
bplugin "github.com/openbao/openbao/sdk/v2/plugin"
)
// Backend returns an instance of the backend, either as a plugin if external
@@ -63,7 +62,7 @@ func (b *backend) reloadBackend(ctx context.Context, storage logical.Storage) er
// Pass a context value so that the plugin client will call the appropriate
// cleanup method for reloading
reloadCtx := context.WithValue(ctx, plugin.ContextKeyPluginReload, "reload")
b.Backend.Cleanup(reloadCtx)
b.Cleanup(reloadCtx)
nb, err := plugin.NewBackendV5(ctx, pluginName, pluginType, pluginVersion, b.config.System, b.config)
if err != nil {
@@ -77,7 +76,7 @@ func (b *backend) reloadBackend(ctx context.Context, storage logical.Storage) er
// Re-initialize the backend in case plugin was reloaded
// after it crashed
err = b.Backend.Initialize(ctx, &logical.InitializationRequest{
err = b.Initialize(ctx, &logical.InitializationRequest{
Storage: storage,
})
if err != nil {
@@ -96,7 +95,7 @@ func (b *backend) HandleRequest(ctx context.Context, req *logical.Request) (*log
// Need to compare string value for case were err comes from plugin RPC
// and is returned as plugin.BasicError type.
if err != nil &&
(err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) {
(err.Error() == rpc.ErrShutdown.Error() || err == plugin.ErrPluginShutdown) {
// Reload plugin if it's an rpc.ErrShutdown
b.mu.Lock()
if b.canary == canary {
@@ -128,7 +127,7 @@ func (b *backend) HandleExistenceCheck(ctx context.Context, req *logical.Request
checkFound, exists, err := b.Backend.HandleExistenceCheck(ctx, req)
b.mu.RUnlock()
if err != nil &&
(err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) {
(err.Error() == rpc.ErrShutdown.Error() || err == plugin.ErrPluginShutdown) {
// Reload plugin if it's an rpc.ErrShutdown
b.mu.Lock()
if b.canary == canary {

3
changelog/1962.txt Normal file
View File

@@ -0,0 +1,3 @@
```release-note:change
Remove the deprecated `creation_statements`, `revocation_statements`, `rollback_statements`, and `renew_statements` fields from the dbplugin `Statements` protobuf message
```

View File

@@ -531,7 +531,7 @@ func (c *AgentCommand) Run(args []string) int {
// Parse 'require_request_header' listener config option, and wrap
// the request handler if necessary
if lnConfig.RequireRequestHeader && ("metrics_only" != lnConfig.Role) {
if lnConfig.RequireRequestHeader && (lnConfig.Role != "metrics_only") {
muxHandler = verifyRequestHeader(muxHandler)
}
@@ -540,7 +540,7 @@ func (c *AgentCommand) Run(args []string) int {
quitEnabled := lnConfig.AgentAPI != nil && lnConfig.AgentAPI.EnableQuit
mux.Handle(consts.AgentPathMetrics, c.handleMetrics())
if "metrics_only" != lnConfig.Role {
if lnConfig.Role != "metrics_only" {
mux.Handle(consts.AgentPathCacheClear, leaseCache.HandleCacheClear(ctx))
mux.Handle(consts.AgentPathQuit, c.handleQuit(quitEnabled))
mux.Handle("/", muxHandler)
@@ -970,7 +970,7 @@ func (c *AgentCommand) storePidFile(pidPath string) error {
// Write out the PID
pid := os.Getpid()
_, err = pidFile.WriteString(fmt.Sprintf("%d", pid))
_, err = fmt.Fprintf(pidFile, "%d", pid)
if err != nil {
return fmt.Errorf("could not write to pid file: %w", err)
}

View File

@@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"fmt"
"maps"
"os"
"strings"
"testing"
@@ -344,10 +345,7 @@ func testAppRoleEndToEnd(t *testing.T, removeSecretIDFile bool, bindSecretID boo
// Make sure it gets renewed
timeout := time.Now().Add(4 * time.Second)
for {
if time.Now().After(timeout) {
break
}
for time.Now().Before(timeout) {
secret, err := client.Auth().Token().LookupSelf()
if err != nil {
t.Fatal(err)
@@ -384,10 +382,7 @@ func testAppRoleEndToEnd(t *testing.T, removeSecretIDFile bool, bindSecretID boo
}
timeout = time.Now().Add(4 * time.Second)
for {
if time.Now().After(timeout) {
break
}
for time.Now().Before(timeout) {
secret, err := client.Auth().Token().LookupSelf()
if err != nil {
t.Fatal(err)
@@ -733,10 +728,7 @@ func testAppRoleWithWrapping(t *testing.T, bindSecretID bool, secretIDLess bool,
// Make sure it gets renewed
timeout := time.Now().Add(4 * time.Second)
for {
if time.Now().After(timeout) {
break
}
for time.Now().Before(timeout) {
secret, err := client.Auth().Token().LookupSelf()
if err != nil {
t.Fatal(err)
@@ -775,10 +767,7 @@ func testAppRoleWithWrapping(t *testing.T, bindSecretID bool, secretIDLess bool,
}
timeout = time.Now().Add(4 * time.Second)
for {
if time.Now().After(timeout) {
break
}
for time.Now().Before(timeout) {
secret, err := client.Auth().Token().LookupSelf()
if err != nil {
t.Fatal(err)
@@ -800,9 +789,7 @@ func addConstraints(add bool, cfg map[string]interface{}) map[string]interface{}
"secret_id_bound_cidrs": "127.0.0.1/32",
"token_bound_cidrs": "127.0.0.1/32",
}
for k, v := range extraConstraints {
cfg[k] = v
}
maps.Copy(cfg, extraConstraints)
}
return cfg
}

View File

@@ -13,7 +13,6 @@ import (
"time"
hclog "github.com/hashicorp/go-hclog"
log "github.com/hashicorp/go-hclog"
"github.com/openbao/openbao/api/v2"
credAppRole "github.com/openbao/openbao/builtin/credential/approle"
"github.com/openbao/openbao/command/agentproxyshared/auth"
@@ -42,10 +41,10 @@ path "/auth/token/create" {
func TestCache_UsingAutoAuthToken(t *testing.T) {
var err error
logger := logging.NewVaultLogger(log.Trace)
logger := logging.NewVaultLogger(hclog.Trace)
coreConfig := &vault.CoreConfig{
DisableCache: true,
Logger: log.NewNullLogger(),
Logger: hclog.NewNullLogger(),
LogicalBackends: map[string]logical.Factory{
"kv": vault.LeasedPassthroughBackendFactory,
},

View File

@@ -68,8 +68,8 @@ func (c *Config) Prune() {
}
c.FoundKeys = nil
c.UnusedKeys = nil
c.SharedConfig.FoundKeys = nil
c.SharedConfig.UnusedKeys = nil
c.FoundKeys = nil
c.UnusedKeys = nil
if c.Telemetry != nil {
c.Telemetry.FoundKeys = nil
c.Telemetry.UnusedKeys = nil
@@ -240,12 +240,8 @@ func (c *Config) Merge(c2 *Config) *Config {
result.TemplateConfig = c2.TemplateConfig
}
for _, l := range c.Templates {
result.Templates = append(result.Templates, l)
}
for _, l := range c2.Templates {
result.Templates = append(result.Templates, l)
}
result.Templates = append(result.Templates, c.Templates...)
result.Templates = append(result.Templates, c2.Templates...)
result.ExitAfterAuth = c.ExitAfterAuth
if c2.ExitAfterAuth {
@@ -267,13 +263,8 @@ func (c *Config) Merge(c2 *Config) *Config {
result.Exec = c2.Exec
}
for _, envTmpl := range c.EnvTemplates {
result.EnvTemplates = append(result.EnvTemplates, envTmpl)
}
for _, envTmpl := range c2.EnvTemplates {
result.EnvTemplates = append(result.EnvTemplates, envTmpl)
}
result.EnvTemplates = append(result.EnvTemplates, c.EnvTemplates...)
result.EnvTemplates = append(result.EnvTemplates, c2.EnvTemplates...)
return result
}

View File

@@ -373,10 +373,7 @@ func testJWTEndToEnd(t *testing.T, ahWrapping, useSymlink, removeJWTAfterReading
// Period of 3 seconds, so should still be alive after 7
timeout := time.Now().Add(7 * time.Second)
cloned.SetToken(origToken)
for {
if time.Now().After(timeout) {
break
}
for time.Now().Before(timeout) {
secret, err := cloned.Auth().Token().LookupSelf()
if err != nil {
t.Fatal(err)
@@ -408,10 +405,7 @@ func testJWTEndToEnd(t *testing.T, ahWrapping, useSymlink, removeJWTAfterReading
// the new token should still be alive after 7
timeout := time.Now().Add(7 * time.Second)
cloned.SetToken(newToken)
for {
if time.Now().After(timeout) {
break
}
for time.Now().Before(timeout) {
secret, err := cloned.Auth().Token().LookupSelf()
if err != nil {
t.Fatal(err)

View File

@@ -1426,7 +1426,7 @@ type userAgentHandler struct {
func (h *userAgentHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method == h.requestMethodToCheck && strings.Contains(req.RequestURI, h.pathToCheck) {
userAgent := req.UserAgent()
if !(userAgent == h.userAgentToCheckFor) {
if userAgent != h.userAgentToCheckFor {
h.t.Fatalf("User-Agent string not as expected. Expected to find %s, got %s", h.userAgentToCheckFor, userAgent)
}
}

View File

@@ -200,9 +200,9 @@ func (ah *AuthHandler) Run(ctx context.Context, am AuthMethod) error {
var header http.Header
var isTokenFileMethod bool
switch am.(type) {
switch am := am.(type) {
case AuthMethodWithClient:
clientToUse, err = am.(AuthMethodWithClient).AuthClient(ah.client)
clientToUse, err = am.AuthClient(ah.client)
if err != nil {
ah.logger.Error("error creating client for authentication call", "error", err, "backoff", backoff)
metrics.IncrCounter([]string{ah.metricsSignifier, "auth", "failure"}, 1)
@@ -221,7 +221,7 @@ func (ah *AuthHandler) Run(ctx context.Context, am AuthMethod) error {
// the only source of retry/backoff.
clientToUse.SetMaxRetries(0)
var secret *api.Secret = new(api.Secret)
secret := new(api.Secret)
if first && ah.token != "" {
ah.logger.Debug("using preloaded token")

View File

@@ -102,7 +102,7 @@ consumption:
case <-ah.OutputCh:
case <-ah.TemplateTokenCh:
// Nothing
case <-time.After(stopTime.Sub(time.Now())):
case <-time.After(time.Until(stopTime)):
if !closed {
cancelFunc()
closed = true

View File

@@ -104,12 +104,12 @@ func NewBoltStorage(config *BoltStorageConfig) (*BoltStorage, error) {
}
func createBoltSchema(tx *bolt.Tx, createVersion string) error {
switch {
case createVersion == "1":
switch createVersion {
case "1":
if err := createV1BoltSchema(tx); err != nil {
return err
}
case createVersion == "2":
case "2":
if err := createV2BoltSchema(tx); err != nil {
return err
}

View File

@@ -25,7 +25,6 @@ import (
"github.com/openbao/openbao/api/v2"
"github.com/openbao/openbao/command/agentproxyshared/cache/cacheboltdb"
"github.com/openbao/openbao/command/agentproxyshared/cache/cachememdb"
"github.com/openbao/openbao/helper/namespace"
nshelper "github.com/openbao/openbao/helper/namespace"
"github.com/openbao/openbao/helper/useragent"
"github.com/openbao/openbao/sdk/v2/helper/consts"
@@ -899,9 +898,9 @@ func (c *LeaseCache) handleRevocationRequest(ctx context.Context, req *SendReque
return false, err
}
_, tokenNSID := namespace.SplitIDFromString(req.Token)
_, tokenNSID := nshelper.SplitIDFromString(req.Token)
for _, index := range indexes {
_, leaseNSID := namespace.SplitIDFromString(index.Lease)
_, leaseNSID := nshelper.SplitIDFromString(index.Lease)
// Only evict leases that match the token's namespace
if tokenNSID == leaseNSID {
index.RenewCtxInfo.CancelFunc()
@@ -918,9 +917,9 @@ func (c *LeaseCache) handleRevocationRequest(ctx context.Context, req *SendReque
return false, err
}
_, tokenNSID := namespace.SplitIDFromString(req.Token)
_, tokenNSID := nshelper.SplitIDFromString(req.Token)
for _, index := range indexes {
_, leaseNSID := namespace.SplitIDFromString(index.Lease)
_, leaseNSID := nshelper.SplitIDFromString(index.Lease)
// Only evict leases that match the token's namespace
if tokenNSID == leaseNSID {
index.RenewCtxInfo.CancelFunc()

View File

@@ -49,11 +49,9 @@ func TestSinkServer(t *testing.T) {
})
defer timer.Stop()
select {
case err := <-errCh:
if err != nil {
t.Fatal(err)
}
err := <-errCh
if err != nil {
t.Fatal(err)
}
for _, path := range []string{path1, path2} {
@@ -131,10 +129,8 @@ func TestSinkServerRetry(t *testing.T) {
// Tell it to shut down and give it time to do so
cancelFunc()
select {
case err := <-errCh:
if err != nil {
t.Fatal(err)
}
err := <-errCh
if err != nil {
t.Fatal(err)
}
}

View File

@@ -189,15 +189,15 @@ func TestAuthEnableCommand_Run(t *testing.T) {
if err != nil {
t.Fatal(err)
}
modLines := strings.Split(string(modFile), "\n")
for _, p := range modLines {
modLines := strings.SplitSeq(string(modFile), "\n")
for p := range modLines {
splitLine := strings.Split(strings.TrimSpace(p), " ")
if len(splitLine) == 0 {
continue
}
potPlug := strings.TrimPrefix(splitLine[0], "github.com/openbao/")
if strings.HasPrefix(potPlug, "vault-plugin-auth-") {
backends = append(backends, strings.TrimPrefix(potPlug, "vault-plugin-auth-"))
if after, ok := strings.CutPrefix(potPlug, "vault-plugin-auth-"); ok {
backends = append(backends, after)
}
}
// Add 1 to account for the "token" backend, which is visible when you walk the filesystem but
@@ -209,7 +209,7 @@ func TestAuthEnableCommand_Run(t *testing.T) {
}
for _, b := range backends {
var expectedResult int = 0
expectedResult := 0
// Not a builtin
if b == "token" {

View File

@@ -994,7 +994,7 @@ func (c *DebugCommand) compress(dst string) error {
ofs := os.DirFS(parent)
if err := fs.WalkDir(ofs, child, func(path string, d fs.DirEntry, err error) error {
var fileType byte = tar.TypeReg
var tarPath string = path
tarPath := path
if d.IsDir() {
fileType = tar.TypeDir
if !strings.HasSuffix(path, "/") {

View File

@@ -182,7 +182,7 @@ func (p PrettyFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{})
func outputStringSlice(buffer *bytes.Buffer, indent string, values []string) {
for _, val := range values {
buffer.WriteString(fmt.Sprintf("%s%s\n", indent, val))
fmt.Fprintf(buffer, "%s%s\n", indent, val)
}
}
@@ -288,7 +288,7 @@ func (t TableFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{})
}
func (t TableFormatter) OutputSealStatusStruct(ui cli.Ui, secret *api.Secret, data interface{}) error {
var status SealStatusOutput = data.(SealStatusOutput)
status := data.(SealStatusOutput)
var sealPrefix string
out := []string{}

View File

@@ -220,6 +220,7 @@ func (p *PathFetch) FetchSurfaceError() error {
}
if strings.Contains(p.FetchError.Error(), "route entry not found") {
//nolint:staticcheck // user-facing error
return fmt.Errorf("Error making API request: was a bad mount given?\n\nOperation: %v\nPath: %v\nOriginal Error:\n%w", p.Operation, p.Path, p.FetchError)
}
@@ -298,6 +299,7 @@ func ValidateMountType(client *api.Client, mount string, expectedType string) er
case "pki":
// Provide clear error message for auth mounts.
if strings.HasPrefix(mount, "auth/") || strings.HasPrefix(mount, "/auth/") {
//nolint:staticcheck // user-facing error
return errors.New("Refusing to run PKI health-check on auth mount; this command is only relevant to PKI secrets engines.")
}
}

View File

@@ -81,11 +81,12 @@ func (h *CAValidityPeriod) LoadConfig(config map[string]interface{}) error {
return fmt.Errorf("failed to parse parameter (%v=%v): %w", parameter, value_raw, err)
}
if name_split[0] == "root" {
switch name_split[0] {
case "root":
h.RootExpiries[status] = value
} else if name_split[0] == "intermediate" {
case "intermediate":
h.IntermediateExpieries[status] = value
} else {
default:
return fmt.Errorf("bad parameter: %v's CA type isn't root/intermediate: %v", parameters, name_split[0])
}
}

View File

@@ -134,11 +134,7 @@ func addPrefixToKVPath(path, mountPath, apiPrefix string, skipIfExists bool) str
}
pathSuffix := strings.TrimPrefix(path, mountPath)
for {
// If the entire mountPath is included in the path, we are done
if pathSuffix != path {
break
}
for pathSuffix == path {
// Trim the parts of the mountPath that are not included in the
// path, for example, in cases where the mountPath contains
// namespaces which are not included in the path.

View File

@@ -962,7 +962,7 @@ func TestKVPatchCommand_StdinFull(t *testing.T) {
for i, args := range cases {
stdinR, stdinW := io.Pipe()
go func() {
stdinW.Write([]byte(fmt.Sprintf(`{"foo%d":"bar%d"}`, i, i)))
_, _ = fmt.Fprintf(stdinW, `{"foo%d":"bar%d"}`, i, i)
stdinW.Close()
}()
code, combined := kvPatchWithRetry(t, client, args, stdinR)
@@ -1030,7 +1030,7 @@ func TestKVPatchCommand_StdinValue(t *testing.T) {
for i, args := range cases {
stdinR, stdinW := io.Pipe()
go func() {
stdinW.Write([]byte(fmt.Sprintf("bar%d", i)))
_, _ = fmt.Fprintf(stdinW, "bar%d", i)
stdinW.Close()
}()

View File

@@ -159,10 +159,7 @@ func RunCustom(args []string, runOpts *RunOptions) int {
args, format, detailed, outputCurlString, outputPolicy = setupEnv(args)
// Don't use color if disabled
useColor := true
if api.ReadBaoVariable(EnvVaultCLINoColor) != "" || color.NoColor {
useColor = false
}
useColor := !color.NoColor && api.ReadBaoVariable(EnvVaultCLINoColor) == ""
if runOpts.Stdout == nil {
runOpts.Stdout = os.Stdout
@@ -328,17 +325,17 @@ func generateCurlString(exitCode int, runOpts *RunOptions, preParsingErrBuf *byt
cs, err := api.LastOutputStringError.CurlString()
if err != nil {
runOpts.Stderr.Write([]byte(fmt.Sprintf("Error creating request string: %s\n", err)))
_, _ = fmt.Fprintf(runOpts.Stderr, "Error creating request string: %s\n", err)
return 1
}
runOpts.Stdout.Write([]byte(fmt.Sprintf("%s\n", cs)))
_, _ = fmt.Fprintf(runOpts.Stdout, "%s\n", cs)
return 0
}
func generatePolicy(exitCode int, runOpts *RunOptions, preParsingErrBuf *bytes.Buffer) int {
if exitCode == 0 {
fmt.Fprint(runOpts.Stderr, "Could not generate policy")
_, _ = fmt.Fprint(runOpts.Stderr, "Could not generate policy")
return 1
}
@@ -354,10 +351,10 @@ func generatePolicy(exitCode int, runOpts *RunOptions, preParsingErrBuf *bytes.B
hcl, err := api.LastOutputPolicyError.HCLString()
if err != nil {
runOpts.Stderr.Write([]byte(fmt.Sprintf("Error assembling policy HCL: %s\n", err)))
_, _ = fmt.Fprintf(runOpts.Stderr, "Error assembling policy HCL: %s\n", err)
return 1
}
runOpts.Stdout.Write([]byte(fmt.Sprintf("%s\n", hcl)))
_, _ = fmt.Fprintf(runOpts.Stdout, "%s\n", hcl)
return 0
}

View File

@@ -36,7 +36,8 @@ import (
"golang.org/x/term"
)
const CoreConfigUninitializedErr = "Diagnose cannot attempt this step because core config could not be set."
//nolint:staticcheck // user-facing error
var ErrCoreConfigUninitialized = errors.New("Diagnose cannot attempt this step because core config could not be set.")
var (
_ cli.Command = (*OperatorDiagnoseCommand)(nil)
@@ -70,7 +71,7 @@ Usage: bao operator diagnose
reproduced.
Start diagnose with a configuration file:
$ bao operator diagnose -config=/etc/openbao/config.hcl
Perform a diagnostic check while OpenBao is still running:
@@ -424,7 +425,7 @@ SEALFAIL:
if seal.Type == "transit" {
checkSealTransit = true
tlsSkipVerify, _ := seal.Config["tls_skip_verify"]
tlsSkipVerify := seal.Config["tls_skip_verify"]
if tlsSkipVerify == "true" {
diagnose.Warn(ctx, "TLS verification is skipped. This is highly discouraged and decreases the security of data transmissions to and from the Vault server.")
return nil
@@ -533,7 +534,7 @@ SEALFAIL:
diagnose.Test(ctx, "Check Core Creation", func(ctx context.Context) error {
var newCoreError error
if coreConfig.RawConfig == nil {
return fmt.Errorf(CoreConfigUninitializedErr)
return ErrCoreConfigUninitialized
}
core, newCoreError := vault.CreateCore(&coreConfig)
if newCoreError != nil {
@@ -574,8 +575,12 @@ SEALFAIL:
// Make sure we close all listeners from this point on
listenerCloseFunc := func() {
var errs error
for _, ln := range lns {
ln.Listener.Close()
errs = errors.Join(errs, ln.Close())
}
if errs != nil {
diagnose.SpotWarn(ctx, "Close Listeners", errs.Error())
}
}

View File

@@ -5,6 +5,7 @@ package command
import (
"fmt"
"slices"
"strings"
"github.com/hashicorp/cli"
@@ -366,15 +367,8 @@ type machineInit struct {
func newMachineInit(req *api.InitRequest, resp *api.InitResponse) *machineInit {
init := &machineInit{}
init.UnsealKeysHex = make([]string, len(resp.Keys))
for i, v := range resp.Keys {
init.UnsealKeysHex[i] = v
}
init.UnsealKeysB64 = make([]string, len(resp.KeysB64))
for i, v := range resp.KeysB64 {
init.UnsealKeysB64[i] = v
}
init.UnsealKeysHex = slices.Clone(resp.Keys)
init.UnsealKeysB64 = slices.Clone(resp.KeysB64)
// If we don't get a set of keys back, it means that we are storing the keys,
// so the key shares and threshold has been set to 1.
@@ -386,15 +380,8 @@ func newMachineInit(req *api.InitRequest, resp *api.InitResponse) *machineInit {
init.UnsealThreshold = req.SecretThreshold
}
init.RecoveryKeysHex = make([]string, len(resp.RecoveryKeys))
for i, v := range resp.RecoveryKeys {
init.RecoveryKeysHex[i] = v
}
init.RecoveryKeysB64 = make([]string, len(resp.RecoveryKeysB64))
for i, v := range resp.RecoveryKeysB64 {
init.RecoveryKeysB64[i] = v
}
init.RecoveryKeysHex = slices.Clone(resp.RecoveryKeys)
init.RecoveryKeysB64 = slices.Clone(resp.RecoveryKeysB64)
init.RecoveryShares = req.RecoveryShares
init.RecoveryThreshold = req.RecoveryThreshold

View File

@@ -364,7 +364,7 @@ func (c *PKIHealthCheckCommand) outputResultsYAML(results map[string][]*healthch
}
func (c *PKIHealthCheckCommand) selectRetCode(results map[string][]*healthcheck.Result) int {
var highestResult healthcheck.ResultStatus = healthcheck.ResultNotApplicable
highestResult := healthcheck.ResultNotApplicable
for _, findings := range results {
for _, finding := range findings {
if finding.Status > highestResult {

View File

@@ -505,7 +505,7 @@ func (c *ProxyCommand) Run(args []string) int {
// Parse 'require_request_header' listener config option, and wrap
// the request handler if necessary
if lnConfig.RequireRequestHeader && ("metrics_only" != lnConfig.Role) {
if lnConfig.RequireRequestHeader && (lnConfig.Role != "metrics_only") {
muxHandler = verifyRequestHeader(muxHandler)
}
@@ -514,7 +514,7 @@ func (c *ProxyCommand) Run(args []string) int {
quitEnabled := lnConfig.ProxyAPI != nil && lnConfig.ProxyAPI.EnableQuit
mux.Handle(consts.ProxyPathMetrics, c.handleMetrics())
if "metrics_only" != lnConfig.Role {
if lnConfig.Role != "metrics_only" {
mux.Handle(consts.ProxyPathCacheClear, leaseCache.HandleCacheClear(ctx))
mux.Handle(consts.ProxyPathQuit, c.handleQuit(quitEnabled))
mux.Handle("/", muxHandler)
@@ -866,7 +866,7 @@ func (c *ProxyCommand) storePidFile(pidPath string) error {
// Write out the PID
pid := os.Getpid()
_, err = pidFile.WriteString(fmt.Sprintf("%d", pid))
_, err = fmt.Fprintf(pidFile, "%d", pid)
if err != nil {
return fmt.Errorf("could not write to pid file: %w", err)
}

View File

@@ -56,8 +56,8 @@ func (c *Config) Prune() {
}
c.FoundKeys = nil
c.UnusedKeys = nil
c.SharedConfig.FoundKeys = nil
c.SharedConfig.UnusedKeys = nil
c.FoundKeys = nil
c.UnusedKeys = nil
if c.Telemetry != nil {
c.Telemetry.FoundKeys = nil
c.Telemetry.UnusedKeys = nil

View File

@@ -18,7 +18,7 @@ import (
// logicalBackendAdjustmentFactor is set to plus 1 for the database backend
// which is a plugin but not found in go.mod files, and minus 1 for the ldap
// and openldap secret backends which have the same underlying plugin.
var logicalBackendAdjustmentFactor = 1 - 1
var logicalBackendAdjustmentFactor = 1 - 1 //nolint:staticcheck // explanation above
func testSecretsEnableCommand(tb testing.TB) (*cli.MockUi, *SecretsEnableCommand) {
tb.Helper()

View File

@@ -580,8 +580,12 @@ func (c *ServerCommand) runRecoveryMode() int {
}
listenerCloseFunc := func() {
var errs error
for _, ln := range lns {
ln.Listener.Close()
errs = errors.Join(errs, ln.Close())
}
if errs != nil {
c.UI.Error(fmt.Sprintf("Error closing listeners: %v", errs))
}
}
@@ -1283,8 +1287,12 @@ func (c *ServerCommand) Run(args []string) int {
// Make sure we close all listeners from this point on
listenerCloseFunc := func() {
var errs error
for _, ln := range lns {
ln.Listener.Close()
errs = errors.Join(errs, ln.Close())
}
if errs != nil {
c.UI.Error(fmt.Sprintf("Error closing listeners: %v", errs))
}
}
@@ -2383,7 +2391,7 @@ func (c *ServerCommand) storePidFile(pidPath string) error {
// Write out the PID
pid := os.Getpid()
_, err = pidFile.WriteString(fmt.Sprintf("%d", pid))
_, err = fmt.Fprintf(pidFile, "%d", pid)
if err != nil {
return fmt.Errorf("could not write to pid file: %w", err)
}
@@ -2486,7 +2494,7 @@ func setSeal(c *ServerCommand, config *server.Config, infoKeys *[]string, info m
config.Seals = append(config.Seals, &configutil.KMS{Type: wrapping.WrapperTypeShamir.String()})
}
}
var createdSeals []vault.Seal = make([]vault.Seal, len(config.Seals))
createdSeals := make([]vault.Seal, len(config.Seals))
for _, configSeal := range config.Seals {
sealType := configSeal.Type
if !configSeal.Disabled && api.ReadBaoVariable("BAO_SEAL_TYPE") != "" {

View File

@@ -228,7 +228,7 @@ storage "%s" {
ui = true
`
certDirEscaped := strings.Replace(certDir, "\\", "\\\\", -1)
certDirEscaped := strings.ReplaceAll(certDir, "\\", "\\\\")
hclStr = fmt.Sprintf(hclStr, certDirEscaped, certDirEscaped, storageType)
parsed, err := ParseConfig(hclStr, "")
if err != nil {

View File

@@ -36,8 +36,8 @@ func TestMetricFilterConfigs(t *testing.T) {
t.Fatalf("Error encountered when loading config %+v", err)
}
assert.Equal(t, tc.expectedFilterDefault, config.SharedConfig.Telemetry.FilterDefault)
assert.Equal(t, tc.expectedPrefixFilter, config.SharedConfig.Telemetry.PrefixFilter)
assert.Equal(t, tc.expectedFilterDefault, config.Telemetry.FilterDefault)
assert.Equal(t, tc.expectedPrefixFilter, config.Telemetry.PrefixFilter)
}
})
}

Some files were not shown because too many files have changed in this diff Show More