2020-10-27 16:53:49 +03:00
|
|
|
{-# LANGUAGE DerivingStrategies #-}
|
2020-04-03 03:00:13 +03:00
|
|
|
|
2018-07-20 10:22:46 +03:00
|
|
|
module Hasura.Server.Auth
|
[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
|
|
|
( getUserInfoWithExpTime,
|
2020-04-03 03:00:13 +03:00
|
|
|
AuthMode (..),
|
2023-03-30 19:31:50 +03:00
|
|
|
compareAuthMode,
|
2020-05-19 17:48:49 +03:00
|
|
|
setupAuthMode,
|
|
|
|
AdminSecretHash,
|
2022-07-26 03:42:05 +03:00
|
|
|
unsafeMkAdminSecretHash,
|
2018-09-27 14:22:49 +03:00
|
|
|
hashAdminSecret,
|
2023-01-06 09:39:10 +03:00
|
|
|
updateJwkCtx,
|
2020-05-28 19:18:26 +03:00
|
|
|
|
|
|
|
-- * WebHook related
|
2020-04-03 03:00:13 +03:00
|
|
|
AuthHookType (..),
|
2022-08-04 05:24:35 +03:00
|
|
|
AuthHook (..),
|
2018-07-20 10:22:46 +03:00
|
|
|
|
2020-10-27 16:53:49 +03:00
|
|
|
-- * JWT related
|
|
|
|
RawJWT,
|
add support for jwt authorization (close #186) (#255)
The API:
1. HGE has `--jwt-secret` flag or `HASURA_GRAPHQL_JWT_SECRET` env var. The value of which is a JSON.
2. The structure of this JSON is: `{"type": "<standard-JWT-algorithms>", "key": "<the-key>"}`
`type` : Standard JWT algos : `HS256`, `RS256`, `RS512` etc. (see jwt.io).
`key`:
i. Incase of symmetric key, the key as it is.
ii. Incase of asymmetric keys, only the public key, in a PEM encoded string or as a X509 certificate.
3. The claims in the JWT token must contain the following:
i. `x-hasura-default-role` field: default role of that user
ii. `x-hasura-allowed-roles` : A list of allowed roles for the user. The default role is overriden by `x-hasura-role` header.
4. The claims in the JWT token, can have other `x-hasura-*` fields where their values can only be strings.
5. The JWT tokens are sent as `Authorization: Bearer <token>` headers.
---
To test:
1. Generate a shared secret (for HMAC-SHA256) or RSA key pair.
2. Goto https://jwt.io/ , add the keys
3. Edit the claims to have `x-hasura-role` (mandatory) and other `x-hasura-*` fields. Add permissions related to the claims to test permissions.
4. Start HGE with `--jwt-secret` flag or `HASURA_GRAPHQL_JWT_SECRET` env var, which takes a JSON string: `{"type": "HS256", "key": "mylongsharedsecret"}` or `{"type":"RS256", "key": "<PEM-encoded-public-key>"}`
5. Copy the JWT token from jwt.io and use it in the `Authorization: Bearer <token>` header.
---
TODO: Support EC public keys. It is blocked on frasertweedale/hs-jose#61
2018-08-30 13:32:09 +03:00
|
|
|
JWTConfig (..),
|
2018-09-27 14:22:49 +03:00
|
|
|
JWTCtx (..),
|
2021-09-24 01:56:37 +03:00
|
|
|
JWKSet (..),
|
2020-10-27 16:53:49 +03:00
|
|
|
processJwt,
|
2019-11-26 15:14:21 +03:00
|
|
|
UserAuthentication (..),
|
2020-10-27 16:53:49 +03:00
|
|
|
|
2021-09-15 11:29:34 +03:00
|
|
|
-- * Exposed for testing
|
|
|
|
getUserInfoWithExpTime_,
|
|
|
|
)
|
add support for jwt authorization (close #186) (#255)
The API:
1. HGE has `--jwt-secret` flag or `HASURA_GRAPHQL_JWT_SECRET` env var. The value of which is a JSON.
2. The structure of this JSON is: `{"type": "<standard-JWT-algorithms>", "key": "<the-key>"}`
`type` : Standard JWT algos : `HS256`, `RS256`, `RS512` etc. (see jwt.io).
`key`:
i. Incase of symmetric key, the key as it is.
ii. Incase of asymmetric keys, only the public key, in a PEM encoded string or as a X509 certificate.
3. The claims in the JWT token must contain the following:
i. `x-hasura-default-role` field: default role of that user
ii. `x-hasura-allowed-roles` : A list of allowed roles for the user. The default role is overriden by `x-hasura-role` header.
4. The claims in the JWT token, can have other `x-hasura-*` fields where their values can only be strings.
5. The JWT tokens are sent as `Authorization: Bearer <token>` headers.
---
To test:
1. Generate a shared secret (for HMAC-SHA256) or RSA key pair.
2. Goto https://jwt.io/ , add the keys
3. Edit the claims to have `x-hasura-role` (mandatory) and other `x-hasura-*` fields. Add permissions related to the claims to test permissions.
4. Start HGE with `--jwt-secret` flag or `HASURA_GRAPHQL_JWT_SECRET` env var, which takes a JSON string: `{"type": "HS256", "key": "mylongsharedsecret"}` or `{"type":"RS256", "key": "<PEM-encoded-public-key>"}`
5. Copy the JWT token from jwt.io and use it in the `Authorization: Bearer <token>` header.
---
TODO: Support EC public keys. It is blocked on frasertweedale/hs-jose#61
2018-08-30 13:32:09 +03:00
|
|
|
where
|
2020-10-27 16:53:49 +03:00
|
|
|
|
2021-09-15 11:29:34 +03:00
|
|
|
import Control.Monad.Trans.Control (MonadBaseControl)
|
|
|
|
import Crypto.Hash qualified as Crypto
|
2021-11-17 10:32:24 +03:00
|
|
|
import Data.ByteArray qualified as BA
|
|
|
|
import Data.ByteString (ByteString)
|
|
|
|
import Data.HashSet qualified as Set
|
|
|
|
import Data.Hashable qualified as Hash
|
2023-01-06 09:39:10 +03:00
|
|
|
import Data.IORef (newIORef, readIORef)
|
2022-02-14 02:33:49 +03:00
|
|
|
import Data.List qualified as L
|
2021-09-15 11:29:34 +03:00
|
|
|
import Data.Text.Encoding qualified as T
|
2023-01-06 09:39:10 +03:00
|
|
|
import Data.Time.Clock (UTCTime, getCurrentTime)
|
2021-05-11 18:18:31 +03:00
|
|
|
import Hasura.Base.Error
|
2021-09-15 11:29:34 +03:00
|
|
|
import Hasura.GraphQL.Transport.HTTP.Protocol (ReqsText)
|
2018-10-25 21:16:25 +03:00
|
|
|
import Hasura.Logging
|
2021-09-15 11:29:34 +03:00
|
|
|
import Hasura.Prelude
|
|
|
|
import Hasura.Server.Auth.JWT hiding (processJwt_)
|
2020-04-03 03:00:13 +03:00
|
|
|
import Hasura.Server.Auth.WebHook
|
add support for jwt authorization (close #186) (#255)
The API:
1. HGE has `--jwt-secret` flag or `HASURA_GRAPHQL_JWT_SECRET` env var. The value of which is a JSON.
2. The structure of this JSON is: `{"type": "<standard-JWT-algorithms>", "key": "<the-key>"}`
`type` : Standard JWT algos : `HS256`, `RS256`, `RS512` etc. (see jwt.io).
`key`:
i. Incase of symmetric key, the key as it is.
ii. Incase of asymmetric keys, only the public key, in a PEM encoded string or as a X509 certificate.
3. The claims in the JWT token must contain the following:
i. `x-hasura-default-role` field: default role of that user
ii. `x-hasura-allowed-roles` : A list of allowed roles for the user. The default role is overriden by `x-hasura-role` header.
4. The claims in the JWT token, can have other `x-hasura-*` fields where their values can only be strings.
5. The JWT tokens are sent as `Authorization: Bearer <token>` headers.
---
To test:
1. Generate a shared secret (for HMAC-SHA256) or RSA key pair.
2. Goto https://jwt.io/ , add the keys
3. Edit the claims to have `x-hasura-role` (mandatory) and other `x-hasura-*` fields. Add permissions related to the claims to test permissions.
4. Start HGE with `--jwt-secret` flag or `HASURA_GRAPHQL_JWT_SECRET` env var, which takes a JSON string: `{"type": "HS256", "key": "mylongsharedsecret"}` or `{"type":"RS256", "key": "<PEM-encoded-public-key>"}`
5. Copy the JWT token from jwt.io and use it in the `Authorization: Bearer <token>` header.
---
TODO: Support EC public keys. It is blocked on frasertweedale/hs-jose#61
2018-08-30 13:32:09 +03:00
|
|
|
import Hasura.Server.Utils
|
2020-04-24 12:10:53 +03:00
|
|
|
import Hasura.Session
|
2022-02-16 10:08:51 +03:00
|
|
|
import Network.HTTP.Client qualified as HTTP
|
|
|
|
import Network.HTTP.Types qualified as HTTP
|
2021-05-11 18:18:31 +03:00
|
|
|
|
2019-11-26 15:14:21 +03:00
|
|
|
-- | Typeclass representing the @UserInfo@ authorization and resolving effect
|
|
|
|
class (Monad m) => UserAuthentication m where
|
|
|
|
resolveUserInfo ::
|
2020-01-23 00:55:55 +03:00
|
|
|
Logger Hasura ->
|
2022-02-16 10:08:51 +03:00
|
|
|
HTTP.Manager ->
|
2019-11-26 15:14:21 +03:00
|
|
|
-- | request headers
|
2022-02-16 10:08:51 +03:00
|
|
|
[HTTP.Header] ->
|
2019-11-26 15:14:21 +03:00
|
|
|
AuthMode ->
|
2021-02-03 10:10:39 +03:00
|
|
|
Maybe ReqsText ->
|
2022-12-15 10:48:18 +03:00
|
|
|
m (Either QErr (UserInfo, Maybe UTCTime, [HTTP.Header], ExtraUserInfo))
|
2018-07-20 10:22:46 +03:00
|
|
|
|
2020-05-19 17:48:49 +03:00
|
|
|
-- | The hashed admin password. 'hashAdminSecret' is our public interface for
|
2020-07-14 22:00:58 +03:00
|
|
|
-- constructing the secret.
|
2020-05-19 17:48:49 +03:00
|
|
|
--
|
|
|
|
-- To prevent misuse and leaking we keep this opaque and don't provide
|
|
|
|
-- instances that could leak information. Likewise for 'AuthMode'.
|
|
|
|
--
|
|
|
|
-- Although this exists only in memory we store only a hash of the admin secret
|
|
|
|
-- primarily in order to:
|
2020-07-14 22:00:58 +03:00
|
|
|
--
|
2020-05-28 19:18:26 +03:00
|
|
|
-- - prevent theoretical timing attacks from a naive `==` check
|
2020-05-19 17:48:49 +03:00
|
|
|
-- - prevent misuse or inadvertent leaking of the secret
|
|
|
|
newtype AdminSecretHash = AdminSecretHash (Crypto.Digest Crypto.SHA512)
|
|
|
|
deriving (Ord, Eq)
|
|
|
|
|
2022-07-26 03:42:05 +03:00
|
|
|
unsafeMkAdminSecretHash :: (Crypto.Digest Crypto.SHA512) -> AdminSecretHash
|
|
|
|
unsafeMkAdminSecretHash = AdminSecretHash
|
|
|
|
|
2021-11-17 10:32:24 +03:00
|
|
|
instance Hash.Hashable AdminSecretHash where
|
|
|
|
hashWithSalt salt (AdminSecretHash h) = Hash.hashWithSalt @ByteString salt $ BA.convert h
|
|
|
|
|
2020-05-28 19:18:26 +03:00
|
|
|
-- We don't want to be able to leak the secret hash. This is a dummy instance
|
|
|
|
-- to support 'Show AuthMode' which we want for testing.
|
|
|
|
instance Show AdminSecretHash where
|
|
|
|
show _ = "(error \"AdminSecretHash hidden\")"
|
|
|
|
|
2020-10-27 16:53:49 +03:00
|
|
|
hashAdminSecret :: Text -> AdminSecretHash
|
2020-05-19 17:48:49 +03:00
|
|
|
hashAdminSecret = AdminSecretHash . Crypto.hash . T.encodeUtf8
|
|
|
|
|
|
|
|
-- | The methods we'll use to derive roles for authenticating requests.
|
|
|
|
--
|
|
|
|
-- @Maybe RoleName@ below is the optionally-defined role for the
|
2020-07-14 22:00:58 +03:00
|
|
|
-- unauthenticated (anonymous) user.
|
2020-05-19 17:48:49 +03:00
|
|
|
--
|
2021-03-01 21:50:24 +03:00
|
|
|
-- See: https://hasura.io/docs/latest/graphql/core/auth/authentication/unauthenticated-access.html
|
2018-07-20 10:22:46 +03:00
|
|
|
data AuthMode
|
|
|
|
= AMNoAuth
|
2021-11-17 10:32:24 +03:00
|
|
|
| AMAdminSecret !(Set.HashSet AdminSecretHash) !(Maybe RoleName)
|
|
|
|
| AMAdminSecretAndHook !(Set.HashSet AdminSecretHash) !AuthHook
|
2022-02-14 02:33:49 +03:00
|
|
|
| AMAdminSecretAndJWT !(Set.HashSet AdminSecretHash) ![JWTCtx] !(Maybe RoleName)
|
2023-03-30 19:31:50 +03:00
|
|
|
deriving (Eq, Show)
|
|
|
|
|
|
|
|
-- | In case JWT is used as an authentication mode, the JWKs are stored inside JWTCtx
|
|
|
|
-- as an `IORef`. `IORef` has pointer equality, so we need to compare the values
|
|
|
|
-- inside the `IORef` to check if the `JWTCtx` is same.
|
|
|
|
compareAuthMode :: AuthMode -> AuthMode -> IO Bool
|
|
|
|
compareAuthMode authMode authMode' = do
|
|
|
|
case (authMode, authMode') of
|
|
|
|
((AMAdminSecretAndJWT adminSecretHash jwtCtx roleName), (AMAdminSecretAndJWT adminSecretHash' jwtCtx' roleName')) -> do
|
|
|
|
-- Since keyConfig of JWTCtx is an IORef it is necessary to extract the value before checking the equality
|
|
|
|
isJwtCtxSame <- zipWithM compareJWTConfig jwtCtx jwtCtx'
|
|
|
|
return $ (adminSecretHash == adminSecretHash') && (and isJwtCtxSame) && (roleName == roleName')
|
|
|
|
_ -> return $ authMode == authMode'
|
|
|
|
where
|
|
|
|
compareJWTConfig :: JWTCtx -> JWTCtx -> IO Bool
|
|
|
|
compareJWTConfig (JWTCtx url keyConfigRef audM iss claims allowedSkew headers) (JWTCtx url' keyConfigRef' audM' iss' claims' allowedSkew' headers') = do
|
|
|
|
keyConfig <- readIORef keyConfigRef
|
|
|
|
keyConfig' <- readIORef keyConfigRef'
|
|
|
|
return $ (url, keyConfig, audM, iss, claims, allowedSkew, headers) == (url', keyConfig', audM', iss', claims', allowedSkew', headers')
|
2020-05-19 17:48:49 +03:00
|
|
|
|
|
|
|
-- | Validate the user's requested authentication configuration, launching any
|
|
|
|
-- required maintenance threads for JWT etc.
|
|
|
|
--
|
|
|
|
-- This must only be run once, on launch.
|
|
|
|
setupAuthMode ::
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
( MonadError Text m,
|
|
|
|
MonadIO m,
|
|
|
|
MonadBaseControl IO m
|
2018-10-25 21:16:25 +03:00
|
|
|
) =>
|
2021-11-17 10:32:24 +03:00
|
|
|
Set.HashSet AdminSecretHash ->
|
2018-12-03 14:19:08 +03:00
|
|
|
Maybe AuthHook ->
|
2022-02-14 02:33:49 +03:00
|
|
|
[JWTConfig] ->
|
2018-10-25 21:16:25 +03:00
|
|
|
Maybe RoleName ->
|
2019-11-28 12:03:14 +03:00
|
|
|
Logger Hasura ->
|
2023-01-06 09:39:10 +03:00
|
|
|
HTTP.Manager ->
|
|
|
|
m AuthMode
|
|
|
|
setupAuthMode adminSecretHashSet mWebHook mJwtSecrets mUnAuthRole logger httpManager =
|
2022-02-14 02:33:49 +03:00
|
|
|
case (not (Set.null adminSecretHashSet), mWebHook, not (null mJwtSecrets)) of
|
|
|
|
(True, Nothing, False) -> return $ AMAdminSecret adminSecretHashSet mUnAuthRole
|
|
|
|
(True, Nothing, True) -> do
|
|
|
|
jwtCtxs <- traverse mkJwtCtx (L.nub mJwtSecrets)
|
|
|
|
pure $ AMAdminSecretAndJWT adminSecretHashSet jwtCtxs mUnAuthRole
|
2020-05-28 19:18:26 +03:00
|
|
|
-- Nothing below this case uses unauth role. Throw a fatal error if we would otherwise ignore
|
|
|
|
-- that parameter, lest users misunderstand their auth configuration:
|
2020-07-14 22:00:58 +03:00
|
|
|
_
|
|
|
|
| isJust mUnAuthRole ->
|
|
|
|
throwError $
|
|
|
|
"Fatal Error: --unauthorized-role (HASURA_GRAPHQL_UNAUTHORIZED_ROLE)"
|
2020-05-28 19:18:26 +03:00
|
|
|
<> requiresAdminScrtMsg
|
|
|
|
<> " and is not allowed when --auth-hook (HASURA_GRAPHQL_AUTH_HOOK) is set"
|
2022-02-14 02:33:49 +03:00
|
|
|
(False, Nothing, False) -> return AMNoAuth
|
|
|
|
(True, Just hook, False) -> return $ AMAdminSecretAndHook adminSecretHashSet hook
|
|
|
|
(False, Just _, False) ->
|
2020-04-03 03:00:13 +03:00
|
|
|
throwError $
|
2019-02-14 12:37:47 +03:00
|
|
|
"Fatal Error : --auth-hook (HASURA_GRAPHQL_AUTH_HOOK)" <> requiresAdminScrtMsg
|
2022-02-14 02:33:49 +03:00
|
|
|
(False, Nothing, True) ->
|
2020-04-03 03:00:13 +03:00
|
|
|
throwError $
|
2019-02-14 12:37:47 +03:00
|
|
|
"Fatal Error : --jwt-secret (HASURA_GRAPHQL_JWT_SECRET)" <> requiresAdminScrtMsg
|
2022-02-14 02:33:49 +03:00
|
|
|
(_, Just _, True) ->
|
2020-04-03 03:00:13 +03:00
|
|
|
throwError
|
2018-10-25 21:16:25 +03:00
|
|
|
"Fatal Error: Both webhook and JWT mode cannot be enabled at the same time"
|
|
|
|
where
|
2019-05-14 09:24:46 +03:00
|
|
|
requiresAdminScrtMsg =
|
|
|
|
" requires --admin-secret (HASURA_GRAPHQL_ADMIN_SECRET) or "
|
|
|
|
<> " --access-key (HASURA_GRAPHQL_ACCESS_KEY) to be set"
|
2018-10-25 21:16:25 +03:00
|
|
|
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
mkJwtCtx :: (MonadIO m, MonadBaseControl IO m, MonadError Text m) => JWTConfig -> m JWTCtx
|
2020-05-19 17:48:49 +03:00
|
|
|
mkJwtCtx JWTConfig {..} = do
|
2023-01-06 09:39:10 +03:00
|
|
|
(jwkUri, jwkKeyConfig) <- case jcKeyOrUrl of
|
|
|
|
Left jwk -> do
|
|
|
|
jwkRef <- liftIO $ newIORef (JWKSet [jwk], Nothing)
|
|
|
|
return (Nothing, jwkRef)
|
|
|
|
-- in case JWT url is provided, an empty JWKSet is initialised,
|
|
|
|
-- which will be populated by the 'updateJWKCtx' poller thread
|
|
|
|
Right uri -> do
|
|
|
|
-- fetch JWK initially and throw error if it fails
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
void $ withJwkError $ fetchJwk logger httpManager uri
|
2023-01-06 09:39:10 +03:00
|
|
|
jwkRef <- liftIO $ newIORef (JWKSet [], Nothing)
|
|
|
|
return (Just uri, jwkRef)
|
2021-02-25 12:02:43 +03:00
|
|
|
let jwtHeader = fromMaybe JHAuthorization jcHeader
|
2023-01-06 09:39:10 +03:00
|
|
|
return $ JWTCtx jwkUri jwkKeyConfig jcAudience jcIssuer jcClaims jcAllowedSkew jwtHeader
|
|
|
|
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
withJwkError a = do
|
|
|
|
res <- runExceptT a
|
|
|
|
onLeft res \case
|
2023-01-06 09:39:10 +03:00
|
|
|
-- when fetching JWK initially, except expiry parsing error, all errors are critical
|
|
|
|
JFEHttpException _ msg -> throwError msg
|
|
|
|
JFEHttpError _ _ _ e -> throwError e
|
|
|
|
JFEJwkParseError _ e -> throwError e
|
|
|
|
JFEExpiryParseError _ _ -> pure (JWKSet [], [])
|
|
|
|
|
2023-03-17 13:29:07 +03:00
|
|
|
-- | Update the JWK based on the expiry time specified in @Expires@ header or
|
|
|
|
-- @Cache-Control@ header
|
2023-01-06 09:39:10 +03:00
|
|
|
updateJwkCtx ::
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
forall m.
|
|
|
|
(MonadIO m, MonadBaseControl IO m) =>
|
2023-01-06 09:39:10 +03:00
|
|
|
AuthMode ->
|
|
|
|
HTTP.Manager ->
|
|
|
|
Logger Hasura ->
|
2023-03-17 13:29:07 +03:00
|
|
|
m ()
|
|
|
|
updateJwkCtx authMode httpManager logger = do
|
2023-01-06 09:39:10 +03:00
|
|
|
case authMode of
|
|
|
|
AMAdminSecretAndJWT _ jwtCtxs _ -> traverse_ updateJwkFromUrl jwtCtxs
|
|
|
|
_ -> pure ()
|
|
|
|
where
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
updateJwkFromUrl :: JWTCtx -> m ()
|
2023-01-06 09:39:10 +03:00
|
|
|
updateJwkFromUrl (JWTCtx url ref _ _ _ _ _) =
|
|
|
|
for_ url \uri -> do
|
|
|
|
(jwkSet, jwkExpiry) <- liftIO $ readIORef ref
|
|
|
|
case jwkSet of
|
|
|
|
-- get the JWKs initially if the JWKSet is empty
|
|
|
|
JWKSet [] -> fetchAndUpdateJWKs logger httpManager uri ref
|
|
|
|
-- if the JWKSet is not empty, get the new JWK based on the
|
|
|
|
-- expiry time
|
|
|
|
_ -> do
|
|
|
|
currentTime <- liftIO getCurrentTime
|
|
|
|
for_ jwkExpiry \expiryTime ->
|
|
|
|
when (currentTime >= expiryTime) $
|
|
|
|
fetchAndUpdateJWKs logger httpManager uri ref
|
2020-02-05 10:07:31 +03:00
|
|
|
|
2020-05-19 17:48:49 +03:00
|
|
|
-- | Authenticate the request using the headers and the configured 'AuthMode'.
|
2019-05-14 09:24:46 +03:00
|
|
|
getUserInfoWithExpTime ::
|
2020-07-15 13:40:48 +03:00
|
|
|
forall m.
|
Rewrite `Tracing` to allow for only one `TraceT` in the entire stack.
This PR is on top of #7789.
### Description
This PR entirely rewrites the API of the Tracing library, to make `interpTraceT` a thing of the past. Before this change, we ran traces by sticking a `TraceT` on top of whatever we were doing. This had several major drawbacks:
- we were carrying a bunch of `TraceT` across the codebase, and the entire codebase had to know about it
- we needed to carry a second class constraint around (`HasReporterM`) to be able to run all of those traces
- we kept having to do stack rewriting with `interpTraceT`, which went from inconvenient to horrible
- we had to declare several behavioral instances on `TraceT m`
This PR rewrite all of `Tracing` using a more conventional model: there is ONE `TraceT` at the bottom of the stack, and there is an associated class constraint `MonadTrace`: any part of the code that happens to satisfy `MonadTrace` is able to create new traces. We NEVER have to do stack rewriting, `interpTraceT` is gone, and `TraceT` and `Reporter` become implementation details that 99% of the code is blissfully unaware of: code that needs to do tracing only needs to declare that the monad in which it operates implements `MonadTrace`.
In doing so, this PR revealed **several bugs in the codebase**: places where we were expecting to trace something, but due to the default instance of `HasReporterM IO` we would actually not do anything. This PR also splits the code of `Tracing` in more byte-sized modules, with the goal of potentially moving to `server/lib` down the line.
### Remaining work
This PR is a draft; what's left to do is:
- [x] make Pro compile; i haven't updated `HasuraPro/Main` yet
- [x] document Tracing by writing a note that explains how to use the library, and the meaning of "reporter", "trace" and "span", as well as the pitfalls
- [x] discuss some of the trade-offs in the implementation, which is why i'm opening this PR already despite it not fully building yet
- [x] it depends on #7789 being merged first
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/7791
GitOrigin-RevId: cadd32d039134c93ddbf364599a2f4dd988adea8
2023-03-13 20:37:16 +03:00
|
|
|
(MonadIO m, MonadBaseControl IO m, MonadError QErr m) =>
|
2019-11-26 15:14:21 +03:00
|
|
|
Logger Hasura ->
|
2022-02-16 10:08:51 +03:00
|
|
|
HTTP.Manager ->
|
|
|
|
[HTTP.Header] ->
|
2019-05-14 09:24:46 +03:00
|
|
|
AuthMode ->
|
2021-02-03 10:10:39 +03:00
|
|
|
Maybe ReqsText ->
|
2022-02-16 10:08:51 +03:00
|
|
|
m (UserInfo, Maybe UTCTime, [HTTP.Header])
|
2020-05-28 19:18:26 +03:00
|
|
|
getUserInfoWithExpTime = getUserInfoWithExpTime_ userInfoFromAuthHook processJwt
|
|
|
|
|
|
|
|
-- Broken out for testing with mocks:
|
|
|
|
getUserInfoWithExpTime_ ::
|
2022-02-16 10:08:51 +03:00
|
|
|
forall m mgr logger.
|
2020-05-28 19:18:26 +03:00
|
|
|
(MonadIO m, MonadError QErr m) =>
|
|
|
|
-- | mock 'userInfoFromAuthHook'
|
2022-02-16 10:08:51 +03:00
|
|
|
( logger ->
|
|
|
|
mgr ->
|
[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
|
|
|
AuthHook ->
|
2022-02-16 10:08:51 +03:00
|
|
|
[HTTP.Header] ->
|
[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
|
|
|
Maybe ReqsText ->
|
2022-02-16 10:08:51 +03:00
|
|
|
m (UserInfo, Maybe UTCTime, [HTTP.Header])
|
2021-09-24 01:56:37 +03:00
|
|
|
) ->
|
2020-05-28 19:18:26 +03:00
|
|
|
-- | mock 'processJwt'
|
2022-02-16 10:08:51 +03:00
|
|
|
( [JWTCtx] ->
|
|
|
|
[HTTP.Header] ->
|
|
|
|
Maybe RoleName ->
|
|
|
|
m (UserInfo, Maybe UTCTime, [HTTP.Header])
|
|
|
|
) ->
|
|
|
|
logger ->
|
|
|
|
mgr ->
|
|
|
|
[HTTP.Header] ->
|
2020-05-28 19:18:26 +03:00
|
|
|
AuthMode ->
|
2021-02-03 10:10:39 +03:00
|
|
|
Maybe ReqsText ->
|
2022-02-16 10:08:51 +03:00
|
|
|
m (UserInfo, Maybe UTCTime, [HTTP.Header])
|
[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
|
|
|
getUserInfoWithExpTime_ userInfoFromAuthHook_ processJwt_ logger manager rawHeaders authMode reqs = case authMode of
|
2020-05-05 22:57:17 +03:00
|
|
|
AMNoAuth -> withNoExpTime $ mkUserInfoFallbackAdminRole UAuthNotSet
|
2020-05-28 19:18:26 +03:00
|
|
|
-- If hasura was started with an admin secret we:
|
|
|
|
-- - check if a secret was sent in the request
|
|
|
|
-- - if so, check it and authorize as admin else fail
|
|
|
|
-- - if not proceed with either webhook or JWT auth if configured
|
2021-11-17 10:32:24 +03:00
|
|
|
AMAdminSecret adminSecretHashSet maybeUnauthRole ->
|
|
|
|
checkingSecretIfSent adminSecretHashSet $
|
2021-11-09 15:00:21 +03:00
|
|
|
withNoExpTime
|
2020-05-05 22:57:17 +03:00
|
|
|
-- Consider unauthorized role, if not found raise admin secret header required exception
|
|
|
|
case maybeUnauthRole of
|
|
|
|
Nothing ->
|
|
|
|
throw401 $
|
|
|
|
adminSecretHeader
|
|
|
|
<> "/"
|
|
|
|
<> deprecatedAccessKeyHeader
|
|
|
|
<> " required, but not found"
|
|
|
|
Just unAuthRole ->
|
|
|
|
mkUserInfo (URBPreDetermined unAuthRole) UAdminSecretNotSent sessionVariables
|
2021-02-03 10:10:39 +03:00
|
|
|
-- this is the case that actually ends up consuming the request AST
|
2021-11-17 10:32:24 +03:00
|
|
|
AMAdminSecretAndHook adminSecretHashSet hook ->
|
|
|
|
checkingSecretIfSent adminSecretHashSet $ userInfoFromAuthHook_ logger manager hook rawHeaders reqs
|
2022-02-14 02:33:49 +03:00
|
|
|
AMAdminSecretAndJWT adminSecretHashSet jwtSecrets unAuthRole ->
|
|
|
|
checkingSecretIfSent adminSecretHashSet $ processJwt_ jwtSecrets rawHeaders unAuthRole
|
2018-07-20 10:22:46 +03:00
|
|
|
where
|
2020-05-28 19:18:26 +03:00
|
|
|
-- CAREFUL!:
|
2020-05-05 22:57:17 +03:00
|
|
|
mkUserInfoFallbackAdminRole adminSecretState =
|
|
|
|
mkUserInfo
|
|
|
|
(URBFromSessionVariablesFallback adminRoleName)
|
|
|
|
adminSecretState
|
|
|
|
sessionVariables
|
2018-07-20 10:22:46 +03:00
|
|
|
|
2020-08-31 19:40:01 +03:00
|
|
|
sessionVariables = mkSessionVariablesHeaders rawHeaders
|
2018-07-20 10:22:46 +03:00
|
|
|
|
2020-05-28 19:18:26 +03:00
|
|
|
checkingSecretIfSent ::
|
2022-02-16 10:08:51 +03:00
|
|
|
Set.HashSet AdminSecretHash -> m (UserInfo, Maybe UTCTime, [HTTP.Header]) -> m (UserInfo, Maybe UTCTime, [HTTP.Header])
|
2021-11-17 10:32:24 +03:00
|
|
|
checkingSecretIfSent adminSecretHashSet actionIfNoAdminSecret = do
|
2020-05-05 22:57:17 +03:00
|
|
|
let maybeRequestAdminSecret =
|
|
|
|
foldl1 (<|>) $
|
|
|
|
map
|
|
|
|
(`getSessionVariableValue` sessionVariables)
|
|
|
|
[adminSecretHeader, deprecatedAccessKeyHeader]
|
|
|
|
|
|
|
|
-- when admin secret is absent, run the action to retrieve UserInfo
|
|
|
|
case maybeRequestAdminSecret of
|
|
|
|
Nothing -> actionIfNoAdminSecret
|
|
|
|
Just requestAdminSecret -> do
|
2021-11-17 10:32:24 +03:00
|
|
|
unless (Set.member (hashAdminSecret requestAdminSecret) adminSecretHashSet) $
|
2020-05-19 17:48:49 +03:00
|
|
|
throw401 $
|
2020-05-05 22:57:17 +03:00
|
|
|
"invalid " <> adminSecretHeader <> "/" <> deprecatedAccessKeyHeader
|
|
|
|
withNoExpTime $ mkUserInfoFallbackAdminRole UAdminSecretSent
|
2019-05-14 09:24:46 +03:00
|
|
|
|
2021-11-09 15:00:21 +03:00
|
|
|
withNoExpTime a = (,Nothing,[]) <$> a
|