* 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>
1618 lines
56 KiB
Go
1618 lines
56 KiB
Go
// Copyright (c) HashiCorp, Inc.
|
|
// SPDX-License-Identifier: BUSL-1.1
|
|
|
|
package authmethods
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/hashicorp/boundary/globals"
|
|
"github.com/hashicorp/boundary/internal/auth"
|
|
"github.com/hashicorp/boundary/internal/auth/ldap"
|
|
"github.com/hashicorp/boundary/internal/auth/oidc"
|
|
"github.com/hashicorp/boundary/internal/auth/password"
|
|
"github.com/hashicorp/boundary/internal/authtoken"
|
|
requestauth "github.com/hashicorp/boundary/internal/daemon/controller/auth"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/common"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/common/scopeids"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/accounts"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/authtokens"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/managed_groups"
|
|
"github.com/hashicorp/boundary/internal/errors"
|
|
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
|
"github.com/hashicorp/boundary/internal/kms"
|
|
"github.com/hashicorp/boundary/internal/listtoken"
|
|
"github.com/hashicorp/boundary/internal/pagination"
|
|
"github.com/hashicorp/boundary/internal/perms"
|
|
"github.com/hashicorp/boundary/internal/requests"
|
|
"github.com/hashicorp/boundary/internal/types/action"
|
|
"github.com/hashicorp/boundary/internal/types/resource"
|
|
"github.com/hashicorp/boundary/internal/types/scope"
|
|
"github.com/hashicorp/boundary/internal/types/subtypes"
|
|
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
|
|
pba "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authtokens"
|
|
"github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes"
|
|
"github.com/hashicorp/go-secure-stdlib/strutil"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/protobuf/proto"
|
|
"google.golang.org/protobuf/types/known/structpb"
|
|
"google.golang.org/protobuf/types/known/wrapperspb"
|
|
)
|
|
|
|
func init() {
|
|
subtypes.RegisterRequestTransformationFunc(&pbs.AuthenticateRequest{}, transformAuthenticateRequestAttributes)
|
|
subtypes.RegisterResponseTransformationFunc(&pbs.AuthenticateResponse{}, transformAuthenticateResponseAttributes)
|
|
}
|
|
|
|
const (
|
|
// general auth method field names
|
|
commandField = "command"
|
|
versionField = "version"
|
|
scopeIdField = "scope_id"
|
|
typeField = "type"
|
|
attributesField = "attributes"
|
|
authMethodIdField = "auth_method_id"
|
|
tokenTypeField = "type"
|
|
isPrimaryField = "is_primary"
|
|
)
|
|
|
|
var (
|
|
// IdActions contains the set of actions that can be performed on
|
|
// individual resources
|
|
// This will be set in init functions in files for each subtype in this package.
|
|
IdActions = make(map[globals.Subtype]action.ActionSet)
|
|
|
|
// CollectionActions contains the set of actions that can be performed on
|
|
// this collection
|
|
CollectionActions = action.NewActionSet(
|
|
action.Create,
|
|
action.List,
|
|
)
|
|
|
|
collectionTypeMap = map[resource.Type]action.ActionSet{
|
|
resource.Account: accounts.CollectionActions,
|
|
resource.ManagedGroup: managed_groups.CollectionActions,
|
|
}
|
|
|
|
additionalResourceGrants = []resource.Type{
|
|
resource.Account,
|
|
resource.ManagedGroup,
|
|
}
|
|
)
|
|
|
|
// Service handles request as described by the pbs.AuthMethodServiceServer interface.
|
|
type Service struct {
|
|
pbs.UnsafeAuthMethodServiceServer
|
|
|
|
kms *kms.Kms
|
|
pwRepoFn common.PasswordAuthRepoFactory
|
|
oidcRepoFn common.OidcAuthRepoFactory
|
|
iamRepoFn common.IamRepoFactory
|
|
atRepoFn common.AuthTokenRepoFactory
|
|
ldapRepoFn common.LdapAuthRepoFactory
|
|
amRepoFn common.AuthMethodRepoFactory
|
|
maxPageSize uint
|
|
}
|
|
|
|
var _ pbs.AuthMethodServiceServer = (*Service)(nil)
|
|
|
|
// NewService returns a auth method service which handles auth method related requests to boundary.
|
|
func NewService(
|
|
ctx context.Context,
|
|
kms *kms.Kms,
|
|
pwRepoFn common.PasswordAuthRepoFactory,
|
|
oidcRepoFn common.OidcAuthRepoFactory,
|
|
iamRepoFn common.IamRepoFactory,
|
|
atRepoFn common.AuthTokenRepoFactory,
|
|
ldapRepoFn common.LdapAuthRepoFactory,
|
|
amRepoFn common.AuthMethodRepoFactory,
|
|
maxPageSize uint,
|
|
opt ...handlers.Option,
|
|
) (Service, error) {
|
|
const op = "authmethods.NewService"
|
|
if kms == nil {
|
|
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing kms")
|
|
}
|
|
if pwRepoFn == nil {
|
|
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing password repository")
|
|
}
|
|
if oidcRepoFn == nil {
|
|
return Service{}, fmt.Errorf("nil oidc repository provided")
|
|
}
|
|
if ldapRepoFn == nil {
|
|
return Service{}, fmt.Errorf("nil ldap repository provided")
|
|
}
|
|
if iamRepoFn == nil {
|
|
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing iam repository")
|
|
}
|
|
if atRepoFn == nil {
|
|
return Service{}, fmt.Errorf("nil auth token repository provided")
|
|
}
|
|
if amRepoFn == nil {
|
|
return Service{}, fmt.Errorf("nil auth method repository provided")
|
|
}
|
|
if maxPageSize == 0 {
|
|
maxPageSize = uint(globals.DefaultMaxPageSize)
|
|
}
|
|
s := Service{
|
|
kms: kms,
|
|
pwRepoFn: pwRepoFn,
|
|
oidcRepoFn: oidcRepoFn,
|
|
iamRepoFn: iamRepoFn,
|
|
atRepoFn: atRepoFn,
|
|
ldapRepoFn: ldapRepoFn,
|
|
amRepoFn: amRepoFn,
|
|
maxPageSize: maxPageSize,
|
|
}
|
|
|
|
return s, nil
|
|
}
|
|
|
|
// ListAuthMethods implements the interface pbs.AuthMethodServiceServer.
|
|
func (s Service) ListAuthMethods(ctx context.Context, req *pbs.ListAuthMethodsRequest) (*pbs.ListAuthMethodsResponse, error) {
|
|
const op = "authmethods.(Service).ListAuthMethods"
|
|
|
|
if err := validateListRequest(ctx, req); err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
authResults := s.authResult(ctx, req.GetScopeId(), action.List, req.GetRecursive())
|
|
if authResults.Error != nil {
|
|
// If it's forbidden, and it's a recursive request, and they're
|
|
// successfully authenticated but just not authorized, keep going as we
|
|
// may have authorization on downstream scopes. Or, if they've not
|
|
// authenticated, still process in case u_anon has permissions.
|
|
if (authResults.Error == handlers.ForbiddenError() || authResults.Error == handlers.UnauthenticatedError()) &&
|
|
req.GetRecursive() &&
|
|
authResults.AuthenticationFinished {
|
|
} else {
|
|
return nil, authResults.Error
|
|
}
|
|
}
|
|
pageSize := int(s.maxPageSize)
|
|
// Use the requested page size only if it is smaller than
|
|
// the configured max.
|
|
if req.GetPageSize() != 0 && uint(req.GetPageSize()) < s.maxPageSize {
|
|
pageSize = int(req.GetPageSize())
|
|
}
|
|
|
|
withUnauthenticatedUser := false
|
|
reqCtx, ok := requests.RequestContextFromCtx(ctx)
|
|
if !ok {
|
|
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
|
|
}
|
|
if reqCtx.UserId == globals.AnonymousUserId {
|
|
withUnauthenticatedUser = true
|
|
}
|
|
|
|
scopeIds, scopeInfoMap, err := scopeids.GetListingScopeIds(
|
|
ctx, s.iamRepoFn, authResults, req.GetScopeId(), resource.AuthMethod, req.GetRecursive())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var filterItemFn func(ctx context.Context, item auth.AuthMethod) (bool, error)
|
|
switch {
|
|
case req.GetFilter() != "":
|
|
// Only use a filter if we need to
|
|
filter, err := handlers.NewFilter(ctx, req.GetFilter())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// TODO: replace the need for this function with some way to convert the `filter`
|
|
// to a domain type. This would allow filtering to happen in the domain, and we could
|
|
// remove this callback altogether.
|
|
filterItemFn = func(ctx context.Context, item auth.AuthMethod) (bool, error) {
|
|
outputOpts, ok, err := newOutputOpts(ctx, item, scopeInfoMap, authResults)
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
if !ok {
|
|
return false, nil
|
|
}
|
|
|
|
pbItem, err := toAuthMethodProto(ctx, item, outputOpts...)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
filterable, err := subtypes.Filterable(ctx, pbItem)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return filter.Match(filterable), nil
|
|
}
|
|
default:
|
|
filterItemFn = func(ctx context.Context, item auth.AuthMethod) (bool, error) {
|
|
return true, nil
|
|
}
|
|
}
|
|
|
|
repo, err := s.amRepoFn()
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
grantsHash, err := authResults.GrantsHash(ctx)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
var listResp *pagination.ListResponse[auth.AuthMethod]
|
|
var sortBy string
|
|
if req.GetListToken() == "" {
|
|
sortBy = "created_time"
|
|
listResp, err = auth.ListAuthMethods(ctx, grantsHash, pageSize, filterItemFn, repo, scopeIds, withUnauthenticatedUser)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
} else {
|
|
listToken, err := handlers.ParseListToken(ctx, req.GetListToken(), resource.AuthMethod, grantsHash)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch st := listToken.Subtype.(type) {
|
|
case *listtoken.PaginationToken:
|
|
sortBy = "created_time"
|
|
listResp, err = auth.ListAuthMethodsPage(ctx, grantsHash, pageSize, filterItemFn, listToken, repo, scopeIds, withUnauthenticatedUser)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
case *listtoken.StartRefreshToken:
|
|
sortBy = "updated_time"
|
|
listResp, err = auth.ListAuthMethodsRefresh(ctx, grantsHash, pageSize, filterItemFn, listToken, repo, scopeIds, withUnauthenticatedUser)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
case *listtoken.RefreshToken:
|
|
sortBy = "updated_time"
|
|
listResp, err = auth.ListAuthMethodsRefreshPage(ctx, grantsHash, pageSize, filterItemFn, listToken, repo, scopeIds, withUnauthenticatedUser)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
default:
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "unexpected list token subtype: %T", st)
|
|
}
|
|
}
|
|
|
|
finalItems := make([]*pb.AuthMethod, 0, len(listResp.Items))
|
|
for _, item := range listResp.Items {
|
|
outputOpts, ok, err := newOutputOpts(ctx, item, scopeInfoMap, authResults)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
if !ok {
|
|
continue
|
|
}
|
|
|
|
pbItem, err := toAuthMethodProto(ctx, item, outputOpts...)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
finalItems = append(finalItems, pbItem)
|
|
}
|
|
respType := "delta"
|
|
if listResp.CompleteListing {
|
|
respType = "complete"
|
|
}
|
|
resp := &pbs.ListAuthMethodsResponse{
|
|
Items: finalItems,
|
|
EstItemCount: uint32(listResp.EstimatedItemCount),
|
|
RemovedIds: listResp.DeletedIds,
|
|
ResponseType: respType,
|
|
SortBy: sortBy,
|
|
SortDir: "desc",
|
|
}
|
|
|
|
if listResp.ListToken != nil {
|
|
resp.ListToken, err = handlers.MarshalListToken(ctx, listResp.ListToken, pbs.ResourceType_RESOURCE_TYPE_AUTH_METHOD)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
// GetAuthMethod implements the interface pbs.AuthMethodServiceServer.
|
|
func (s Service) GetAuthMethod(ctx context.Context, req *pbs.GetAuthMethodRequest) (*pbs.GetAuthMethodResponse, error) {
|
|
const op = "authmethods.(Service).GetAuthMethod"
|
|
|
|
if err := validateGetRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
authResults := s.authResult(ctx, req.GetId(), action.Read, false)
|
|
if authResults.Error != nil {
|
|
return nil, authResults.Error
|
|
}
|
|
am, err := s.getFromRepo(ctx, req.GetId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
outputFields, ok := requests.OutputFields(ctx)
|
|
if !ok {
|
|
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
|
|
}
|
|
|
|
outputOpts := make([]handlers.Option, 0, 3)
|
|
outputOpts = append(outputOpts, handlers.WithOutputFields(outputFields))
|
|
if outputFields.Has(globals.ScopeField) {
|
|
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedActionsField) {
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, am.GetPublicId(), IdActions[globals.ResourceInfoFromPrefix(am.GetPublicId()).Subtype]).Strings()))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
|
collectionActions, err := requestauth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope, am.GetPublicId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
|
}
|
|
|
|
item, err := toAuthMethodProto(ctx, am, outputOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &pbs.GetAuthMethodResponse{Item: item}, nil
|
|
}
|
|
|
|
// CreateAuthMethod implements the interface pbs.AuthMethodServiceServer.
|
|
func (s Service) CreateAuthMethod(ctx context.Context, req *pbs.CreateAuthMethodRequest) (*pbs.CreateAuthMethodResponse, error) {
|
|
const op = "authmethods.(Service).CreateAuthMethod"
|
|
|
|
if err := validateCreateRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
authResults := s.authResult(ctx, req.GetItem().GetScopeId(), action.Create, false)
|
|
if authResults.Error != nil {
|
|
return nil, authResults.Error
|
|
}
|
|
am, err := s.createInRepo(ctx, authResults.Scope.GetId(), req.GetItem())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
outputFields, ok := requests.OutputFields(ctx)
|
|
if !ok {
|
|
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
|
|
}
|
|
|
|
outputOpts := make([]handlers.Option, 0, 3)
|
|
outputOpts = append(outputOpts, handlers.WithOutputFields(outputFields))
|
|
if outputFields.Has(globals.ScopeField) {
|
|
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedActionsField) {
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, am.GetPublicId(), IdActions[globals.ResourceInfoFromPrefix(am.GetPublicId()).Subtype]).Strings()))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
|
collectionActions, err := requestauth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope, am.GetPublicId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
|
}
|
|
|
|
item, err := toAuthMethodProto(ctx, am, outputOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &pbs.CreateAuthMethodResponse{Item: item, Uri: fmt.Sprintf("auth-methods/%s", item.GetId())}, nil
|
|
}
|
|
|
|
// UpdateAuthMethod implements the interface pbs.AuthMethodServiceServer.
|
|
func (s Service) UpdateAuthMethod(ctx context.Context, req *pbs.UpdateAuthMethodRequest) (*pbs.UpdateAuthMethodResponse, error) {
|
|
const op = "authmethods.(Service).UpdateAuthMethod"
|
|
|
|
if err := validateUpdateRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
authResults := s.authResult(ctx, req.GetId(), action.Update, false)
|
|
if authResults.Error != nil {
|
|
return nil, authResults.Error
|
|
}
|
|
am, dryRun, err := s.updateInRepo(ctx, authResults.Scope.GetId(), req)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Match(errors.T(errors.InvalidParameter), err):
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "Unable to update auth method: %v.", err)
|
|
default:
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
outputFields, ok := requests.OutputFields(ctx)
|
|
if !ok {
|
|
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
|
|
}
|
|
|
|
outputOpts := make([]handlers.Option, 0, 3)
|
|
outputOpts = append(outputOpts, handlers.WithOutputFields(outputFields))
|
|
if outputFields.Has(globals.ScopeField) {
|
|
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedActionsField) {
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, am.GetPublicId(), IdActions[globals.ResourceInfoFromPrefix(am.GetPublicId()).Subtype]).Strings()))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
|
collectionActions, err := requestauth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope, am.GetPublicId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
|
}
|
|
|
|
item, err := toAuthMethodProto(ctx, am, outputOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if item.GetOidcAuthMethodsAttributes() != nil && dryRun {
|
|
item.GetOidcAuthMethodsAttributes().DryRun = true
|
|
}
|
|
|
|
return &pbs.UpdateAuthMethodResponse{Item: item}, nil
|
|
}
|
|
|
|
// ChangeState implements the interface pbs.AuthMethodServiceServer.
|
|
func (s Service) ChangeState(ctx context.Context, req *pbs.ChangeStateRequest) (*pbs.ChangeStateResponse, error) {
|
|
const op = "authmethods.(Service).ChangeState"
|
|
|
|
if err := validateChangeStateRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
authResults := s.authResult(ctx, req.GetId(), action.ChangeState, false)
|
|
if authResults.Error != nil {
|
|
return nil, authResults.Error
|
|
}
|
|
am, err := s.changeStateInRepo(ctx, req)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Match(errors.T(errors.InvalidParameter), err):
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "Unable to change auth method state: %v.", err)
|
|
default:
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
outputFields, ok := requests.OutputFields(ctx)
|
|
if !ok {
|
|
return nil, errors.New(ctx, errors.Internal, op, "no request context found")
|
|
}
|
|
|
|
outputOpts := make([]handlers.Option, 0, 3)
|
|
outputOpts = append(outputOpts, handlers.WithOutputFields(outputFields))
|
|
if outputFields.Has(globals.ScopeField) {
|
|
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedActionsField) {
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, am.GetPublicId(), IdActions[globals.ResourceInfoFromPrefix(am.GetPublicId()).Subtype]).Strings()))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
|
collectionActions, err := requestauth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope, am.GetPublicId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
|
}
|
|
|
|
item, err := toAuthMethodProto(ctx, am, outputOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &pbs.ChangeStateResponse{Item: item}, nil
|
|
}
|
|
|
|
// DeleteAuthMethod implements the interface pbs.AuthMethodServiceServer.
|
|
func (s Service) DeleteAuthMethod(ctx context.Context, req *pbs.DeleteAuthMethodRequest) (*pbs.DeleteAuthMethodResponse, error) {
|
|
if err := validateDeleteRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
authResults := s.authResult(ctx, req.GetId(), action.Delete, false)
|
|
if authResults.Error != nil {
|
|
return nil, authResults.Error
|
|
}
|
|
_, err := s.deleteFromRepo(ctx, authResults.Scope.GetId(), req.GetId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &pbs.DeleteAuthMethodResponse{}, nil
|
|
}
|
|
|
|
// Authenticate implements the interface pbs.AuthenticationServiceServer.
|
|
func (s Service) Authenticate(ctx context.Context, req *pbs.AuthenticateRequest) (*pbs.AuthenticateResponse, error) {
|
|
const op = "authmethod_service.(Service).Authenticate"
|
|
|
|
if err := validateAuthenticateRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
switch globals.ResourceInfoFromPrefix(req.GetAuthMethodId()).Subtype {
|
|
case password.Subtype:
|
|
if err := validateAuthenticatePasswordRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
case oidc.Subtype:
|
|
if err := validateAuthenticateOidcRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
case ldap.Subtype:
|
|
if err := validateAuthenticateLdapRequest(ctx, req); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
authResults := s.authResult(ctx, req.GetAuthMethodId(), action.Authenticate, false)
|
|
if authResults.Error != nil {
|
|
return nil, authResults.Error
|
|
}
|
|
|
|
switch globals.ResourceInfoFromPrefix(req.GetAuthMethodId()).Subtype {
|
|
case password.Subtype:
|
|
return s.authenticatePassword(ctx, req, &authResults)
|
|
|
|
case oidc.Subtype:
|
|
return s.authenticateOidc(ctx, req, &authResults)
|
|
case ldap.Subtype:
|
|
return s.authenticateLdap(ctx, req, &authResults)
|
|
}
|
|
return nil, errors.New(ctx, errors.Internal, op, "Invalid auth method subtype not caught in validation function.")
|
|
}
|
|
|
|
func (s Service) getFromRepo(ctx context.Context, id string) (auth.AuthMethod, error) {
|
|
var lookupErr error
|
|
var am auth.AuthMethod
|
|
switch globals.ResourceInfoFromPrefix(id).Subtype {
|
|
case password.Subtype:
|
|
repo, err := s.pwRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
am, lookupErr = repo.LookupAuthMethod(ctx, id)
|
|
|
|
case oidc.Subtype:
|
|
repo, err := s.oidcRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
am, lookupErr = repo.LookupAuthMethod(ctx, id)
|
|
|
|
case ldap.Subtype:
|
|
repo, err := s.ldapRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
am, lookupErr = repo.LookupAuthMethod(ctx, id)
|
|
|
|
default:
|
|
return nil, handlers.NotFoundErrorf("Unrecognized id.")
|
|
}
|
|
|
|
if lookupErr != nil {
|
|
if errors.IsNotFoundError(lookupErr) {
|
|
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id)
|
|
}
|
|
return nil, lookupErr
|
|
}
|
|
if am == nil {
|
|
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id)
|
|
}
|
|
|
|
return am, nil
|
|
}
|
|
|
|
func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (auth.AuthMethod, error) {
|
|
const op = "authmethods.(Service).createInRepo"
|
|
var out auth.AuthMethod
|
|
switch item.GetType() {
|
|
case password.Subtype.String():
|
|
am, err := s.createPwInRepo(ctx, scopeId, item)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
if am == nil {
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
|
|
}
|
|
out = am
|
|
case oidc.Subtype.String():
|
|
am, err := s.createOidcInRepo(ctx, scopeId, item)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
if am == nil {
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
|
|
}
|
|
out = am
|
|
case ldap.Subtype.String():
|
|
am, err := s.createLdapInRepo(ctx, scopeId, item)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
if am == nil {
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
|
|
}
|
|
out = am
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s Service) updateInRepo(ctx context.Context, scopeId string, req *pbs.UpdateAuthMethodRequest) (auth.AuthMethod, bool, error) {
|
|
const op = "authmethods.(Service).updateInRepo"
|
|
|
|
var am auth.AuthMethod
|
|
var dryRun bool
|
|
|
|
switch globals.ResourceInfoFromPrefix(req.GetId()).Subtype {
|
|
case password.Subtype:
|
|
pam, err := s.updatePwInRepo(ctx, scopeId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
|
if err != nil {
|
|
return nil, false, errors.Wrap(ctx, err, op)
|
|
}
|
|
if pam == nil {
|
|
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update auth method but no error returned from repository.")
|
|
}
|
|
am = pam
|
|
|
|
case oidc.Subtype:
|
|
oam, dr, err := s.updateOidcInRepo(ctx, scopeId, req)
|
|
if err != nil {
|
|
return nil, false, errors.Wrap(ctx, err, op)
|
|
}
|
|
if oam == nil {
|
|
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update auth method but no error returned from repository.")
|
|
}
|
|
am = oam
|
|
dryRun = dr
|
|
|
|
case ldap.Subtype:
|
|
lam, err := s.updateLdapInRepo(ctx, scopeId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
|
if err != nil {
|
|
_, apiErr := err.(*handlers.ApiError)
|
|
switch {
|
|
case apiErr:
|
|
return nil, false, err
|
|
case errors.Match(errors.T(errors.InvalidParameter), err):
|
|
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, err.Error())
|
|
default:
|
|
return nil, false, errors.Wrap(ctx, err, op)
|
|
}
|
|
}
|
|
if lam == nil {
|
|
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update auth method but no error returned from repository.")
|
|
}
|
|
am = lam
|
|
}
|
|
|
|
return am, dryRun, nil
|
|
}
|
|
|
|
func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, error) {
|
|
const op = "authmethods.(Service).deleteFromRepo"
|
|
var rows int
|
|
var dErr error
|
|
switch globals.ResourceInfoFromPrefix(id).Subtype {
|
|
case password.Subtype:
|
|
repo, err := s.pwRepoFn()
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
rows, dErr = repo.DeleteAuthMethod(ctx, scopeId, id)
|
|
|
|
case oidc.Subtype:
|
|
repo, err := s.oidcRepoFn()
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
rows, dErr = repo.DeleteAuthMethod(ctx, id)
|
|
case ldap.Subtype:
|
|
repo, err := s.ldapRepoFn()
|
|
if err != nil {
|
|
return false, errors.Wrap(ctx, err, op)
|
|
}
|
|
rows, dErr = repo.DeleteAuthMethod(ctx, id)
|
|
default:
|
|
return false, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("invalid auth method subtype: %q", globals.ResourceInfoFromPrefix(id).Subtype.String()))
|
|
}
|
|
|
|
if dErr != nil {
|
|
if errors.IsNotFoundError(dErr) {
|
|
return false, nil
|
|
}
|
|
return false, errors.Wrap(ctx, dErr, op, errors.WithMsg("unable to delete auth method"))
|
|
}
|
|
|
|
return rows > 0, nil
|
|
}
|
|
|
|
func (s Service) changeStateInRepo(ctx context.Context, req *pbs.ChangeStateRequest) (auth.AuthMethod, error) {
|
|
const op = "authmethod_service.(Service).changeStateInRepo"
|
|
|
|
switch globals.ResourceInfoFromPrefix(req.GetId()).Subtype {
|
|
case oidc.Subtype:
|
|
repo, err := s.oidcRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
attrs := req.GetOidcChangeStateAttributes()
|
|
var opts []oidc.Option
|
|
if attrs.GetDisableDiscoveredConfigValidation() {
|
|
opts = append(opts, oidc.WithForce())
|
|
}
|
|
|
|
var am *oidc.AuthMethod
|
|
switch oidcStateMap[attrs.GetState()] {
|
|
case inactiveState:
|
|
am, err = repo.MakeInactive(ctx, req.GetId(), req.GetVersion())
|
|
case privateState:
|
|
am, err = repo.MakePrivate(ctx, req.GetId(), req.GetVersion(), opts...)
|
|
case publicState:
|
|
am, err = repo.MakePublic(ctx, req.GetId(), req.GetVersion(), opts...)
|
|
default:
|
|
err = errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unrecognized state %q", attrs.GetState()))
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return am, nil
|
|
}
|
|
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "Given auth method type does not support changing state")
|
|
}
|
|
|
|
func (s Service) authResult(ctx context.Context, id string, a action.Type, isRecursive bool) requestauth.VerifyResults {
|
|
const op = "authmethods.(Service).authResult"
|
|
res := requestauth.VerifyResults{}
|
|
|
|
var parentId string
|
|
opts := []requestauth.Option{
|
|
requestauth.WithAction(a),
|
|
requestauth.WithRecursive(isRecursive),
|
|
requestauth.WithFetchAdditionalResourceGrants(additionalResourceGrants...),
|
|
}
|
|
|
|
switch a {
|
|
case action.List, action.Create:
|
|
parentId = id
|
|
iamRepo, err := s.iamRepoFn()
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
scp, err := iamRepo.LookupScope(ctx, parentId)
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
if scp == nil {
|
|
res.Error = handlers.NotFoundError()
|
|
return res
|
|
}
|
|
default:
|
|
var authMeth auth.AuthMethod
|
|
switch globals.ResourceInfoFromPrefix(id).Subtype {
|
|
case password.Subtype:
|
|
repo, err := s.pwRepoFn()
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
am, err := repo.LookupAuthMethod(ctx, id)
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
if am == nil {
|
|
res.Error = handlers.NotFoundError()
|
|
return res
|
|
}
|
|
authMeth = am
|
|
case oidc.Subtype:
|
|
repo, err := s.oidcRepoFn()
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
am, err := repo.LookupAuthMethod(ctx, id)
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
if am == nil {
|
|
res.Error = handlers.NotFoundError()
|
|
return res
|
|
}
|
|
authMeth = am
|
|
case ldap.Subtype:
|
|
repo, err := s.ldapRepoFn()
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
am, err := repo.LookupAuthMethod(ctx, id)
|
|
if err != nil {
|
|
res.Error = err
|
|
return res
|
|
}
|
|
if am == nil {
|
|
res.Error = handlers.NotFoundError()
|
|
return res
|
|
}
|
|
authMeth = am
|
|
default:
|
|
res.Error = errors.New(ctx, errors.InvalidPublicId, op, "unrecognized auth method type")
|
|
return res
|
|
}
|
|
parentId = authMeth.GetScopeId()
|
|
opts = append(opts, requestauth.WithId(id))
|
|
}
|
|
opts = append(opts, requestauth.WithScopeId(parentId))
|
|
return requestauth.Verify(ctx, resource.AuthMethod, opts...)
|
|
}
|
|
|
|
func toAuthMethodProto(ctx context.Context, in auth.AuthMethod, opt ...handlers.Option) (*pb.AuthMethod, error) {
|
|
opts := handlers.GetOpts(opt...)
|
|
if opts.WithOutputFields == nil {
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building auth method proto")
|
|
}
|
|
outputFields := *opts.WithOutputFields
|
|
|
|
out := pb.AuthMethod{}
|
|
if outputFields.Has(globals.IdField) {
|
|
out.Id = in.GetPublicId()
|
|
}
|
|
if outputFields.Has(globals.ScopeIdField) {
|
|
out.ScopeId = in.GetScopeId()
|
|
}
|
|
if outputFields.Has(globals.IsPrimaryField) {
|
|
out.IsPrimary = in.GetIsPrimaryAuthMethod()
|
|
}
|
|
if outputFields.Has(globals.DescriptionField) && in.GetDescription() != "" {
|
|
out.Description = wrapperspb.String(in.GetDescription())
|
|
}
|
|
if outputFields.Has(globals.NameField) && in.GetName() != "" {
|
|
out.Name = wrapperspb.String(in.GetName())
|
|
}
|
|
if outputFields.Has(globals.CreatedTimeField) {
|
|
out.CreatedTime = in.GetCreateTime().GetTimestamp()
|
|
}
|
|
if outputFields.Has(globals.UpdatedTimeField) {
|
|
out.UpdatedTime = in.GetUpdateTime().GetTimestamp()
|
|
}
|
|
if outputFields.Has(globals.VersionField) {
|
|
out.Version = in.GetVersion()
|
|
}
|
|
if outputFields.Has(globals.ScopeField) {
|
|
out.Scope = opts.WithScope
|
|
}
|
|
if outputFields.Has(globals.AuthorizedActionsField) {
|
|
out.AuthorizedActions = opts.WithAuthorizedActions
|
|
}
|
|
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
|
out.AuthorizedCollectionActions = opts.WithAuthorizedCollectionActions
|
|
}
|
|
switch i := in.(type) {
|
|
case *password.AuthMethod:
|
|
if outputFields.Has(globals.TypeField) {
|
|
out.Type = password.Subtype.String()
|
|
}
|
|
if !outputFields.Has(globals.AttributesField) {
|
|
break
|
|
}
|
|
out.Attrs = &pb.AuthMethod_PasswordAuthMethodAttributes{
|
|
PasswordAuthMethodAttributes: &pb.PasswordAuthMethodAttributes{
|
|
MinLoginNameLength: i.GetMinLoginNameLength(),
|
|
MinPasswordLength: i.GetMinPasswordLength(),
|
|
},
|
|
}
|
|
case *oidc.AuthMethod:
|
|
if outputFields.Has(globals.TypeField) {
|
|
out.Type = oidc.Subtype.String()
|
|
}
|
|
if !outputFields.Has(globals.AttributesField) {
|
|
break
|
|
}
|
|
attrs := &pb.OidcAuthMethodAttributes{
|
|
ClientId: wrapperspb.String(i.GetClientId()),
|
|
ClientSecretHmac: i.ClientSecretHmac,
|
|
IdpCaCerts: i.GetCertificates(),
|
|
State: i.GetOperationalState(),
|
|
SigningAlgorithms: i.GetSigningAlgs(),
|
|
AllowedAudiences: i.GetAudClaims(),
|
|
ClaimsScopes: i.GetClaimsScopes(),
|
|
AccountClaimMaps: i.GetAccountClaimMaps(),
|
|
Prompts: i.GetPrompts(),
|
|
}
|
|
if i.DisableDiscoveredConfigValidation {
|
|
attrs.DisableDiscoveredConfigValidation = true
|
|
}
|
|
if i.GetIssuer() != "" {
|
|
attrs.Issuer = wrapperspb.String(i.Issuer)
|
|
}
|
|
if len(i.GetApiUrl()) > 0 {
|
|
attrs.ApiUrlPrefix = wrapperspb.String(i.GetApiUrl())
|
|
attrs.CallbackUrl = fmt.Sprintf("%s/v1/auth-methods/oidc:authenticate:callback", i.GetApiUrl())
|
|
}
|
|
switch i.GetMaxAge() {
|
|
case 0:
|
|
case -1:
|
|
attrs.MaxAge = wrapperspb.UInt32(0)
|
|
default:
|
|
attrs.MaxAge = wrapperspb.UInt32(uint32(i.GetMaxAge()))
|
|
}
|
|
|
|
out.Attrs = &pb.AuthMethod_OidcAuthMethodsAttributes{
|
|
OidcAuthMethodsAttributes: attrs,
|
|
}
|
|
case *ldap.AuthMethod:
|
|
if outputFields.Has(globals.TypeField) {
|
|
out.Type = ldap.Subtype.String()
|
|
}
|
|
if !outputFields.Has(globals.AttributesField) {
|
|
break
|
|
}
|
|
attrs := &pb.LdapAuthMethodAttributes{
|
|
State: i.GetOperationalState(),
|
|
StartTls: i.GetStartTls(),
|
|
InsecureTls: i.GetInsecureTls(),
|
|
DiscoverDn: i.GetDiscoverDn(),
|
|
AnonGroupSearch: i.GetAnonGroupSearch(),
|
|
Urls: i.GetUrls(),
|
|
EnableGroups: i.GetEnableGroups(),
|
|
Certificates: i.GetCertificates(),
|
|
ClientCertificateKeyHmac: base64.RawURLEncoding.EncodeToString(i.GetClientCertificateKeyHmac()),
|
|
BindPasswordHmac: base64.RawURLEncoding.EncodeToString(i.GetBindPasswordHmac()),
|
|
UseTokenGroups: i.GetUseTokenGroups(),
|
|
MaximumPageSize: i.GetMaximumPageSize(),
|
|
}
|
|
if i.GetUpnDomain() != "" {
|
|
attrs.UpnDomain = wrapperspb.String(i.GetUpnDomain())
|
|
}
|
|
if i.GetUserDn() != "" {
|
|
attrs.UserDn = wrapperspb.String(i.GetUserDn())
|
|
}
|
|
if i.GetUserAttr() != "" {
|
|
attrs.UserAttr = wrapperspb.String(i.GetUserAttr())
|
|
}
|
|
if i.GetUserFilter() != "" {
|
|
attrs.UserFilter = wrapperspb.String(i.GetUserFilter())
|
|
}
|
|
if i.GetGroupDn() != "" {
|
|
attrs.GroupDn = wrapperspb.String(i.GetGroupDn())
|
|
}
|
|
if i.GetGroupAttr() != "" {
|
|
attrs.GroupAttr = wrapperspb.String(i.GetGroupAttr())
|
|
}
|
|
if i.GetGroupFilter() != "" {
|
|
attrs.GroupFilter = wrapperspb.String(i.GetGroupFilter())
|
|
}
|
|
if i.GetClientCertificate() != "" {
|
|
attrs.ClientCertificate = wrapperspb.String(i.GetClientCertificate())
|
|
}
|
|
if i.GetBindDn() != "" {
|
|
attrs.BindDn = wrapperspb.String(i.GetBindDn())
|
|
}
|
|
if len(i.GetAccountAttributeMaps()) > 0 {
|
|
attrs.AccountAttributeMaps = i.GetAccountAttributeMaps()
|
|
}
|
|
if i.GetDereferenceAliases() != "" {
|
|
attrs.DereferenceAliases = wrapperspb.String(i.GetDereferenceAliases())
|
|
}
|
|
|
|
out.Attrs = &pb.AuthMethod_LdapAuthMethodsAttributes{
|
|
LdapAuthMethodsAttributes: attrs,
|
|
}
|
|
}
|
|
return &out, nil
|
|
}
|
|
|
|
func toAuthTokenProto(t *authtoken.AuthToken) *pba.AuthToken {
|
|
return &pba.AuthToken{
|
|
Id: t.GetPublicId(),
|
|
Token: t.GetToken(),
|
|
UserId: t.GetIamUserId(),
|
|
AuthMethodId: t.GetAuthMethodId(),
|
|
AccountId: t.GetAuthAccountId(),
|
|
CreatedTime: t.GetCreateTime().GetTimestamp(),
|
|
UpdatedTime: t.GetUpdateTime().GetTimestamp(),
|
|
ApproximateLastUsedTime: t.GetApproximateLastAccessTime().GetTimestamp(),
|
|
ExpirationTime: t.GetExpirationTime().GetTimestamp(),
|
|
}
|
|
}
|
|
|
|
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
|
// requirements on the structure of the request. They verify that:
|
|
// - The path passed in is correctly formatted
|
|
// - All required parameters are set
|
|
// - There are no conflicting parameters provided
|
|
func validateGetRequest(ctx context.Context, req *pbs.GetAuthMethodRequest) error {
|
|
const op = "authmethod.validateGetRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "Missing request")
|
|
}
|
|
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix)
|
|
}
|
|
|
|
func validateCreateRequest(ctx context.Context, req *pbs.CreateAuthMethodRequest) error {
|
|
const op = "authmethod.validateCreateRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "Missing request")
|
|
}
|
|
return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string {
|
|
badFields := map[string]string{}
|
|
if !handlers.ValidId(handlers.Id(req.GetItem().GetScopeId()), scope.Org.Prefix()) &&
|
|
scope.Global.String() != req.GetItem().GetScopeId() {
|
|
badFields[scopeIdField] = "This field must be 'global' or a valid org scope id."
|
|
}
|
|
if req.GetItem().GetIsPrimary() {
|
|
badFields[isPrimaryField] = "This field is read only."
|
|
}
|
|
switch req.GetItem().GetType() {
|
|
case password.Subtype.String():
|
|
// Password attributes are not required when creating a password auth method.
|
|
case oidc.Subtype.String():
|
|
attrs := req.GetItem().GetOidcAuthMethodsAttributes()
|
|
if attrs == nil {
|
|
// OIDC attributes are required when creating an OIDC auth method.
|
|
badFields[attributesField] = "Attributes are required for creating an OIDC auth method."
|
|
} else {
|
|
if attrs.GetIssuer().GetValue() != "" {
|
|
iss, err := url.Parse(attrs.GetIssuer().GetValue())
|
|
if err != nil {
|
|
badFields[issuerField] = fmt.Sprintf("Cannot be parsed as a url. %v", err)
|
|
}
|
|
if iss != nil {
|
|
if !strutil.StrListContains([]string{"http", "https"}, iss.Scheme) {
|
|
badFields[issuerField] = fmt.Sprintf("Must have schema %q or %q specified", "http", "https")
|
|
}
|
|
} else {
|
|
badFields[issuerField] = "Cannot be parsed as a url"
|
|
}
|
|
}
|
|
if attrs.GetDisableDiscoveredConfigValidation() {
|
|
badFields[disableDiscoveredConfigValidationField] = "Field is not allowed at create time."
|
|
}
|
|
if attrs.GetClientId().GetValue() == "" {
|
|
badFields[clientIdField] = "Field required for creating an OIDC auth method."
|
|
}
|
|
if attrs.GetClientSecret().GetValue() == "" {
|
|
badFields[clientSecretField] = "Field required for creating an OIDC auth method."
|
|
}
|
|
if attrs.GetClientSecretHmac() != "" {
|
|
badFields[clientSecretHmacField] = "Field is read only."
|
|
}
|
|
if attrs.GetState() != "" {
|
|
badFields[stateField] = "Field is read only."
|
|
}
|
|
if attrs.GetCallbackUrl() != "" {
|
|
badFields[callbackUrlField] = "Field is read only."
|
|
}
|
|
if len(attrs.GetSigningAlgorithms()) > 0 {
|
|
for _, sa := range attrs.GetSigningAlgorithms() {
|
|
if !oidc.SupportedAlgorithm(oidc.Alg(sa)) {
|
|
badFields[signingAlgorithmField] = fmt.Sprintf("Contains unsupported algorithm %q", sa)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if len(attrs.GetPrompts()) > 0 {
|
|
prompts := strutil.RemoveDuplicatesStable(attrs.GetPrompts(), false)
|
|
|
|
if strutil.StrListContains(prompts, string(oidc.None)) && len(prompts) > 1 {
|
|
badFields[promptsField] = fmt.Sprintf(`prompts (%s) includes "none" with other values`, prompts)
|
|
} else {
|
|
for _, p := range attrs.GetPrompts() {
|
|
if !oidc.SupportedPrompt(oidc.PromptParam(p)) {
|
|
badFields[promptsField] = fmt.Sprintf("Contains unsupported prompt %q", p)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if strings.TrimSpace(attrs.GetApiUrlPrefix().GetValue()) == "" {
|
|
// TODO: When we start accepting the address used in the request make this an optional field.
|
|
badFields[apiUrlPrefixField] = "This field is required."
|
|
} else {
|
|
if cu, err := url.Parse(attrs.GetApiUrlPrefix().GetValue()); err != nil || (cu.Scheme != "http" && cu.Scheme != "https") || cu.Host == "" {
|
|
badFields[apiUrlPrefixField] = fmt.Sprintf("%q cannot be parsed as a url.", attrs.GetApiUrlPrefix().GetValue())
|
|
}
|
|
}
|
|
if len(attrs.GetIdpCaCerts()) > 0 {
|
|
if _, err := oidc.ParseCertificates(ctx, attrs.GetIdpCaCerts()...); err != nil {
|
|
badFields[idpCaCertsField] = fmt.Sprintf("Cannot parse CA certificates. %v", err.Error())
|
|
}
|
|
}
|
|
if len(attrs.GetClaimsScopes()) > 0 {
|
|
for _, cs := range attrs.GetClaimsScopes() {
|
|
if cs == oidc.DefaultClaimsScope {
|
|
badFields[claimsScopesField] = fmt.Sprintf("%s is the default scope and cannot be added as optional %q", oidc.DefaultClaimsScope, cs)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if len(attrs.GetAccountClaimMaps()) > 0 {
|
|
acm, err := oidc.ParseAccountClaimMaps(ctx, attrs.GetAccountClaimMaps()...)
|
|
if err != nil {
|
|
badFields[accountClaimMapsField] = fmt.Sprintf("Contains invalid map %q", err.Error())
|
|
}
|
|
foundTo := make(map[string]bool, len(attrs.GetAccountClaimMaps()))
|
|
for _, m := range acm {
|
|
if foundTo[m.To] {
|
|
badFields[accountClaimMapsField] = fmt.Sprintf("%s=%s contains invalid map - multiple maps to the same Boundary to-claim %s", m.From, m.To, m.To)
|
|
}
|
|
foundTo[m.To] = true
|
|
}
|
|
}
|
|
}
|
|
case ldap.Subtype.String():
|
|
if len(req.GetItem().GetLdapAuthMethodsAttributes().GetUrls()) == 0 {
|
|
badFields[urlsField] = "At least one URL is required"
|
|
}
|
|
validateLdapAttributes(ctx, req.GetItem().GetLdapAuthMethodsAttributes(), badFields)
|
|
default:
|
|
badFields[typeField] = fmt.Sprintf("This is a required field and must be %q.", password.Subtype.String())
|
|
}
|
|
return badFields
|
|
})
|
|
}
|
|
|
|
func validateUpdateRequest(ctx context.Context, req *pbs.UpdateAuthMethodRequest) error {
|
|
const op = "authmethod.validateUpdateRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing request")
|
|
}
|
|
return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string {
|
|
badFields := map[string]string{}
|
|
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), isPrimaryField) {
|
|
badFields[isPrimaryField] = "This field is read only."
|
|
}
|
|
switch globals.ResourceInfoFromPrefix(req.GetId()).Subtype {
|
|
case password.Subtype:
|
|
if req.GetItem().GetType() != "" && req.GetItem().GetType() != password.Subtype.String() {
|
|
badFields[typeField] = "Cannot modify the resource type."
|
|
}
|
|
case oidc.Subtype:
|
|
if req.GetItem().GetType() != "" && req.GetItem().GetType() != oidc.Subtype.String() {
|
|
badFields[typeField] = "Cannot modify the resource type."
|
|
}
|
|
attrs := req.GetItem().GetOidcAuthMethodsAttributes()
|
|
if attrs != nil {
|
|
if attrs.DryRun && attrs.DisableDiscoveredConfigValidation {
|
|
badFields[disableDiscoveredConfigValidationField] = "This field cannot be set to true with dry_run."
|
|
}
|
|
|
|
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), apiUrlPrefixField) {
|
|
// TODO: When we start accepting the address used in the request make this an optional field.
|
|
if strings.TrimSpace(attrs.GetApiUrlPrefix().GetValue()) == "" {
|
|
badFields[apiUrlPrefixField] = "This field should not be set to empty."
|
|
}
|
|
if cu, err := url.Parse(attrs.GetApiUrlPrefix().GetValue()); err != nil || (cu.Scheme != "http" && cu.Scheme != "https") || cu.Host == "" {
|
|
badFields[apiUrlPrefixField] = fmt.Sprintf("%q cannot be parsed as a url.", attrs.GetApiUrlPrefix().GetValue())
|
|
}
|
|
}
|
|
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), issuerField) {
|
|
if attrs.GetIssuer().GetValue() != "" {
|
|
iss, err := url.Parse(attrs.GetIssuer().GetValue())
|
|
if err != nil {
|
|
badFields[issuerField] = fmt.Sprintf("Cannot be parsed as a url. %v", err)
|
|
}
|
|
if iss != nil && !strutil.StrListContains([]string{"http", "https"}, iss.Scheme) {
|
|
badFields[issuerField] = fmt.Sprintf("Must have schema %q or %q specified", "http", "https")
|
|
}
|
|
}
|
|
}
|
|
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), apiUrlPrefixField) {
|
|
if attrs.GetApiUrlPrefix().GetValue() != "" {
|
|
cu, err := url.Parse(attrs.GetApiUrlPrefix().GetValue())
|
|
if err != nil || cu.Host == "" {
|
|
badFields[apiUrlPrefixField] = fmt.Sprintf("%q cannot be parsed as a url.", attrs.GetApiUrlPrefix().GetValue())
|
|
}
|
|
if !strutil.StrListContains([]string{"http", "https"}, cu.Scheme) {
|
|
badFields[apiUrlPrefixField] = fmt.Sprintf("Must have schema %q or %q specified", "http", "https")
|
|
}
|
|
}
|
|
}
|
|
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), clientSecretField) && attrs.GetClientSecret().GetValue() == "" {
|
|
badFields[clientSecretField] = "Can change but cannot unset this field."
|
|
}
|
|
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), clientIdField) && attrs.GetClientId().GetValue() == "" {
|
|
badFields[clientIdField] = "Can change but cannot unset this field."
|
|
}
|
|
|
|
if attrs.GetClientSecretHmac() != "" {
|
|
badFields[clientSecretHmacField] = "Field is read only."
|
|
}
|
|
if attrs.GetState() != "" {
|
|
badFields[stateField] = "Field is read only."
|
|
}
|
|
if attrs.GetCallbackUrl() != "" {
|
|
badFields[callbackUrlField] = "Field is read only."
|
|
}
|
|
|
|
if len(attrs.GetSigningAlgorithms()) > 0 {
|
|
for _, sa := range attrs.GetSigningAlgorithms() {
|
|
if !oidc.SupportedAlgorithm(oidc.Alg(sa)) {
|
|
badFields[signingAlgorithmField] = fmt.Sprintf("Contains unsupported algorithm %q", sa)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if len(attrs.GetPrompts()) > 0 {
|
|
prompts := strutil.RemoveDuplicatesStable(attrs.GetPrompts(), false)
|
|
|
|
if strutil.StrListContains(prompts, string(oidc.None)) && len(prompts) > 1 {
|
|
badFields[promptsField] = fmt.Sprintf(`prompts (%s) includes "none" with other values`, prompts)
|
|
} else {
|
|
for _, p := range attrs.GetPrompts() {
|
|
if !oidc.SupportedPrompt(oidc.PromptParam(p)) {
|
|
badFields[promptsField] = fmt.Sprintf("Contains unsupported prompt %q", p)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if len(attrs.GetIdpCaCerts()) > 0 {
|
|
if _, err := oidc.ParseCertificates(ctx, attrs.GetIdpCaCerts()...); err != nil {
|
|
badFields[idpCaCertsField] = fmt.Sprintf("Cannot parse CA certificates. %v", err.Error())
|
|
}
|
|
}
|
|
if len(attrs.GetClaimsScopes()) > 0 {
|
|
for _, cs := range attrs.GetClaimsScopes() {
|
|
if cs == oidc.DefaultClaimsScope {
|
|
badFields[claimsScopesField] = fmt.Sprintf("%s is the default scope and cannot be added as optional %q", oidc.DefaultClaimsScope, cs)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if len(attrs.GetAccountClaimMaps()) > 0 {
|
|
acm, err := oidc.ParseAccountClaimMaps(ctx, attrs.GetAccountClaimMaps()...)
|
|
if err != nil {
|
|
badFields[accountClaimMapsField] = fmt.Sprintf("Contains invalid map %q", err.Error())
|
|
} else {
|
|
foundTo := make(map[string]bool, len(attrs.GetAccountClaimMaps()))
|
|
for _, m := range acm {
|
|
if foundTo[m.To] {
|
|
badFields[accountClaimMapsField] = fmt.Sprintf("%s=%s contains invalid map - multiple maps to the same Boundary to-claim %s", m.From, m.To, m.To)
|
|
}
|
|
foundTo[m.To] = true
|
|
|
|
to, err := oidc.ConvertToAccountToClaim(ctx, m.To)
|
|
if err != nil {
|
|
badFields[accountClaimMapsField] = fmt.Sprintf("%s=%s contains invalid map %q", m.From, m.To, err.Error())
|
|
break
|
|
}
|
|
if to == oidc.ToSubClaim {
|
|
badFields[accountClaimMapsField] = fmt.Sprintf("%s=%s contains invalid map: not allowed to update sub claim maps", m.From, m.To)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
case ldap.Subtype:
|
|
if req.GetItem().GetType() != "" && req.GetItem().GetType() != ldap.Subtype.String() {
|
|
badFields[typeField] = "Cannot modify the resource type."
|
|
}
|
|
validateLdapAttributes(ctx, req.GetItem().GetLdapAuthMethodsAttributes(), badFields)
|
|
default:
|
|
badFields["id"] = "Incorrectly formatted identifier."
|
|
}
|
|
return badFields
|
|
}, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix)
|
|
}
|
|
|
|
func validateDeleteRequest(ctx context.Context, req *pbs.DeleteAuthMethodRequest) error {
|
|
const op = "authmethod.validateDeleteRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "Missing request")
|
|
}
|
|
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix)
|
|
}
|
|
|
|
func validateListRequest(ctx context.Context, req *pbs.ListAuthMethodsRequest) error {
|
|
const op = "authmethod.validateListRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "Missing request")
|
|
}
|
|
badFields := map[string]string{}
|
|
if !handlers.ValidId(handlers.Id(req.GetScopeId()), scope.Org.Prefix()) &&
|
|
req.GetScopeId() != scope.Global.String() {
|
|
badFields[scopeIdField] = "This field must be 'global' or a valid org scope id."
|
|
}
|
|
if _, err := handlers.NewFilter(ctx, req.GetFilter()); err != nil {
|
|
badFields["filter"] = fmt.Sprintf("This field could not be parsed. %v", err)
|
|
}
|
|
if len(badFields) > 0 {
|
|
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateChangeStateRequest(ctx context.Context, req *pbs.ChangeStateRequest) error {
|
|
const op = "authmethod.validateChangeStateRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "Missing request")
|
|
}
|
|
if st := globals.ResourceInfoFromPrefix(req.GetId()).Subtype; st != oidc.Subtype {
|
|
return handlers.NotFoundErrorf("This endpoint is only available for the %q Auth Method type.", oidc.Subtype.String())
|
|
}
|
|
badFields := make(map[string]string)
|
|
if req.GetVersion() == 0 {
|
|
badFields[versionField] = "Resource version is required."
|
|
}
|
|
|
|
attrs := req.GetOidcChangeStateAttributes()
|
|
if attrs == nil {
|
|
badFields[attributesField] = "Attributes are required when changing an auth method."
|
|
} else {
|
|
switch oidcStateMap[attrs.GetState()] {
|
|
case inactiveState, privateState, publicState:
|
|
default:
|
|
badFields[stateField] = fmt.Sprintf("Only supported values are %q, %q, or %q.", inactiveState.String(), privateState.String(), publicState.String())
|
|
}
|
|
}
|
|
if len(badFields) > 0 {
|
|
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateAuthenticateRequest(ctx context.Context, req *pbs.AuthenticateRequest) error {
|
|
const op = "authmethod.validateAuthenticateRequest"
|
|
if req == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "Missing request")
|
|
}
|
|
|
|
badFields := make(map[string]string)
|
|
|
|
if strings.TrimSpace(req.GetAuthMethodId()) == "" {
|
|
badFields[authMethodIdField] = "This is a required field."
|
|
} else {
|
|
st := globals.ResourceInfoFromPrefix(req.GetAuthMethodId()).Subtype
|
|
switch st {
|
|
case password.Subtype, oidc.Subtype, ldap.Subtype:
|
|
default:
|
|
badFields[authMethodIdField] = "Unknown auth method type."
|
|
}
|
|
}
|
|
|
|
if len(badFields) > 0 {
|
|
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s Service) ConvertInternalAuthTokenToApiAuthToken(ctx context.Context, tok *authtoken.AuthToken) (*pba.AuthToken, error) {
|
|
const op = "authmethod.ConvertInternalAuthTokenToApiAuthToken"
|
|
iamRepo, err := s.iamRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if tok == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing auth token.")
|
|
}
|
|
if tok.Token == "" {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token.")
|
|
}
|
|
if tok.GetPublicId() == "" {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token public ID.")
|
|
}
|
|
if tok.GetScopeId() == "" {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "Empty token, scope ID.")
|
|
}
|
|
token, err := authtoken.EncryptToken(ctx, s.kms, tok.GetScopeId(), tok.GetPublicId(), tok.GetToken())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
tok.Token = tok.GetPublicId() + "_" + token
|
|
prot := toAuthTokenProto(tok)
|
|
|
|
scp, err := iamRepo.LookupScope(ctx, tok.GetScopeId())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if scp == nil {
|
|
return nil, err
|
|
}
|
|
prot.Scope = &scopes.ScopeInfo{
|
|
Id: scp.GetPublicId(),
|
|
Type: scp.GetType(),
|
|
ParentScopeId: scp.GetParentId(),
|
|
}
|
|
|
|
return prot, nil
|
|
}
|
|
|
|
func (s Service) convertToAuthenticateResponse(ctx context.Context, req *pbs.AuthenticateRequest, authResults *requestauth.VerifyResults, tok *pba.AuthToken) (*pbs.AuthenticateResponse, error) {
|
|
const op = "authmethod.convertToAuthenticateResponse"
|
|
if req == nil {
|
|
return nil, handlers.InvalidArgumentErrorf("Nil request.", nil)
|
|
}
|
|
if authResults == nil {
|
|
return nil, handlers.InvalidArgumentErrorf("Nil auth results.", nil)
|
|
}
|
|
if authResults.Scope == nil {
|
|
return nil, handlers.InvalidArgumentErrorf("Missing auth results scope.", nil)
|
|
}
|
|
if authResults.Scope.Id == "" {
|
|
return nil, handlers.InvalidArgumentErrorf("Missing auth results scope ID.", nil)
|
|
}
|
|
if tok == nil {
|
|
return nil, handlers.InvalidArgumentErrorf("Missing auth token", nil)
|
|
}
|
|
res := &perms.Resource{
|
|
ScopeId: authResults.Scope.Id,
|
|
Type: resource.AuthToken,
|
|
}
|
|
// Auth methods are only at global or org, so we can figure out the parent
|
|
if strings.HasPrefix(res.ScopeId, scope.Org.Prefix()) {
|
|
res.ParentScopeId = scope.Global.String()
|
|
}
|
|
tokenType := req.GetType()
|
|
if tokenType == "" {
|
|
// Fall back to deprecated field if type is not set
|
|
tokenType = req.GetTokenType()
|
|
}
|
|
|
|
tok.AuthorizedActions = authResults.FetchActionSetForId(ctx, tok.Id, authtokens.IdActions, requestauth.WithResource(res)).Strings()
|
|
return &pbs.AuthenticateResponse{
|
|
Command: req.GetCommand(),
|
|
Attrs: &pbs.AuthenticateResponse_AuthTokenResponse{
|
|
AuthTokenResponse: tok,
|
|
},
|
|
Type: tokenType,
|
|
}, nil
|
|
}
|
|
|
|
func transformAuthenticateRequestAttributes(ctx context.Context, msg proto.Message) error {
|
|
const op = "authmethod.transformAuthenticateRequestAttributes"
|
|
authRequest, ok := msg.(*pbs.AuthenticateRequest)
|
|
if !ok {
|
|
return fmt.Errorf("%s: message is not an AuthenticateRequest", op)
|
|
}
|
|
attrs := authRequest.GetAttributes()
|
|
if attrs == nil {
|
|
return nil
|
|
}
|
|
switch globals.ResourceInfoFromPrefix(authRequest.GetAuthMethodId()).Subtype {
|
|
case password.Subtype:
|
|
newAttrs := &pbs.PasswordLoginAttributes{}
|
|
if err := handlers.StructToProto(attrs, newAttrs); err != nil {
|
|
return err
|
|
}
|
|
authRequest.Attrs = &pbs.AuthenticateRequest_PasswordLoginAttributes{
|
|
PasswordLoginAttributes: newAttrs,
|
|
}
|
|
case oidc.Subtype:
|
|
switch authRequest.GetCommand() {
|
|
case startCommand:
|
|
newAttrs := &pbs.OidcStartAttributes{}
|
|
if err := handlers.StructToProto(attrs, newAttrs); err != nil {
|
|
return err
|
|
}
|
|
authRequest.Attrs = &pbs.AuthenticateRequest_OidcStartAttributes{
|
|
OidcStartAttributes: newAttrs,
|
|
}
|
|
case callbackCommand:
|
|
newAttrs := &pb.OidcAuthMethodAuthenticateCallbackRequest{}
|
|
if err := handlers.StructToProto(attrs, newAttrs, handlers.WithDiscardUnknownFields(true)); err != nil {
|
|
return err
|
|
}
|
|
authRequest.Attrs = &pbs.AuthenticateRequest_OidcAuthMethodAuthenticateCallbackRequest{
|
|
OidcAuthMethodAuthenticateCallbackRequest: newAttrs,
|
|
}
|
|
case tokenCommand:
|
|
newAttrs := &pb.OidcAuthMethodAuthenticateTokenRequest{}
|
|
if err := handlers.StructToProto(attrs, newAttrs); err != nil {
|
|
return err
|
|
}
|
|
authRequest.Attrs = &pbs.AuthenticateRequest_OidcAuthMethodAuthenticateTokenRequest{
|
|
OidcAuthMethodAuthenticateTokenRequest: newAttrs,
|
|
}
|
|
default:
|
|
return fmt.Errorf("%s: unknown command %q", op, authRequest.GetCommand())
|
|
}
|
|
case ldap.Subtype:
|
|
newAttrs := &pbs.LdapLoginAttributes{}
|
|
if err := handlers.StructToProto(attrs, newAttrs); err != nil {
|
|
return err
|
|
}
|
|
authRequest.Attrs = &pbs.AuthenticateRequest_LdapLoginAttributes{
|
|
LdapLoginAttributes: newAttrs,
|
|
}
|
|
default:
|
|
return &subtypes.UnknownSubtypeIDError{
|
|
ID: authRequest.GetAuthMethodId(),
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func transformAuthenticateResponseAttributes(ctx context.Context, msg proto.Message) error {
|
|
const op = "authmethod.transformAuthenticateResponseAttributes"
|
|
authResponse, ok := msg.(*pbs.AuthenticateResponse)
|
|
if !ok {
|
|
return fmt.Errorf("%s: message is not an AuthenticateResponse", op)
|
|
}
|
|
attrs := authResponse.GetAttrs()
|
|
if attrs == nil {
|
|
return nil
|
|
}
|
|
var newAttrs *structpb.Struct
|
|
var err error
|
|
switch attrs := attrs.(type) {
|
|
case *pbs.AuthenticateResponse_Attributes:
|
|
// No transformation necessary
|
|
newAttrs = attrs.Attributes
|
|
case *pbs.AuthenticateResponse_AuthTokenResponse:
|
|
newAttrs, err = handlers.ProtoToStruct(ctx, attrs.AuthTokenResponse)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
case *pbs.AuthenticateResponse_OidcAuthMethodAuthenticateStartResponse:
|
|
newAttrs, err = handlers.ProtoToStruct(ctx, attrs.OidcAuthMethodAuthenticateStartResponse)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
case *pbs.AuthenticateResponse_OidcAuthMethodAuthenticateCallbackResponse:
|
|
newAttrs, err = handlers.ProtoToStruct(ctx, attrs.OidcAuthMethodAuthenticateCallbackResponse)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
case *pbs.AuthenticateResponse_OidcAuthMethodAuthenticateTokenResponse:
|
|
newAttrs, err = handlers.ProtoToStruct(ctx, attrs.OidcAuthMethodAuthenticateTokenResponse)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
return fmt.Errorf("%s: unknown attributes type %T", op, attrs)
|
|
}
|
|
authResponse.Attrs = &pbs.AuthenticateResponse_Attributes{
|
|
Attributes: newAttrs,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func newOutputOpts(ctx context.Context, item auth.AuthMethod, scopeInfoMap map[string]*scopes.ScopeInfo, authResults requestauth.VerifyResults) ([]handlers.Option, bool, error) {
|
|
res := perms.Resource{
|
|
Type: resource.AuthMethod,
|
|
}
|
|
res.Id = item.GetPublicId()
|
|
res.ScopeId = item.GetScopeId()
|
|
res.ParentScopeId = scopeInfoMap[item.GetScopeId()].GetParentScopeId()
|
|
authorizedActions := authResults.FetchActionSetForId(ctx, item.GetPublicId(), IdActions[globals.ResourceInfoFromPrefix(item.GetPublicId()).Subtype], requestauth.WithResource(&res)).Strings()
|
|
if len(authorizedActions) == 0 {
|
|
return nil, false, nil
|
|
}
|
|
|
|
outputFields := authResults.FetchOutputFields(res, action.List).SelfOrDefaults(authResults.UserId)
|
|
outputOpts := make([]handlers.Option, 0, 3)
|
|
outputOpts = append(outputOpts, handlers.WithOutputFields(outputFields))
|
|
if outputFields.Has(globals.ScopeField) {
|
|
outputOpts = append(outputOpts, handlers.WithScope(scopeInfoMap[item.GetScopeId()]))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedActionsField) {
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions))
|
|
}
|
|
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
|
collectionActions, err := requestauth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope, item.GetPublicId())
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
|
}
|
|
return outputOpts, true, nil
|
|
}
|