open-vault/sdk/framework/backend_test.go

838 lines
19 KiB
Go
Raw Normal View History

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
2015-03-15 23:39:49 +00:00
package framework
2015-03-14 04:15:20 +00:00
import (
"context"
"fmt"
"net/http"
2015-03-14 04:15:20 +00:00
"reflect"
"strings"
2015-03-18 00:15:23 +00:00
"sync/atomic"
2015-03-14 04:15:20 +00:00
"testing"
"time"
2015-03-14 06:58:20 +00:00
"github.com/hashicorp/go-secure-stdlib/strutil"
Allow Multiple Issuers in PKI Secret Engine Mounts - PKI Pod (#15277) * Starter PKI CA Storage API (#14796) * Simple starting PKI storage api for CA rotation * Add key and issuer storage apis * Add listKeys and listIssuers storage implementations * Add simple keys and issuers configuration storage api methods * Handle resolving key, issuer references The API context will usually have a user-specified reference to the key. This is either the literal string "default" to select the default key, an identifier of the key, or a slug name for the key. Here, we wish to resolve this reference to an actual identifier that can be understood by storage. Also adds the missing Name field to keys. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add method to fetch an issuer's cert bundle This adds a method to construct a certutil.CertBundle from the specified issuer identifier, optionally loading its corresponding key for signing. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Refactor certutil PrivateKey PEM handling This refactors the parsing of PrivateKeys from PEM blobs into shared methods (ParsePEMKey, ParseDERKey) that can be reused by the existing Bundle parsing logic (ParsePEMBundle) or independently in the new issuers/key-based PKI storage code. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add importKey, importCert to PKI storage importKey is generally preferable to the low-level writeKey for adding new entries. This takes only the contents of the private key (as a string -- so a PEM bundle or a managed key handle) and checks if it already exists in the storage. If it does, it returns the existing key instance. Otherwise, we create a new one. In the process, we detect any issuers using this key and link them back to the new key entry. The same holds for importCert over importKey, with the note that keys are not modified when importing certificates. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add tests for importing issuers, keys This adds tests for importing keys and issuers into the new storage layout, ensuring that identifiers are correctly inferred and linked. Note that directly writing entries to storage (writeKey/writeissuer) will take KeyID links from the parent entry and should not be used for import; only existing entries should be updated with this info. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Implement PKI storage migration. - Hook into the backend::initialize function, calling the migration on a primary only. - Migrate an existing certificate bundle to the new issuers and key layout * Make fetchCAInfo aware of new storage layout This allows fetchCAInfo to fetch a specified issuer, via a reference parameter provided by the user. We pass that into the storage layer and have it return a cert bundle for us. Finally, we need to validate that it truly has the key desired. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Begin /issuers API endpoints This implements the fetch operations around issuers in the PKI Secrets Engine. We implement the following operations: - LIST /issuers - returns a list of known issuers' IDs and names. - GET /issuer/:ref - returns a JSON blob with information about this issuer. - POST /issuer/:ref - allows configuring information about issuers, presently just its name. - DELETE /issuer/:ref - allows deleting the specified issuer. - GET /issuer/:ref/{der,pem} - returns a raw API response with just the DER (or PEM) of the issuer's certificate. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add import to PKI Issuers API This adds the two core import code paths to the API: /issuers/import/cert and /issuers/import/bundle. The former differs from the latter in that the latter allows the import of keys. This allows operators to restrict importing of keys to privileged roles, while allowing more operators permission to import additional certificates (not used for signing, but instead for path/chain building). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add /issuer/:ref/sign-intermediate endpoint This endpoint allows existing issuers to be used to sign intermediate CA certificates. In the process, we've updated the existing /root/sign-intermediate endpoint to be equivalent to a call to /issuer/default/sign-intermediate. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add /issuer/:ref/sign-self-issued endpoint This endpoint allows existing issuers to be used to sign self-signed certificates. In the process, we've updated the existing /root/sign-self-issued endpoint to be equivalent to a call to /issuer/default/sign-self-issued. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add /issuer/:ref/sign-verbatim endpoint This endpoint allows existing issuers to be used to directly sign CSRs. In the process, we've updated the existing /sign-verbatim endpoint to be equivalent to a call to /issuer/:ref/sign-verbatim. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Allow configuration of default issuers Using the new updateDefaultIssuerId(...) from the storage migration PR allows for easy implementation of configuring the default issuer. We restrict callers from setting blank defaults and setting default to default. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Fix fetching default issuers After setting a default issuer, one should be able to use the old /ca, /ca_chain, and /cert/{ca,ca_chain} endpoints to fetch the default issuer (and its chain). Update the fetchCertBySerial helper to no longer support fetching the ca and prefer fetchCAInfo for that instead (as we've already updated that to support fetching the new issuer location). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add /issuer/:ref/{sign,issue}/:role This updates the /sign and /issue endpoints, allowing them to take the default issuer (if none is provided by a role) and adding issuer-specific versions of them. Note that at this point in time, the behavior isn't yet ideal (as /sign/:role allows adding the ref=... parameter to override the default issuer); a later change adding role-based issuer specification will fix this incorrect behavior. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add support root issuer generation * Add support for issuer generate intermediate end-point * Update issuer and key arguments to consistent values - Update all new API endpoints to use the new agreed upon argument names. - issuer_ref & key_ref to refer to existing - issuer_name & key_name for new definitions - Update returned values to always user issuer_id and key_id * Add utility methods to fetch common ref and name arguments - Add utility methods to fetch the issuer_name, issuer_ref, key_name and key_ref arguments from data fields. - Centralize the logic to clean up these inputs and apply various validations to all of them. * Rename common PKI backend handlers - Use the buildPath convention for the function name instead of common... * Move setting PKI defaults from writeCaBundle to proper import{keys,issuer} methods - PR feedback, move setting up the default configuration references within the import methods instead of within the writeCaBundle method. This should now cover all use cases of us setting up the defaults properly. * Introduce constants for issuer_ref, rename isKeyDefaultSet... * Fix legacy PKI sign-verbatim api path - Addresses some test failures due to an incorrect refactoring of a legacy api path /sign-verbatim within PKI * Use import code to handle intermediate, config/ca The existing bundle import code will satisfy the intermediate import; use it instead of the old ca_bundle import logic. Additionally, update /config/ca to use the new import code as well. While testing, a panic was discovered: > reflect.Value.SetMapIndex: value of type string is not assignable to type pki.keyId This was caused by returning a map with type issuerId->keyId; instead switch to returning string->string maps so the audit log can properly HMAC them. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Clarify error message on missing defaults When the default issuer and key are missing (and haven't yet been specified), we should clarify that error message. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Update test semantics for new changes This makes two minor changes to the existing test suite: 1. Importing partial bundles should now succeed, where they'd previously error. 2. fetchCertBySerial no longer handles CA certificates. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add support for deleting all keys, issuers The old DELETE /root code must now delete all keys and issuers for backwards compatibility. We strongly suggest calling individual delete methods (DELETE /key/:key_ref or DELETE /issuer/:issuer_ref) instead, for finer control. In the process, we detect whether the deleted key/issuers was set as the default. This will allow us to warn (from the single key/deletion issuer code) whether or not the default was deleted (while allowing the operation to succeed). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Introduce defaultRef constant within PKI - Replace hardcoded "default" references with a constant to easily identify various usages. - Use the addIssuerRefField function instead of redefining the field in various locations. * Rework PKI test TestBackend_Root_Idempotency - Validate that generate/root calls are no longer idempotent, but the bundle importing does not generate new keys/issuers - As before make sure that the delete root api resets everything - Address a bug within the storage that we bombed when we had multiple different key types within storage. * Assign Name=current to migrated key and issuer - Detail I missed from the RFC was to assign the Name field as "current" for migrated key and issuer. * Build CRL upon PKI intermediary set-signed api called - Add a call to buildCRL if we created an issuer within pathImportIssuers - Augment existing FullCAChain to verify we have a proper CRL post set-signed api call - Remove a code block writing out "ca" storage entry that is no longer used. * Identify which certificate or key failed When importing complex chains, we should identify in which certificate or key the failure occurred. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * PKI migration writes out empty migration log entry - Since the elements of the struct were not exported we serialized an empty migration log to disk and would re-run the migration * Add chain-building logic to PKI issuers path With the one-entry-per-issuer approach, CA Chains become implicitly constructed from the pool of issuers. This roughly matches the existing expectations from /config/ca (wherein a chain could be provided) and /intemediate/set-signed (where a chain may be provided). However, in both of those cases, we simply accepted a chain. Here, we need to be able to reconstruct the chain from parts on disk. However, with potential rotation of roots, we need to be aware of disparate chains. Simply concating together all issuers isn't sufficient. Thus we need to be able to parse a certificate's Issuer and Subject field and reconstruct valid (and potentially parallel) parent<->child mappings. This attempts to handle roots, intermediates, cross-signed intermediates, cross-signed roots, and rotated keys (wherein one might not have a valid signature due to changed key material with the same subject). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Return CA Chain when fetching issuers This returns the CA Chain attribute of an issuer, showing its computed chain based on other issuers in the database, when fetching a specific issuer. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add testing for chain building Using the issuance infrastructure, we generate new certificates (either roots or intermediates), positing that this is roughly equivalent to importing an external bundle (minus error handling during partial imports). This allows us to incrementally construct complex chains, creating reissuance cliques and cross-signing cycles. By using ECDSA certificates, we avoid high signature verification and key generation times. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Allow manual construction of issuer chain Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Fix handling of duplicate names With the new issuer field (manual_chain), we can no longer err when a name already exists: we might be updating the existing issuer (with the same name), but changing its manual_chain field. Detect this error and correctly handle it. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add tests for manual chain building We break the clique, instead building these chains manually, ensuring that the remaining chains do not change and only the modified certs change. We then reset them (back to implicit chain building) and ensure we get the same results as earlier. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add stricter verification of issuers PEM format This ensures each issuer is only a single certificate entry (as validated by count and parsing) without any trailing data. We further ensure that each certificate PEM has leading and trailing spaces removed with only a single trailing new line remaining. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Fix full chain building Don't set the legacy IssuingCA field on the certificate bundle, as we prefer the CAChain field over it. Additionally, building the full chain could result in duplicate certificates when the CAChain included the leaf certificate itself. When building the full chain, ensure we don't include the bundle's certificate twice. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add stricter tests for full chain construction We wish to ensure that each desired certificate in the chain is only present once. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Rename PKI types to avoid constant variable name collisions keyId -> keyID issuerId -> issuerID key -> keyEntry issuer -> issuerEntry keyConfig -> keyConfigEntry issuerConfig -> issuerConfigEntry * Update CRL handling for multiple issuers When building CRLs, we've gotta make sure certs issued by that issuer land up on that issuer's CRL and not some other CRL. If no CRL is found (matching a cert), we'll place it on the default CRL. However, in the event of equivalent issuers (those with the same subject AND the same key material) -- perhaps due to reissuance -- we'll only create a single (unified) CRL for them. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Allow fetching updated CRL locations This updates fetchCertBySerial to support querying the default issuer's CRL. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Remove legacy CRL storage location test case Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Update to CRLv2 Format to copy RawIssuer When using the older Certificate.CreateCRL(...) call, Go's x509 library copies the parsed pkix.Name version of the CRL Issuer's Subject field. For certain constructed CAs, this fails since pkix.Name is not suitable for round-tripping. This also builds a CRLv1 (per RFC 5280) CRL. In updating to the newer x509.CreateRevocationList(...) call, we can construct the CRL in the CRLv2 format and correctly copy the issuer's name. However, this requires holding an additional field per-CRL, the CRLNumber field, which is required in Go's implementation of CRLv2 (though OPTIONAL in the spec). We store this on the new LocalCRLConfigEntry object, per-CRL. Co-authored-by: Alexander Scheel <alex.scheel@hashicorp.com> Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add comment regarding CRL non-assignment in GOTO In previous versions of Vault, it was possible to sign an empty CRL (when the CRL was disabled and a force-rebuild was requested). Add a comment about this case. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Allow fetching the specified issuer's CRL We add a new API endpoint to fetch the specified issuer's CRL directly (rather than the default issuer's CRL at /crl and /certs/crl). We also add a new test to validate the CRL in a multi-root scenario and ensure it is signed with the correct keys. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add new PKI key prefix to seal wrapped storage (#15126) * Refactor common backend initialization within backend_test - Leverage an existing helper method within the PKI backend tests to setup a PKI backend with storage. * Add ability to read legacy cert bundle if the migration has not occurred on secondaries. - Track the migration state forbidding an issuer/key writing api call if we have not migrated - For operations that just need to read the CA bundle, use the same tracking variable to switch between reading the legacy bundle or use the new key/issuer storage. - Add an invalidation function that will listen for updates to our log path to refresh the state on secondary clusters. * Always write migration entry to trigger secondary clusters to wake up - Some PR feedback and handle a case in which the primary cluster does not have a CA bundle within storage but somehow a secondary does. * Update CA Chain to report entire chain This merges the ca_chain JSON field (of the /certs/ca_chain path) with the regular certificate field, returning the root of trust always. This also affects the non-JSON (raw) endpoints as well. We return the default issuer's chain here, rather than all known issuers (as that may not form a strict chain). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Allow explicit issuer override on roles When a role is used to generate a certificate (such as with the sign/ and issue/ legacy paths or the legacy sign-verbatim/ paths), we prefer that issuer to the one on the request. This allows operators to set an issuer (other than default) for requests to be issued against, effectively making the change no different from the users' perspective as it is "just" a different role name. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add tests for role-based issuer selection Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Expand NotAfter limit enforcement behavior Vault previously strictly enforced NotAfter/ttl values on certificate requests, erring if the requested TTL extended past the NotAfter date of the issuer. In the event of issuing an intermediate, this behavior was ignored, instead permitting the issuance. Users generally do not think to check their issuer's NotAfter date when requesting a certificate; thus this behavior was generally surprising. Per RFC 5280 however, issuers need to maintain status information throughout the life cycle of the issued cert. If this leaf cert were to be issued for a longer duration than the parent issuer, the CA must still maintain revocation information past its expiration. Thus, we add an option to the issuer to change the desired behavior: - err, to err out, - permit, to permit the longer NotAfter date, or - truncate, to silently truncate the expiration to the issuer's NotAfter date. Since expiration of certificates in the system's trust store are not generally validated (when validating an arbitrary leaf, e.g., during TLS validation), permit should generally only be used in that case. However, browsers usually validate intermediate's validity periods, and thus truncate should likely be used (as with permit, the leaf's chain will not validate towards the end of the issuance period). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add tests for expanded issuance behaviors Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add warning on keyless default issuer (#15178) Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Update PKI to new Operations framework (#15180) The backend Framework has updated Callbacks (used extensively in PKI) to become deprecated; Operations takes their place and clarifies forwarding of requests. We switch to the new format everywhere, updating some bad assumptions about forwarding along the way. Anywhere writes are handled (that should be propagated to all nodes in all clusters), we choose to forward the request all the way up to the performance primary cluster's primary node. This holds for issuers/keys, roles, and configs (such as CRL config, which is globally set for all clusters despite all clusters having their own separate CRL). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Kitography/vault 5474 rebase (#15150) * These parts work (put in signature so that backend wouldn't break, but missing fields, desc, etc.) * Import and Generate API calls w/ needed additions to SDK. * make fmt * Add Help/Sync Text, fix some of internal/exported/kms code. * Fix PEM/DER Encoding issue. * make fmt * Standardize keyIdParam, keyNameParam, keyTypeParam * Add error response if key to be deleted is in use. * replaces all instances of "default" in code with defaultRef * Updates from Callbacks to Operations Function with explicit forwarding. * Fixes a panic with names not being updated everywhere. * add a logged error in addition to warning on deleting default key. * Normalize whitespace upon importing keys. Authored-by: Alexander Scheel <alexander.m.scheel@gmail.com> * Fix isKeyInUse functionality. * Fixes tests associated with newline at end of key pem. * Add alternative proposal PKI aliased paths (#15211) * Add aliased path for root/rotate/:exported This adds a user-friendly path name for generating a rotated root. We automatically choose the name "next" for the newly generated root at this path if it doesn't already exist. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add aliased path for intermediate/cross-sign This allows cross-signatures to work. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add path for replacing the current root This updates default to point to the value of the issuer with name "next" rather than its current value. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Remove plural issuers/ in signing paths These paths use a single issuer and thus shouldn't include the plural issuers/ as a path prefix, instead using the singular issuer/ path prefix. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Only warn if default issuer was imported When the default issuer was not (re-)imported, we'd fail to find it, causing an extraneous warning about missing keys, even though this issuer indeed had a key. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add missing issuer sign/issue paths Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Clean up various warnings within the PKI package (#15230) * Rebuild CRLs on secondary performance clusters post migration and on new/updated issuers - Hook into the backend invalidation function so that secondaries are notified of new/updated issuer or migrations occuring on the primary cluster. Upon notification schedule a CRL rebuild to take place upon the next process to read/update the CRL or within the periodic function if no request comes in. * Schedule rebuilding PKI CRLs on active nodes only - Address an issue that we were scheduling the rebuilding of a CRL on standby nodes, which would not be able to write to storage. - Fix an issue with standby nodes not correctly determining that a migration previously occurred. * Return legacy CRL storage path when no migration has occurred. * Handle issuer, keys locking (#15227) * Handle locking of issuers during writes We need a write lock around writes to ensure serialization of modifications. We use a single lock for both issuer and key updates, in part because certain operations (like deletion) will potentially affect both. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add missing b.useLegacyBundleCaStorage guards Several locations needed to guard against early usage of the new issuers endpoint pre-migration. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Address PKI to properly support managed keys (#15256) * Address codebase for managed key fixes * Add proper public key comparison for better managed key support to importKeys * Remove redundant public key fetching within PKI importKeys * Correctly handle rebuilding remaining chains When deleting a specific issuer, we might impact the chains. From a consistency perspective, we need to ensure the remaining chains are correct and don't refer to the since-deleted issuer, so trigger a full rebuild here. We don't need to call this in the delete-the-world (DELETE /root) code path, as there shouldn't be any remaining issuers or chains to build. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Remove legacy CRL bundle on world deletion When calling DELETE /root, we should remove the legacy CRL bundle, since we're deleting the legacy CA issuer bundle as well. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Remove deleted issuers' CRL entries Since CRLs are no longer resolvable after deletion (due to missing issuer ID, which will cause resolution to fail regardless of if an ID or a name/default reference was used), we should delete these CRLs from storage to avoid leaking them. In the event that this issuer comes back (with key material), we can simply rebuild the CRL at that time (from the remaining revoked storage entries). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add unauthed JSON fetching of CRLs, Issuers (#15253) Default to fetching JSON CRL for consistency This makes the bare issuer-specific CRL fetching endpoint return the JSON-wrapped CRL by default, moving the DER CRL to a specific endpoint. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> Add JSON-specific endpoint for fetching issuers Unlike the unqualified /issuer/:ref endpoint (which also returns JSON), we have a separate /issuer/:ref/json endpoint to return _only_ the PEM-encoded certificate and the chain, mirroring the existing /cert/ca endpoint but for a specific issuer. This allows us to make the endpoint unauthenticated, whereas the bare endpoint would remain authenticated and usually privileged. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> Add tests for raw JSON endpoints Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add unauthenticated issuers endpoints to PKI table This adds the unauthenticated issuers endpoints? - LIST /issuers, - Fetching _just_ the issuer certificates (in JSON/DER/PEM form), and - Fetching the CRL of this issuer (in JSON/DER/PEM form). Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * Add issuer usage restrictions bitset This allows issuers to have usage restrictions, limiting whether they can be used to issue certificates or if they can generate CRLs. This allows certain issuers to not generate a CRL (if the global config is with the CRL enabled) or allows the issuer to not issue new certificates (but potentially letting the CRL generation continue). Setting both fields to false effectively forms a soft delete capability. Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com> * PKI Pod rotation Add Base Changelog (#15283) * PKI Pod rotation changelog. * Use feature release-note formatting of changelog. Co-authored-by: Steven Clark <steven.clark@hashicorp.com> Co-authored-by: Kit Haines <kit.haines@hashicorp.com> Co-authored-by: kitography <khaines@mit.edu>
2022-05-11 16:42:28 +00:00
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/logical"
"github.com/stretchr/testify/require"
2015-03-14 04:15:20 +00:00
)
2015-03-14 06:22:48 +00:00
func BenchmarkBackendRoute(b *testing.B) {
patterns := []string{
"foo",
"bar/(?P<name>.+?)",
"baz/(?P<name>what)",
`aws/policy/(?P<policy>\w)`,
`aws/(?P<policy>\w)`,
}
backend := &Backend{Paths: make([]*Path, 0, len(patterns))}
for _, p := range patterns {
backend.Paths = append(backend.Paths, &Path{Pattern: p})
}
// Warm any caches
backend.Route("aws/policy/foo")
// Reset the timer since we did a lot above
2015-03-14 06:22:48 +00:00
b.ResetTimer()
// Run through and route. We do a sanity check of the return value
2015-03-14 06:22:48 +00:00
for i := 0; i < b.N; i++ {
if p := backend.Route("aws/policy/foo"); p == nil {
2015-03-14 06:22:48 +00:00
b.Fatal("p should not be nil")
}
}
}
2015-03-14 06:58:20 +00:00
func TestBackend_impl(t *testing.T) {
2015-03-15 21:57:19 +00:00
var _ logical.Backend = new(Backend)
2015-03-14 06:58:20 +00:00
}
func TestBackendHandleRequestFieldWarnings(t *testing.T) {
handler := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
return &logical.Response{
Data: map[string]interface{}{
"an_int": data.Get("an_int"),
"a_string": data.Get("a_string"),
"name": data.Get("name"),
},
}, nil
}
backend := &Backend{
Paths: []*Path{
{
Pattern: "foo/bar/(?P<name>.+)",
Fields: map[string]*FieldSchema{
"an_int": {Type: TypeInt},
"a_string": {Type: TypeString},
"name": {Type: TypeString},
},
Operations: map[logical.Operation]OperationHandler{
logical.UpdateOperation: &PathOperation{Callback: handler},
},
},
},
}
ctx := context.Background()
resp, err := backend.HandleRequest(ctx, &logical.Request{
Operation: logical.UpdateOperation,
Path: "foo/bar/baz",
Data: map[string]interface{}{
"an_int": 10,
"a_string": "accepted",
"unrecognized1": "unrecognized",
"unrecognized2": 20.2,
"name": "noop",
},
})
require.NoError(t, err)
require.NotNil(t, resp)
t.Log(resp.Warnings)
require.Len(t, resp.Warnings, 2)
require.True(t, strutil.StrListContains(resp.Warnings, "Endpoint ignored these unrecognized parameters: [unrecognized1 unrecognized2]"))
require.True(t, strutil.StrListContains(resp.Warnings, "Endpoint replaced the value of these parameters with the values captured from the endpoint's path: [name]"))
}
2015-03-14 06:58:20 +00:00
func TestBackendHandleRequest(t *testing.T) {
callback := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
2015-03-15 21:57:19 +00:00
return &logical.Response{
2015-03-14 06:58:20 +00:00
Data: map[string]interface{}{
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
"value": data.Get("value"),
2015-03-14 06:58:20 +00:00
},
}, nil
}
handler := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
return &logical.Response{
Data: map[string]interface{}{
"amount": data.Get("amount"),
},
}, nil
}
2015-03-14 06:58:20 +00:00
b := &Backend{
Paths: []*Path{
{
2015-03-14 06:58:20 +00:00
Pattern: "foo/bar",
Fields: map[string]*FieldSchema{
"value": {Type: TypeInt},
2015-03-14 06:58:20 +00:00
},
2015-03-15 21:57:19 +00:00
Callbacks: map[logical.Operation]OperationFunc{
logical.ReadOperation: callback,
},
2015-03-14 06:58:20 +00:00
},
{
Pattern: "foo/baz/handler",
Fields: map[string]*FieldSchema{
"amount": {Type: TypeInt},
},
Operations: map[logical.Operation]OperationHandler{
logical.ReadOperation: &PathOperation{Callback: handler},
},
},
{
Pattern: "foo/both/handler",
Fields: map[string]*FieldSchema{
"amount": {Type: TypeInt},
},
Callbacks: map[logical.Operation]OperationFunc{
logical.ReadOperation: callback,
},
Operations: map[logical.Operation]OperationHandler{
logical.ReadOperation: &PathOperation{Callback: handler},
},
},
2015-03-14 06:58:20 +00:00
},
system: &logical.StaticSystemView{},
2015-03-14 06:58:20 +00:00
}
for _, path := range []string{"foo/bar", "foo/baz/handler", "foo/both/handler"} {
key := "value"
if strings.Contains(path, "handler") {
key = "amount"
}
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.ReadOperation,
Path: path,
Data: map[string]interface{}{key: "42"},
})
if err != nil {
t.Fatalf("err: %s", err)
}
if resp.Data[key] != 42 {
t.Fatalf("bad: %#v", resp)
}
2015-03-14 06:58:20 +00:00
}
}
func TestBackendHandleRequest_Forwarding(t *testing.T) {
tests := map[string]struct {
fwdStandby bool
fwdSecondary bool
isLocal bool
isStandby bool
isSecondary bool
expectFwd bool
nilSysView bool
}{
"no forward": {
expectFwd: false,
},
"no forward, local restricted": {
isSecondary: true,
fwdSecondary: true,
isLocal: true,
expectFwd: false,
},
"no forward, forwarding not requested": {
isSecondary: true,
isStandby: true,
expectFwd: false,
},
"forward, secondary": {
fwdSecondary: true,
isSecondary: true,
expectFwd: true,
},
"forward, standby": {
fwdStandby: true,
isStandby: true,
expectFwd: true,
},
"no forward, only secondary": {
fwdSecondary: true,
isStandby: true,
expectFwd: false,
},
"no forward, only standby": {
fwdStandby: true,
isSecondary: true,
expectFwd: false,
},
"nil system view": {
nilSysView: true,
expectFwd: false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
var replState consts.ReplicationState
if test.isStandby {
replState.AddState(consts.ReplicationPerformanceStandby)
}
if test.isSecondary {
replState.AddState(consts.ReplicationPerformanceSecondary)
}
b := &Backend{
Paths: []*Path{
{
Pattern: "foo",
Operations: map[logical.Operation]OperationHandler{
logical.ReadOperation: &PathOperation{
Callback: func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
return nil, nil
},
ForwardPerformanceSecondary: test.fwdSecondary,
ForwardPerformanceStandby: test.fwdStandby,
},
},
},
},
system: &logical.StaticSystemView{
LocalMountVal: test.isLocal,
ReplicationStateVal: replState,
},
}
if test.nilSysView {
b.system = nil
}
_, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.ReadOperation,
Path: "foo",
})
if !test.expectFwd && err != nil {
t.Fatalf("unexpected err: %v", err)
}
if test.expectFwd && err != logical.ErrReadOnly {
t.Fatalf("expected ErrReadOnly, got: %v", err)
}
})
}
}
func TestBackendHandleRequest_badwrite(t *testing.T) {
callback := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
return &logical.Response{
Data: map[string]interface{}{
"value": data.Get("value").(bool),
},
}, nil
}
b := &Backend{
Paths: []*Path{
{
Pattern: "foo/bar",
Fields: map[string]*FieldSchema{
"value": {Type: TypeBool},
},
Callbacks: map[logical.Operation]OperationFunc{
2016-01-07 15:30:47 +00:00
logical.UpdateOperation: callback,
},
},
},
}
resp, err := b.HandleRequest(context.Background(), &logical.Request{
2016-01-07 15:30:47 +00:00
Operation: logical.UpdateOperation,
Path: "foo/bar",
Data: map[string]interface{}{"value": "3false3"},
})
if err != nil {
t.Fatalf("err: %s", err)
}
if !strings.Contains(resp.Data["error"].(string), "Field validation failed") {
t.Fatalf("bad: %#v", resp)
}
}
2015-03-14 06:58:20 +00:00
func TestBackendHandleRequest_404(t *testing.T) {
callback := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
2015-03-15 21:57:19 +00:00
return &logical.Response{
2015-03-14 06:58:20 +00:00
Data: map[string]interface{}{
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
"value": data.Get("value"),
2015-03-14 06:58:20 +00:00
},
}, nil
}
b := &Backend{
Paths: []*Path{
{
2015-03-14 06:58:20 +00:00
Pattern: `foo/bar`,
Fields: map[string]*FieldSchema{
"value": {Type: TypeInt},
2015-03-14 06:58:20 +00:00
},
2015-03-15 21:57:19 +00:00
Callbacks: map[logical.Operation]OperationFunc{
logical.ReadOperation: callback,
},
2015-03-14 06:58:20 +00:00
},
},
}
_, err := b.HandleRequest(context.Background(), &logical.Request{
2015-03-15 21:57:19 +00:00
Operation: logical.ReadOperation,
Path: "foo/baz",
Data: map[string]interface{}{"value": "84"},
2015-03-14 06:58:20 +00:00
})
2015-03-15 21:57:19 +00:00
if err != logical.ErrUnsupportedPath {
2015-03-14 06:58:20 +00:00
t.Fatalf("err: %s", err)
}
}
func TestBackendHandleRequest_help(t *testing.T) {
b := &Backend{
Paths: []*Path{
{
Pattern: "foo/bar",
Fields: map[string]*FieldSchema{
"value": {Type: TypeInt},
},
HelpSynopsis: "foo",
HelpDescription: "bar",
},
},
}
resp, err := b.HandleRequest(context.Background(), &logical.Request{
2015-03-15 21:57:19 +00:00
Operation: logical.HelpOperation,
Path: "foo/bar",
Data: map[string]interface{}{"value": "42"},
})
if err != nil {
t.Fatalf("err: %s", err)
}
if resp.Data["help"] == nil {
t.Fatalf("bad: %#v", resp)
}
}
2015-04-04 03:36:47 +00:00
func TestBackendHandleRequest_helpRoot(t *testing.T) {
b := &Backend{
Help: "42",
}
resp, err := b.HandleRequest(context.Background(), &logical.Request{
2015-04-04 03:36:47 +00:00
Operation: logical.HelpOperation,
Path: "",
})
if err != nil {
t.Fatalf("err: %s", err)
}
if resp.Data["help"] == nil {
t.Fatalf("bad: %#v", resp)
}
}
func TestBackendHandleRequest_renewAuth(t *testing.T) {
b := &Backend{}
resp, err := b.HandleRequest(context.Background(), logical.RenewAuthRequest("/foo", &logical.Auth{}, nil))
if err != nil {
t.Fatalf("err: %s", err)
}
if !resp.IsError() {
t.Fatalf("bad: %#v", resp)
}
}
func TestBackendHandleRequest_renewAuthCallback(t *testing.T) {
called := new(uint32)
callback := func(context.Context, *logical.Request, *FieldData) (*logical.Response, error) {
atomic.AddUint32(called, 1)
return nil, nil
}
b := &Backend{
AuthRenew: callback,
}
_, err := b.HandleRequest(context.Background(), logical.RenewAuthRequest("/foo", &logical.Auth{}, nil))
if err != nil {
t.Fatalf("err: %s", err)
}
if v := atomic.LoadUint32(called); v != 1 {
t.Fatalf("bad: %#v", v)
}
}
2015-03-19 19:20:25 +00:00
func TestBackendHandleRequest_renew(t *testing.T) {
called := new(uint32)
callback := func(context.Context, *logical.Request, *FieldData) (*logical.Response, error) {
atomic.AddUint32(called, 1)
2015-03-19 19:20:25 +00:00
return nil, nil
}
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
secret := &Secret{
Type: "foo",
Renew: callback,
}
2015-03-19 19:20:25 +00:00
b := &Backend{
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
Secrets: []*Secret{secret},
2015-03-19 19:20:25 +00:00
}
_, err := b.HandleRequest(context.Background(), logical.RenewRequest("/foo", secret.Response(nil, nil).Secret, nil))
2015-03-19 19:20:25 +00:00
if err != nil {
t.Fatalf("err: %s", err)
}
if v := atomic.LoadUint32(called); v != 1 {
2015-03-19 19:20:25 +00:00
t.Fatalf("bad: %#v", v)
}
}
2015-03-19 18:41:41 +00:00
func TestBackendHandleRequest_revoke(t *testing.T) {
called := new(uint32)
callback := func(context.Context, *logical.Request, *FieldData) (*logical.Response, error) {
atomic.AddUint32(called, 1)
2015-03-19 18:41:41 +00:00
return nil, nil
}
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
secret := &Secret{
Type: "foo",
Revoke: callback,
}
2015-03-19 18:41:41 +00:00
b := &Backend{
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
Secrets: []*Secret{secret},
2015-03-19 18:41:41 +00:00
}
_, err := b.HandleRequest(context.Background(), logical.RevokeRequest("/foo", secret.Response(nil, nil).Secret, nil))
2015-03-19 18:41:41 +00:00
if err != nil {
t.Fatalf("err: %s", err)
}
if v := atomic.LoadUint32(called); v != 1 {
2015-03-19 18:41:41 +00:00
t.Fatalf("bad: %#v", v)
}
}
2015-03-18 00:15:23 +00:00
func TestBackendHandleRequest_rollback(t *testing.T) {
called := new(uint32)
callback := func(_ context.Context, req *logical.Request, kind string, data interface{}) error {
2015-03-18 00:15:23 +00:00
if data == "foo" {
atomic.AddUint32(called, 1)
2015-03-18 00:15:23 +00:00
}
return nil
2015-03-18 00:15:23 +00:00
}
b := &Backend{
2016-05-14 23:35:36 +00:00
WALRollback: callback,
WALRollbackMinAge: 1 * time.Millisecond,
2015-03-18 00:15:23 +00:00
}
storage := new(logical.InmemStorage)
if _, err := PutWAL(context.Background(), storage, "kind", "foo"); err != nil {
2015-03-18 00:15:23 +00:00
t.Fatalf("err: %s", err)
}
time.Sleep(10 * time.Millisecond)
_, err := b.HandleRequest(context.Background(), &logical.Request{
2015-03-18 00:15:23 +00:00
Operation: logical.RollbackOperation,
Path: "",
Storage: storage,
})
if err != nil {
t.Fatalf("err: %s", err)
}
if v := atomic.LoadUint32(called); v != 1 {
2015-03-18 00:15:23 +00:00
t.Fatalf("bad: %#v", v)
}
}
func TestBackendHandleRequest_rollbackMinAge(t *testing.T) {
called := new(uint32)
callback := func(_ context.Context, req *logical.Request, kind string, data interface{}) error {
if data == "foo" {
atomic.AddUint32(called, 1)
}
return nil
}
b := &Backend{
2016-05-14 23:35:36 +00:00
WALRollback: callback,
WALRollbackMinAge: 5 * time.Second,
}
storage := new(logical.InmemStorage)
if _, err := PutWAL(context.Background(), storage, "kind", "foo"); err != nil {
t.Fatalf("err: %s", err)
}
_, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.RollbackOperation,
Path: "",
Storage: storage,
})
if err != nil {
t.Fatalf("err: %s", err)
}
if v := atomic.LoadUint32(called); v != 0 {
t.Fatalf("bad: %#v", v)
}
}
func TestBackendHandleRequest_unsupportedOperation(t *testing.T) {
callback := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
2015-03-15 21:57:19 +00:00
return &logical.Response{
Data: map[string]interface{}{
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
"value": data.Get("value"),
},
}, nil
}
b := &Backend{
Paths: []*Path{
{
Pattern: `foo/bar`,
Fields: map[string]*FieldSchema{
"value": {Type: TypeInt},
},
2015-03-15 21:57:19 +00:00
Callbacks: map[logical.Operation]OperationFunc{
logical.ReadOperation: callback,
},
},
},
}
_, err := b.HandleRequest(context.Background(), &logical.Request{
2016-01-07 15:30:47 +00:00
Operation: logical.UpdateOperation,
Path: "foo/bar",
Data: map[string]interface{}{"value": "84"},
})
2015-03-15 21:57:19 +00:00
if err != logical.ErrUnsupportedOperation {
t.Fatalf("err: %s", err)
}
}
2015-03-14 06:58:20 +00:00
func TestBackendHandleRequest_urlPriority(t *testing.T) {
callback := func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) {
2015-03-15 21:57:19 +00:00
return &logical.Response{
2015-03-14 06:58:20 +00:00
Data: map[string]interface{}{
vault: clean up VaultID duplications, make secret responses clearer /cc @armon - This is a reasonably major refactor that I think cleans up a lot of the logic with secrets in responses. The reason for the refactor is that while implementing Renew/Revoke in logical/framework I found the existing API to be really awkward to work with. Primarily, we needed a way to send down internal data for Vault core to store since not all the data you need to revoke a key is always sent down to the user (for example the user than AWS key belongs to). At first, I was doing this manually in logical/framework with req.Storage, but this is going to be such a common event that I think its something core should assist with. Additionally, I think the added context for secrets will be useful in the future when we have a Vault API for returning orphaned out keys: we can also return the internal data that might help an operator. So this leads me to this refactor. I've removed most of the fields in `logical.Response` and replaced it with a single `*Secret` pointer. If this is non-nil, then the response represents a secret. The Secret struct encapsulates all the lease info and such. It also has some fields on it that are only populated at _request_ time for Revoke/Renew operations. There is precedent for this sort of behavior in the Go stdlib where http.Request/http.Response have fields that differ based on client/server. I copied this style. All core unit tests pass. The APIs fail for obvious reasons but I'll fix that up in the next commit.
2015-03-19 22:11:42 +00:00
"value": data.Get("value"),
2015-03-14 06:58:20 +00:00
},
}, nil
}
b := &Backend{
Paths: []*Path{
{
2015-03-14 06:58:20 +00:00
Pattern: `foo/(?P<value>\d+)`,
Fields: map[string]*FieldSchema{
"value": {Type: TypeInt},
2015-03-14 06:58:20 +00:00
},
2015-03-15 21:57:19 +00:00
Callbacks: map[logical.Operation]OperationFunc{
logical.ReadOperation: callback,
},
2015-03-14 06:58:20 +00:00
},
},
}
resp, err := b.HandleRequest(context.Background(), &logical.Request{
2015-03-15 21:57:19 +00:00
Operation: logical.ReadOperation,
Path: "foo/42",
Data: map[string]interface{}{"value": "84"},
2015-03-14 06:58:20 +00:00
})
if err != nil {
t.Fatalf("err: %s", err)
}
if resp.Data["value"] != 42 {
t.Fatalf("bad: %#v", resp)
}
}
func TestBackendRoute(t *testing.T) {
cases := map[string]struct {
Patterns []string
Path string
Match string
}{
"no match": {
[]string{"foo"},
"bar",
"",
},
"exact": {
[]string{"foo"},
"foo",
"^foo$",
},
"regexp": {
[]string{"fo+"},
"foo",
"^fo+$",
},
"anchor-start": {
[]string{"bar"},
"foobar",
"",
},
"anchor-end": {
[]string{"bar"},
"barfoo",
"",
},
"anchor-ambiguous": {
[]string{"mounts", "sys/mounts"},
"sys/mounts",
"^sys/mounts$",
},
}
for n, tc := range cases {
paths := make([]*Path, len(tc.Patterns))
for i, pattern := range tc.Patterns {
paths[i] = &Path{Pattern: pattern}
}
b := &Backend{Paths: paths}
result := b.Route(tc.Path)
match := ""
if result != nil {
match = result.Pattern
}
if match != tc.Match {
t.Fatalf("bad: %s\n\nExpected: %s\nGot: %s",
n, tc.Match, match)
}
}
}
func TestBackendSecret(t *testing.T) {
cases := map[string]struct {
Secrets []*Secret
Search string
Match bool
}{
"no match": {
[]*Secret{{Type: "foo"}},
"bar",
false,
},
"match": {
[]*Secret{{Type: "foo"}},
"foo",
true,
},
}
for n, tc := range cases {
b := &Backend{Secrets: tc.Secrets}
result := b.Secret(tc.Search)
if tc.Match != (result != nil) {
t.Fatalf("bad: %s\n\nExpected match: %v", n, tc.Match)
}
if result != nil && result.Type != tc.Search {
t.Fatalf("bad: %s\n\nExpected matching type: %#v", n, result)
}
}
}
2015-03-14 04:15:20 +00:00
func TestFieldSchemaDefaultOrZero(t *testing.T) {
cases := map[string]struct {
Schema *FieldSchema
Value interface{}
}{
"default set": {
&FieldSchema{Type: TypeString, Default: "foo"},
"foo",
},
"default not set": {
&FieldSchema{Type: TypeString},
"",
},
"default duration set": {
&FieldSchema{Type: TypeDurationSecond, Default: 60},
60,
},
"default duration int64": {
&FieldSchema{Type: TypeDurationSecond, Default: int64(60)},
60,
},
"default duration string": {
&FieldSchema{Type: TypeDurationSecond, Default: "60s"},
60,
},
"illegal default duration string": {
&FieldSchema{Type: TypeDurationSecond, Default: "h1"},
0,
},
"default duration time.Duration": {
&FieldSchema{Type: TypeDurationSecond, Default: 60 * time.Second},
60,
},
"default duration not set": {
&FieldSchema{Type: TypeDurationSecond},
0,
},
2018-08-13 18:02:44 +00:00
"default signed positive duration set": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: 60},
60,
},
"default signed positive duration int64": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: int64(60)},
60,
},
"default signed positive duration string": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: "60s"},
60,
},
"illegal default signed duration string": {
&FieldSchema{Type: TypeDurationSecond, Default: "-h1"},
0,
},
"default signed positive duration time.Duration": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: 60 * time.Second},
60,
},
"default signed negative duration set": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: -60},
-60,
},
"default signed negative duration int64": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: int64(-60)},
-60,
},
"default signed negative duration string": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: "-60s"},
-60,
},
"default signed negative duration time.Duration": {
&FieldSchema{Type: TypeSignedDurationSecond, Default: -60 * time.Second},
-60,
},
"default signed negative duration not set": {
&FieldSchema{Type: TypeSignedDurationSecond},
0,
},
2018-08-13 18:02:44 +00:00
"default header not set": {
&FieldSchema{Type: TypeHeader},
http.Header{},
},
2015-03-14 04:15:20 +00:00
}
for name, tc := range cases {
actual := tc.Schema.DefaultOrZero()
if !reflect.DeepEqual(actual, tc.Value) {
t.Errorf("bad: %s\n\nExpected: %#v\nGot: %#v",
2015-03-14 04:15:20 +00:00
name, tc.Value, actual)
}
}
}
AWS upgrade role entries (#7025) * upgrade aws roles * test upgrade aws roles * Initialize aws credential backend at mount time * add a TODO * create end-to-end test for builtin/credential/aws * fix bug in initializer * improve comments * add Initialize() to logical.Backend * use Initialize() in Core.enableCredentialInternal() * use InitializeRequest to call Initialize() * improve unit testing for framework.Backend * call logical.Backend.Initialize() from all of the places that it needs to be called. * implement backend.proto changes for logical.Backend.Initialize() * persist current role storage version when upgrading aws roles * format comments correctly * improve comments * use postUnseal funcs to initialize backends * simplify test suite * improve test suite * simplify logic in aws role upgrade * simplify aws credential initialization logic * simplify logic in aws role upgrade * use the core's activeContext for initialization * refactor builtin/plugin/Backend * use a goroutine to upgrade the aws roles * misc improvements and cleanup * do not run AWS role upgrade on DR Secondary * always call logical.Backend.Initialize() when loading a plugin. * improve comments * on standbys and DR secondaries we do not want to run any kind of upgrade logic * fix awsVersion struct * clarify aws version upgrade * make the upgrade logic for aws auth more explicit * aws upgrade is now called from a switch * fix fallthrough bug * simplify logic * simplify logic * rename things * introduce currentAwsVersion const to track aws version * improve comments * rearrange things once more * conglomerate things into one function * stub out aws auth initialize e2e test * improve aws auth initialize e2e test * finish aws auth initialize e2e test * tinker with aws auth initialize e2e test * tinker with aws auth initialize e2e test * tinker with aws auth initialize e2e test * fix typo in test suite * simplify logic a tad * rearrange assignment * Fix a few lifecycle related issues in #7025 (#7075) * Fix panic when plugin fails to load
2019-07-05 23:55:40 +00:00
func TestInitializeBackend(t *testing.T) {
var inited bool
backend := &Backend{InitializeFunc: func(context.Context, *logical.InitializationRequest) error {
inited = true
return nil
}}
backend.Initialize(nil, &logical.InitializationRequest{Storage: nil})
if !inited {
t.Fatal("backend should be open")
}
}
// TestFieldTypeMethods tries to ensure our switch-case statements for the
// FieldType "enum" are complete.
func TestFieldTypeMethods(t *testing.T) {
unknownFormat := convertType(TypeInvalid).format
for i := TypeInvalid + 1; i < typeInvalidMax; i++ {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
if i.String() == TypeInvalid.String() {
t.Errorf("unknown type string for %d", i)
}
if convertType(i).format == unknownFormat {
t.Errorf("unknown schema for %d", i)
}
_ = i.Zero()
})
}
}