* refactor (oidc): Stop emitting error for not found token id
Stop emitting errors when authtoken repo.IssueAuthToken is called and
there's if no pending token. It's not an "normal" state and not
an error condition.
* feature (audit tagging): Add tags for auth method requests/responses
Including testing functions for asserting audit events created
when a service is called
* refactor (controller): Use a grpc server for the grpc-gateway
This starts a grpc server for the grpc-gateway. The new gateway
server uses an in-memory listener which also supports "dialing", so
the http proxy can connect to the in-memory listener.
This change allows us to use all grpc server features and was in part
motivated by a need for an interceptor of inbound requests. With that
said, having a "proper" grpc server for the gateway will provide a lot
more flexibility and capabilities moving forward.
The request context will still be verified via middleware in the
http proxy (see wrapHandlerWithCommonFuncs). This verified context
will be serialized into a protobuf and sent along to the grpc-gateway
via metadata where an interceptor will add the verified request
info to the request's context (see requestCtxInterceptor). The
interceptor will verify the serialized request info via a shared ticket
with it's companion in-memory http proxy. FYI: the ticket is simply
random base62 string (see db.NewPrivateId).
This change also necessitated a minor change to services. We need to
return an empty response instead of nil, nil when there are no errors
and the response is empty.
* refactor (handlers): Rename gRPC Gateway filter
Originally, this was called an OutgoingInterceptor, which is an
unfortunate name since it's not an interceptor. Now that we're
refactoring the gateway stuff and have proper interceptors, renaming
this should remove ambiguity
* refactor: Rework how 204 with empty msg is handled
Recent changes to grpc gateway has necessitated a change to how
204s are handled by the gateway
* tests (bats): Check status codes for delete operations
This moves all of the tcp target functionality into a tcp package. It
also establishes a Register function in the target package to allow
specific target types to be registered at initilazation time. When
registering, a target type needs to provide its Subtype, as well as some
RepositoryHooks that are used by the target Repository.
The existing logic was to ignore Forbidden errors when recursively
listing in favor of looking for downstream scopes with appropriate
permissions. The problem is that when there is actually no
authentication token at all, what comes back is an Unauthenticated
error. Therefore if you didn't have permissions on the ingress scope
(e.g. the default of `global`) but did downstream for the anonymous
user, you'd get back an error.
I don't think there's any security issue with doing this; the user could
always have simply started the search at a downstream scope to begin
with so nothing more is being revealed, this just fixes behavior to
match expectations in this case.
A test was added for one of the services; the code is exactly the same
across them. The reason that the existing tests that were added with the
output fields testing didn't catch this is that even though they were
specifying `u_anon` as the user, the disabled test context skipped the
logic that would return a 401 in this case. It turns out that fixing
this is very complicated because we don't have a great way in most tests
of defining grants to put onto the generated scopes, so even if a true
anonymous context was added each test would require the anonymous user
to have list permissions on whatever resource was under test, requiring
a lot of role and grant and principal finagling. This is probably a good
longer-term TODO but not one that seemed worth it for this fix.
Fixes ICU-2301
This moves the generated pb files to the `sdk` module. This allows third parties to make use of them if desired (e.g. in upcoming plugins) and moves away from the `gen` nomenclature in the directory, since we are going to be adding some extra interface functions to the messages.
This adds functionality to ensure that connections are closed on a
worker when the server is shut down or reloaded.
Connections are closed, and then the shutdown process waits for the next
report to the controller to go through, waiting the grace period that
was added in #1330. The rest of shutdown is then proceeded with.
Listener shutdown has been moved to the start of the process to ensure
that new connections can't be made while we are shutting down.
Additionally, functionality has been added to force shut down servers
after a second interrupt has been received after the first one. This
takes the form of code in both the server and dev mode code paths that
just performs an os.Exit if another shutdown is received during the
normal shutdown process.
Additionally, the commit also includes some refactoring to tests so that
we could use some of the new E2E testing code to test session
connections during shutdown and reload.
Additionally, this fixes a panic in worker startup when there are no
controllers defined. Looks like the shutdown call was attempting to call
into the controller, not the worker.
Finally, this also removes the extra shutdown within the outer worker
startup.
Shutdown is actually handled within the inner StartWorker(), attempting
shutdown on errors was actually leading to potential use of an
uninitialized worker, which is leading to panics in testing.
This commit adds the support to do the following:
* Mark connections for non-reporting workers as closed. This is the
controller counterpart to the worker functionality (see #1330). This is
written as a scheduled job that does the work DB-side in a single atomic
query.
* Works to reconcile states if such a broken controller-worker
connection resumes and a worker reports a connection as connected that
should be disconnected. In this case, the controller will send an update
request, and the worker will honor it and terminate the connection.
* Further refinement of the grace period setting has been added here.
We have converged on the current server "liveness" setting as our
default here, which is half of the previous 30s (15 seconds, in other
words). Additionally, this is now configurable on the controller and
worker side, with the caveat that it's currently impossible to do so in
config as the setting has been untagged in HCL. This is exposed so that
we can run some sophisticated testing scenarios where we skew the grace
period to either the controller or worker to ensure the aforementioned
reconciliation works.
* Some repository functions have been added to support the new
functionality, in addition to some test code to the worker to allow
querying of session state while testing.
* Finally, we've added some add timestamp subtraction functions
as well, basically serving as the opposite of the addition functions.
This backports some test work that is being added in #1340 to assert
that the worker is actually marking connections closed in its *local*
state on a failure to contact the controller. This was missed in #1357
during some late-stage refactoring.
Summary of the changes:
* If we can't actually contact the controller during connection closure
to mark the connections as closed, we actually construct a "fake"
response that just simply includes a closed state for all connections
requested. This is then used to update the local connection state.
* Added a 3 second timeout to the CloseConnection request to the
controller to ensure the call to close connections completed in a
timely manner and did not hang indefinitely.
Testing enhancements:
* Added a new helper in TestHelper called LookupSession that allows the
lookup of a session from the worker's internal session state.
* This is used in the new ExpectConnectionStateOnWorker check in the E2E
test, which is part of a larger amount of enhancements to the E2E test
that are coming in #1340.
* Added a ConnectionStatusFromProtoVal helper function to the session
package to allow the conversion of protobuf connection status values to
their higher-level counterparts; essentially it is a reverse of
ConnectionStatus.ProtoVal. This is used in some of our tests (with more
coming in #1340) to just help with keeping things more idiomatic.
Finally, there is some minor error refactoring, and we also change the
timeout on internal status and connection close requests to the
controller to 5 seconds.
This commit adds some rudimentary functionality for cleaning up
connections on controller failure, or more specifically, a failure to
communicate with the controllers.
In this scenario, when a status cannot be sent for any reason for longer
than 30 seconds, the worker will close all connections that are normally
not cleaned up (so for sessions that currently are *not* in the progress
of being canceled or terminated). Status requests now time out after 10
seconds if they are not made successfully.
Session status is not touched during this process, but natural cleanup
or connectionless sessions will still occur. This should be okay, as the
session should be added on re-connect if need be.
A few other changes are made to cancelConnections: first, error logging
has been moved to the function so that we can handle errors requesting
cancellation directly within the function; this entails simply just
locally marking these connections as closed with a warning. Second,
there was a minor logging bug where closed connections were not properly
being noted in the last trace log, this has been fixed.
Additional changes:
* Circle: Set acceptance test no_output_timeout to 30m
* Fix down migrations
* Udpates due to merge
* Sentinel values only have to be greater than 0
* Create credential related sdk structs and methods.
* Post merge interface updating.
* Removing scratch code that was not cleaned up.
* updates
* Convert client certificate and client certificate keys into pem blocks and validate.
* Add newline at end of file.
* Faster check for "s" at the end of a resource name when generating from templates.
* make fmt
* updates
* Add dynamic credentials to a session
* Refactor: move contents of file
* updates
* Updates
* Add InvalidDynamicCredential error
* Assign credentials
* Allow updating client certificates seperate from the client certificate key.
* Replace application purpose string with enum value
* PR feedback / fix go test .
* Delete dead code
* Use common view
* Refactor: extract interface and rename method
* Refactor: move code to eliminate privPurpLibrary
* Add comment to requestMap
* Refactor: do not export methods on an unexported struct
* Update internal/db/schema/migrations/postgres/10/03_vault_credential.up.sql
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
* Add comments to credential Purpose constants
* Reorder switch statements to handle errors first
* PR feedback
* update
* fix merge
* Organizing the scheduler code and extract the individual store creation test helper function.
* Run 'make fmt'
* Create certificate when creating store. Allow vault address to be passed in as option
* Refactor: rename database views and associated structs
This change renames two database views and associated go structs to use
a consistent naming pattern. Views ending in 'private' contain encrypted
credentials needed for connecting to Vault. Views ending in 'public'
mirror the 'private' views but do not include any encrypted values.
This change does not include any changes to functionality or behavior.
* Adding SAD target operations for credential libraries to the SDK.
* Add status field and enumeration table for credential status
* Refactor: rename Status to TokenStatus
* Add status to vault credentials
* Creating the template for the CLI and helper functions.
* Add private database view for vault credentials
* Add scope_id to view and cleanup TODO comment
* Reformat embedded sql queries
* Add vault client helpers
* updates
* white space
* Add LookupLease test
* CLI commands for Store work. Renamed fields in proto w/ vault prefix.
* Test issue credentials with client TLS
* Add additional checks to vault ping
* Add an error for vault token capabilities and create a VaultToken error kind
* Add support for working with Vault policies
* Use Vault 1.7.2 for testing
* Add testing helper for creating a vault client with a non-root token
* Fix Vault renew lease test
The Vault renew lease endpoint accepts an optional duration parameter
for requesting the number of seconds to extend the lease by. However,
Vault is not required to honor this request.
* Add a var for the required capabilities of a boundary Vault token
* Enhance the test helper for adding a policy to Vault
* Allow the test role in postgresql to revoke credentials
* Remove out of date comments
* Enhance Vault test helpers for the database secrets engine
* Reformat comments
* Add a method for getting the capabilities of the current Vault token
* Add revoke lease to internal Vault client
* Reformat: combine err return line with check for nil line
* Remove redundant checks in test code
Remove checks in test code that are redundant with checks in the test
harness.
* Refactor CreateToken test helper to return the secret and the token
* Fix build failures caused by signature change in vault.CreateToken
* Fix Vault version and Vault API link in comments
* ran `make gen` after merging from mgaffney-vault.
* Remove Vault prefix from attribute fields in API, create a base CLI option for adding field prefixes. format now uses that prefix for error reporting.
* Template now allows attaching attribute field prefixes.
* Credential store uses PrefixAttributeFieldErrorsWithSubactionPrefix.
* Fixing naming of vault flags and helper flags.
* Updating more references to generated api methods.
* Make the capabilities String method more readable
* Add comment outlining PrintApiError usage of Options.
* Refactor test to move declarations closer to first use
* Fix comment
* Implement revoke method on vault repository
* Tests now verify certs, CA, and tokens, addresses can be updated in a store.
* Added test for creating store with pk/cert in same field.
* Allo updating certificates seperate from private key. Only contact backing vault service when updating token.
* Fixing bad tests and removing unused code.
* Adding tests for various ways of updating tokens.
* Add private credential
* Add token revocation job and cred renewal/revocation job
* Regen after merge.
* Fixing field mask related merge error.
* Create Library CLI. Removes vault prefix from path. Adds a WithoutCleanup testOption for vault.
* Set all credentials to revoked when a token is revoked
* Fixing missed renaming update.
* fix copy/paste error.
* Fixing code generation errors after merge.
* make gen after merge.
* Update internal/cmd/commands/credentialstorescmd/vault_funcs.go
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
* Update internal/cmd/commands/credentialstorescmd/vault_funcs.go
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
* Update internal/cmd/commands/credentialstorescmd/vault_funcs.go
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
* Refactor: move migrations from 10 to 12
* Removing logic from transaction.
* wrapping client errors in the calling op for CredentialStore's client() method.
* Redact token
* redact client key
* updates
* Add trigger to revoke credentials when session is canceled or terminated
* Fixing some help text for some flags.
* Add ability to load values from files (file://) or environment variables (env://).
* Updating comments
* fix bad merge
* feedback
* Adding issued credentials to sessions.
* Error on capabilities
* updates
* Expose NewVaulTestServer
* Add godoc
* Adding generated SessionCredential struct for API.
* Progress on building handler test for Authorize Session.
* feedback
* Update policies
* Add 'revoke' as a status for Vault Tokens
* Add delete_time to vault credential store
* Create dynamic credentials at session creation time.
* Tests pass with credentials attached to AuthorizedSession result.
* Only call issue if there are credentials to issue.
* Fixing output only issues. Adding type to credential library.
* Fix test to clear un/pw generated. confirm generated un/pw changes from 1 authorize session call to another.
* Update lookupTokenError
* Add delete_time to private credential store
* Refactor: move private store to separate file
* Fixing tests for AuthorizeSession and verifying error cases.
* Only create the credential repo if there are credentials to issue.
* Rename Library field to CredentialLibrary.
* Fixing missing change of Library to CredentialLibrary.
* Removing Default SDK functions for fields which are required and update CLI to match.
* Replace resource specific id variables with "id" and the input parmater for paths to be just a single string and the resource name as it should show up in the path.
* Soft delete vault credential stores
* Prevent new SQL functions from silently overwriting existing functions
* Rename "Hmac" to "HMAC" in the human readable cli response table.
* Fix tests
* Add vault database cleanup jobs
* Add ability to set the token period in the vault test harness
* updates
* Add not_null_columns func test
* remove unused struct
* Up no output timeout
* Validate current vault token on addr update
* Fix client cert change test
* add cert test
* Update revocation job where
* Fix comment
* Use Vault's default port in CLI help strings
* Remove down migrations
* Increase migration file numbers by 1
* Run make migrations
* Move migrations from 12 to 10
* Increase Circle CI timeout for acceptance tests
* Fix spelling mistake in error messages
* ASD cmds for Target and returning credentials to AuthSession request (#1338)
* Add Add/Set/Remove commands for libraries on Targets. Return credentials on AuthorizeSession request.
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
Co-authored-by: Louis Ruch <louisruch@gmail.com>
Co-authored-by: Todd Knight <T.Alan.Knight@gmail.com>
Co-authored-by: Jeff Mitchell <jeffrey.mitchell@gmail.com>
Fixing the session passing around its key ID (which had previously been
blank) exposed another issue which was caught during bats tests:
WithKeyId statements using the wrong key, which prior to now had been
ignored because the argument was empty, resulting in an ineffective
option. This fixes those situations.
It also updates a bats test that didn't get updated in the CLI return
status PR.
* Sessions support for read:self and cancel:self permissions. This is automatic with fallback; no API change is needed.
* Strips out values from listing if only self actions are allowed on the resource and the user ID is different. This prevents a default ACL of id=*;type=session;actions=read:self,cancel:self from causing all values to be visible when listing.
* Adds an unprivileged user to development/testing instances. This user has only default permissions plus the ability to authorize sessions in the default target.
This is a wire breaking change for json errors since we have removed and renamed a few fields, and changed part of the structure of the returned json error.
* Remove redundant fields in Status, details.error_id, details.TraceId and details.request_id from API errors.
* Added wrapped errors and "ops" field to indicate the internal operation of the errors returned by the API.
* Added error cli error reporting of Op and wrapped errors.
* tests: ensure default user can connect to default target and ensure created target has intended host sets
* docs: update readme for CLI tests with how to run against arbitrary clusters
* feat: override auth variables in CLI tests