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

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

224 lines
7.8 KiB
Haskell
Raw Normal View History

{-# LANGUAGE UndecidableInstances #-}
module Hasura.RQL.DDL.Permission.Internal
( CreatePerm (..),
DropPerm (..),
permissionIsDefined,
assertPermDefined,
interpColSpec,
getDepHeadersFromVal,
getDependentHeaders,
annBoolExp,
procBoolExp,
procLogicalModelBoolExp,
)
where
2018-06-27 16:11:32 +03:00
import Control.Lens hiding ((.=))
import Data.Aeson.KeyMap qualified as KM
2018-06-27 16:11:32 +03:00
import Data.Aeson.Types
import Data.HashMap.Strict qualified as HashMap
import Data.HashSet qualified as Set
import Data.Sequence qualified as Seq
import Data.Text qualified as T
import Data.Text.Extended
import Hasura.Base.Error
import Hasura.LogicalModel.Types (LogicalModelName)
2020-08-27 19:36:39 +03:00
import Hasura.Prelude
import Hasura.RQL.IR.BoolExp
import Hasura.RQL.Types.Backend
import Hasura.RQL.Types.BoolExp
import Hasura.RQL.Types.Column (ColumnReference (ColumnReferenceColumn))
import Hasura.RQL.Types.Common
import Hasura.RQL.Types.Metadata.Backend
import Hasura.RQL.Types.Permission
import Hasura.RQL.Types.Relationships.Local
import Hasura.RQL.Types.Roles (RoleName)
import Hasura.RQL.Types.SchemaCache
import Hasura.RQL.Types.SchemaCacheTypes
import Hasura.RQL.Types.Table
import Hasura.Server.Utils
2018-06-27 16:11:32 +03:00
-- | Intrepet a 'PermColSpec' column specification, which can either refer to a
-- list of named columns or all columns.
interpColSpec :: [Column b] -> PermColSpec b -> [Column b]
interpColSpec _ (PCCols cols) = cols
interpColSpec allColumns PCStar = allColumns
2018-06-27 16:11:32 +03:00
permissionIsDefined ::
PermType -> RolePermInfo backend -> Bool
permissionIsDefined pt rpi = isJust
case pt of
PTSelect -> rpi ^. permSel $> ()
PTInsert -> rpi ^. permIns $> ()
PTUpdate -> rpi ^. permUpd $> ()
PTDelete -> rpi ^. permDel $> ()
2018-06-27 16:11:32 +03:00
assertPermDefined ::
(Backend backend, MonadError QErr m) =>
2018-06-27 16:11:32 +03:00
RoleName ->
PermType ->
TableInfo backend ->
2018-06-27 16:11:32 +03:00
m ()
assertPermDefined role pt tableInfo =
unless (any (permissionIsDefined pt) rpi) $
2018-06-27 16:11:32 +03:00
throw400 PermissionDenied $
An `ErrorMessage` type, to encapsulate. This introduces an `ErrorMessage` newtype which wraps `Text` in a manner which is designed to be easy to construct, and difficult to deconstruct. It provides functionality similar to `Data.Text.Extended`, but designed _only_ for error messages. Error messages are constructed through `fromString`, concatenation, or the `toErrorValue` function, which is designed to be overridden for all meaningful domain types that might show up in an error message. Notably, there are not and should never be instances of `ToErrorValue` for `String`, `Text`, `Int`, etc. This is so that we correctly represent the value in a way that is specific to its type. For example, all `Name` values (from the _graphql-parser-hs_ library) are single-quoted now; no exceptions. I have mostly had to add `instance ToErrorValue` for various backend types (and also add newtypes where necessary). Some of these are not strictly necessary for this changeset, as I had bigger aspirations when I started. These aspirations have been tempered by trying and failing twice. As such, in this changeset, I have started by introducing this type to the `parseError` and `parseErrorWith` functions. In the future, I would like to extend this to the `QErr` record and the various `throwError` functions, but this is a much larger task and should probably be done in stages. For now, `toErrorMessage` and `fromErrorMessage` are provided for conversion to and from `Text`, but the intent is to stop exporting these once all error messages are converted to the new type. PR-URL: https://github.com/hasura/graphql-engine-mono/pull/5018 GitOrigin-RevId: 84b37e238992e4312255a87ca44f41af65e2d89a
2022-07-18 23:26:01 +03:00
"'"
<> tshow pt
<> "'"
<> " permission on "
<> tableInfoName tableInfo
<<> " for role "
<> role
<<> " does not exist"
2018-06-27 16:11:32 +03:00
where
rpi = HashMap.lookup role $ _tiRolePermInfoMap tableInfo
2018-06-27 16:11:32 +03:00
newtype CreatePerm a b = CreatePerm (WithTable b (PermDef b a))
deriving instance (Backend b, FromJSON (PermDef b a)) => FromJSON (CreatePerm a b)
2018-06-27 16:11:32 +03:00
data CreatePermP1Res a = CreatePermP1Res
{ cprInfo :: a,
cprDeps :: [SchemaDependency]
2018-06-27 16:11:32 +03:00
}
deriving (Show, Eq)
2018-06-27 16:11:32 +03:00
procBoolExp ::
( QErrM m,
TableCoreInfoRM b m,
BackendMetadata b,
GetAggregationPredicatesDeps b
) =>
SourceName ->
TableName b ->
FieldInfoMap (FieldInfo b) ->
BoolExp b ->
m (AnnBoolExpPartialSQL b, Seq SchemaDependency)
procBoolExp source tn fieldInfoMap be = do
let rhsParser = BoolExpRHSParser parseCollectableType PSESession
rootFieldInfoMap <-
fmap _tciFieldInfoMap $
lookupTableCoreInfo tn
`onNothingM` throw500 ("unexpected: " <> tn <<> " doesn't exist")
abe <- annBoolExp rhsParser rootFieldInfoMap fieldInfoMap $ unBoolExp be
let deps = getBoolExpDeps source tn abe
return (abe, Seq.fromList deps)
2018-06-27 16:11:32 +03:00
-- | Interpret a 'BoolExp' into an 'AnnBoolExp', collecting any dependencies as
-- we go. At the moment, the only dependencies we're likely to encounter are
-- independent dependencies on other tables. For example, "this user can only
-- select from this logical model if their ID is in the @allowed_users@ table".
procLogicalModelBoolExp ::
forall b m.
( QErrM m,
TableCoreInfoRM b m,
BackendMetadata b,
GetAggregationPredicatesDeps b
) =>
SourceName ->
LogicalModelName ->
FieldInfoMap (FieldInfo b) ->
BoolExp b ->
m (AnnBoolExpPartialSQL b, Seq SchemaDependency)
procLogicalModelBoolExp source lmn fieldInfoMap be = do
let -- The parser for the "right hand side" of operations. We use @rhsParser@
-- as the name here for ease of grepping, though it's maybe a bit vague.
-- More specifically, if we think of an operation that combines a field
-- (such as those in tables or native queries) on the /left/ with a value
-- or session variable on the /right/, this is a parser for the latter.
rhsParser :: BoolExpRHSParser b m (PartialSQLExp b)
rhsParser = BoolExpRHSParser parseCollectableType PSESession
-- In Native Queries, there are no relationships (unlike tables, where one
-- table can reference another). This means that our root fieldInfoMap is
-- always going to be the same as our current fieldInfoMap, so we just pass
-- the same one in twice.
abe <- annBoolExp rhsParser fieldInfoMap fieldInfoMap (unBoolExp be)
let -- What dependencies do we have on the schema cache in order to process
-- this boolean expression? This dependency system is explained more
-- thoroughly in the 'buildLogicalModelSelPermInfo' inline comments.
deps :: [SchemaDependency]
deps = getLogicalModelBoolExpDeps source lmn abe
return (abe, Seq.fromList deps)
annBoolExp ::
(QErrM m, TableCoreInfoRM b m, BackendMetadata b) =>
BoolExpRHSParser b m v ->
FieldInfoMap (FieldInfo b) ->
FieldInfoMap (FieldInfo b) ->
GBoolExp b ColExp ->
m (AnnBoolExp b v)
annBoolExp rhsParser rootFieldInfoMap fim boolExp =
case boolExp of
BoolAnd exps -> BoolAnd <$> procExps exps
BoolOr exps -> BoolOr <$> procExps exps
BoolNot e -> BoolNot <$> annBoolExp rhsParser rootFieldInfoMap fim e
BoolExists (GExists refqt whereExp) ->
withPathK "_exists" $ do
refFields <- withPathK "_table" $ askFieldInfoMapSource refqt
annWhereExp <- withPathK "_where" $ annBoolExp rhsParser rootFieldInfoMap refFields whereExp
return $ BoolExists $ GExists refqt annWhereExp
BoolField fld -> BoolField <$> annColExp rhsParser rootFieldInfoMap fim fld
where
procExps = mapM (annBoolExp rhsParser rootFieldInfoMap fim)
annColExp ::
(QErrM m, TableCoreInfoRM b m, BackendMetadata b) =>
BoolExpRHSParser b m v ->
FieldInfoMap (FieldInfo b) ->
FieldInfoMap (FieldInfo b) ->
ColExp ->
m (AnnBoolExpFld b v)
annColExp rhsParser rootFieldInfoMap colInfoMap (ColExp fieldName colVal) = do
colInfo <- askFieldInfo colInfoMap fieldName
case colInfo of
FIColumn pgi -> AVColumn pgi <$> parseBoolExpOperations (_berpValueParser rhsParser) rootFieldInfoMap colInfoMap (ColumnReferenceColumn pgi) colVal
Support nested object fields in DC API and use this to implement nest… ## Description This change adds support for nested object fields in HGE IR and Schema Cache, the Data Connectors backend and API, and the MongoDB agent. ### Data Connector API changes - The `/schema` endpoint response now includes an optional set of GraphQL type definitions. Table column types can refer to these definitions by name. - Queries can now include a new field type `object` which contains a column name and a nested query. This allows querying into a nested object within a field. ### MongoDB agent changes - Add support for querying into nested documents using the new `object` field type. ### HGE changes - The `Backend` type class has a new type family `XNestedObjects b` which controls whether or not a backend supports querying into nested objects. This is currently enabled only for the `DataConnector` backend. - For backends that support nested objects, the `FieldInfo` type gets a new constructor `FINestedObject`, and the `AnnFieldG` type gets a new constructor `AFNestedObject`. - If the DC `/schema` endpoint returns any custom GraphQL type definitions they are stored in the `TableInfo` for each table in the source. - During schema cache building, the function `addNonColumnFields` will check whether any column types match custom GraphQL object types stored in the `TableInfo`. If so, they are converted into `FINestedObject` instead of `FIColumn` in the `FieldInfoMap`. - When building the `FieldParser`s from `FieldInfo` (function `fieldSelection`) any `FINestedObject` fields are converted into nested object parsers returning `AFNestedObject`. - The `DataConnector` query planner converts `AFNestedObject` fields into `object` field types in the query sent to the agent. ## Limitations ### HGE not yet implemented: - Support for nested arrays - Support for nested objects/arrays in mutations - Support for nested objects/arrays in order-by - Support for filters (`where`) in nested objects/arrays - Support for adding custom GraphQL types via track table metadata API - Support for interface and union types - Tests for nested objects ### Mongo agent not yet implemented: - Generate nested object types from validation schema - Support for aggregates - Support for order-by - Configure agent port - Build agent in CI - Agent tests for nested objects and MongoDB agent PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7844 GitOrigin-RevId: aec9ec1e4216293286a68f9b1af6f3f5317db423
2023-04-11 04:29:05 +03:00
FINestedObject {} ->
throw400 NotSupported "nested object not supported"
FIRelationship relInfo -> do
relBoolExp <- decodeValue colVal
relFieldInfoMap <- askFieldInfoMapSource $ riRTable relInfo
annRelBoolExp <- annBoolExp rhsParser rootFieldInfoMap relFieldInfoMap $ unBoolExp relBoolExp
return $ AVRelationship relInfo annRelBoolExp
FIComputedField computedFieldInfo ->
AVComputedField <$> buildComputedFieldBooleanExp (BoolExpResolver annBoolExp) rhsParser rootFieldInfoMap colInfoMap computedFieldInfo colVal
-- Using remote fields in the boolean expression is not supported.
FIRemoteRelationship {} ->
throw400 UnexpectedPayload "remote field unsupported"
getDepHeadersFromVal :: Value -> [Text]
getDepHeadersFromVal val = case val of
Object o -> parseObject o
_ -> parseOnlyString val
2018-06-27 16:11:32 +03:00
where
parseOnlyString v = case v of
(String t)
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
| isSessionVariable t -> [T.toLower t]
| isReqUserId t -> [userIdHeader]
| otherwise -> []
_ -> []
parseObject o =
concatMap getDepHeadersFromVal (KM.elems o)
getDependentHeaders :: BoolExp b -> HashSet Text
getDependentHeaders (BoolExp boolExp) =
Set.fromList $ flip foldMap boolExp $ \(ColExp _ v) -> getDepHeadersFromVal v
2018-06-27 16:11:32 +03:00
data DropPerm b = DropPerm
{ dipSource :: SourceName,
dipTable :: TableName b,
dipRole :: RoleName
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
}
instance (Backend b) => FromJSON (DropPerm b) where
parseJSON = withObject "DropPerm" $ \o ->
DropPerm
<$> o .:? "source" .!= defaultSource
<*> o .: "table"
<*> o .: "role"