graphql-engine/server/src-lib/Hasura/RQL/DDL/Permission.hs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

436 lines
16 KiB
Haskell
Raw Normal View History

2018-06-27 16:11:32 +03:00
module Hasura.RQL.DDL.Permission
( CreatePerm,
runCreatePerm,
PermDef (..),
InsPerm (..),
InsPermDef,
buildInsPermInfo,
SelPerm (..),
SelPermDef,
buildSelPermInfo,
UpdPerm (..),
UpdPermDef,
buildUpdPermInfo,
DelPerm (..),
DelPermDef,
buildDelPermInfo,
IsPerm (..),
DropPerm,
runDropPerm,
dropPermissionInMetadata,
SetPermComment (..),
runSetPermComment,
)
where
import Control.Lens (Lens', (.~), (^?))
import Data.Aeson
import Data.HashMap.Strict qualified as HM
import Data.HashMap.Strict.InsOrd qualified as OMap
import Data.HashSet qualified as HS
import Data.Kind (Type)
import Data.Text.Extended
import Hasura.Base.Error
import Hasura.EncJSON
import Hasura.Prelude
import Hasura.RQL.DDL.Permission.Internal
import Hasura.RQL.DML.Internal
import Hasura.RQL.Types
import Hasura.SQL.AnyBackend qualified as AB
import Hasura.SQL.Types
import Hasura.Session
2018-06-27 16:11:32 +03:00
backend only insert permissions (rfc #4120) (#4224) * move user info related code to Hasura.User module * the RFC #4120 implementation; insert permissions with admin secret * revert back to old RoleName based schema maps An attempt made to avoid duplication of schema contexts in types if any role doesn't possess any admin secret specific schema * fix compile errors in haskell test * keep 'user_vars' for session variables in http-logs * no-op refacto * tests for admin only inserts * update docs for admin only inserts * updated CHANGELOG.md * default behaviour when admin secret is not set * fix x-hasura-role to X-Hasura-Role in pytests * introduce effective timeout in actions async tests * update docs for admin-secret not configured case * Update docs/graphql/manual/api-reference/schema-metadata-api/permission.rst Co-Authored-By: Marion Schleifer <marion@hasura.io> * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * a complete iteration backend insert permissions accessable via 'x-hasura-backend-privilege' session variable * console changes for backend-only permissions * provide tooltip id; update labels and tooltips; * requested changes * requested changes - remove className from Toggle component - use appropriate function name (capitalizeFirstChar -> capitalize) * use toggle props from definitelyTyped * fix accidental commit * Revert "introduce effective timeout in actions async tests" This reverts commit b7a59c19d643520cfde6af579889e1038038438a. * generate complete schema for both 'default' and 'backend' sessions * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * remove unnecessary import, export Toggle as is * update session variable in tooltip * 'x-hasura-use-backend-only-permissions' variable to switch * update help texts * update docs * update docs * update console help text * regenerate package-lock * serve no backend schema when backend_only: false and header set to true - Few type name refactor as suggested by @0x777 * update CHANGELOG.md * Update CHANGELOG.md * Update CHANGELOG.md * fix a merge bug where a certain entity didn't get removed Co-authored-by: Marion Schleifer <marion@hasura.io> Co-authored-by: Rishichandra Wawhal <rishi@hasura.io> Co-authored-by: rikinsk <rikin.kachhia@gmail.com> Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
2020-04-24 12:10:53 +03:00
{- Note [Backend only permissions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As of writing this note, Hasura permission system is meant to be used by the
frontend. After introducing "Actions", the webhook handlers now can make GraphQL
mutations to the server with some backend logic. These mutations shouldn't be
exposed to frontend for any user since they'll bypass the business logic.
For example:-
We've a table named "user" and it has a "email" column. We need to validate the
email address. So we define an action "create_user" and it expects the same inputs
as "insert_user" mutation (generated by Hasura). Now, a role has permission for both
actions and insert operation on the table. If the insert permission is not marked
as "backend_only: true" then it visible to the frontend client along with "creat_user".
Backend only permissions adds an additional privilege to Hasura generated operations.
Those are accessable only if the request is made with `x-hasura-admin-secret`
(if authorization is configured), `x-hasura-use-backend-only-permissions`
(value must be set to "true"), `x-hasura-role` to identify the role and other
required session variables.
backend_only `x-hasura-admin-secret` `x-hasura-use-backend-only-permissions` Result
------------ --------------------- ------------------------------------- ------
FALSE ANY ANY Mutation is always visible
TRUE FALSE ANY Mutation is always hidden
TRUE TRUE (OR NOT-SET) FALSE Mutation is hidden
TRUE TRUE (OR NOT-SET) TRUE Mutation is shown
-}
procSetObj ::
forall b m.
(QErrM m, BackendMetadata b) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
Maybe (ColumnValues b Value) ->
m (PreSetColsPartial b, [Text], [SchemaDependency])
procSetObj source tn fieldInfoMap mObj = do
(setColTups, deps) <- withPathK "set" $
fmap unzip $
forM (HM.toList setObj) $ \(pgCol, val) -> do
ty <-
askColumnType fieldInfoMap pgCol $
"column " <> pgCol <<> " not found in table " <>> tn
sqlExp <- parseCollectableType (CollectableTypeScalar ty) val
let dep = mkColDep @b (getDepReason sqlExp) source tn pgCol
return ((pgCol, sqlExp), dep)
return (HM.fromList setColTups, depHeaders, deps)
where
setObj = fromMaybe mempty mObj
depHeaders = getDepHeadersFromVal $ Object $ mapKeys toTxt setObj
getDepReason = bool DRSessionVariable DROnType . isStaticValue
class IsPerm a where
type PermInfo a = (r :: BackendType -> Type) | r -> a
permAccessor ::
(ToJSON (a b), BackendMetadata b) =>
PermAccessor b (PermInfo a b)
buildPermInfo ::
(ToJSON (a b), BackendMetadata b, QErrM m, TableCoreInfoRM b m) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
PermDef (a b) ->
m (WithDeps (PermInfo a b))
getPermAcc1 ::
(ToJSON (a b), BackendMetadata b) =>
PermDef (a b) ->
PermAccessor b (PermInfo a b)
getPermAcc1 _ = permAccessor
getPermAcc2 ::
(ToJSON (a b), BackendMetadata b) =>
DropPerm a b ->
PermAccessor b (PermInfo a b)
getPermAcc2 _ = permAccessor
addPermToMetadata ::
(ToJSON (a b), BackendMetadata b) =>
PermDef (a b) ->
TableMetadata b ->
TableMetadata b
doesPermissionExistInMetadata ::
forall b.
TableMetadata b ->
RoleName ->
PermType ->
Bool
doesPermissionExistInMetadata tableMetadata roleName = \case
PTInsert -> hasPermissionTo tmInsertPermissions
PTSelect -> hasPermissionTo tmSelectPermissions
PTUpdate -> hasPermissionTo tmUpdatePermissions
PTDelete -> hasPermissionTo tmDeletePermissions
where
hasPermissionTo :: forall a. Lens' (TableMetadata b) (Permissions a) -> Bool
hasPermissionTo perms = isJust $ tableMetadata ^? perms . ix roleName
runCreatePerm ::
forall m b a.
(ToJSON (a b), IsPerm a, UserInfoM m, CacheRWM m, MonadError QErr m, MetadataM m, BackendMetadata b) =>
CreatePerm a b ->
m EncJSON
runCreatePerm (CreatePerm (WithTable source tableName permissionDefn)) = do
tableMetadata <- askTableMetadata @b source tableName
let permAcc = getPermAcc1 permissionDefn
permissionType = permAccToType permAcc
ptText = permTypeToCode permissionType
role = _pdRole permissionDefn
metadataObject =
MOSourceObjId source $
AB.mkAnyBackend $
SMOTableObj @b tableName $
MTOPerm role permissionType
-- NOTE: we check if a permission exists for a `(table, role)` entity in the metadata
-- and not in the `RolePermInfoMap b` because there may exist a permission for the `role`
-- which is an inherited one, so we check it in the metadata directly
-- The metadata will not contain the permissions for the admin role,
-- because the graphql-engine automatically creates the role and it's
-- assumed that the admin role is an implicit role of the graphql-engine.
when (doesPermissionExistInMetadata tableMetadata role permissionType || role == adminRoleName) $
throw400 AlreadyExists $
ptText <> " permission already defined on table " <> tableName <<> " with role " <>> role
buildSchemaCacheFor metadataObject $
MetadataModifier $
tableMetadataSetter @b source tableName %~ addPermToMetadata permissionDefn
pure successMsg
runDropPerm ::
forall b a m.
(ToJSON (a b), IsPerm a, UserInfoM m, CacheRWM m, MonadError QErr m, MetadataM m, BackendMetadata b) =>
DropPerm a b ->
m EncJSON
runDropPerm dp@(DropPerm source table role) = do
tableMetadata <- askTableMetadata @b source table
let permType = permAccToType $ getPermAcc2 dp
unless (doesPermissionExistInMetadata tableMetadata role permType) $ do
let errMsg =
mconcat
[ permTypeToCode permType <> " permission on " <>> table,
" for role " <>> role,
" does not exist"
]
throw400 PermissionDenied errMsg
withNewInconsistentObjsCheck $
buildSchemaCache $
MetadataModifier $
tableMetadataSetter @b source table %~ dropPermissionInMetadata role permType
return successMsg
buildInsPermInfo ::
forall b m.
(QErrM m, TableCoreInfoRM b m, BackendMetadata b) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
PermDef (InsPerm b) ->
m (WithDeps (InsPermInfo b))
buildInsPermInfo source tn fieldInfoMap (PermDef _rn (InsPerm checkCond set mCols mBackendOnly) _) =
2019-04-17 12:48:41 +03:00
withPathK "permission" $ do
(be, beDeps) <- withPathK "check" $ procBoolExp source tn fieldInfoMap checkCond
(setColsSQL, setHdrs, setColDeps) <- procSetObj source tn fieldInfoMap set
void $
withPathK "columns" $ do
indexedForM insCols $ \col -> do
-- Check that all columns specified do in fact exist and are columns
_ <- askColumnType fieldInfoMap col relInInsErr
-- Check that the column is insertable
ci <- askColInfo fieldInfoMap col ""
unless (_cmIsInsertable $ ciMutability ci) $
throw500
( "Column " <> col
<<> " is not insertable and so cannot have insert permissions defined"
)
let fltrHeaders = getDependentHeaders checkCond
reqHdrs = fltrHeaders `HS.union` (HS.fromList setHdrs)
insColDeps = map (mkColDep @b DRUntyped source tn) insCols
deps = mkParentDep @b source tn : beDeps ++ setColDeps ++ insColDeps
insColsWithoutPresets = insCols \\ HM.keys setColsSQL
backend only insert permissions (rfc #4120) (#4224) * move user info related code to Hasura.User module * the RFC #4120 implementation; insert permissions with admin secret * revert back to old RoleName based schema maps An attempt made to avoid duplication of schema contexts in types if any role doesn't possess any admin secret specific schema * fix compile errors in haskell test * keep 'user_vars' for session variables in http-logs * no-op refacto * tests for admin only inserts * update docs for admin only inserts * updated CHANGELOG.md * default behaviour when admin secret is not set * fix x-hasura-role to X-Hasura-Role in pytests * introduce effective timeout in actions async tests * update docs for admin-secret not configured case * Update docs/graphql/manual/api-reference/schema-metadata-api/permission.rst Co-Authored-By: Marion Schleifer <marion@hasura.io> * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * a complete iteration backend insert permissions accessable via 'x-hasura-backend-privilege' session variable * console changes for backend-only permissions * provide tooltip id; update labels and tooltips; * requested changes * requested changes - remove className from Toggle component - use appropriate function name (capitalizeFirstChar -> capitalize) * use toggle props from definitelyTyped * fix accidental commit * Revert "introduce effective timeout in actions async tests" This reverts commit b7a59c19d643520cfde6af579889e1038038438a. * generate complete schema for both 'default' and 'backend' sessions * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * remove unnecessary import, export Toggle as is * update session variable in tooltip * 'x-hasura-use-backend-only-permissions' variable to switch * update help texts * update docs * update docs * update console help text * regenerate package-lock * serve no backend schema when backend_only: false and header set to true - Few type name refactor as suggested by @0x777 * update CHANGELOG.md * Update CHANGELOG.md * Update CHANGELOG.md * fix a merge bug where a certain entity didn't get removed Co-authored-by: Marion Schleifer <marion@hasura.io> Co-authored-by: Rishichandra Wawhal <rishi@hasura.io> Co-authored-by: rikinsk <rikin.kachhia@gmail.com> Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
2020-04-24 12:10:53 +03:00
return (InsPermInfo (HS.fromList insColsWithoutPresets) be setColsSQL backendOnly reqHdrs, deps)
2018-06-27 16:11:32 +03:00
where
backendOnly = Just True == mBackendOnly
allInsCols = map ciColumn $ filter (_cmIsInsertable . ciMutability) $ getCols fieldInfoMap
insCols = interpColSpec allInsCols (fromMaybe PCStar mCols)
relInInsErr = "Only table columns can have insert permissions defined, not relationships or other field types"
2018-06-27 16:11:32 +03:00
instance IsPerm InsPerm where
type PermInfo InsPerm = InsPermInfo
2018-06-27 16:11:32 +03:00
permAccessor = PAInsert
buildPermInfo = buildInsPermInfo
addPermToMetadata permDef =
tmInsertPermissions %~ OMap.insert (_pdRole permDef) permDef
buildSelPermInfo ::
forall b m.
(QErrM m, TableCoreInfoRM b m, BackendMetadata b) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
SelPerm b ->
m (WithDeps (SelPermInfo b))
buildSelPermInfo source tn fieldInfoMap sp = withPathK "permission" $ do
let pgCols = interpColSpec (map ciColumn $ (getCols fieldInfoMap)) $ spColumns sp
2018-06-27 16:11:32 +03:00
(boolExp, boolExpDeps) <-
withPathK "filter" $
procBoolExp source tn fieldInfoMap $ spFilter sp
2018-06-27 16:11:32 +03:00
-- check if the columns exist
void $
withPathK "columns" $
indexedForM pgCols $ \pgCol ->
askColumnType fieldInfoMap pgCol autoInferredErr
2018-06-27 16:11:32 +03:00
-- validate computed fields
scalarComputedFields <-
withPathK "computed_fields" $
indexedForM computedFields $ \fieldName -> do
computedFieldInfo <- askComputedFieldInfo fieldInfoMap fieldName
case _cfiReturnType computedFieldInfo of
CFRScalar _ -> pure fieldName
CFRSetofTable returnTable ->
throw400 NotSupported $
"select permissions on computed field " <> fieldName
<<> " are auto-derived from the permissions on its returning table "
<> returnTable
<<> " and cannot be specified manually"
let deps =
mkParentDep @b source tn :
boolExpDeps ++ map (mkColDep @b DRUntyped source tn) pgCols
++ map (mkComputedFieldDep @b DRUntyped source tn) scalarComputedFields
2018-06-27 16:11:32 +03:00
depHeaders = getDependentHeaders $ spFilter sp
mLimit = spLimit sp
withPathK "limit" $ mapM_ onlyPositiveInt mLimit
2018-06-27 16:11:32 +03:00
let pgColsWithFilter = HM.fromList $ map (,Nothing) pgCols
[Preview] Inherited roles for postgres read queries fixes #3868 docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de` Note: To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`. Introduction ------------ This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`. How are select permissions of different roles are combined? ------------------------------------------------------------ A select permission includes 5 things: 1. Columns accessible to the role 2. Row selection filter 3. Limit 4. Allow aggregation 5. Scalar computed fields accessible to the role Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`. Let's say the following GraphQL query is queried with the `combined_roles` role. ```graphql query { employees { address phone } } ``` This will translate to the following SQL query: ```sql select (case when (P1 or P2) then address else null end) as address, (case when P2 then phone else null end) as phone from employee where (P1 or P2) ``` The other parameters of the select permission will be combined in the following manner: 1. Limit - Minimum of the limits will be the limit of the inherited role 2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation 3. Scalar computed fields - same as table column fields, as in the above example APIs for inherited roles: ---------------------- 1. `add_inherited_role` `add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments `role_name`: the name of the inherited role to be added (String) `role_set`: list of roles that need to be combined (Array of Strings) Example: ```json { "type": "add_inherited_role", "args": { "role_name":"combined_user", "role_set":[ "user", "user1" ] } } ``` After adding the inherited role, the inherited role can be used like single roles like earlier Note: An inherited role can only be created with non-inherited/singular roles. 2. `drop_inherited_role` The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument: `role_name`: name of the inherited role to be dropped Example: ```json { "type": "drop_inherited_role", "args": { "role_name":"combined_user" } } ``` Metadata --------- The derived roles metadata will be included under the `experimental_features` key while exporting the metadata. ```json { "experimental_features": { "derived_roles": [ { "role_name": "manager_is_employee_too", "role_set": [ "employee", "manager" ] } ] } } ``` Scope ------ Only postgres queries and subscriptions are supported in this PR. Important points: ----------------- 1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done. TODOs ------- - [ ] Tests - [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features - [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?) - [ ] Introspection test with a inherited role (nullability changes in a inherited role) - [ ] Docs - [ ] Changelog Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com> GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
scalarComputedFieldsWithFilter = HS.toMap (HS.fromList scalarComputedFields) $> Nothing
let selPermInfo =
SelPermInfo pgColsWithFilter scalarComputedFieldsWithFilter boolExp mLimit allowAgg depHeaders
return (selPermInfo, deps)
2018-06-27 16:11:32 +03:00
where
allowAgg = spAllowAggregations sp
computedFields = spComputedFields sp
2018-06-27 16:11:32 +03:00
autoInferredErr = "permissions for relationships are automatically inferred"
instance IsPerm SelPerm where
type PermInfo SelPerm = SelPermInfo
2018-06-27 16:11:32 +03:00
permAccessor = PASelect
buildPermInfo source tn fieldInfoMap (PermDef _ a _) =
buildSelPermInfo source tn fieldInfoMap a
2018-06-27 16:11:32 +03:00
addPermToMetadata permDef =
tmSelectPermissions %~ OMap.insert (_pdRole permDef) permDef
buildUpdPermInfo ::
forall b m.
(QErrM m, TableCoreInfoRM b m, BackendMetadata b) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
UpdPerm b ->
m (WithDeps (UpdPermInfo b))
buildUpdPermInfo source tn fieldInfoMap (UpdPerm colSpec set fltr check) = do
(be, beDeps) <-
withPathK "filter" $
procBoolExp source tn fieldInfoMap fltr
backend only insert permissions (rfc #4120) (#4224) * move user info related code to Hasura.User module * the RFC #4120 implementation; insert permissions with admin secret * revert back to old RoleName based schema maps An attempt made to avoid duplication of schema contexts in types if any role doesn't possess any admin secret specific schema * fix compile errors in haskell test * keep 'user_vars' for session variables in http-logs * no-op refacto * tests for admin only inserts * update docs for admin only inserts * updated CHANGELOG.md * default behaviour when admin secret is not set * fix x-hasura-role to X-Hasura-Role in pytests * introduce effective timeout in actions async tests * update docs for admin-secret not configured case * Update docs/graphql/manual/api-reference/schema-metadata-api/permission.rst Co-Authored-By: Marion Schleifer <marion@hasura.io> * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * a complete iteration backend insert permissions accessable via 'x-hasura-backend-privilege' session variable * console changes for backend-only permissions * provide tooltip id; update labels and tooltips; * requested changes * requested changes - remove className from Toggle component - use appropriate function name (capitalizeFirstChar -> capitalize) * use toggle props from definitelyTyped * fix accidental commit * Revert "introduce effective timeout in actions async tests" This reverts commit b7a59c19d643520cfde6af579889e1038038438a. * generate complete schema for both 'default' and 'backend' sessions * Apply suggestions from code review Co-Authored-By: Marion Schleifer <marion@hasura.io> * remove unnecessary import, export Toggle as is * update session variable in tooltip * 'x-hasura-use-backend-only-permissions' variable to switch * update help texts * update docs * update docs * update console help text * regenerate package-lock * serve no backend schema when backend_only: false and header set to true - Few type name refactor as suggested by @0x777 * update CHANGELOG.md * Update CHANGELOG.md * Update CHANGELOG.md * fix a merge bug where a certain entity didn't get removed Co-authored-by: Marion Schleifer <marion@hasura.io> Co-authored-by: Rishichandra Wawhal <rishi@hasura.io> Co-authored-by: rikinsk <rikin.kachhia@gmail.com> Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
2020-04-24 12:10:53 +03:00
checkExpr <- traverse (withPathK "check" . procBoolExp source tn fieldInfoMap) check
2018-06-27 16:11:32 +03:00
(setColsSQL, setHeaders, setColDeps) <- procSetObj source tn fieldInfoMap set
2018-06-27 16:11:32 +03:00
-- check if the columns exist
void $
withPathK "columns" $
indexedForM updCols $ \updCol -> do
-- Check that all columns specified do in fact exist and are columns
_ <- askColumnType fieldInfoMap updCol relInUpdErr
-- Check that the column is updatable
ci <- askColInfo fieldInfoMap updCol ""
unless (_cmIsUpdatable $ ciMutability ci) $
throw500
( "Column " <> updCol
<<> " is not updatable and so cannot have update permissions defined"
)
2018-06-27 16:11:32 +03:00
let updColDeps = map (mkColDep @b DRUntyped source tn) allUpdCols
deps = mkParentDep @b source tn : beDeps ++ maybe [] snd checkExpr ++ updColDeps ++ setColDeps
2018-06-27 16:11:32 +03:00
depHeaders = getDependentHeaders fltr
reqHeaders = depHeaders `HS.union` (HS.fromList setHeaders)
updColsWithoutPreSets = updCols \\ HM.keys setColsSQL
2018-06-27 16:11:32 +03:00
return (UpdPermInfo (HS.fromList updColsWithoutPreSets) tn be (fst <$> checkExpr) setColsSQL reqHeaders, deps)
2018-06-27 16:11:32 +03:00
where
allUpdCols = map ciColumn $ filter (_cmIsUpdatable . ciMutability) $ getCols fieldInfoMap
updCols = interpColSpec allUpdCols colSpec
relInUpdErr = "Only table columns can have update permissions defined, not relationships or other field types"
2018-06-27 16:11:32 +03:00
instance IsPerm UpdPerm where
type PermInfo UpdPerm = UpdPermInfo
2018-06-27 16:11:32 +03:00
permAccessor = PAUpdate
buildPermInfo source tn fieldInfoMap (PermDef _ a _) =
buildUpdPermInfo source tn fieldInfoMap a
2018-06-27 16:11:32 +03:00
addPermToMetadata permDef =
tmUpdatePermissions %~ OMap.insert (_pdRole permDef) permDef
buildDelPermInfo ::
forall b m.
(QErrM m, TableCoreInfoRM b m, BackendMetadata b) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
DelPerm b ->
m (WithDeps (DelPermInfo b))
buildDelPermInfo source tn fieldInfoMap (DelPerm fltr) = do
(be, beDeps) <-
withPathK "filter" $
procBoolExp source tn fieldInfoMap fltr
let deps = mkParentDep @b source tn : beDeps
2018-06-27 16:11:32 +03:00
depHeaders = getDependentHeaders fltr
return (DelPermInfo tn be depHeaders, deps)
2018-06-27 16:11:32 +03:00
instance IsPerm DelPerm where
type PermInfo DelPerm = DelPermInfo
2018-06-27 16:11:32 +03:00
permAccessor = PADelete
buildPermInfo source tn fieldInfoMap (PermDef _ a _) =
buildDelPermInfo source tn fieldInfoMap a
2018-06-27 16:11:32 +03:00
addPermToMetadata permDef =
tmDeletePermissions %~ OMap.insert (_pdRole permDef) permDef
data SetPermComment b = SetPermComment
{ apSource :: !SourceName,
apTable :: !(TableName b),
apRole :: !RoleName,
apPermission :: !PermType,
apComment :: !(Maybe Text)
Clean metadata arguments ## Description Thanks to #1664, the Metadata API types no longer require a `ToJSON` instance. This PR follows up with a cleanup of the types of the arguments to the metadata API: - whenever possible, it moves those argument types to where they're used (RQL.DDL.*) - it removes all unrequired instances (mostly `ToJSON`) This PR does not attempt to do it for _all_ such argument types. For some of the metadata operations, the type used to describe the argument to the API and used to represent the value in the metadata are one and the same (like for `CreateEndpoint`). Sometimes, the two types are intertwined in complex ways (`RemoteRelationship` and `RemoteRelationshipDef`). In the spirit of only doing uncontroversial cleaning work, this PR only moves types that are not used outside of RQL.DDL. Furthermore, this is a small step towards separating the different types all jumbled together in RQL.Types. ## Notes This PR also improves several `FromJSON` instances to make use of `withObject`, and to use a human readable string instead of a type name in error messages whenever possible. For instance: - before: `expected Object for Object, but encountered X` after: `expected Object for add computed field, but encountered X` - before: `Expecting an object for update query` after: `expected Object for update query, but encountered X` This PR also renames `CreateFunctionPermission` to `FunctionPermissionArgument`, to remove the quite surprising `type DropFunctionPermission = CreateFunctionPermission`. This PR also deletes some dead code, mostly in RQL.DML. This PR also moves a PG-specific source resolving function from DDL.Schema.Source to the only place where it is used: App.hs. https://github.com/hasura/graphql-engine-mono/pull/1844 GitOrigin-RevId: a594521194bb7fe6a111b02a9e099896f9fed59c
2021-07-27 13:41:42 +03:00
}
2018-06-27 16:11:32 +03:00
instance (Backend b) => FromJSON (SetPermComment b) where
parseJSON = withObject "SetPermComment" $ \o ->
SetPermComment
<$> o .:? "source" .!= defaultSource
<*> o .: "table"
<*> o .: "role"
<*> o .: "permission"
<*> o .:? "comment"
2018-06-27 16:11:32 +03:00
runSetPermComment ::
forall b m.
(QErrM m, CacheRWM m, MetadataM m, BackendMetadata b) =>
SetPermComment b ->
m EncJSON
runSetPermComment (SetPermComment source table roleName permType comment) = do
tableInfo <- askTabInfo @b source table
-- assert permission exists and return appropriate permission modifier
permModifier <- case permType of
PTInsert -> do
[Preview] Inherited roles for postgres read queries fixes #3868 docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de` Note: To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`. Introduction ------------ This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`. How are select permissions of different roles are combined? ------------------------------------------------------------ A select permission includes 5 things: 1. Columns accessible to the role 2. Row selection filter 3. Limit 4. Allow aggregation 5. Scalar computed fields accessible to the role Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`. Let's say the following GraphQL query is queried with the `combined_roles` role. ```graphql query { employees { address phone } } ``` This will translate to the following SQL query: ```sql select (case when (P1 or P2) then address else null end) as address, (case when P2 then phone else null end) as phone from employee where (P1 or P2) ``` The other parameters of the select permission will be combined in the following manner: 1. Limit - Minimum of the limits will be the limit of the inherited role 2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation 3. Scalar computed fields - same as table column fields, as in the above example APIs for inherited roles: ---------------------- 1. `add_inherited_role` `add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments `role_name`: the name of the inherited role to be added (String) `role_set`: list of roles that need to be combined (Array of Strings) Example: ```json { "type": "add_inherited_role", "args": { "role_name":"combined_user", "role_set":[ "user", "user1" ] } } ``` After adding the inherited role, the inherited role can be used like single roles like earlier Note: An inherited role can only be created with non-inherited/singular roles. 2. `drop_inherited_role` The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument: `role_name`: name of the inherited role to be dropped Example: ```json { "type": "drop_inherited_role", "args": { "role_name":"combined_user" } } ``` Metadata --------- The derived roles metadata will be included under the `experimental_features` key while exporting the metadata. ```json { "experimental_features": { "derived_roles": [ { "role_name": "manager_is_employee_too", "role_set": [ "employee", "manager" ] } ] } } ``` Scope ------ Only postgres queries and subscriptions are supported in this PR. Important points: ----------------- 1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done. TODOs ------- - [ ] Tests - [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features - [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?) - [ ] Introspection test with a inherited role (nullability changes in a inherited role) - [ ] Docs - [ ] Changelog Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com> GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
assertPermDefined roleName PAInsert tableInfo
pure $ tmInsertPermissions . ix roleName . pdComment .~ comment
PTSelect -> do
[Preview] Inherited roles for postgres read queries fixes #3868 docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de` Note: To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`. Introduction ------------ This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`. How are select permissions of different roles are combined? ------------------------------------------------------------ A select permission includes 5 things: 1. Columns accessible to the role 2. Row selection filter 3. Limit 4. Allow aggregation 5. Scalar computed fields accessible to the role Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`. Let's say the following GraphQL query is queried with the `combined_roles` role. ```graphql query { employees { address phone } } ``` This will translate to the following SQL query: ```sql select (case when (P1 or P2) then address else null end) as address, (case when P2 then phone else null end) as phone from employee where (P1 or P2) ``` The other parameters of the select permission will be combined in the following manner: 1. Limit - Minimum of the limits will be the limit of the inherited role 2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation 3. Scalar computed fields - same as table column fields, as in the above example APIs for inherited roles: ---------------------- 1. `add_inherited_role` `add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments `role_name`: the name of the inherited role to be added (String) `role_set`: list of roles that need to be combined (Array of Strings) Example: ```json { "type": "add_inherited_role", "args": { "role_name":"combined_user", "role_set":[ "user", "user1" ] } } ``` After adding the inherited role, the inherited role can be used like single roles like earlier Note: An inherited role can only be created with non-inherited/singular roles. 2. `drop_inherited_role` The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument: `role_name`: name of the inherited role to be dropped Example: ```json { "type": "drop_inherited_role", "args": { "role_name":"combined_user" } } ``` Metadata --------- The derived roles metadata will be included under the `experimental_features` key while exporting the metadata. ```json { "experimental_features": { "derived_roles": [ { "role_name": "manager_is_employee_too", "role_set": [ "employee", "manager" ] } ] } } ``` Scope ------ Only postgres queries and subscriptions are supported in this PR. Important points: ----------------- 1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done. TODOs ------- - [ ] Tests - [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features - [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?) - [ ] Introspection test with a inherited role (nullability changes in a inherited role) - [ ] Docs - [ ] Changelog Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com> GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
assertPermDefined roleName PASelect tableInfo
pure $ tmSelectPermissions . ix roleName . pdComment .~ comment
PTUpdate -> do
[Preview] Inherited roles for postgres read queries fixes #3868 docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de` Note: To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`. Introduction ------------ This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`. How are select permissions of different roles are combined? ------------------------------------------------------------ A select permission includes 5 things: 1. Columns accessible to the role 2. Row selection filter 3. Limit 4. Allow aggregation 5. Scalar computed fields accessible to the role Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`. Let's say the following GraphQL query is queried with the `combined_roles` role. ```graphql query { employees { address phone } } ``` This will translate to the following SQL query: ```sql select (case when (P1 or P2) then address else null end) as address, (case when P2 then phone else null end) as phone from employee where (P1 or P2) ``` The other parameters of the select permission will be combined in the following manner: 1. Limit - Minimum of the limits will be the limit of the inherited role 2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation 3. Scalar computed fields - same as table column fields, as in the above example APIs for inherited roles: ---------------------- 1. `add_inherited_role` `add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments `role_name`: the name of the inherited role to be added (String) `role_set`: list of roles that need to be combined (Array of Strings) Example: ```json { "type": "add_inherited_role", "args": { "role_name":"combined_user", "role_set":[ "user", "user1" ] } } ``` After adding the inherited role, the inherited role can be used like single roles like earlier Note: An inherited role can only be created with non-inherited/singular roles. 2. `drop_inherited_role` The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument: `role_name`: name of the inherited role to be dropped Example: ```json { "type": "drop_inherited_role", "args": { "role_name":"combined_user" } } ``` Metadata --------- The derived roles metadata will be included under the `experimental_features` key while exporting the metadata. ```json { "experimental_features": { "derived_roles": [ { "role_name": "manager_is_employee_too", "role_set": [ "employee", "manager" ] } ] } } ``` Scope ------ Only postgres queries and subscriptions are supported in this PR. Important points: ----------------- 1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done. TODOs ------- - [ ] Tests - [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features - [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?) - [ ] Introspection test with a inherited role (nullability changes in a inherited role) - [ ] Docs - [ ] Changelog Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com> GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
assertPermDefined roleName PAUpdate tableInfo
pure $ tmUpdatePermissions . ix roleName . pdComment .~ comment
PTDelete -> do
[Preview] Inherited roles for postgres read queries fixes #3868 docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de` Note: To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`. Introduction ------------ This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`. How are select permissions of different roles are combined? ------------------------------------------------------------ A select permission includes 5 things: 1. Columns accessible to the role 2. Row selection filter 3. Limit 4. Allow aggregation 5. Scalar computed fields accessible to the role Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`. Let's say the following GraphQL query is queried with the `combined_roles` role. ```graphql query { employees { address phone } } ``` This will translate to the following SQL query: ```sql select (case when (P1 or P2) then address else null end) as address, (case when P2 then phone else null end) as phone from employee where (P1 or P2) ``` The other parameters of the select permission will be combined in the following manner: 1. Limit - Minimum of the limits will be the limit of the inherited role 2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation 3. Scalar computed fields - same as table column fields, as in the above example APIs for inherited roles: ---------------------- 1. `add_inherited_role` `add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments `role_name`: the name of the inherited role to be added (String) `role_set`: list of roles that need to be combined (Array of Strings) Example: ```json { "type": "add_inherited_role", "args": { "role_name":"combined_user", "role_set":[ "user", "user1" ] } } ``` After adding the inherited role, the inherited role can be used like single roles like earlier Note: An inherited role can only be created with non-inherited/singular roles. 2. `drop_inherited_role` The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument: `role_name`: name of the inherited role to be dropped Example: ```json { "type": "drop_inherited_role", "args": { "role_name":"combined_user" } } ``` Metadata --------- The derived roles metadata will be included under the `experimental_features` key while exporting the metadata. ```json { "experimental_features": { "derived_roles": [ { "role_name": "manager_is_employee_too", "role_set": [ "employee", "manager" ] } ] } } ``` Scope ------ Only postgres queries and subscriptions are supported in this PR. Important points: ----------------- 1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done. TODOs ------- - [ ] Tests - [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features - [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?) - [ ] Introspection test with a inherited role (nullability changes in a inherited role) - [ ] Docs - [ ] Changelog Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com> GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
assertPermDefined roleName PADelete tableInfo
pure $ tmDeletePermissions . ix roleName . pdComment .~ comment
let metadataObject =
MOSourceObjId source $
AB.mkAnyBackend $
SMOTableObj @b table $
MTOPerm roleName permType
buildSchemaCacheFor metadataObject $
MetadataModifier $
tableMetadataSetter @b source table %~ permModifier
pure successMsg