Commit Graph
244 Commits
Author SHA1 Message Date
Jim 4df3b40def feature (db): Add support for multi-column PKs (#1658) 2021-11-03 14:04:47 -04:00
Timothy Messier 1a24a0fc2f feat(sqltest): Make container name configurable 2021-11-03 07:44:51 -04:00
Timothy Messier 1b7cfb1704 feat(target): Add support for credential library validation
Target subtypes must now implement another repository hook to validate
any CredentialLibraries that are being added/set. This allows for
subtypes to determine the valid set of CredentialLibraries.

For tcp.Targets only CredentialLibaries with
credential.ApplicationPurpose are allowed. If any other purpose is
provided an error is returned.
2021-10-29 10:01:52 -04:00
Timothy Messier 2cc58ff901 refact(target): Change repository to take CredentialLibraries
This change removes the hard-coded credential purpose for the Credential
Libraries. It also moves the logic of creating CredentialLibraries from
CredentialSources out of the repository and into the targets.Service.
This refactor will allow for additional credential purposes to be
supported in both the service and the repository.
2021-10-29 10:01:52 -04:00
Jeff Mitchell 1782f6a4e4 Enhance worker connection security (#1641)
This stores worker connection nonces within the database to ensure
uniqueness of connections. Prior the connection required any attacker to
be able to decrypt the incoming encrypted authentication message in
order to replay (and if the attacker has access to the KMS you have
bigger problems), but with this change even if an attacker does have
access to the KMS key, they cannot reuse the same message. (If they're
able to encrypt against the KMS key, they can still act as a worker with
a new message, so this only really helps if they only have decryption
capabilities.)
2021-10-27 20:32:07 -04:00
Michael Gaffney c361e6ec22 fix(warehouse): Add primary key to credential group membership table (#1636) 2021-10-26 05:20:34 -04:00
Jim 1ce9a71b53 feature (db): Add on conflict support to db.Create(...) (#1612) 2021-10-21 11:11:56 -04:00
Timothy Messier eac433f7ff refact(target): Move tcp into subpackage
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.
2021-10-19 10:44:51 -04:00
Jim 3b99ded7ad refactor: Update gorm deps (#1591)
Our recent upstream PR was merged into gorm.  We needed to change
just a few bits to migrate our gorm dep back to the upstream source.
2021-10-13 11:10:11 -04:00
Michael Gaffney 7ccab48a3c style: Run make fmt 2021-10-11 16:00:32 -04:00
Timothy Messier e3f7c263b0 refactor(sqltest): Update init script to support migration editions
This updates the docker image used for tests to support the new location
for sql migration files and the concept of editions. It continues to
process the old paths for now if the new directory does not exist, so
that the same image can be used during the transition.
2021-10-08 06:50:26 -04:00
Timothy Messier 8caaf3e076 refactor(schema): Add support for migration editions
This refactors the schema package and subpackages to support editions.
An Edition is a collection of sql migrations. A given boundary binary
can have multiple migration editions. The `schema.Manager` is updated to
apply the necessary migrations in the correct order, leveraging an
Edition's priority to determine the order in which the separate Editions
are applied.

The sql migration files are now nested under a directory for the
edition.

This also switches from the generated code to using embed, which
eliminates the need for the `make migrations` target and the generated
code. As such this commit removes the target and generated code.

See:
    https://pkg.go.dev/embed
2021-10-08 06:50:26 -04:00
Jim 8d6dee09a9 refact: Add db.DB wrapper and refact all test fixtures to use it. (#1535)
* refact: Changes required for gorm v2

* refact: Add db.DB wrapper and refact all test fixtures to use it

Stop leaking the gorm abstraction within our unit tests.

* refact: Migrate direct calls to pq to pgx driver

The refactor will remove the remaining direct dependencies on
the pq driver which has been deprecated in favor of the pgx
driver.

It includes the addition of common.SqlOpen which is a wrapper around
sql.Open, which is needed to deal with the driver name changing from
"postgres" to "pgx" but in our code base the dialect and driver are
synonyms.
2021-09-30 09:17:27 -04:00
Jim 136ac00b49 refact: Changes required for gorm v2 (#1528) 2021-09-30 08:47:34 -04:00
Jeff Mitchell 7fc712de44 Bump protoc 2021-09-17 16:23:25 -04:00
Timothy Messier 99d0d2f682 wh: Add wh_credential_dimension and bridge tables
This adds new dimension table to record credential information. Since a
session can have multiple credentials, the wh_session_accumulating_fact
is is linked to the credential_dimensions via bridge tables,
wh_credential_group and wh_credential_group_membership. When a session
is inserted, the credental group and credential dimensions will be
upserted. If the group changed in any way, a new group is inserted along
with all of the corresponding credentials.
2021-09-16 08:53:11 -04:00
Timothy Messier 75388f727a test: Refactor to use dbtest package instead of docker
This swaps the test initialization to use the dbtest package so each
test will get a fresh database created from a template database, instead
of a completely new docker container.
2021-09-09 13:42:01 -04:00
Timothy Messier 90e2c871f0 refactor(wh): Remove host prefix from wh_user_dimension org fields
These fields are being refactored so they conform with the new
wh_credential_dimension. This will inform Business Intelligence tools
that these attributes conform across dimensions.
2021-08-30 14:25:30 -04:00
Timothy Messier 026f09a9a8 refactor(wh): Rename primary and foreign key columns
The tables in the operational part of the Boundary database (meaning
non-warehouse tables) suffix primary key columns and foreign key columns
with `_id`. Many of these columns appear in the warehouse dimension and
fact tables as normal attributes, not primary keys or foreign keys. To
disambiguate ID columns from operational tables, the primary key column
for dimension tables will be renamed from `id` to `key` and the foreign
key columns in the fact tables will be renamed to change the suffix from
`_id` to `_key`.
2021-08-30 14:25:30 -04:00
Timothy Messier c8bf1917f5 db: Refactor test setup for pre-populated data
Now when initializing the test database for sql tests,
it will load the colors persona data into the database. This will
provide a data set that tests can use without needing to call
`wtt_load`.

The main motivation is to allow for a separation of setup and test
execution that requires crossing a transaction boundary. The pgTap tests
are required to exectue as a single transaction, so that the rollback
can reset the state, and each test can be isolated. However, can cause
issues with some test senarios, particuarly with the use of some times
releated functions like `current_timestamp` and `now` which return the
time that the current transaction started. This creates an issue if a
test relies on some setup that sets a time via `now`, then an update
that expects a new time via `now`.

See: https://www.postgresql.org/docs/13/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT
2021-08-30 14:25:30 -04:00
Michael Gaffney 5f88243ddc Fix db migration that adds support for OIDC in the data warehouse (#1471)
Four new columns were added to the `wh_user_dimension` table to support
OIDC. The data type for the columns was originally `wh_dim_text` which
is a domain type with a `not null` restriction. Adding the new columns
caused the migration to fail if the `wh_user_dimension` table had any
rows in it because the existing rows would violate the `not null`
restriction.

Closes #1469
2021-08-18 22:18:51 -04:00
Timothy Messier 0f19009cea feat(wh): Add oidc related columns to wh_user_dimension (#1455)
This adds new columns to the wh_user_dimension to provide additional
data from OIDC that does not apply to Password Auth.

Note: Given the specifics of the data, it is possible these columns may
be used by other auth methods in the future, hence the lack of `oidc` in
the column names.

The specific columns are:

- auth_method_external_id
    For OIDC this is the Issuer
- auth_account_external_id
    For OIDC this is the Subject
- auth_account_full_name
    For OIDC this is the account's Full Name, and can be `None`.
- auth_account_email
    For OIDC this is the account's Email, and can be `None`.

For all of these new columns, they will be `Not Applicable` if the auth
method is Password.
2021-08-11 18:45:14 -04:00
Timothy Messier 624bdbf0c2 test(db): Add baseline tests for wh_user_dimension (#1454)
This sets up the configuration for running a new suite of tests that are
written in sql, to test the sql logic implemented in plpgsql functions
and triggers. It is primarily designed to provides tests for the data
warehouse functionality that is implemented purely in sql.

The infrastructure to run these tests leverages docker. It creates one
docker container using the `library/postgres` image and provisions the
database with the boundary sql migrations and test helper functions.  A
separate docker container is run that has the pgtap extension and
pg_prove cli to execute the tests.

As noted, pgtap is used for the tests. This postgresql extension
provides a number of helpful assertion functions to make writing sql
tests easier. It also, along with the pg_prove cli, provides readable
test output.

Along with the new testing infrastructure this commit establishes a
baseline of tests for the wh_user_dimension:

- Unit tests for individual views and functions:
    - whx_user_dimension_source
    - whx_user_dimension_target
    - wh_upsert_user
- Integration tests for that verify that the wh_user_dimension gets
  populated correctly when sessions are inserted or updated. This
  ensures that:
    - the trigger runs on session insert
    - the trigger results in the correct changes to the
      wh_user_dimension.

This commit provides a `Makefile` to run the tests locally that provides
support for:

- Setting the postgres docker image to easily test multiple versions.
- Passing through options to pg_prove
- Passing the test list to run individual tests
- Additional targets to separately startup the database image to quickly
  re-run tests while developing new tests.

Lastly configures circleci to run this test suite as a matrix build
in parallel with the other tests. The matrix build tests multiple
versions of postgres:

- latest
- 13-alpine
- 12-alpine
- 11-alpine

See:
    https://pgtap.org/
2021-08-11 13:25:32 -04:00
Jim 477b541bf0 Events: ongoing clean up of eventing (#1448) 2021-08-05 10:54:10 -04:00
Todd Knight 39cc245966 Make gen after make tools. Includes make fmt of existing non generated files. (#1438) 2021-08-02 10:46:09 -07:00
s-christoffandJim 6b78108ecf Update primary error functions to take a context, deprecate old functions (#1358)
* add new error funcs which take a ctx and deprecate existing funcs

* use context where available when writing error events

* remove circular internal/errors pkg dep

* suppress some chatty errors using errors.WithoutEvent()

* convert auth oidc funcs to take context where needed to write events

Co-authored-by: Jim <jlambert@hashicorp.com>
2021-07-29 20:52:56 -04:00
Jim 70ad081e39 Events: convert from hclog to events (#1409) 2021-07-28 06:31:16 -04:00
Jeff Mitchell 528d54b4ad Add token/userinfo claims to account read output (#1419)
This is very useful when trying to write managed groups filters as you
can directly look at the structure of the claims for the accounts you're
trying to filter.

The output of the claims in text format on the CLI currently leaves
something to be desired. I started revamping some of the formatting
functions and it quickly got very fragile. Fundamentally at this point
we're likely better off -- now that we have a good idea what our output
format/standards are like -- rewriting the formatting code. I'll take
that as a tasker as I have a lot of ideas...
2021-07-26 17:52:18 -04:00
Chris MarchesiandMichael Gaffney 1ebb8efab6 Apply extra review feedback from #1340 (#1400)
* internal/servers/controller: refactor WaitForNextWorkerStatusUpdate

* internal/servers/worker: use connId instead of conn.GetConnectionId()

* internal/servers/worker: remove Worker.logClose

* internal/session: complement versus inclusive state search

* internal/session: use ScanRows instead of Scan

* internal/session: make closeConnectionsForDeadServersCte results gormable

* internal/tests/cluster: rename TestWorkerSessionCleanup to TestSessionCleanup

* Simplify SQL query for CloseConnectionsForDeadWorkers (#1410)

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
2021-07-23 15:02:15 -07:00
Jeff Mitchell 140c54e319 Repoint base62 import 2021-07-14 17:31:58 -07:00
Chris Marchesi 5a70875726 internal/servers/controller: Worker failure connection cleanup (#1340)
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.
2021-07-14 09:14:24 -07:00
Jeff Mitchell 2cbcf9a563 Update usage of shared-secure-libs (#1393) 2021-07-12 21:06:22 -04:00
Chris Marchesi 895de869ab internal/db: add enumeration constraints for the server table (#1386)
This adds enumeration constraints to the server table, ensuring that no
servers can be added other than the types "controller" and "worker".

This should already be impossible to do in code, but this adds a check
on the database level to ensure it's the case as well.
2021-07-09 08:19:16 -07:00
Louis Ruch 26a0303b38 Add sentinel and sanitize package (#1353)
* Add sentinel migrations

* Add sentinel and sanitize package
2021-06-25 13:30:03 -07:00
df35699c4e Integrate with Vault to retrieve and manage per session credentials (#1308)
* 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>
2021-06-22 22:26:26 -04:00
Louis Ruch 054549d81e Allow where without args in searchWhere (#1333)
* Allow where without args in searchWhere
2021-06-20 16:16:51 -07:00
Louis Ruch 8e4323c31c Scheduler run jobs failure (#1310)
* Drop wt_private_id from job table

* Add server id len constraint on job_run table
2021-06-15 15:32:23 -07:00
Louis RuchandMichael Gaffney 649ed32504 Scheduler updates (#1311)
* Scheduler updates

* Add convenience methods to db/timestamp.Timestamp

* Remove recursive loop

Co-authored-by: Michael Gaffney <mike@gaffney.cc>
2021-06-11 11:36:14 -07:00
Jeff Mitchell 9ecc384007 Add managed group support to role principals (#1270) 2021-06-04 10:44:57 -04:00
Jeff Mitchell 15bd1a5245 Add initial SQL for managed groups (#1253) 2021-05-26 20:43:36 -04:00
Jeff Mitchell 7ee8ddba6a True up some spelling 2021-05-14 16:26:25 -04:00
Jeff Mitchell 6f34da8923 Add cleanup of dead connections no longer reported by a worker (#1220) 2021-05-14 13:23:12 -04:00
Louis Ruch feb5d7385d Louis job scheduler (#1197)
* Adds job repo
* Adds scheduler
* Adds plugin table which is a place holder for future expansion of the scheduler. Currently all jobs that are created are linked to the pi_system plugin which are jobs that are held in a local registeredJobs map populated at controller startup.
2021-05-06 14:54:10 -07:00
Michael Gaffney 120b5e4c79 Run make migrations 2021-05-05 10:53:08 -04:00
Jim 2437cdcc8d OIDC: add support for account claim maps (#1186) 2021-05-04 08:41:04 -04:00
s-christoff 9ceeb3bd65 Add -container-image flag (#1112) 2021-05-03 13:11:28 -05:00
Jim 25e657fa51 Ongoing OIDC: support to request additional OIDC scopes from the IdP (#1175) 2021-04-28 06:53:13 -04:00
Jim Lambert be7fc67842 regenerate migrations 2021-04-22 07:38:58 -04:00
Jim 3ee651deab fix primary account data returned for users when a passwd auth method is the primary auth method (#1154) 2021-04-21 19:10:54 -04:00
Jim 75108cbc8b Ongoing OIDC: return the primary account info along with the user. (#1145) 2021-04-20 20:33:56 -04:00