Commit Graph

81 Commits

Author SHA1 Message Date
hc-github-team-secure-vault-core 1d9e560f0f
backport of commit 2f677665b37fcced51737cdef7abbebb4c719529 (#21527)
Co-authored-by: Max Bowsher <maxbowsher@gmail.com>
2023-07-06 20:01:33 +00:00
hc-github-team-secure-vault-core 96596f255b
backport of commit e65d295c8809f4cc61b63bbc03293586c71c5483 (#20906)
Co-authored-by: Max Bowsher <maxbowsher@gmail.com>
2023-05-31 19:41:39 +00:00
claire bontempo 5f64520dac
UI: remove references to comma separation for string array edit types (#20163)
* remove intercepting helpText

* add subtext directly to StringList input component

* update tests and add coverage for new openapi-attrs util

* update test

* add warning validation to input

* lol is this right i dont know go

* literally no idea what im doing

* add Description to display attrs struct

* update struct comment

* add descriptions to remaining go fields

* add missing comma

* remaining commas..."

* add description to display attrs

* update tests

* update tests

* add changelog;

* Update ui/app/utils/openapi-to-attrs.js

* update tests following backend changes

* clearly name variable

* format files

* no longer need to test for modified tooltip since coming from backend now
2023-04-19 16:16:30 +00:00
Anton Averchenkov 624acfe62a
openapi: Better comments for OperationPrefix/Verb/Suffix (#20162) 2023-04-13 18:47:14 -04:00
Mike Palmiotto 3ebe35b0d4
Fix RFC3339 comment typo (#20100) 2023-04-11 20:11:05 +00:00
Anton Averchenkov 35d07e91d2
Fix OpenAPI-related tests (#19983) 2023-04-04 18:27:20 -04:00
Anton Averchenkov 4564a3534b
openapi: Improve operationId/request/response naming strategy (#19319) 2023-04-04 13:14:40 -04:00
Anton Averchenkov 4d10063cbd
openapi: Fix logic for labeling unauthenticated/sudo paths (#19600) 2023-03-20 13:25:09 -04:00
Hamid Ghaf 27bb03bbc0
adding copyright header (#19555)
* adding copyright header

* fix fmt and a test
2023-03-15 09:00:52 -07:00
Tom Proctor 480c1dc85b
sdk: Fix fmt + add FieldType test (#19493)
* sdk: Fix fmt + add FieldType test

* Add test comment
2023-03-10 18:07:48 +00:00
valli_0x 8e9680223d
bug: correct sdk handling of the zero int64 value (#18729)
* bug: correct handling of the zero int64 value

* Update changelog/18729.txt

---------

Co-authored-by: valli_0x <personallune@mail.ru>
Co-authored-by: Tom Proctor <tomhjp@users.noreply.github.com>
2023-03-09 11:25:45 +00:00
Christopher Swenson 5864075c30
Add events sending routed from plugins (#18834)
This isn't perfect for sure, but it's solidifying and becoming a useful
base to work off.

This routes events sent from auth and secrets plugins to the main
`EventBus` in the Vault Core. Events sent from plugins are automatically
tagged with the namespace and plugin information associated with them.
2023-02-03 13:24:16 -08:00
Anton Averchenkov 7b356f0366
openapi: Add default values to the thing_mount_path parameters (#18935) 2023-01-31 19:37:16 -05:00
Max Bowsher 9d863a92ce
Fix multiple OpenAPI generation issues with new AST-based generator (#18554)
* Regexp metacharacter `.` should be escaped when used literally

The paths including `/.well-known/` in the Vault API could currently
technically be invoked with any random character in place of the dot.

* Replace implementation of OpenAPI path translator with regexp AST-based one

* Add changelog

* Typo fix from PR review - thanks!

Co-authored-by: Anton Averchenkov <84287187+averche@users.noreply.github.com>

* Add comment based on review feedback

* Change style of error handling as suggested in code review

* Make a further tweak to the handling of the error case

* Add more tests, testing cases which fail with the previous implementation

* Resolve issue with a test, and improve comment

---------

Co-authored-by: Anton Averchenkov <84287187+averche@users.noreply.github.com>
2023-01-31 16:27:39 -05:00
Max Bowsher 4c5f583f39
OpenAPI `generic_mount_paths` follow-up (#18663)
* OpenAPI `generic_mount_paths` follow-up

An incremental improvement within larger context discussed in #18560.

* Following the revert in #18617, re-introduce the change from
  `{mountPath}` to `{<path-of-mount>_mount_path}`; this is needed, as
  otherwise paths from multiple plugins would clash - e.g. almost every
  auth method would provide a conflicting definition for
  `auth/{mountPath}/login`, and the last one written into the map would
  win.

* Move the half of the functionality that was in `sdk/framework/` to
  `vault/logical_system.go` with the rest; this is needed, as
  `sdk/framework/` gets compiled in to externally built plugins, and
  therefore there may be version skew between it and the Vault main
  code. Implementing the `generic_mount_paths` feature entirely on one
  side of this boundary frees us from problems caused by this.

* Update the special exception that recognizes `system` and `identity`
  as singleton mounts to also include the other two singleton mounts,
  `cubbyhole` and `auth/token`.

* Include a comment that documents to restricted circumstances in which
  the `generic_mount_paths` option makes sense to use:

	    // Note that for this to actually be useful, you have to be using it with
	    // a Vault instance in which you have mounted one of each secrets engine
	    // and auth method of types you are interested in, at paths which identify
	    // their type, and for the KV secrets engine you will probably want to
	    // mount separate kv-v1 and kv-v2 mounts to include the documentation for
	    // each of those APIs.

* Fix tests

Also remove comment "// TODO update after kv repo update" which was
added 4 years ago in #5687 - the implied update has not happened.

* Add changelog

* Update 18663.txt
2023-01-17 23:07:11 -05:00
Max Bowsher 91855bce22
Fix a very old comment to include query-string parameters (#18557)
Vault has gradually had the ability to pass query-string parameters
added to GET, then DELETE, and now recently LIST requests. Update
a comment which seems to date back to when no query-string parameters
were used at all.
2023-01-17 12:29:30 -05:00
Anton Averchenkov 9696600e59
Add response schema validation methods & test helpers (#18635)
This pull request adds 3 functions (and corresponding tests):

`testhelpers/response_validation.go`:

  - `ValidateResponse`
  - `ValidateResponseData`
  
field_data.go:

  - `ValidateStrict` (has the "strict" validation logic)

The functions are primarily meant to be used in tests to ensure that the responses are consistent with the defined response schema. An example of how the functions can be used in tests can be found in #18636.

### Background

This PR is part of the ongoing work to add structured responses in Vault OpenAPI (VLT-234)
2023-01-13 14:55:56 -05:00
Anton Averchenkov c7f40361eb
Revert "Add mount path into the default generated openapi.json spec (#17926)" (#18617)
* Revert "Add mount path into the default generated openapi.json spec (UI) (#17926)"

This reverts commit db8efac708e5385ec871be9558507eeaf54ac972.

* Revert "Remove `generic_mount_paths` field (#18558)"

This reverts commit 79c8f626c59ca11bb8e7f460d40b09f5e0cec76d.
2023-01-10 11:16:59 -05:00
Anton Averchenkov 493040d147
Add mount path into the default generated openapi.json spec (UI) (#17926) 2022-12-08 12:15:54 -05:00
Nick Cabatoff 342b61984a
Move version out of SDK. (#14229)
Move version out of SDK.  For now it's a copy rather than move: the part not addressed by this change is sdk/helper/useragent.String, which we'll want to remove in favour of PluginString.  That will have to wait until we've removed uses of useragent.String from all builtins.
2022-12-07 13:29:51 -05:00
Anton Averchenkov a54678fb6b
Add logic to generate openapi response structures (#18192) 2022-12-05 11:11:06 -05:00
AnPucel b554a453e2
Make request objects required (#17909) 2022-11-11 14:05:12 -08:00
Anton Averchenkov f9fac68980
Revert "Add mount path into the default generated openapi.json spec (#17839)" (#17890)
This reverts commit 02064eccb42bb2ec1a3d12ec0d49c661312acd2d.
2022-11-10 15:39:53 -08:00
Anton Averchenkov f3aea876b9
Add mount path into the default generated openapi.json spec (#17839)
The current behaviour is to only add mount paths into the generated `opeanpi.json` spec if a `generic_mount_paths` flag is added to the request. This means that we would have to maintain two different `openapi.json` files, which is not ideal. The new solution in this PR is to add `{mount_path}` into every path with a default value specified:

```diff
--    "/auth/token/accessors/": {
++    "/auth/{mount_path}/accessors/": {
      "parameters": [
        {
          "name": "mount_path",
          "description": "....",
          "in": "path",
          "schema": {
            "type": "string",
++          "default": "token"
          }
        }
      ],
```

Additionally, fixed the logic to generate the `operationId` (used to generate method names in the code generated from OpenAPI spec). It had a bug where the ID had `mountPath` in it. The new ID will look like this:

```diff
-- "operationId": "listAuthMountpathAccessors",
++ "operationId": "listTokenAccessors",
```
2022-11-10 15:44:43 -05:00
Steven Clark 05a5928b8d
Update missing go-kms-wrapping v2 dep and address some ENT->OSS drift (#17178)
* Update missing go-kms-wrapping v2 dep and address some ENT->OSS drift

* Bump go-kms-wrapping/wrappers/gcpckms/v2 to v2.0.1
2022-09-19 10:23:40 -04:00
Christopher Swenson b136a7ecd8
Add plugin version to GRPC interface (#17088)
Add plugin version to GRPC interface

Added a version interface in the sdk/logical so that it can be shared between all plugin types, and then wired it up to RunningVersion in the mounts, auth list, and database systems.

I've tested that this works with auth, database, and secrets plugin types, with the following logic to populate RunningVersion:

If a plugin has a PluginVersion() method implemented, then that is used
If not, and the plugin is built into the Vault binary, then the go.mod version is used
Otherwise, the it will be the empty string.
My apologies for the length of this PR.

* Placeholder backend should be external

We use a placeholder backend (previously a framework.Backend) before a
GRPC plugin is lazy-loaded. This makes us later think the plugin is a
builtin plugin.

So we added a `placeholderBackend` type that overrides the
`IsExternal()` method so that later we know that the plugin is external,
and don't give it a default builtin version.
2022-09-15 16:37:59 -07:00
Josh Black d8e0a13aae
update gofumpt to 0.3.1 and reformat the repo (#17055)
* update gofumpt to 0.3.1 and reformat the repo

* output the version of the formatter we're using
2022-09-07 17:31:20 -07:00
Violet Hynes 0b3d7fdf10
VAULT-7698 Fix ignored parameter warnings for endpoint arbitrary data options (#16794)
* VAULT-7698 Fix warnings for endpoint arbitrary data options

* VAULT-7698 Add changelog
2022-08-23 08:51:23 -04:00
Eng Zer Jun 61262ad98e
refactor: replace strings.Replace with strings.ReplaceAll (#15392)
strings.ReplaceAll(s, old, new) is a wrapper function for
strings.Replace(s, old, new, -1). But strings.ReplaceAll is more
readable and removes the hardcoded -1.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2022-08-03 15:22:48 -04:00
AnPucel 3215cdbd32
Dynamic parameter for mountpaths in OpenApi Spec generation(#15835)
"generic_mount_paths" query parameter for OpenApiSpec generation
2022-06-30 07:43:04 -07:00
Alexander Scheel 4f6c6ac317
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 12:42:28 -04:00
AnPucel 2b5be0adec
[VAULT-5813] Remove duplicate sha_256 in SystemCatalogRequest OAS (#15163) 2022-04-25 13:12:08 -07:00
AnPucel f38248f5e5
[VAULT-5887] TypeInt64 support added to OpenApi Spec generation (#15104)
Adding handling for TypeInt64 to OAS types
2022-04-22 15:37:12 -07:00
Chris Capurso d9280b0fb0
fix TypeCommaIntSlice panic caused by json.Number input (#15072)
* fix TypeCommaIntSlice panic caused by json.Number input

* add changelog entry
2022-04-18 16:43:16 -04:00
Chris Capurso 46591ec54d
sort list of unrecognized params in response warning (#15073) 2022-04-18 15:45:08 -04:00
Hamid Ghaf a12271af46
forwarding requests subjected to Login MFA to the active node (#15009)
* forwarding requests subjected to Login MFA to the active node

* CL, and making fmt happy
2022-04-13 10:11:53 -04:00
Alexander Scheel 112d622b40
Run `make fmt` (#15011)
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-04-12 17:11:33 -04:00
Vishal Nayak ad3bf3173c
Warnings indicating ignored and replaced parameters (#14962)
* Warnings indicating ignored and replaced parameters

* Avoid additional var creation

* Add warnings only if the response is non-nil

* Return the response even when error is non-nil

* Fix tests

* Rearrange comments

* Print warning in the log

* Fix another test

* Add CL
2022-04-11 09:57:12 -04:00
Chris Capurso dc4aae642a
Fix panic caused by parsing `json.Number` values for TypeCommaStringSlice fields (#14522)
* go-secure-stdlib/parseutil to v0.1.4

* add TypeCommaStringSlice for json.Number

* add changelog entry

* upgrade go-secure-stdlib/parseutil to v0.1.4 in sdk

* move json number TypeCommaStringSlice test

* go mod download for api; go mod tidy
2022-03-28 11:07:55 -04:00
Anton Averchenkov c425078008
Change OpenAPI code generator to extract request objects (#14217) 2022-03-11 19:00:26 -05:00
hghaf099 f541cf196b
adding docs for the framework Required field (#13884)
* adding docs for the framework Required field

* minor fix

* Update sdk/framework/backend.go

Co-authored-by: Jim Kalafut <jkalafut@hashicorp.com>

Co-authored-by: Jim Kalafut <jkalafut@hashicorp.com>
2022-02-03 11:44:01 -05:00
Josh Black d249fad2df
reformat using 'make fmt' (#13794) 2022-01-27 10:06:34 -08:00
VAL 6652203569
Distinguish LIST-only paths in OpenAPI (#13643)
* Distinguish LIST-only paths in OpenAPI

* add changelog

* Put enum field inside schema
2022-01-18 09:21:44 -08:00
Chris Capurso fc75aabd03
use GetOkErr in patch handler so type coercion errors result in error response (#13191)
* use GetOkErr in patch handler so unknown fields result in error response

* do not error on unknown fields for patch handling

* godoc update for HandlePatchOperation
2022-01-12 09:32:59 -05:00
Vinny Mannello 2680f0b198
[Vault-4628] OpenAPI endpoint not expanding root alternations (#13487) 2021-12-22 15:36:47 -08:00
Brian Kassouf 57c568e511
Update some SDK dependency versions (#12828)
* Update some SDK dependency versions

* Update API go.sum

* Update jsonpatch to v5
2021-10-14 09:47:32 -07:00
Chris Capurso bbb4ab4a41
Add HTTP PATCH support to KV (#12687)
* handle HTTP PATCH requests as logical.PatchOperation

* update go.mod, go.sum

* a nil response for logical.PatchOperation should result in 404

* respond with 415 for incorrect MIME type in PATCH Content-Type header

* add abstraction to handle PatchOperation requests

* add ACLs for patch

* Adding JSON Merge support to the API client

* add HTTP PATCH tests to check high level response logic

* add permission-based 'kv patch' tests in prep to add HTTP PATCH

* adding more 'kv patch' CLI command tests

* fix TestHandler_Patch_NotFound

* Fix TestKvPatchCommand_StdinValue

* add audit log test for HTTP PATCH

* patch CLI changes

* add patch CLI tests

* change JSONMergePatch func to accept a ctx

* fix TestKVPatchCommand_RWMethodNotExists and TestKVPatchCommand_RWMethodSucceeds to specify -method flag

* go fmt

* add a test to verify patching works by default with the root token

* add changelog entry

* get vault-plugin-secrets-kv@add-patch-support

* PR feedback

* reorder some imports; go fmt

* add doc comment for HandlePatchOperation

* add json-patch@v5.5.0 to go.mod

* remove unnecessary cancelFunc for WriteBytes

* remove default for -method

* use stable version of json-patch; go mod tidy

* more PR feedback

* temp go get vault-plugin-secrets-kv@master until official release

Co-authored-by: Josh Black <raskchanky@users.noreply.github.com>
2021-10-13 15:24:31 -04:00
John-Michael Faircloth 2abf916ddb
Add support to parameterize unauthenticated paths (#12668)
* store unauthenticated path wildcards in map

* working unauthenticated paths with basic unit tests

* refactor wildcard logic

* add parseUnauthenticatedPaths unit tests

* use parseUnauthenticatedPaths when reloading backend

* add more wildcard test cases

* update special paths doc; add changelog

* remove buggy prefix check; add test cases

* prevent false positives for prefix matches

If we ever encounter a mismatched segment, break and set a flag to
prevent false positives for prefix matches.

If it is a match we need to do a prefix check. But we should not return
unless HasPrefix also evaluates to true. Otherwise we should let the for
loop continue to check other possibilities and only return false once
all wildcard paths have been evaluated.

* refactor switch and add more test cases

* remove comment leftover from debug session

* add more wildcard path validation and test cases

* update changelong; feature -> improvement

* simplify wildcard segment matching logic

* refactor wildcard matching into func

* fix glob matching, add more wildcard validation, refactor

* refactor common wildcard errors to func

* move doc comment to logical.Paths

* optimize wildcard paths storage with pre-split slices

* fix comment typo

* fix test case after changing wildcard paths storage type

* move prefix check to parseUnauthenticatedPaths

* tweak regex, remove unneeded array copy, refactor

* add test case around wildcard and glob matching
2021-10-13 11:51:20 -05:00
Jeff Mitchell f7147025dd
Migrate to sdk/internalshared libs in go-secure-stdlib (#12090)
* Swap sdk/helper libs to go-secure-stdlib

* Migrate to go-secure-stdlib reloadutil

* Migrate to go-secure-stdlib kv-builder

* Migrate to go-secure-stdlib gatedwriter
2021-07-15 20:17:31 -04:00
Chris Capurso 505e3f9a89
[VAULT-2825] Fix erroneous 500 resp for field validation errors (#12042)
* [VAULT-2825] Correctly respond with 400 rather than 500 for field validation errors

* [VAULT-2825] Add changelog entry

* [VAULT-2825] Simplify test assertion
2021-07-12 13:39:28 -04:00