* 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>
602 lines
19 KiB
PL/PgSQL
602 lines
19 KiB
PL/PgSQL
-- Copyright (c) HashiCorp, Inc.
|
|
-- SPDX-License-Identifier: BUSL-1.1
|
|
|
|
begin;
|
|
|
|
create table iam_scope_type_enm (
|
|
string text not null primary key
|
|
constraint only_predefined_scope_types_allowed
|
|
check(string in ('unknown', 'global', 'org', 'project'))
|
|
);
|
|
|
|
insert into iam_scope_type_enm (string)
|
|
values
|
|
('unknown'),
|
|
('global'),
|
|
('org'),
|
|
('project');
|
|
|
|
-- define the immutable fields of iam_scope_type_enm
|
|
create trigger immutable_columns before update on iam_scope_type_enm
|
|
for each row execute procedure immutable_columns('string');
|
|
|
|
create table iam_scope (
|
|
public_id wt_scope_id primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
name text,
|
|
type text not null
|
|
references iam_scope_type_enm(string)
|
|
constraint only_known_scope_types_allowed
|
|
check(
|
|
(
|
|
type = 'global'
|
|
and parent_id is null
|
|
)
|
|
or (
|
|
type = 'org'
|
|
and parent_id = 'global'
|
|
)
|
|
or (
|
|
type = 'project'
|
|
and parent_id is not null
|
|
and parent_id != 'global'
|
|
)
|
|
),
|
|
description text,
|
|
parent_id text
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
|
|
-- version allows optimistic locking of the role when modifying the role
|
|
-- itself and when modifying dependent items like principal roles.
|
|
version wt_version
|
|
);
|
|
|
|
create table iam_scope_global (
|
|
scope_id wt_scope_id primary key
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade
|
|
constraint only_one_global_scope_allowed
|
|
check(
|
|
scope_id = 'global'
|
|
),
|
|
name text unique
|
|
);
|
|
|
|
create table iam_scope_org (
|
|
scope_id wt_scope_id primary key
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
parent_id wt_scope_id not null
|
|
references iam_scope_global(scope_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
name text,
|
|
unique (parent_id, name)
|
|
);
|
|
|
|
create table iam_scope_project (
|
|
scope_id wt_scope_id not null
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
parent_id wt_public_id not null
|
|
references iam_scope_org(scope_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
name text,
|
|
unique(parent_id, name),
|
|
unique(scope_id),
|
|
primary key(scope_id, parent_id)
|
|
);
|
|
|
|
create or replace function iam_sub_scopes_func() returns trigger
|
|
as $$
|
|
declare parent_type int;
|
|
begin
|
|
if new.type = 'global' then
|
|
insert into iam_scope_global (scope_id, name)
|
|
values
|
|
(new.public_id, new.name);
|
|
return new;
|
|
end if;
|
|
if new.type = 'org' then
|
|
insert into iam_scope_org (scope_id, parent_id, name)
|
|
values
|
|
(new.public_id, new.parent_id, new.name);
|
|
return new;
|
|
end if;
|
|
if new.type = 'project' then
|
|
insert into iam_scope_project (scope_id, parent_id, name)
|
|
values
|
|
(new.public_id, new.parent_id, new.name);
|
|
return new;
|
|
end if;
|
|
raise exception 'unknown scope type';
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger iam_scope_insert after insert on iam_scope
|
|
for each row execute procedure iam_sub_scopes_func();
|
|
|
|
create or replace function disallow_global_scope_deletion() returns trigger
|
|
as $$
|
|
begin
|
|
if old.type = 'global' then
|
|
raise exception 'deletion of global scope not allowed';
|
|
end if;
|
|
return old;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger iam_scope_disallow_global_deletion before delete on iam_scope
|
|
for each row execute procedure disallow_global_scope_deletion();
|
|
|
|
create trigger update_time_column before update on iam_scope
|
|
for each row execute procedure update_time_column();
|
|
|
|
create trigger default_create_time_column before insert on iam_scope
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger update_version_column after update on iam_scope
|
|
for each row execute procedure update_version_column();
|
|
|
|
-- define the immutable fields for iam_scope
|
|
create trigger immutable_columns before update on iam_scope
|
|
for each row execute procedure immutable_columns('public_id', 'create_time', 'type', 'parent_id');
|
|
|
|
-- define the immutable fields of iam_scope_global
|
|
create trigger immutable_columns before update on iam_scope_global
|
|
for each row execute procedure immutable_columns('scope_id');
|
|
|
|
-- define the immutable fields of iam_scope_org
|
|
create trigger immutable_columns before update on iam_scope_org
|
|
for each row execute procedure immutable_columns('scope_id');
|
|
|
|
-- define the immutable fields of iam_scope_project
|
|
create trigger immutable_columns before update on iam_scope_project
|
|
for each row execute procedure immutable_columns('scope_id');
|
|
|
|
|
|
-- iam_sub_names will allow us to enforce the different name constraints for
|
|
-- orgs and projects via a before update trigger on the iam_scope
|
|
-- table.
|
|
create or replace function iam_sub_names() returns trigger
|
|
as $$
|
|
begin
|
|
if new.name != old.name then
|
|
if new.type = 'global' then
|
|
update iam_scope_global set name = new.name where scope_id = old.public_id;
|
|
return new;
|
|
end if;
|
|
if new.type = 'org' then
|
|
update iam_scope_org set name = new.name where scope_id = old.public_id;
|
|
return new;
|
|
end if;
|
|
if new.type = 'project' then
|
|
update iam_scope_project set name = new.name where scope_id = old.public_id;
|
|
return new;
|
|
end if;
|
|
raise exception 'unknown scope type';
|
|
end if;
|
|
return new;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger iam_sub_names before update on iam_scope
|
|
for each row execute procedure iam_sub_names();
|
|
|
|
insert into iam_scope (public_id, name, type, description)
|
|
values ('global', 'global', 'global', 'Global Scope');
|
|
|
|
create table iam_user (
|
|
public_id wt_user_id primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
name text,
|
|
description text,
|
|
scope_id wt_scope_id not null
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
unique(name, scope_id),
|
|
version wt_version,
|
|
|
|
-- The order of columns is important for performance. See:
|
|
-- https://dba.stackexchange.com/questions/58970/enforcing-constraints-two-tables-away/58972#58972
|
|
-- https://dba.stackexchange.com/questions/27481/is-a-composite-index-also-good-for-queries-on-the-first-field
|
|
unique(scope_id, public_id)
|
|
);
|
|
|
|
create or replace function user_scope_id_valid() returns trigger
|
|
as $$
|
|
begin
|
|
perform from iam_scope where public_id = new.scope_id and type in ('global', 'org');
|
|
if not found then
|
|
raise exception 'invalid scope type for user creation';
|
|
end if;
|
|
return new;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
-- Dropped in 83/01_iam_role_grant_scope since we moved to multiple scopes per
|
|
-- role
|
|
create or replace function grant_scope_id_valid() returns trigger
|
|
as $$
|
|
declare parent_scope_id text;
|
|
declare role_scope_type text;
|
|
begin
|
|
-- There is a not-null constraint so ensure that if the value passed in is
|
|
-- empty we simply set to the scope ID
|
|
if new.grant_scope_id = '' or new.grant_scope_id is null then
|
|
new.grant_scope_id = new.scope_id;
|
|
end if;
|
|
-- If the scopes match, it's allowed
|
|
if new.grant_scope_id = new.scope_id then
|
|
return new;
|
|
end if;
|
|
-- Fetch the type of scope
|
|
select isc.type from iam_scope isc where isc.public_id = new.scope_id into role_scope_type;
|
|
-- Always allowed
|
|
if role_scope_type = 'global' then
|
|
return new;
|
|
end if;
|
|
-- Never allowed; the case where it's set to the same scope ID as the project
|
|
-- itself is covered above
|
|
if role_scope_type = 'project' then
|
|
raise exception 'invalid to set grant_scope_id to non-same scope_id when role scope type is project';
|
|
end if;
|
|
if role_scope_type = 'org' then
|
|
-- Look up the parent scope ID for the scope ID given
|
|
select isc.parent_id from iam_scope isc where isc.public_id = new.grant_scope_id into parent_scope_id;
|
|
-- Allow iff the grant scope ID's parent matches the role's scope ID; that
|
|
-- is, match if the role belongs to a direct child scope of this
|
|
-- org
|
|
if parent_scope_id = new.scope_id then
|
|
return new;
|
|
end if;
|
|
raise exception 'grant_scope_id is not a child project of the role scope';
|
|
end if;
|
|
raise exception 'unknown scope type';
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create or replace function disallow_iam_predefined_user_deletion() returns trigger
|
|
as $$
|
|
begin
|
|
if old.public_id = 'u_anon' then
|
|
raise exception 'deletion of anonymous user not allowed';
|
|
end if;
|
|
if old.public_id = 'u_auth' then
|
|
raise exception 'deletion of authenticated user not allowed';
|
|
end if;
|
|
if old.public_id = 'u_recovery' then
|
|
raise exception 'deletion of recovery user not allowed';
|
|
end if;
|
|
return old;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger update_version_column after update on iam_user
|
|
for each row execute procedure update_version_column();
|
|
|
|
create trigger ensure_user_scope_id_valid before insert or update on iam_user
|
|
for each row execute procedure user_scope_id_valid();
|
|
|
|
create trigger update_time_column before update on iam_user
|
|
for each row execute procedure update_time_column();
|
|
|
|
create trigger default_create_time_column before insert on iam_user
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger iam_user_disallow_predefined_user_deletion before delete on iam_user
|
|
for each row execute procedure disallow_iam_predefined_user_deletion();
|
|
|
|
-- TODO: Do we want to disallow changing the name or description?
|
|
insert into iam_user (public_id, name, description, scope_id)
|
|
values ('u_anon', 'anonymous', 'The anonymous user matches any request, whether authenticated or not', 'global');
|
|
|
|
insert into iam_user (public_id, name, description, scope_id)
|
|
values ('u_auth', 'authenticated', 'The authenticated user matches any user that has a valid token', 'global');
|
|
|
|
insert into iam_user (public_id, name, description, scope_id)
|
|
values ('u_recovery', 'recovery', 'The recovery user is used for any request that was performed with the recovery KMS workflow', 'global');
|
|
|
|
-- define the immutable fields for iam_user
|
|
create trigger immutable_columns before update on iam_user
|
|
for each row execute procedure immutable_columns('public_id', 'create_time', 'scope_id');
|
|
|
|
create table iam_role (
|
|
public_id wt_role_id primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
name text,
|
|
description text,
|
|
scope_id wt_scope_id not null
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
grant_scope_id wt_scope_id not null
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
unique(name, scope_id),
|
|
version wt_version,
|
|
|
|
-- add unique index so a composite fk can be declared.
|
|
unique(scope_id, public_id)
|
|
);
|
|
|
|
-- Grants are immutable, which is enforced via the trigger below
|
|
-- Altered in 100/05_iam_grant.up.sql to add constraint on canonical_grant
|
|
create table iam_role_grant (
|
|
create_time wt_timestamp,
|
|
role_id wt_role_id -- pk
|
|
references iam_role(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
canonical_grant text -- pk
|
|
constraint canonical_grant_must_not_be_empty
|
|
check(
|
|
length(trim(canonical_grant)) > 0
|
|
),
|
|
raw_grant text not null
|
|
constraint raw_grant_must_not_be_empty
|
|
check(
|
|
length(trim(raw_grant)) > 0
|
|
),
|
|
primary key(role_id, canonical_grant)
|
|
);
|
|
|
|
-- iam_immutable_role_grant() ensures that grants assigned to roles are immutable.
|
|
create or replace function iam_immutable_role_grant() returns trigger
|
|
as $$
|
|
begin
|
|
raise exception 'role grants are immutable';
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger immutable_role_grant before update on iam_role_grant
|
|
for each row execute procedure iam_immutable_role_grant();
|
|
|
|
create trigger default_create_time_column before insert on iam_role_grant
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger update_version_column after update on iam_role
|
|
for each row execute procedure update_version_column();
|
|
|
|
create trigger update_time_column before update on iam_role
|
|
for each row execute procedure update_time_column();
|
|
|
|
create trigger default_create_time_column before insert on iam_role
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger ensure_grant_scope_id_valid before insert or update on iam_role
|
|
for each row execute procedure grant_scope_id_valid();
|
|
|
|
-- define the immutable fields for iam_role (started trigger name with "a_" so
|
|
-- it will run first)
|
|
create trigger a_immutable_columns before update on iam_role
|
|
for each row execute procedure immutable_columns('public_id', 'create_time', 'scope_id');
|
|
|
|
create or replace function recovery_user_not_allowed() returns trigger
|
|
as $$
|
|
declare
|
|
new_value text;
|
|
begin
|
|
execute format('SELECT $1.%I', tg_argv[0]) into new_value using new;
|
|
if new_value = 'u_recovery' then
|
|
raise exception '"u_recovery" not allowed here"';
|
|
end if;
|
|
return new;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create table iam_group (
|
|
public_id wt_public_id primary key,
|
|
create_time wt_timestamp,
|
|
update_time wt_timestamp,
|
|
name text,
|
|
description text,
|
|
scope_id wt_scope_id not null
|
|
references iam_scope(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
unique(name, scope_id),
|
|
-- version allows optimistic locking of the group when modifying the group
|
|
-- itself and when modifying dependent items like group members.
|
|
version wt_version,
|
|
|
|
-- add unique index so a composite fk can be declared.
|
|
unique(scope_id, public_id)
|
|
);
|
|
|
|
create trigger update_version_column after update on iam_group
|
|
for each row execute procedure update_version_column();
|
|
|
|
create trigger update_time_column before update on iam_group
|
|
for each row execute procedure update_time_column();
|
|
|
|
create trigger default_create_time_column before insert on iam_group
|
|
for each row execute procedure default_create_time();
|
|
|
|
-- define the immutable fields for iam_group
|
|
create trigger immutable_columns before update on iam_group
|
|
for each row execute procedure immutable_columns('public_id', 'create_time', 'scope_id');
|
|
|
|
-- iam_user_role contains roles that have been assigned to users. Users can be
|
|
-- from any scope. The rows in this table must be immutable after insert, which
|
|
-- will be ensured with a before update trigger using
|
|
-- iam_immutable_role_principal().
|
|
create table iam_user_role (
|
|
create_time wt_timestamp,
|
|
role_id wt_role_id
|
|
references iam_role(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
principal_id wt_user_id
|
|
references iam_user(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
primary key (role_id, principal_id)
|
|
);
|
|
|
|
-- iam_group_role contains roles that have been assigned to groups.
|
|
-- Groups can be from any scope. The rows in this table must be immutable after
|
|
-- insert, which will be ensured with a before update trigger using
|
|
-- iam_immutable_role_principal().
|
|
create table iam_group_role (
|
|
create_time wt_timestamp,
|
|
role_id wt_role_id
|
|
references iam_role(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
principal_id wt_public_id
|
|
references iam_group(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
primary key (role_id, principal_id)
|
|
);
|
|
|
|
-- get_scoped_principal_id is used by the iam_principle_role view as a convient
|
|
-- way to create <scope_id>:<principal_id> to reference principals from
|
|
-- other scopes than the role's scope.
|
|
create or replace function get_scoped_principal_id(role_scope text, principal_scope text, principal_id text) returns text
|
|
as $$
|
|
begin
|
|
if role_scope = principal_scope then
|
|
return principal_id;
|
|
end if;
|
|
return principal_scope || ':' || principal_id;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
-- iam_principle_role provides a consolidated view all principal roles assigned
|
|
-- (user and group roles).
|
|
-- REPLACED in 9/04_oidc_managed_group_principal_role
|
|
create view iam_principal_role as
|
|
select
|
|
ur.create_time,
|
|
ur.principal_id,
|
|
ur.role_id,
|
|
u.scope_id as principal_scope_id,
|
|
r.scope_id as role_scope_id,
|
|
get_scoped_principal_id(r.scope_id, u.scope_id, ur.principal_id) as scoped_principal_id,
|
|
'user' as type
|
|
from
|
|
iam_user_role ur,
|
|
iam_role r,
|
|
iam_user u
|
|
where
|
|
ur.role_id = r.public_id and
|
|
u.public_id = ur.principal_id
|
|
union
|
|
select
|
|
gr.create_time,
|
|
gr.principal_id,
|
|
gr.role_id,
|
|
g.scope_id as principal_scope_id,
|
|
r.scope_id as role_scope_id,
|
|
get_scoped_principal_id(r.scope_id, g.scope_id, gr.principal_id) as scoped_principal_id,
|
|
'group' as type
|
|
from
|
|
iam_group_role gr,
|
|
iam_role r,
|
|
iam_group g
|
|
where
|
|
gr.role_id = r.public_id and
|
|
g.public_id = gr.principal_id;
|
|
|
|
-- iam_immutable_role_principal() ensures that roles assigned to principals are immutable.
|
|
create or replace function iam_immutable_role_principal() returns trigger
|
|
as $$
|
|
begin
|
|
raise exception 'roles are immutable';
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger immutable_role_principal before update on iam_user_role
|
|
for each row execute procedure iam_immutable_role_principal();
|
|
|
|
create trigger recovery_user_not_allowed_user_role before insert on iam_user_role
|
|
for each row execute procedure recovery_user_not_allowed('principal_id');
|
|
|
|
create trigger default_create_time_column before insert on iam_user_role
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger immutable_role_principal before update on iam_group_role
|
|
for each row execute procedure iam_immutable_role_principal();
|
|
|
|
create trigger default_create_time_column before insert on iam_group_role
|
|
for each row execute procedure default_create_time();
|
|
|
|
-- iam_group_member_user is an association table that represents groups with
|
|
-- associated users.
|
|
create table iam_group_member_user (
|
|
create_time wt_timestamp,
|
|
group_id wt_public_id
|
|
references iam_group(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
member_id wt_user_id
|
|
references iam_user(public_id)
|
|
on delete cascade
|
|
on update cascade,
|
|
primary key (group_id, member_id)
|
|
);
|
|
|
|
-- iam_immutable_group_member() ensures that group members are immutable.
|
|
create or replace function iam_immutable_group_member() returns trigger
|
|
as $$
|
|
begin
|
|
raise exception 'group members are immutable';
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
create trigger default_create_time_column before insert on iam_group_member_user
|
|
for each row execute procedure default_create_time();
|
|
|
|
create trigger iam_immutable_group_member before update on iam_group_member_user
|
|
for each row execute procedure iam_immutable_group_member();
|
|
|
|
create trigger recovery_user_not_allowed_group_member before insert on iam_group_member_user
|
|
for each row execute procedure recovery_user_not_allowed('member_id');
|
|
|
|
-- get_scoped_member_id is used by the iam_group_member view as a convient
|
|
-- way to create <scope_id>:<member_id> to reference members from
|
|
-- other scopes than the group's scope.
|
|
create or replace function get_scoped_member_id(group_scope text, member_scope text, member_id text) returns text
|
|
as $$
|
|
begin
|
|
if group_scope = member_scope then
|
|
return member_id;
|
|
end if;
|
|
return member_scope || ':' || member_id;
|
|
end;
|
|
$$ language plpgsql;
|
|
|
|
-- iam_group_member provides a consolidated view of group members.
|
|
create view iam_group_member as
|
|
select
|
|
gm.create_time,
|
|
gm.group_id,
|
|
gm.member_id,
|
|
u.scope_id as member_scope_id,
|
|
g.scope_id as group_scope_id,
|
|
get_scoped_member_id(g.scope_id, u.scope_id, gm.member_id) as scoped_member_id,
|
|
'user' as type
|
|
from
|
|
iam_group_member_user gm,
|
|
iam_user u,
|
|
iam_group g
|
|
where
|
|
gm.member_id = u.public_id and
|
|
gm.group_id = g.public_id;
|
|
|
|
|
|
commit;
|