Commit Graph
93 Commits
Author SHA1 Message Date
aditya2548 f8363dd06e [COMPLIANCE] Update Copyright & License Headers 2026-04-06 15:48:57 +05:30
429247f407 [COMPLIANCE] Update Copyright Headers (#6282)
* [COMPLIANCE] Update Copyright and License Headers

* chore: make gen to generate files with copyright headers

* chore: update missed copyright headers

---------

Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com>
Co-authored-by: Justin Nguyen <justin.nguyen@hashicorp.com>
2026-01-28 11:05:07 -06:00
1f17313a39 Normalise grants and roles tables to improve grants query performance (#5846)
* Create function to define valid set of scopes for each resource (#5558)

* Create function to define valid set of scopes for each resource

* chore(iam): Update validScopeTypes() to use scope.AllowedIn()

* chore(scope): Initialize with iota

* feat(scope): Return an error instead scope.Unknown

* feat(iam): Replace interface method `validScopeTypes` with `getResourceType`

This allows us to call scope.AllowedIn() in one place vs in each implementation of `validScopeTypes`

* chore(resource): Refactor other package functions into methods on resource.Type

* fix(scope): Add defensive checks around invalid resource types

* docs(resource): Add AllowedIn() to the areas to update when adding a new resource type

* docs(resource): Improve error message when an invalid type is provided

* test(grants): GrantsForUsers tests for Group resource (#5443)

* test(grants): WIP: First stab at group associations

* test(grants): Add GrantsForUser test for groups

* chore(grants): Consolidate repetitive setup logic into functions

* test(grants): Add GrantsForUser test for managed groups

* test(grants): Add another user with different grants

Ensure that non-applicable grants should not be returned because they are not applicable to the user

* chore(grants): cleanup

* chore(grants): Move common setup steps into a helper function

* feat: Define new grants tables (#5486)

Create new tables for grants:

1. `iam_role_global`:
  Roles that are placed in the global scope will be persisted in the `iam_role_global` table. A global role has a `grant_scope` which must be one of:
  * descendants
  * children
  * individual

  This enforces that a global role's grants either apply to:
  *  All orgs and projects.
  *  All orgs.
  *  An individual set of orgs and/or projects.

  When the `grant_scope` is set to `individual`, entries for the specific set of orgs and/or projects can be added to the 
  `iam_role_global_individual_grant_scope` table.

  Separately, a global role can be set to also apply its grant to the global scope by setting `grant_this_role_scope` to true.

2. `iam_role_org`:
  Roles that are placed in an org scope will be persisted in the `iam_role_org` table. An org role has a `grant_scope` which must be one of:
  * children
  * individual

  This enforces that an org role's grants either apply to:
  * All projects in the org.
  * An individual set of projects in the org.

  When the `grant_scope` is set to `individual`, entries for the specific set of projects can be added to the 
  `iam_role_org_individual_grant_scope` table.
  **NOTE**: The projects must belong to the org's scope

  Separately, an org role can be set to also apply its grant to the org by setting `grant_this_role_scope` to true.

3. `resource_enm`: 
  Contains all boundary resources. This is used by `iam_grant` to set the resource from a canonical_grant.

4. `iam_grant`
Stores the canonical grant string and the resource for filtering on specific grants.

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>
Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* add name scope id unique constraints to all iam_role tables (#5623)

* Bosorawis domain iam role subtypes (#5626)

* add subtype storage definitions

* make gen

* add all subtype definitions

* add const for grant scope individual

* remove unnecessary baseRole subtype

* add new proto files to make target protobuild

* make gen to get protoc-go-inject-tag

* add clone, setTableName, and GetScope tests

* add ResourceType and Actions test

* add create and delete tests for globalROle

* finish create and delete tests

* add trigger for deleting base role

* add trigger to sync update_time back to base iam_role table

* add update tests

* fix missing err checks

* fix iam_role delete subtype trigger function name and use new.update_time instead of now()

* add struct documentation to role subtypes

* add version update check

* add todo comment:

* bosorawis sql split global grants scope table (#5638)

* split iam_role_global_individual_grant_scope to have separate tables for org and project

* small comment change

* small comment change

* WIP: add tests

* remove grant_scope as immutable column

* add trigger to delete individual grant scope when grant_scope changes

* add a test that covers changing grant_scope

* rename function and trigger in iam_role_global

* improve assertion in sqltest for iam_role_global

* update iam_role_org to delete redundant grants scope

* minor comment fix

* no longer handle individual grant scope deletion with triggers and rename some functions

* add trigger test for grant_scope

* rename delete_base_iam_role to delete_iam_role_subtype

* SQL formatting use now() instead of interval

* bosorawis domain iam implement getRoleScopeType (#5629)

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* rename test

* change error code to RecordNotFound

* Update internal/iam/repository_role.go

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* switch to slice instead of counter

---------

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* domain: iam: upgrade repository code to use new tables (#5643)

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* split iam_role_global_individual_grant_scope to have separate tables for org and project

* small comment change

* small comment change

* WIP: add tests

* remove grant_scope as immutable column

* add trigger to delete individual grant scope when grant_scope changes

* add a test that covers changing grant_scope

* rename function and trigger in iam_role_global

* improve assertion in sqltest for iam_role_global

* update iam_role_org to delete redundant grants scope

* minor comment fix

* no longer handle individual grant scope deletion with triggers and rename some functions

* rename test

* add all subtype definitions

* remove unnecessary baseRole subtype

* add clone, setTableName, and GetScope tests

* add ResourceType and Actions test

* add create and delete tests for globalROle

* finish create and delete tests

* add trigger for deleting base role

* add trigger to sync update_time back to base iam_role table

* add update tests

* fix missing err checks

* fix iam_role delete subtype trigger function name and use new.update_time instead of now()

* add struct documentation to role subtypes

* add version update check

* implement getRoleScopeId

* implement getRoleScopeId

* save

* remove struct embedding from iam.Role

* fix tests to use new iam.Role definition

* repository_role_test.go move to new iam.Role model

* repository_principal_role_test.go use new iam.Role model

* repository_role_grant_test.go use new iam.Role model in test

* add oplog info to sql schema

* internal/iam/testing.go use new role schema in TestRole

* add toRole helper function to all role subtype

* remove tests that are no longer relevant

* internal/iam/repository_scope.go use new iam model

* internal/iam/repository_role_grant.go use new iam model

* internal/iam/repository_principal_role.go use new iam model

* internal/iam/repository_role_test.go add test case for global scoped role

* internal/iam/repository_grant_scope.go use new iam model

* fix query

* make create and lookup role work and add tests

* add role id to getRoleScopeId error message

* make DeleteRole work with new model and add tests

* fix update

* ensure oplog.ReplayableMessage is implemented on all role subtypes

* internal/iam/repository_role_grant.go fix slugging version properly

* internal/iam/repository_role.go minor correction to error message saying org instead of scope

* internal/iam/repository_role_test.go add more update tests

* add immutable_fields tests

* fix rebase

* change error code to RecordNotFound

* refactor to use getScopeType

* fix delete test

* add getRoleScope utility function

* repository_principal_role.go: refactor to remove multiple switch statements

* repository_role_grant.go: refactor to reduce LOC

* repository_role.go small refactor to use alloc func

* repository_grant_scope.go refactor

* review comments

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* rename test

* change error code to RecordNotFound

* Update internal/iam/repository_role.go

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* switch to slice instead of counter

* fix merge mistakes

* handling special scopes in test function

* fix TestRoleWithGrants

* fix minor typo

* make gen

* fix comment typos

* Bosorawis domain iam role use new model list role (#5676)

* add and use new list roles query

* run make gen

* tweaked returned error

* replace tabs with spaces in query string

* missed one tab

* remove leading spaces

---------

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* Domain: iam: Repository: update list-grant-scope and test setup to use new model (#5679)

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* split iam_role_global_individual_grant_scope to have separate tables for org and project

* small comment change

* small comment change

* WIP: add tests

* remove grant_scope as immutable column

* add trigger to delete individual grant scope when grant_scope changes

* add a test that covers changing grant_scope

* rename function and trigger in iam_role_global

* improve assertion in sqltest for iam_role_global

* update iam_role_org to delete redundant grants scope

* minor comment fix

* no longer handle individual grant scope deletion with triggers and rename some functions

* rename test

* add all subtype definitions

* remove unnecessary baseRole subtype

* add clone, setTableName, and GetScope tests

* add ResourceType and Actions test

* add create and delete tests for globalROle

* finish create and delete tests

* add trigger for deleting base role

* add trigger to sync update_time back to base iam_role table

* add update tests

* fix missing err checks

* fix iam_role delete subtype trigger function name and use new.update_time instead of now()

* add struct documentation to role subtypes

* add version update check

* implement getRoleScopeId

* implement getRoleScopeId

* save

* remove struct embedding from iam.Role

* fix tests to use new iam.Role definition

* repository_role_test.go move to new iam.Role model

* repository_principal_role_test.go use new iam.Role model

* repository_role_grant_test.go use new iam.Role model in test

* add oplog info to sql schema

* internal/iam/testing.go use new role schema in TestRole

* add toRole helper function to all role subtype

* remove tests that are no longer relevant

* internal/iam/repository_scope.go use new iam model

* internal/iam/repository_role_grant.go use new iam model

* internal/iam/repository_principal_role.go use new iam model

* internal/iam/repository_role_test.go add test case for global scoped role

* internal/iam/repository_grant_scope.go use new iam model

* fix query

* make create and lookup role work and add tests

* add role id to getRoleScopeId error message

* make DeleteRole work with new model and add tests

* fix update

* ensure oplog.ReplayableMessage is implemented on all role subtypes

* internal/iam/repository_role_grant.go fix slugging version properly

* internal/iam/repository_role.go minor correction to error message saying org instead of scope

* internal/iam/repository_role_test.go add more update tests

* add immutable_fields tests

* fix rebase

* change error code to RecordNotFound

* refactor to use getScopeType

* fix delete test

* add getRoleScope utility function

* repository_principal_role.go: refactor to remove multiple switch statements

* repository_role_grant.go: refactor to reduce LOC

* repository_role.go small refactor to use alloc func

* repository_grant_scope.go refactor

* review comments

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* rename test

* change error code to RecordNotFound

* Update internal/iam/repository_role.go

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* switch to slice instead of counter

* fix merge mistakes

* handling special scopes in test function

* fix TestRoleWithGrants

* fix minor typo

* make gen

* fix comment typos

* Bosorawis domain iam role use new model list role (#5676)

* add and use new list roles query

* run make gen

* tweaked returned error

* replace tabs with spaces in query string

* missed one tab

* remove leading spaces

* move ListRoleGrantScopes to repository_grant_scope.go

* rename repository_grant_scope to repository_role_grant_scope

* add proto definition for global role individual grant scope tables

* fix test from removing embeded struct from RoleGrantScope

* add grant_scope to proto definition

* implement GlobalRoleIndividualOrgGrantScope and GlobalRoleIndividualProjectGrantScope

* update comment

* run make gen to update comment

* implement OrgRoleIndividualGrantScope and add tests

* implement part of ListRoleGrantScopes

* Add more test

* add more test cases and remove add-grants test

* unexport listRoleGrantScopes

* use reader from function parameter instead of struct method

* rename test to match actual function

* run make gen

* unexport individual grants structs

* unexport individual grants structs - missed one file

* change TestRole and TestRoleGrantScope function to support new model

* add validation for special scopes

* add role_org_individual_grant_scope.pb.go to protobuild make target

* remove dead code from listRoleGrantScopes

* fix testRoleGrantScopeSpecial not handling org role special scope properly

* add back query removed by rebase

---------

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* feat: grantsForUser for Global Resources (#5612)

* feat: grantsForUser for Global Resources

add query to fetch grants for a user for resources that are only globally scoped

* Update query based on change to bifurcate individual table

* Create subtests for different resources

* Return grant.grant_scope instead of the request scope

* Remove 'individual' subquery & unused reqScope parameter

* Use sql.Named for better readability

* Fix op function name

* Remove individual grant scope logic from global resource repo function

No need to handle individual grant scopes since global resources can only be queried via 'this' grant scope at the global scope.

* Fix row scan order

* Remove data gen function

* Adjust query formatting

Remove canonical_grant filter from query. `iam_grant.canonical_grant` is a primary key, so it can't be null anyway -- no need to filter out null canonical grants

* Use the consts for u_auth and u_anon

* Specify "empty" instead of "NULL" in struct field comment

* Build query args with `pq.Array` instead of `fmt.Sprintf`

* Fix TestGrantsForUserGlobalResources

No longer using a hard-coded value for roleVersion

* Refactor grantsForUserGlobalResources tests into testcases

* go mod tidy

* Update query comment for correctness

---------

Co-authored-by: dkanney <dkanney@terpmail.umd.edu>
Co-authored-by: dkanney <david.kanney@hashicorp.com>

* Bosorawis domain iam implement role grant scopes all (#5701)

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* split iam_role_global_individual_grant_scope to have separate tables for org and project

* small comment change

* small comment change

* WIP: add tests

* remove grant_scope as immutable column

* add trigger to delete individual grant scope when grant_scope changes

* add a test that covers changing grant_scope

* rename function and trigger in iam_role_global

* improve assertion in sqltest for iam_role_global

* update iam_role_org to delete redundant grants scope

* minor comment fix

* no longer handle individual grant scope deletion with triggers and rename some functions

* rename test

* add all subtype definitions

* remove unnecessary baseRole subtype

* add clone, setTableName, and GetScope tests

* add ResourceType and Actions test

* add create and delete tests for globalROle

* finish create and delete tests

* add trigger for deleting base role

* add trigger to sync update_time back to base iam_role table

* add update tests

* fix missing err checks

* fix iam_role delete subtype trigger function name and use new.update_time instead of now()

* add struct documentation to role subtypes

* add version update check

* implement getRoleScopeId

* implement getRoleScopeId

* save

* remove struct embedding from iam.Role

* fix tests to use new iam.Role definition

* repository_role_test.go move to new iam.Role model

* repository_principal_role_test.go use new iam.Role model

* repository_role_grant_test.go use new iam.Role model in test

* add oplog info to sql schema

* internal/iam/testing.go use new role schema in TestRole

* add toRole helper function to all role subtype

* remove tests that are no longer relevant

* internal/iam/repository_scope.go use new iam model

* internal/iam/repository_role_grant.go use new iam model

* internal/iam/repository_principal_role.go use new iam model

* internal/iam/repository_role_test.go add test case for global scoped role

* internal/iam/repository_grant_scope.go use new iam model

* fix query

* make create and lookup role work and add tests

* add role id to getRoleScopeId error message

* make DeleteRole work with new model and add tests

* fix update

* ensure oplog.ReplayableMessage is implemented on all role subtypes

* internal/iam/repository_role_grant.go fix slugging version properly

* internal/iam/repository_role.go minor correction to error message saying org instead of scope

* internal/iam/repository_role_test.go add more update tests

* add immutable_fields tests

* fix rebase

* change error code to RecordNotFound

* refactor to use getScopeType

* fix delete test

* add getRoleScope utility function

* repository_principal_role.go: refactor to remove multiple switch statements

* repository_role_grant.go: refactor to reduce LOC

* repository_role.go small refactor to use alloc func

* repository_grant_scope.go refactor

* review comments

* implement getRoleScopeId

* move query to query.go

* improve notfound err message

* improve other err messages

* use named parameter and move getRoleScopeId implementation

* moved getRoleScopeId test

* rename getRoleScopeId to getRoleScopeType

* fix public_id ambiguous error

* undo unintended change to getUserWithAccount

* fix the correct query

* rename test

* change error code to RecordNotFound

* Update internal/iam/repository_role.go

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* switch to slice instead of counter

* fix merge mistakes

* handling special scopes in test function

* fix TestRoleWithGrants

* fix minor typo

* make gen

* fix comment typos

* Bosorawis domain iam role use new model list role (#5676)

* add and use new list roles query

* run make gen

* tweaked returned error

* move ListRoleGrantScopes to repository_grant_scope.go

* rename repository_grant_scope to repository_role_grant_scope

* add proto definition for global role individual grant scope tables

* fix test from removing embeded struct from RoleGrantScope

* add grant_scope to proto definition

* implement GlobalRoleIndividualOrgGrantScope and GlobalRoleIndividualProjectGrantScope

* update comment

* run make gen to update comment

* implement OrgRoleIndividualGrantScope and add tests

* implement part of ListRoleGrantScopes

* Add more test

* add more test cases and remove add-grants test

* unexport listRoleGrantScopes

* use reader from function parameter instead of struct method

* rename test to match actual function

* run make gen

* unexport individual grants structs

* unexport individual grants structs - missed one file

* change TestRole and TestRoleGrantScope function to support new model

* add validation for special scopes

* add role_org_individual_grant_scope.pb.go to protobuild make target

* remove dead code from listRoleGrantScopes

* fix testRoleGrantScopeSpecial not handling org role special scope properly

* change proto grant_this default to true

* make TestRole readback the role to get updated version

* implement toRoleGrantScope function on the subtypes

* implement conversion function

* add tests and AddRoleGrantScope before refactor

* working delete grant scope before refactor

* remove unused functions

* refactor repository_role_grant_scope.go

* add tests for SetRoleGrantScopes

* all tests passing

* refactor repository_role_grant_scope.go again

* run make gen

* no longer embed Resource in roleScopeGranter interface and make interface all internal functions

* add additional test case

* fix minor typo

* add a constraint check for iam_role_org.grant_scope

* refactor and comment repository_role_grant_scope.go and add test cases

* remove unused code

* rename roleScopeGranter to roleGrantScopeUpdater

* interface and function rename

* address PR comments

* remove redundant constraint on iam_role_org

* address pr comments

* grant this scope to role by default when creating a role

* tweak comments and variable names

---------

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* feat: add grant_this_role_scope column to iam_role_project (#5738)

* add grant_this_role_scope and sqltes for iam_project_role

* update role_project.proto to add grant_this_role_scope field

* fix missing fields in role_project.proto

* support GrantThisRoleScope field in iam/testing.go

* update repository_scope to set GrantThisRoleScope to true

* add GrantThisRoleScope to projec role tests to role_test.go

* add grant_this_role_scope check to query.go

* update roleGrantScopeUpdater to split setGrantScope to setHierarchicalGrantScope and removeHierarchicalGrantScope

* update create_role to set default vaule for iam_role_project.grant_this_role_scope

* update set, add, delete, list role grant scopes to support grant_this_role_scope in project_role

* rename methods

* run make gen

* make TestRole not bump version when creating roles with default 'this' grants

* address pr comments

* fix variable names

* feat: grantsForUser for Org resources (#5663)

* Create grantsForUser query for Org resources

* Finish & format query

* Change name of field in query

From 'role_type' to 'role_parent_scope_id'

* Finish grantsForUserOrgResources test

- Refactor to match the usual testcase pattern
- Use test functions to create test resources

* Remove unnecessary check against GrantScopeThis

"this" now has its own field and no longer lives alongside the other grant scopes, so we should not check for it against grantScope

* Ignore children & descendant grant scopes when querying org resources

The only grant_scope that mattters when querying org resources is 'this'

* Refactor query to simplify repo function

Create separate CTEs for each case: global special (children or descendant), global individual, and org (this). This allows us to query directly into perms.GrantTuple; no additional logic required.

* feat: grantsForUser for Project resources (#5669)

* Reuse testInput

* Create grantsForUserProjectResources query

* Create grantsForUserProjectResources repo func

* Create tests for grantsForUserProjectResources

* Split up CTEs by grant scope and simplify repo function

* Add test cases for missing reqScope id

* Remove unnecessary join to iam_scope_org table

* Reuse 'roles_with_grants' CTE across the grantsForUser queriers

* Change reqScope parameter type from `Scope` to `string` (#5748)

* Change 'reqScope' parameter type to: string

* Simplify grantsForUserGlobalQuery & repo func

* Test: GrantsForUser for Accounts for various user to role relationships (#5631)

* test(iam): Refactor GrantsForUser tests into a single test

* test(iam): Extend TestGrantsForUser to include Account resource

Note: These tests will fail until GrantsForUser is refactored to return only grants whose scopes are applicable to this resource

* test(iam): test(iam): Add Target resource to TestGrantsForUser

* feat: grantsForUser for recursive Global or Org resources (#5747)

* Create query: grantsForUserGlobalAndOrgResourcesQuery

* Create repo function: grantsForUserGlobalAndOrgResourcesRecursive

* Create tests for grantsForUserGlobalAndOrgResources

* Restrict recursive list for Global/Org resources to global scope only

Return error for non-recursive scopes

* Remove unused option parameter

* Add additional scope and test cases

- Test for grants against a resource with no permission granted for it
- Test for grants against a specific resource id without an explicit type set in the grant string
- Add a project scope to ensure its grants aren't returned

* Return error when passed 'Unknown' or 'All' resource type

* Use constants for 'unknown' & '*' resources

* feat: grantsForUser for recursive Project resources (#5783)

* Create query: grantsForUserProjectResourcesGlobalScopeQuery

* Create query: grantsForUserProjectResourcesOrgScopeQuery

* Create repo function: grantsForUserProjectResourcesRecursiveScopes

* Add recursive testcases to existing grantsForUserProjectResource test function

* Address PR feedback

- Add testcases for Unknown & All resource types
- Change a grant string to a pinned resource. Its resource type changed from Target type to Unknown type
- Call through to grantsForUserProjectResources when reqScopeId is a project scope (i.e. a non-recursve scope)

* Add 'Recursive' to query var naming

* feat: migration hook grants refactor (#5733)

* scaffolding

* comments

* rename migration number

* implement FindIllegalAssociations for 97006 hook

* refactor findIllegalAssociation query

* implement RepairIllegalAssociations and refactor queries

* make gen

* fix missing err check

* pr feedback fix hook fix message wording

* sql formatting

* update comment

* sql formatting

* Apply suggestions from code review

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* change 'illegal' to 'invalid'

* pr comment feedback

* small comment update

---------

Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* feat: grantsForUser for Global/Org/Project resources (#5807)

* Change naming to be consistent with other grantsForUser functions

* Create grantsForUser query for global-scoped Global/Org/Proj resources

* Create grantsForUser repo function for Global/Org/Proj resources

* Create tests for grantsForUserGlobalOrOrgOrProjectResources

* Create grantsForUser query for org-scoped Globa/Org/Proj resources

* Add tests for grantsForUser Global/Org/Proj resource query's org & project request_scopes

* Add clarifying comments and shorter naming convention

* Add 'children' grant_scoped org roles to result set

* feat: grants: add resource type parameters to GrantsForUser (#5750)

* add resource.Type to auth.Verify callchain

* remove WithType option

* update internal/auth/additional_verification_test.go to no longer use WithType

* handle explicit resource type in aclAndGrantHashForUser

* update interceptor_test.go to use resource.Scope for testing auth.Verify

* use resource.Scope to test Audit events

* add godoc comment on GrantsForUser

* add recursive options to iam

* add recursive options to auth

* internal/auth/ldap/managed_group_role_grants_test.go fix GrantsForUser signature

* internal/daemon/controller/handlers/accounts/account_service_test.go fix GrantsForUser signature

* update GrantsForUser godoc

* replace GrantsForUser tests with a new version with scoped down grants

* add mix type assignment to TestGrantsForUser

* move GrantsForUser test to internal/iam/repository_role_grant_ext_test.go

* remove unused options

* rewrite GrantsForUser tests to match the new expectation

* handle recursive call in s.authResult

* fix missing import from rebase

* resolve ListResolvableAlias destination permissions properly

* use global scope for ListResolvableAlias aclAndGrantHashForUser

* make auth.WithRecursive take boolean input

* make iam.WithRecursive option takes a boolean input

* auth/options_test.go add assertion for default option values

* make gen

* add back ACL tests to grants for user

* Support previous grants use-cases  (#5823)

* rename parameter to TestManagedGroupMember

* make replace old GrantsForUser with new queries

* fix tests and bugs where global grants don't get resolved

* remove unnecessary grants from grantsForUserProjectResourcesOrgScopeRecursiveQuery

* return full grants for any recursive call

* handle this and role scope ID in test

* order list result by create time instead of update time

* add missing err check

* handle converting role scope ID to this in grant scope API

* fix role service tests

* correct default scope role name

* add special handling in grantsForUser for scope resource

* fix tests to match role creation that does not bump version

* creating alias in invalid scope now returns permissions denied instead of internal

* remove test which looks for account in an authmethod in project scope which is an invalid config

* fix TestLdapManagedGroupRoleGrants to use scope appropriate resource for the test

* fix TestFetchActionSetForId and split org/proj test cases

* Validate reqScopeId for grantsForUserRecursive()

* Update tests based on recursive grantsForUser changes

* Remove last recursive function in favor of grantsForUserRecursive()

* move Scope resource to be AllowedIn all scope types

* allow multiple resouce types when calling auth.Verify down to GrantsForUsers

* use append instead of ranging over slice

* minor fix to tests

* Skip default role creation to avoid returning default role in test

* Update wantErrMsg to accommodate multiple resource types

* Add new entries to TestGrantsForUser test results based on recursive query changes

* Update unneccessaryRoles in recursive global/org test case based on changes to recursive query

---------

Co-authored-by: dkanney <david.kanney@hashicorp.com>

* Migrate roles and grants to new table structure (#5814)

* Refactor migration files to create tables, functions, triggers, and complete the actual data migration in their own files.

update migrations and tests

clean up removed files

rebase onto bosorawis-sql-grants-migration-hook

* Add comments to migration files, clean up some formatting, and add 30k project roles to test migration efficiency

update migrations go test file

Delete duplicate test file

* Fix formatting in migration files

* Rename hook number to reflect new number of migration files
split migrations into hook files, large test file, and more specific test functions

* Include missed oss file

* Apply suggestions from code review

Co-authored-by: Sorawis Nilparuk (Bo) <sorawis.nilparuk@hashicorp.com>

---------

Co-authored-by: Sorawis Nilparuk (Bo) <sorawis.nilparuk@hashicorp.com>

* Refactor GrantsForUser subqueries to use aggregate functions (#5822)

* Use shorter var name

* Refactor grantsForUserGlobalResourcesQuery: Use aggregate function array_agg to reduce rows returned from DB

Adding mutliple grants to a role exposes the need to aggregate certain fields (canonical_grant).
- Before this change, a row is returned for each distinct canonical grant for each role.
- After this change, only one row is returned per role. Each row contains an array of all canonical_grants that apply to the role.

* Refactor grantsForUserOrgResourcesQuery: Use aggregate function array_agg to reduce rows returned from DB

Adding mutliple grants to a role exposes the need to aggregate certain fields (individual_grant_scopes, canonical_grant).
- Before this change, a row is returned for each distinct canonical grant for each role.
- After this change, only one row is returned per role. Each row contains an array of all canonical_grants (and individual_grant_scopes) that apply to the role.

* Refactor grantsForUserProjectResourcesQuery: Use aggregate function array_agg to reduce rows returned from DB

Adding mutliple grants to a role exposes the need to aggregate certain fields (individual_grant_scopes, canonical_grant).
- Before this change, a row is returned for each distinct canonical grant for each role.
- After this change, only one row is returned per role. Each row contains an array of all canonical_grants (and individual_grant_scopes) that apply to the role.

* Address PR feedback

* Finish PR feedback

* Remove unnecessary if-check

* Match test name to function name

* Refactor grantsForUserRecursiveQuery: Use aggregate function array_agg to reduce rows returned from DB

* fix broken test (#5842)

* update tests to not check a table that will be dropped in the migration (#5847)

* Fix global scope's parent scope id (#5844)

* Use variable over hard-coded string

* 'global' scope should have no parent scope

* Clean up migrated tables (#5837)

* Refactor migration files to create tables, functions, triggers, and complete the actual data migration in their own files.

update migrations and tests

clean up removed files

rebase onto bosorawis-sql-grants-migration-hook

* Add comments to migration files, clean up some formatting, and add 30k project roles to test migration efficiency

update migrations go test file

Delete duplicate test file

* Fix formatting in migration files

* Rename hook number to reflect new number of migration files
split migrations into hook files, large test file, and more specific test functions

* Drop unneeded iam_role_grant_scope table and unneeded name, description, and version columns from iam_role

* fix whitespace

* fix broken sql from removing iam role grant scope (#5860)

* Ensure table drop also cascades changes to cross-table dependencies

* fix broken pgtap from removing iam-role-grant-scope table

* drop trigger which deletes from iam-role-grant-scope

---------

Co-authored-by: Michael Milton <michael.milton@hashicorp.com>

* test(groups): add grants tests for groups API (#5403)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* move a test to _test package

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* reorganize tests

* make gen

* feat: add grants tests for billing resource (#5559)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* reorganize tests

* make gen

* feat: add grants tests for billing resource

add test coverage for testing grants with billing resource. This tests `monthly-active-users` action with billing.

billing does not support output_fields so there are no tests for that

* add negative test coverage for descendant scope and org scope

* move negative tests to the billing resource

* revert alias changes

* revert alias test name change

* resolve rebase conflict

---------

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>

* Add grants tests for accounts (#5566)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* small comment change

* refactor role grants out of authtoken package

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* undo merge mistakes

* fix merge mistakes

* Trigger CI checks

* refactor auth/iam grants test setup

* Trigger CI checks

* add CRUDL tests

* add change-password and set-password tests

* add UpdateAccount, ChangePassword, SetPassword tests

* add ListAccount output_fields test

* make gen

* fix error message

* rebased against llb

* make gen

* fix post rebase

* fix typo

* make some tests use type-specific grants

* fix rebase issue

* add negative test to read

* test(credentials): Add grants tests (#5608)

* test(credentials): List tests

* test(credentials): Get tests

* test(credentials): Add "attributes" output_field & one its subtypes to the Read tests

* test(credentials): Create tests

* test(credentials): Update tests

* test(credentials): Delete tests

* test(credentials): Add additional test cases for pinned cred store id

* feat: add grants tests for alias (#5550)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* reorganize tests

* make gen

* feat: add grants tests for alias

add test coverage for testing grants with alias resource. This tests all actions with aliases and different grant scopes

* add tests for output fields

* add more test cases for actions, id

* update output assert to use shared assert function

* rebase

* use hashicorp/go-uuid instead of google/uuid

---------

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>
Co-authored-by: Elim Tsiagbey <elim.tsiagbey@hashicorp.com>

* test: add grants tests for host_catalogs (#5573)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* move a test to _test package

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* reorganize tests

* make gen

* Trigger CI checks

* test: add grants tests for host_catalogs

* add test coverage for output fields and write actions

* add missing error check assertions

* fixup! address PR comments

* fixup! fix lint errors

* chore(host_catalogs_test): Remove duplicate import

* test(hostcatalogs): Add tests for actions w/o grants

* test(hostcatalogs): Use ldap managed group for all test cases

* feat: add grants tests for billing resource (#5559)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* reorganize tests

* make gen

* feat: add grants tests for billing resource

add test coverage for testing grants with billing resource. This tests `monthly-active-users` action with billing.

billing does not support output_fields so there are no tests for that

* add negative test coverage for descendant scope and org scope

* move negative tests to the billing resource

* revert alias changes

* revert alias test name change

* resolve rebase conflict

---------

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>

* Add grants tests for accounts (#5566)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* small comment change

* refactor role grants out of authtoken package

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* undo merge mistakes

* fix merge mistakes

* Trigger CI checks

* refactor auth/iam grants test setup

* Trigger CI checks

* add CRUDL tests

* add change-password and set-password tests

* add UpdateAccount, ChangePassword, SetPassword tests

* add ListAccount output_fields test

* make gen

* fix error message

* rebased against llb

* make gen

* fix post rebase

* fix typo

* make some tests use type-specific grants

* fix rebase issue

* add negative test to read

* test(credentials): Add grants tests (#5608)

* test(credentials): List tests

* test(credentials): Get tests

* test(credentials): Add "attributes" output_field & one its subtypes to the Read tests

* test(credentials): Create tests

* test(credentials): Update tests

* test(credentials): Delete tests

* test(credentials): Add additional test cases for pinned cred store id

* feat: add grants tests for alias (#5550)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* reorganize tests

* make gen

* feat: add grants tests for alias

add test coverage for testing grants with alias resource. This tests all actions with aliases and different grant scopes

* add tests for output fields

* add more test cases for actions, id

* update output assert to use shared assert function

* rebase

* use hashicorp/go-uuid instead of google/uuid

---------

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>
Co-authored-by: Elim Tsiagbey <elim.tsiagbey@hashicorp.com>

* test(hostcatalogs): Add an additional project to "create" test cases

---------

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>
Co-authored-by: dkanney <dkanney@terpmail.umd.edu>
Co-authored-by: David Kanney <david.kanney@hashicorp.com>

* Add grants tests for authmethods (#5569)

* test(authmethods): Simplify read actions test cases

* test(authmethods): Create grants tests for write actions

* test(authmethods): Create test cases for action: authenticate

* test(authmethods): Update tests to use userFunc & other changes from upstream branch

* test(authmethods): Add output_fields to ReadActions tests

* test(authmethods): Add output_fields to WriteActions tests

* chore(authmethods_test): Consolidate common output fields into a single struct

* test(authmethods): Add test cases for project roles

* test(authmethods): Fix authenticate testcases

* test(authmethods): Add tests granting permission to specific ids using multiple roles

* test(hostsets): add grants tests (#5591)

* test(hostsets): List tests

* test(hostsets): Get tests

* test(hostsets): Create tests

* test(hostsets): Update tests

* test(hostsets): Delete tests

* test(hostsets}: AddHostSetHosts tests

* test(hostsets): RemoveHostSetHosts tests

* test(hostsets): SetHostSetHosts tests

* test(hostsets): Use unique host-catalog names to avoid duplicate key DB errors

* test(hostsets): Add second project to enforce exclusivity when Listing host-sets

* test: credentials store grants (#5592)

* first test with all the required setup

* v1 of test

* add primitive func and more test

* refactor read tests into a single top level

* move token generation to a function

* add test for creates

* add delete tests

* add update test

* only check for version and update_time

* move setup resource into testcase to support grants with specific ID

* add member tests

* add group-member test example with multiple actions

* remove duplicate group membership tests

* ran make gen

* fix missing parentID bug

* fix typo

* fix test names and add test cases

* switch from google/uuid to hashicorp/go-uuid

* add comment to groupmember tests

* small comment change

* pull shared test utility code from PR #5418

* refactor role grants out of authtoken package

* unexport utility function

* Remove dead code

* lint and make gen

* fix role cration logic

* fix password TestAccountFunc implementation

* implement TestAccountFunc for LDAP

* implement TestAccountFunc for OIDC

* implement TestUserFunc for managed groups

* use managed groups in grants test

* undo removal of authtoken.TestAuthTokenWithRoles for future refactor

* switch from list to map based test case for create tests

* undo merge mistakes

* fix merge mistakes

* lint

* add setup examples

* add output fields tests for getgroup

* reimplement with reflect

* add test for CreateGroup

* add all single resource action tests

* add list test

* rename function argument

* move AssertOutputFields to handlers package

* fix lint

* make gen

* use proto.Message instead of custom interface

* switch to hashicorp/go-uuid

* fix typo

* fix error message

* id= to ids=

* make generating test accounts more randomized

* Trigger CI checks

* refactor auth/iam grants test setup

* lint

* minor comment fix

* use Id instead of ID

* make user/account setup in iam returns account instead of just account ID

* missed one change

* save

* add list tests

* add get test

* add create and delete test

* add delete and update tests

* more tests

* fix collection_authorized_actions grants not resolving

* complete output_fields tests

* fix import groups

* make gen

* fixed broken tests

* fix rebase

* switch all tests to TestUserGroupGrantsFunc

* remove duplicate test

* test: add grants tests for managed groups resource (#5642)

* test: add grants tests for managed groups resource

* PR reviews

* address PR comments

* test: add grants tests for auth tokens resource (#5644)

* test: add grants tests for auth tokens resource

* add authorized actions tests for resources with sub-resources (#5835)

* add authorized actions tests for resources with sub-resources

* make gen

* bosorawis remove TestRoleGrantsForToken (#5840)

* refactor auth method grants tests

* refactor credential libraries grants tests

* refactor hosts grants tests

* refactor roles grants tests

* refactor scopes grants tests

* refactor tcp targets grants tests

* refactor users grants tests

* refactor worker grants tests

* fix authmethod test broken during the refactor

* remove authtoken.TestRoleGrantsForToken

* add pinned ID test

* correct event name

* fix make gen and lint

* Remove old test Role creation code

Removing leftover logic from old grants data model because it caused Group-association tests to fail

* update go mod

* run make gen and move new migrations to new folder (#5862)

* run make gen and move new migrations to new folder

* make tools and make gen

* update hook number

* update prior migration

* move 97005 to 97001 for consistency

* test: add grants tests for session resource (#5855)

* add grants tests for sessions

* fix missing parentScopeId

* make gen

* Resolve GrantsForUser queries via resolveQuery() (#5836)

* Add validation for nil resource type

* Remove redundant recursive test

* Refactor GrantsForUser() to perform query resolution & data mapping

- Remove grantsForUser sub-functions
- Resolve grantsForUser queries via resolveQuery()
- resolveQuery() and map data to GrantTuples in GrantsForUser()

* remove dead code

---------

Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>

* add grants tests for scope resource (#5845) (#5865)

* 'List' tests for scopes

* 'Get' tests for scopes

* 'Create' tests for scopes

* 'List Key Version Destruction Jobs' tests for scopes

* Add output_fields testing to 'Get' test

* Add additional test case for list-key-version-destruction-jobs

* test: add grants tests for roles resource (#5864)

* add grants tests for roles

* make gen

* test: add grants tests for worker resource (#5841)

* add read createControllerLed createWorkerLed tests

# Conflicts:
#	internal/daemon/controller/handlers/workers/grants_test.go

* minor refactor

* add output fields tests for list

* add tests for addworkertags readcertificateauthority reinitializecertificateauthority

* finish all worker api tests

* fix make gen and lint

* fix unchecked error lint

* add missing output fields assertion

* Bosorawis fix set role grant scope not handle children grant already exist (#5868)

* add new test case where role already has children and attempt to set children and individual project

* handle case where role already has children grant scope attempt to set children and project

* test: add grants tests for target resource (#5861)

* additional tests to target resource

* add test coverage for SetTargetCredentialSources

* make gen

* review suggestions

* test: add grants test for user resource and fix ACL bug (#5869)

* add some list-resolvable-aliases tests

* fix missing fields

* add more test and found edge case with children grants

* more list-resolvable test cases

* fix edge case where resource ids not overlapping between parent and child are not considered

* resolve conflict

* remove name, version, description from expect output_fields

* remove name and description from toProto and add godoc comment

---------

Co-authored-by: David Kanney <david.kanney@hashicorp.com>
Co-authored-by: Elim Tsiagbey <elim.tsiagbey@hashicorp.com>
Co-authored-by: Sorawis Nilparuk <sorawis.nilparuk@hashicorp.com>
Co-authored-by: Elim Tsiagbey <elimty02@gmail.com>
Co-authored-by: dkanney <dkanney@terpmail.umd.edu>
2025-06-20 15:31:57 -04:00
Irena Rindos f7c55678e0 chore: remove more dead code (#5640) 2025-04-02 15:09:17 -04:00
Todd 5a06e4fe66 Auto generate the permissions pages. (#4786)
* Auto generate the permissions pages.

* Add add- set- remove- auto descriptions. Hide scope line when no scope provided

* Document the resource info struct
2024-05-10 12:49:48 -07:00
Todd 0d67b86543 Add ListResolvableAliases to the user service (#4609)
* Add ListResolvableAliases to the user service

There are a few non common ways this method uses our ACL
and grant system. A user is able to list resolvable
aliases for another user if they are granted permission
to do so. That means we had to load the grants for
the user being listed for and not the requester when
determining if an alias is able to resolve to a destination
for which the requested user has permission.

Similarly, the grant hash used for the list pagination
is required to be that of the user being listed and not
the requester.
2024-04-17 08:26:46 -07:00
Todd e848e76b48 Create Alias Domain Object and Repo (#4275)
* Create alias domain object resource

* Add paginated listing

* fixing ratelimit related panics

* Address reviewer comments

* remove NewAlias value checks
2024-02-29 15:51:24 -08:00
Michael Milton 2e69d59dd2 feat(billing): Add cli subcommand for monthly active user counts 2024-02-23 15:44:10 +00:00
Michael Milton 280e9abb89 feat(billing): Add service handlers for monthly active user counts 2024-02-23 15:44:09 +00:00
Jeff MitchellandDamian Debkowski 35cef97bd4 Linter fixes PR 3 (#4415)
* Linter fixes

* fix(bsr): update test to register TEST protocol once

---------

Co-authored-by: Damian Debkowski <damian.debkowski@hashicorp.com>
2024-02-16 08:30:16 -05:00
Jeff Mitchell 25bce9e8ff Fix linter warnings 2024-02-13 15:50:11 -05:00
f5dd457b34 Multiple grant scope IDs (#4251)
Co-authored-by: Timothy Messier <tim.messier@gmail.com>
Co-authored-by: Todd <github@quaddi.com>
2024-01-23 14:33:09 -05:00
Damian Debkowski 2dda19aafe fix: reapply-storage-policy 2024-01-16 13:53:44 -08:00
Damian Debkowski 7dce1206ab feat(types): support new grant types 2024-01-16 13:53:44 -08:00
Hugo edbb33de5b feat(handlers): Implement Policy Service
This also includes adding new grant and type primitives, as well as
package domain names.
2024-01-16 13:53:43 -08:00
Timothy Messier 61fcd857ec feat(resource): Add function to get type from plural string 2023-12-04 16:20:44 +00:00
Timothy Messier 3f4a723541 feat(action): Add registrar for valid actions by resource 2023-12-04 16:20:29 +00:00
Timothy Messier c52caae345 refact(action): Make ActionSet behave as a set instead of a list
This switches the implementation of an ActionSet from a slice to a map
to ensure the elements in an ActionSet are unique. This allows for other
packages to perform set operations such as a union or difference without
needing to account for duplicates.
2023-12-04 16:20:29 +00:00
Johan Brandhorst-Satzkorn a89573b35f subtypes,handlers: add runtime trace regions (#4060)
* subtypes,handlers: add runtime trace regions

The subtype.Filterable and handlers.ProtoToStruct functions
are costly and worth measuring whenever runtime tracing
is in use. This has almost no cost when tracing is not in use,
so there's little harm in having them in place.

* testing: Add TRACING.md

TRACING.md contains information about how to perform
Go runtime tracing of the Boundary application.
2023-11-27 13:37:04 -08:00
b6df5693b5 Add generic read/update/delete commands (#3992)
* Add generic read/update/delete commands

This adds three generic commands that use the resource prefix to
determine the subcommand to run and pass through args over to that
subcommand. Since this occurs very early on and to avoid loading
essentially every internal resource package, I moved subtype definitions
to globals.

This replaces #3967

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>

* De-duplicate Subtype code (#4031)

Co-authored-by: Timothy Messier <tim.messier@gmail.com>

---------

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Co-authored-by: Timothy Messier <tim.messier@gmail.com>
2023-11-15 19:55:46 -05:00
Jeff Mitchell a9e372930d Revert 0bf60996c5 (#3990)
Post-merge some issues were discovered with the ways typing is used for
proto reflection. This will be reworked without moving the subtypes
around.
2023-11-02 16:03:47 -04:00
Jeff MitchellandJohan Brandhorst-Satzkorn 0bf60996c5 Add generic read/update/delete commands (#3967)
* Add generic read/update/delete commands

This adds three generic commands that use the resource prefix to
determine the subcommand to run and pass through args over to that
subcommand. Since this occurs very early on and to avoid loading
essentially every internal resource package, I moved subtype definitions
to globals.

* Update main.go

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>

* Update changelog and remove another deprecated command

---------

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
2023-11-01 16:24:16 -04:00
hashicorp-copywrite[bot]andJohan Brandhorst-Satzkorn 29da0bcb92 [COMPLIANCE] License changes (#3567)
* Adding explicit MPL license for sub-package.

This directory and its subdirectories (packages) contain files licensed with the MPLv2 `LICENSE` file in this directory and are intentionally licensed separately from the BSL `LICENSE` file at the root of this repository.

* Adding explicit MPL license for sub-package

This directory and its subdirectories (packages) contain files licensed with the MPLv2 `LICENSE` file in this directory and are intentionally licensed separately from the BSL `LICENSE` file at the root of this repository.

* Updating the license from MPL to Business Source License

Going forward, this project will be licensed under the Business Source License v1.1. Please see our blog post for more details at https://hashi.co/bsl-blog, FAQ at www.hashicorp.com/licensing-faq, and details of the license at www.hashicorp.com/bsl.

* Update copyright file headers to BUS-1.1

* Rerun make gen

This will pick up the last of the license changes

* Revert "Rerun make gen"

This reverts commit dbe0968bffd92745d8663c6940debae098395a6b.

* Remove copywrite from generation script

The current version of copywrite is not sophisticated enough
to only apply the copywrite changes to certain subdirectories,
so to avoid accidentally relicensing our api and sdk modules,
we will stop running the copywrite script until such time
that it can do the right thing.

* License protobuf API as MPL

The protobuf API files are used to generate the SDK,
since we want the SDK to be MPL, the protobuf files
must also be MPL. This extends to all protobuf files
whose sources end up in the SDK directory, including:

- internal/proto/controller/api
- internal/proto/controller/custom_options
- internal/proto/plugin

It also includes the generated service directory in
internal/gen/controller/api/services, since they are
generated from the protobuf sources used for the SDK.

* Change website license file name

This makes the naming scheme consistent with the rest
of the repository.

* Add note on licensing to README

* Set copywrite license to BUSL

* Revert "Add note on licensing to README"

This reverts commit 4d865a91a7a4f11605f0dc4609355d7e3c3cfffe.

---------

Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com>
Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
2023-08-11 10:31:53 -07:00
Jeff Mitchell 8322916fb4 Remove all deprecated Err/Wrap/E calls (#3286) 2023-06-14 21:55:24 -04:00
Jim e4d6742514 feat (action/resource): add Download and SessionRecording 2023-05-31 12:18:16 +00:00
Louis Ruch 8ea61054cd feat(storage): Add support for Storage Bucket API 2023-05-31 12:18:14 +00:00
Jeff Mitchell fc664eb35f Improve grant validation (#3081)
This adds several relationships into the resource package that are then
made use of to improve the grant validation that runs during Parse. By
understanding mappings between ID and resource type the validation
checks can far better align with actual allowed grant formats so we can
find several common misunderstandings before they simply result in an
authorization failure.

In the future some of these functions could be used in the logic in the
actual ACL checks but it's not currently necessary and I don't want to
lump that change in with this.

Note that the tests have not meaningfully changed, but they _have_ had
to be updated because the stricter validation is actually catching
issues.
2023-03-16 10:11:55 -04:00
Jeff Mitchell d391dc6ab7 Add top level resource prefix function in globals (#3075) 2023-03-13 12:27:43 -04:00
Jeff Mitchell b76b24a4ad Move prefixes for many packages into the globals package (#3069)
This is a prerequisite for some enhancements to grant validation
2023-03-10 15:06:39 -05:00
Johan Brandhorst-Satzkorn 3c29308673 chore: Add license headers to all files 2023-02-03 15:54:27 -08:00
edd323b73a Key Rotation/Destruction (#2477) (#2607)
* Key Rotation/Destruction (#2477)

* fix: Correct kms.CreateKeys comment

This method does not return anything.

* feat(kms): Add new ListKeys method

The new ListKeys method wraps the underlying KMS wrapper,
returning all the keys in the scope specified.

* feat(scopes): Add new scope actions for key management

Adds list-keys, rotate-keys and revoke-keys actions for scopes.

* feat(scopes): Add ListKeys API endpoint

This new endpoint lists all keys in a scope

* feat(api): Add ListKeys to Scopes client

This has to be a custom function because it is a custom action
and doesn't map well to any of the existing templates, or
generalises well in a way that would make it reasonable
to create a new template.

* feat(cli): Add new scopes list-keys command

* add RotateKeys function to the kms repository

* Add Rotate Keys Endpoint to Scopes Api (#2360)

* add rotate keys endpoint

* add tests for RotateKeys endpoint

* remove that one comment I forgot about

* addressing more PR comments

* Add Rotate Keys CLI Command (#2395)

* add cli command and client

* add bats tests

* fix some info text and pr comments

* write a new rotate keys description

* Add Missing DEK Foreign Keys (#2408)

* add missing fks

* mark key as nullable in gorm

* update tests to use a new wrapper with a real key_id

* fix formatting in test and add keys for auth_token test

* replace key values

* revert postgres_40_01_test.go

* style: reformat sql for readability

* refactor: change type of key_id columns to kms_private_id

* Store key_id and scope_id with oplog entries, re-type columns referencing data key version (#2431)

* fix(db): Correct types of data key version referencers

* fix(oplog): Fix missing error handling

* feat(oplog): Store key_id and scope_id with oplog entries

This migration truncates all existing oplog entries, as
migrating existing data would have been complex and
likely unnecessary.

* Update view references

* Always delete oplog entries when dropping keys

* Fix rebase issues

* Fix sql tests

* Add schema for new kms destruction jobs (#2479)

* feat: Add schema for new kms destruction jobs

The schema lets us manage destruction jobs per-table
while providing a guarantee that only one run is running
at a time.

* Apply suggestions from code review

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* Fix table reference and tests

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* update domain, api, and cli to all include key versions in outputs (#2472)

* update domain, api, and cli to all include key versions in outputs

* fix go sum

* add migration to fix immutable error

* fix final test issue as well as make gen issue

* rebase and fix

* address johan pr comments

* make gen, didn't realize comments were included

* update migrations based on new migration 55 file 03

* Move migrations to 56

* feat: Add key version rewrapping function registry (#2478)

The new RegisterTableRewrapFn can be used by a domain
to register a callback to use when rewrapping data in a
specific table name.

* feat(kms): Add scopeId to RewrapFn (#2539)

This makes it much easier for rewrap functions to look up
the correct wrapper and limit the number of rows searched.

* Update Root Cert Proto Definition (#2542)

* update root cert proto definition to properly identify public_key as the table primary key

* add the test fix as well

* Rewrap Functions for Encrypted Tables (#2532)

* add oidc rewrap

* add argon2 config rewrap

* add auth token rewrapping

* add worker auth cert rewrapping

* check the err

* add username password credential rewrapping

* add ssh private key credential rewrapping

* add vault client certificate rewrap function

* add host catalog secret rewrap function

* cleanup a little

* add host vault token rewrap function

* add session credential rewrap function

* add session rewrap function

* add worker auth rewrap function

* update test to include full assert gamut

* add session rewrap function TEST

* bring all tests up to current standards, make more readable, and include full assert gamut

* rework all rewrap functions to utilize scope id

* update comments, queries, sql refs, etc, in response to PR comments

* forgot a comment

* remove hmac updates and fix a couple comments again

* Rewrapping Registered Tables Test (#2555)

* add the registered table test as well as the two missing rewrap functions

* address pr comments, add db r/w conversions, cmp.diff, sql comment, remove (now) faulty immutable test

* Add ability to list key version destruction jobs, recurring jobs and destroying key versions (#2498)

* feat(kms): Add ability to list data key version destruction jobs

* feat(scopes): Add ListKeyVersionDestructionJobs

* feat(cli): Add list-key-version-destruction-jobs

* feat(kms): Add recurring job that performs table rewrapping

The new recurring job runs for each job table with a registered
rewrapping callback. It attempts to become the running run and
start its rewrapping, gracefully handling sudden interruptions
by resuming it's work if it finds evidence of sudden interruption.

* feat(kms): Add recurring job for destroying key versions

The new job monitors the database for data key version destruction
jobs that have finished rewrapping all its data, performing
the final data key version revocation.

* feat(kms): Add DestroyKeyVersion

DestroyKeyVersion immediately destroys a key version
if it is a root key version or a data key version
which encrypts no data. If the data key version
encrypts data which needs to be rewrapped, it
queues an asynchronous job to complete the rewrapping
operation.

* feat(scopes): Add DestroyKeyVersion API endpoint

* feat(cli): Add scopes destroy-key-version CLI command

* Ensure all secret updates include key ID (#2556)

* feat(all): Ensure all secret updates include key ID

When updating a secret, it is paramount that the key ID
is also updated, as it is the only means we have of ensuring
that we only destroy keys once there is no more data
associated with the key.

* Remove fix to session repository for now

This breaks the current private key derivation method

* add new encrypt/decrypt funcs and made necessary proto changes (#2557)

* add new encrypt/decrypt funcs and made necessary proto changes

* address all PR comments

* fix test panic

* add param checking to rewraps

* fix(schema): Correctly organize migrations again

* Review comments part 1

* Review comments part 2

* Review comments part 3

* Store cert private key, encrypt tofu token (#2583)

* fix(session): store cert private key, encrypt tofu token

Previously, we would derive a session certificate private key from
the session key used in each project, and not store the key. We
would also encrypt the tofu token with the database key but not
store a reference to this key in the database.

This change fixes this by replacing our key derivation with a key
generation step, and instead store the generated key, encrypted,
in the database. We also ensure that any new tofu tokens are
encrypted with the same key.

To handle existing sessions, we lazily rewrite the sessions whenever
a user lists them. There is a minor risk that a user could end up
destroying the database key that encrypts the tofu token before
that session has been rewrapped, but this is going to be rare and
temporary.

* feat(session): Allow the random source for secrets to be configured

* Review comments

* Minor fixes

* More minor fixes

* More small fixes

Co-authored-by: Danielle Miu <dani.miu@hashicorp.com>
Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com>
Co-authored-by: Michael Gaffney <mike@gaffney.cc>
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* fix(session): Unset session key ID when scope is deleted

Unsetting the key ID allows the session to live beyond the lifetime of
the scope, while allowing the scope to cascade delete its keys.

* fix(migrations): Rewrite migration 56 tests

These tests can no longer use the normal test helpers
as they try to use the new oplog table structure, so we
have to manually write all the interactions.

* fix(migrations): Rename migration 58 file name

This was the name used in the release branch, update
it to the new migration number.

* fix(e2e): Add some comments and debug to kms tests

* fix(session): Handle empty project and user IDs in read

When a project or user is deleted, the session is automatically
canceled and the respective field on the session is unset.
LookupSession did not handle this case gracefully, and would
error on decryption in this state. Skip decrypting sessions that
do not have either a user or project to avoid this error. The
decrypted values are not used for a canceled session.

* Fix worker test

* Increase test timeout

Co-authored-by: Danielle Miu <dani.miu@hashicorp.com>
Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com>
Co-authored-by: Michael Gaffney <mike@gaffney.cc>
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
2022-11-16 18:17:28 -05:00
Johan Brandhorst-Satzkorn f57454b6b9 Rewrite interface{} to any (#2535)
* chore: Rewrite interface{} to any

* Add ignore revs
2022-10-25 19:29:38 -04:00
Jeff Mitchell 53b5e532d5 Remove deprecated methods/fields on targets (#2393) 2022-09-15 09:20:08 -04:00
Irena Rindos 18dff62b7b Merge BYOW GA branch to main (#2398)
* feat(workers): Add ability to read and reinitialize cert authority (#2312)

* feat(workers): Return Release Version on worker list and read (#2377)

* feat(cli): Read and reinitialize worker certificate authority (#2387)
2022-09-08 13:19:21 -04:00
Jeff MitchellandIrena Rindos 01fb949d0b Add controller-led worker auth flow (#2413)
This adds an action to the API that allows pulling out an activation
token that can be given to a worker in its config (directly or via env
or file). The worker can pass this along with its normal request in
place of its normal nonce and the server will automatically accept it.

Co-authored-by: Irena Rindos <irenarindos@users.noreply.github.com>
2022-09-02 14:32:41 -04:00
Johan Brandhorst-Satzkorn aef9073fa6 Upgrade to Go 1.19 (#2347) 2022-08-25 12:12:24 -04:00
Haotian 28f53a64b4 feat(workers): implement worker service add/set/remove api tags 2022-07-14 10:19:03 -07:00
Jeff Mitchell 704d68848c Merge remote-tracking branch 'origin/main' into llb-byow 2022-06-15 16:45:00 -05:00
Louis Ruch 68eb6e2bed chore(targets): remove deprecated credential libraries on target resources (#1533) 2022-06-15 08:56:24 -07:00
Louis Ruch 58d546cdd4 feat(credential): Add static credential store and username_password credential 2022-06-14 13:01:17 -07:00
Damian DebkowskiandJohan Brandhorst-Satzkorn 3441fa0447 (fix) added more context to error details for cli command (#2170)
* (test) added more context to error details for cli commands

* (fix) refactor solution to utilize custom error type casting

* (test) added api unit test to validate InvalidArgumentError return message

* Update internal/types/subtypes/error.go

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>

* (refactor) rename InvalidArgumentError into UnknownSubtypeIDError

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
2022-06-14 08:52:53 -07:00
Jeff Mitchell 5d3facf561 Merge remote-tracking branch 'origin/main' into llb-byow 2022-06-10 19:05:27 -04:00
Jeff Mitchell d6362f9e5e Restrict anonymous user capabilities (#2156) 2022-06-09 11:30:01 -04:00
Jim fdf43fc4fe feature (worker): add CreateWorker(...) service (aka API) (#2143) 2022-06-07 11:50:30 -04:00
Jeff Mitchell c59d0df611 Add worker creation ACLs (#2138)
This is a bit more than simply adding the action; we had some
checks to ensure that list/create could only happen/not happen
in some cases and those had to be modified to account for
subactions.
2022-06-05 16:43:02 -04:00
Todd b58dada40d Move the server daemons into their own package (#2061)
* Move the server daemons into their own package

With this change the internal/server package now is dedicated to the server domain (workers and controllers) and not to the server daemons.
The hope is that this will make it easier to keep the daemons decoupled from the representation of the servers in the database.
2022-05-09 12:45:10 -07:00
Timothy Messier c8be4a9890 refact(target): Switch subtype attributes to oneof
This updates the target resources to use a oneof for attributes. This
allows requests to the targets service to leverage the new
subtypes.AttributeTransformerInterceptor so that attributes are strongly
typed prior to the service handler.
2022-04-20 13:32:32 -04:00
Johan Brandhorst-Satzkorn 5b71aa6212 refact(subtype): Remove copied structToProto methods
The original idea was for these methods to eventually become
entirely encapsulated by the subtype package, but as it turns
out we still have use for them in custom transformation functions,
so move the subtype package to use these shared functions
instead.
2022-04-20 13:32:31 -04:00
Johan Brandhorst-Satzkorn 6d56fcd26f feat(subtypes): Add new transformation registration option
This allows the user to register a custom transformation callback
for a specific protobuf message, in cases where the transformation
is sufficiently complex for it to be cumbersome to formalise
the logic through protobuf options.
2022-04-20 13:32:31 -04:00
Johan Brandhorst-Satzkorn 1fd44ee0f1 refact(subtypes): Remove return from transformations
This return value is just a reference to the input, which
is being mutated. We may as well make that clear via
the signature, which will also simplify the new custom
transformation function registration logic.
2022-04-20 13:32:31 -04:00