Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Grant access to schema for role (#36) #37

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,17 @@ new Schema(this, "Schema", {
})
```

One may need a role permitted for using schema:

```ts
new Schema(this, "Schema", {
provider: provider,
schemaName: "myschema",
databaseName: database.databaseName,
role: role,
})
```

## Sql

You can insert arbitrary SQL into your database with the `Sql` construct:
Expand Down
48 changes: 42 additions & 6 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ interface DatabaseUpdateProps extends DatabaseProps {
MasterOwner: string
}

interface SchemaProps {
/**
* Optional role is granted permissions.
*/
RoleName?: string
}

const maxAttempts = 20

const jumpTable: JumpTable = {
Expand All @@ -73,14 +80,34 @@ const jumpTable: JumpTable = {
},
},
schema: {
Create: async (resourceId: string) => {
return format("create schema if not exists %I", resourceId)
Create: async (resourceId: string, props: SchemaProps) => {
const sql: string[] = [format("create schema if not exists %I", resourceId)]
if (props.RoleName) {
grantRoleForSchema(resourceId, props.RoleName).forEach((stmt) => sql.push(stmt))
}
return sql
},
Update: async (resourceId: string, oldResourceId: string) => {
return format("alter schema %I rename to %I", oldResourceId, resourceId)
Update: async (resourceId: string, oldResourceId: string, props: SchemaProps) => {
const sql: string[] = []
// TODO: revoke old role-name if props.RoleName was removed or changed
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that needs doing (and be tested).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You did those notes as well:

https://github.com/berenddeboer/cdk-rds-sql/blob/main/src/handler.ts#L118
https://github.com/berenddeboer/cdk-rds-sql/blob/main/src/handler.ts#L160

If the handler would be prepared to get old props as well I would have done this check. It is out of the scope of this little change to refactor the handler.

if (props.RoleName) {
revokeRoleFromSchema(oldResourceId, props.RoleName).forEach((stmt) =>
sql.push(stmt)
)
}
sql.push(format("alter schema %I rename to %I", oldResourceId, resourceId))
if (props.RoleName) {
grantRoleForSchema(resourceId, props.RoleName).forEach((stmt) => sql.push(stmt))
}
return sql
},
Delete: (resourceId: string) => {
return format("drop schema if exists %I cascade", resourceId)
Delete: (resourceId: string, props: SchemaProps) => {
const sql: string[] = []
if (props.RoleName) {
revokeRoleFromSchema(resourceId, props.RoleName).forEach((stmt) => sql.push(stmt))
}
sql.push(format("drop schema if exists %I cascade", resourceId))
return sql
},
},
role: {
Expand Down Expand Up @@ -230,6 +257,15 @@ END$$;`,
},
}

const grantRoleForSchema = (schema: string, roleName: string) => [
format("GRANT USAGE ON SCHEMA %I TO %I", schema, roleName),
format("GRANT CREATE ON SCHEMA %I TO %I", schema, roleName),
]
const revokeRoleFromSchema = (schema: string, roleName: string) => [
format("REVOKE CREATE ON SCHEMA %I FROM %I", schema, roleName),
format("REVOKE ALL ON SCHEMA %I FROM %I", schema, roleName),
]

const log =
process.env.LOGGER === "true"
? console.debug
Expand Down
8 changes: 8 additions & 0 deletions src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Construct } from "constructs"
import { IDatabase } from "./database"
import { RdsSqlResource } from "./enum"
import { Provider } from "./provider"
import { Role } from "./role"

export interface SchemaProps {
/**
Expand All @@ -21,6 +22,11 @@ export interface SchemaProps {
* Schema name.
*/
readonly schemaName: string

/**
* Optional role to be granted for managing tables in schema
*/
readonly role?: Role
}

export class Schema extends CustomResource {
Expand All @@ -34,10 +40,12 @@ export class Schema extends CustomResource {
ResourceId: props.schemaName,
SecretArn: props.provider.secret.secretArn,
DatabaseName: props.database ? props.database.databaseName : undefined,
RoleName: props.role ? props.role.roleName : undefined,
},
})
this.node.addDependency(props.provider)
this.schemaName = props.schemaName
if (props.database) this.node.addDependency(props.database)
if (props.role) this.node.addDependency(props.role)
}
}
36 changes: 34 additions & 2 deletions test/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
databaseExists,
databaseOwnerIs,
rowCount,
roleGrantedForSchema,
} from "./util"
import { handler } from "../src/handler"

Expand Down Expand Up @@ -67,6 +68,7 @@ test("schema", async () => {
const create = createRequest("schema", oldSchemaName)
await handler(create)
expect(SecretsManagerClientMock).toHaveBeenCalledTimes(1)

const client = await newClient()
try {
expect(await schemaExists(client, oldSchemaName)).toEqual(true)
Expand All @@ -76,9 +78,39 @@ test("schema", async () => {
expect(await schemaExists(client, newSchemaName)).toEqual(true)

// CloudFormation will send a delete afterward, so test that too
const remove = deleteRequest("schema", oldSchemaName)
const remove = deleteRequest("schema", newSchemaName)
await handler(remove)
expect(await schemaExists(client, oldSchemaName)).toEqual(false)
expect(await schemaExists(client, newSchemaName)).toEqual(false)

// create role for testing
const roleName = "schematest"
const createRole = createRequest("role", roleName, {
PasswordArn: "arn:aws:secretsmanager:us-east-1:123456789:secret:dummy",
DatabaseName: "postgres",
})
await handler(createRole)

const createWithRole = createRequest("schema", oldSchemaName, {
RoleName: roleName,
})
await handler(createWithRole)
expect(await roleGrantedForSchema(client, oldSchemaName, roleName)).toEqual(true)
const updateWithRole = updateRequest("schema", oldSchemaName, newSchemaName, {
RoleName: roleName,
})
await handler(updateWithRole)
expect(await roleGrantedForSchema(client, oldSchemaName, roleName)).toEqual(false)
expect(await roleGrantedForSchema(client, newSchemaName, roleName)).toEqual(true)
const removeWithRole = deleteRequest("schema", newSchemaName, {
RoleName: roleName,
})
await handler(removeWithRole)
expect(await roleGrantedForSchema(client, newSchemaName, roleName)).toEqual(false)

const removeRole = deleteRequest("role", roleName, {
DatabaseName: "postgres",
})
await handler(removeRole)
} finally {
await client.end()
}
Expand Down
17 changes: 17 additions & 0 deletions test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,23 @@ export const schemaExists = async (client: Client, schema: string): Promise<bool
return schemas.find((s) => s === schema) !== undefined
}

export const roleGrantedForSchema = async (
client: Client,
schema: string,
role: string
): Promise<boolean> => {
const sql = `select nspname as schema_name, r.rolname as role_name,\
pg_catalog.has_schema_privilege(r.rolname, nspname, 'CREATE') as create_grant,\
pg_catalog.has_schema_privilege(r.rolname, nspname, 'USAGE') as usage_grant\
from pg_namespace pn,pg_catalog.pg_roles r \
where array_to_string(nspacl,',') like '%'||r.rolname||'%' and nspowner > 1 \
and nspname = '${schema}' and r.rolname = '${role}'`
const { rows } = await client.query(sql)
return (
rows.length === 1 && rows[0].create_grant === true && rows[0].usage_grant === true
)
}

const getSchemas = async (client: Client): Promise<string[]> => {
const { rows } = await client.query(
"select schema_name from information_schema.schemata"
Expand Down