AWS CDK - How to use "placeholder" token with Low Level cfn constructs - aws-cloudformation

I am using CDK (in typescript) to define an AWS Timestream DB and a table inside it.
I want to allow AWS to set the name of the database (and avoid hardcoding it). The problem is how to reference that database name in the table construct.
CDK users' will know that the actual database name is not defined until it is created in AWS (which is after the CDK code that defines the table is executed). For this purpose, CDK created the idea of a placeholder Token (my emphasis).
I know that in the higher level CDK constructs, the placeholder Token is already defined. This doesn't seem to be the case for low level cfn constructs.
Here is some sample code to explain:
This code uses the higher level dynamo construct and lambda and works:
const table = new dynamodb.Table(this, id);
const lambda = new lambda.Function(this, id);
lambda.addEnvironment("TABLE_NAME", table.tableName)
console.log(`table Token is: ${table.tableName}`); // prints *like* "${Token[TOKEN.540]}"
This is the code I am writing for AWS Timestream and no token is generated:
const db = new ts.CfnDatabase(this, id);
console.log(`database name is is: ${db.databaseName}`); // prints null
const table = new ts.CfnTable(this, id, {
databaseName: db.databaseName,
});// this will break as databaseName is null
My questions:
Why: why doesn't the lower level construct generate the Token.
How: I think I can create a token and assign it to db.databaseName but I have no clue how to populate that Token with data when the cdk deploy is run.
Any help on sample code to generate the Token and populate it would be greatly appreciated.

You are probably looking for ref instead of databaseName:
const db = new ts.CfnDatabase(this, id);
console.log(`database name is is: ${db.ref}`); // prints null
const table = new ts.CfnTable(this, id, {
databaseName: db.ref,
});
This corresponds 1:1 to the AWS::Timestream::Database CloudFormation resource. As the docs describe, the Ref return value represents the database name.
Background: properties exposed in "CFN resources" (also known as L1 resources), include both the resource properties (as they are configured when the object is initialized) and resource attributes, which is what you are after.

Related

Where are Hasura roles stored?

I want to create authentication apis in Hasura. My user can have differrent roles when signing up. Thinking of maintaining an Enum table for the same. So that I can have a foreign key/type from it in the user table. However, I intend to create a postgress trigger on this enum table, such that everytime, new role is added, a new hasura role should also be created to allow for JWT authentication and authorization accordingly.
Where does hasura stores its Hasrua role.
Answer 1 (direct answer)
Not sure this is something the app developer should edit.
All Hasura metadata (including roles/permissions) is in Postgres.
The schema is "hdb_catalog". The table is "hdb_metadata".
You can query this using:
SELECT * FROM "hdb_catalog"."hdb_metadata" WHERE id = 1;
It contains a large JSON document. It's better to look at it using PGAdmin.
Answer 2 (dynamic roles)
It looks like you're trying to get dynamic roles in place.
There is a great Youtube video that explains how to model it:
https://youtu.be/-18zZO3DrLY?t=1370

Is there a way to setup a field-level authorisation on FaunaDB + GraphQL?

I'm having troubles finding a way to hide user emails from everyone, except the owner (user has access to only his email). Is there a way to hide a certain document field, for a certain roles?
Here is an example I found that creates a role with dynamic access to the whole User collection:
CreateRole({
name: "tier1_role",
membership: {
resource: Collection("User"),
predicate: Query(
Lambda("userRef",
// User attribute based rule:
// It grants access only if the User has TIER1 role.
// If so, further rules specified in the privileges
// section are applied next.
Equals(Select(["data", "role"], Get(Var("userRef"))), "TIER1")
)
)
},
privileges: [
{
// Note: 'allUsers' Index is used to retrieve the
// documents from the File collection. Therefore,
// read access to the Index is required here as well.
resource: Index("allUsers"),
actions: { read: true }
}
]
})
I tried to change it a bit, but I wasn't able to set up field-level access.
Let's say I'd set up FaunaDB with GraphQL schema below.
enum UserRole {
TIER1
}
type User {
email: String! #unique
username: String! #unique
role: UserRole!
}
type Query {
allUsers: [User!]
}
type Mutation {
addUsers(new_users: [UserInput]): [User]
#resolver(name: "add_users", paginated: false)
}
How do create a FaunaDB role in such a way that all of the users (except the current one) in resulting array from allUsers query, will not have email field?
I could break User collection into two: one is public, the other is accessible to a document owner, but this sounds wrong.
I'm new to the noSQL concept, so maybe I'm looking at this problem from the wrong perspective?
it's a request that came up a few times. You probably want to do this straight in FaunaDB's ABAC role system but although it provides row-level security, hiding a specific field is currently not provided yet. The feedback has been logged though, we will look into it.
The current way to do this is to split out Users from Accounts and fetch Users instead of Accounts. It would be useful to have something like hidden fields though in the future.
If you think of it, in this case, it does make sense to split authentication information from User information. You never know that you might offer another way to authentication in the future. I still recall from the Phoenix Framework book that they do it there was well and considered it a good practice.
You could also make a thin wrapper using Apollo in a serverless function and filter out these fields when you pass through the results. There is a guide that explains how to build such a thin Apollo middleware that just delegates to FaunaDB https://www.gatlin.io/blog/post/social-login-with-faunadb-and-auth0

How to reconcile Relay/GraphQL's globalId with mobgodb's _id?

I'm planning to use mobgodb as my backend storage and graphql + relay for the client-server communication.
How can I reconcile Relay's globalId and Mongo id? Should they even be the same, if not how can I connect one to another?
I think there are two options:
Use mongoose and set the id option to true on your models, it will generate an id attribute with the hex string
or on your graphql schemas add an id field and resolve it this way (not tested)
resolve(me) {
return me._id.toString()
}
globalIdField is usually used to define the id field for the graphql entity and internally it uses toGlobalId function which accepts the id as the 2nd argument. fromGlobalId function could then be used in the node interface definition to extract both id and the defined type.
Here is a mongodb example of how to define the id field, and then use it.

Check if database with specified name exists or not

As you may know that whenever we set a new database inside "sails-orientdb adapter" configurations it creates database, now on the creation time of the database of course database will be created if there is no database inside orientdb with this name, now I want to create vertices related to a class you can say those vertices are defaults of my application, whenever new database will be created those defaults will also be created, but when database already exists those defaults will also be skipped.
Now, is there any function like exists() available inside Waterline or Oriento which can check that database with the specified name inside configurations exists or not inside orientdb and return true or false?
There is not a function .exists() but Oriento has a function named .list() which will list all DBs and allows checking if a particular DB is present. To do this from Sails-OrientDB you can use the custom method .getServer() as follows:
// Assume a model named "Post"
Post.getServer()
.list()
.then(function (dbs) {
var dbExists = _.find(dbs, function(db) {
return db.name === 'myDatabaseName';
});
console.log('myDatabaseName exists:', dbExists);
});
This is the logic that Sails-OrientDB uses to determine if the DB exists before creating it: https://github.com/appscot/sails-orientdb/blob/master/lib/connection.js#L604-L608

Preceding any database access with specific command in CakePHP

I'm new to CakePHP and using version 1.3.
How can I dynamically change the 'schema' property as found in DATABASE_CONFIG prior to any database operation? What is the class where I could have the postgres-specific command "set search_path to 'schema_xyz'" executed before any database interaction?
I want to use Postgres' ability to maintain multiple distinct namespaces (aka schema in postgres parlance) within a single database to implement multi-tenancy in my application. That is, every namespace will contain the same set of tables, but evidently with different content. Here, it's important not to understand schema as meaning table metadata, but rather as the postgres-specific concept of namespace where a schema is a container for tables. The exact Postgres command isn't important. What is, is the mechanism by which it can be invoked, and steering clear of Cake's typical meaning of table description, as seen in the SchemaShell. The only place I have found where Cake exposes the concept of namespace is in the database.php file, which is then used when the DB connection is first established. See: api13.cakephp.org/view_source/dbo-postgres/#line-113 (new user link limit, sorry)
if ($this->connection) {
$this->connected = true;
$this->_execute("SET search_path TO " . $config['schema']);
I want to set that search_path before ALL DB queries, not just at connection time as is currently done.
As a proof of concept, I have tried setting $useDbConfig in my models, but according to the debug output where the SQL commands are printed, this only seems to affect a subset of all queries. I've moved this up into app_model.php with the same result. As did augmenting that with creating a db_config instance on the fly and passing to the ConnectionManager through loadDataSource. Maybe I should slap that code in all flavors of before... methods.
I have seen many posts online where people discuss using one of several DB configurations in database.php to use different databases for dev, lab and production environments. But I have a single database with multiple namespaces/schemas. Also, my number of such namespaces will be too high and dynamic to make hardcoding a new variable in database.php practical.
Thus, where is the spot in CakePHP where I could insert something to set the search_path prior to any database command? I'll deal with optimizing that later. Remember that I'm new to Cake, so try to be as specific as you can. Let me know if I can clarify this question.
Thanks in advance. Here's the partially working code snippet:
class AppModel extends Model {
function beforeFind($queryData)
{
App::import("ConnectionManager");
$cm = &ConnectionManager::getInstance();
$namespace = 'xyz_namespace'; //name of the new schema/namespace/search path
$new_db_config_name = 'new_config'; //name for the new DB config to be used in the ConnectionManager
$new_db_config = $cm->config->default; //copy the 'default' DB config into an array
$new_db_config['schema'] = $namespace; //change/add the new schema/namespace/search path
$cm->create($new_db_config_name, $new_db_config); //turn the array into a DbConfig object
$cm->loadDataSource($new_db_config_name); //load the new DbConfig into the ConnectionManager
$this->useDbConfig = $new_db_config_name; //tell the model to new use the Db Config
return $queryData;
}
}
There is a very simple way in PostgreSQL if you want to switch schema per login role:
ALTER ROLE foo SET search_path=bar, public;
ALTER ROLE baz SET search_path=bam, public;
Thus a connection initiated by that role has that search_path set automatically.
If your login names are the same as the desired schema names, there is an even simpler way, I quote the fine manual:
If one of the list items is the special value $user, then the schema
having the name returned by SESSION_USER is substituted, if there is
such a schema. (If not, $user is ignored.)
But be advised that - the fine manual again:
Role-specific variable settings take effect only at login; SET ROLE
and SET SESSION AUTHORIZATION do not process role-specific variable
settings.
If I understand your question correctly, (bear with me, I know little about Postgres but basically I think you mean, reloading the schema whenever the table perspective changes?), here's how to dynamically switch schemas in your controller:
// Model::getDataSource()->configKeyName holds whichever db config you're using
if ($this->Model->getDataSource()->configKeyName != 'default') {
// do something...
$this->loadModel("Special")
$this->Model->table = "extras";
$this->Model->schema(true);
} else {
// predictably, Model::setDataSource($configKey) changes configs
$this->Model->setDataSource("offsite"); // this could be a string variable
}
Or from the model, $this->getDataSource()->configKeyName and $this->schema(true) and so forth. Note $this->schema(true) actually reloads the model schema and registers it with cake. app_model, a component, or config/bootstrap might be an appropriate place for this. I'm not sure where Cake would have defined the search_path the first time, but it would almost certainly be a property of the dataSource object and could be redefined there just like the table name, etc. And then reload Cake's schema to register the changed path. It is necessary to ensure Cake unloads any default it may have picked up, and load the correct schema based on the currently defined table. (It sounds like this may have been the only step you were missing.)
If this does not answer your question or if I misunderstood, let me know. HTH. :)