|
| 1 | +# Copyright 2021 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# postgres.py contains all database specific functions for connecting |
| 16 | +# and querying a postgreSQL database |
| 17 | + |
| 18 | +import sqlalchemy |
| 19 | +from google.cloud.sql.connector import connector |
| 20 | +from google.cloud.sql.connector.instance_connection_manager import IPTypes |
| 21 | +from iam_groups_authn.utils import RoleService, async_wrap |
| 22 | +from google.auth.transport.requests import Request |
| 23 | + |
| 24 | + |
| 25 | +class PostgresRoleService(RoleService): |
| 26 | + """Class for managing a Postgres DB user's role grants.""" |
| 27 | + |
| 28 | + def __init__(self, db): |
| 29 | + """Initialize a PostgresRoleService object. |
| 30 | +
|
| 31 | + Args: |
| 32 | + db: Database connection object. |
| 33 | + """ |
| 34 | + self.db = db |
| 35 | + |
| 36 | + @async_wrap |
| 37 | + def fetch_role_grants(self, group_name): |
| 38 | + """Fetch mappings of group roles granted to DB users. |
| 39 | +
|
| 40 | + Args: |
| 41 | + group_name: IAM group name prefix of email that is used as group role. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + results: List of results for given query. |
| 45 | + """ |
| 46 | + # postgres query to get users with group role |
| 47 | + stmt = sqlalchemy.text( |
| 48 | + "SELECT pg_roles.rolname, (SELECT pg_roles.rolname FROM pg_roles WHERE oid = pg_auth_members.member) FROM pg_roles, pg_auth_members WHERE pg_auth_members.roleid = (SELECT oid FROM pg_roles WHERE rolname= :group_name) and pg_roles.rolname= :group_name" |
| 49 | + ) |
| 50 | + # create connection to db instance |
| 51 | + with self.db.connect() as db_connection: |
| 52 | + # query users with roles |
| 53 | + results = db_connection.execute(stmt, {"group_name": group_name}).fetchall() |
| 54 | + return results |
| 55 | + |
| 56 | + @async_wrap |
| 57 | + def create_group_role(self, role): |
| 58 | + """Verify or create DB role. |
| 59 | +
|
| 60 | + Given a group role, verify existance of role on DB or create new role |
| 61 | + to manage DB users. |
| 62 | +
|
| 63 | + Args: |
| 64 | + role: Name of group role to be verified or created as new role. |
| 65 | + """ |
| 66 | + # check if group role exists, otherwise create it |
| 67 | + check_stmt = sqlalchemy.text("SELECT 1 FROM pg_roles WHERE rolname= :role") |
| 68 | + stmt = sqlalchemy.text(f'CREATE ROLE "{role}"') |
| 69 | + # create connection to db instance |
| 70 | + with self.db.connect() as db_connection: |
| 71 | + # check if role already exists |
| 72 | + role_check = db_connection.execute(check_stmt, {"role": role}).fetchone() |
| 73 | + # if role does not exist, create it |
| 74 | + if not role_check: |
| 75 | + db_connection.execute(stmt) |
| 76 | + |
| 77 | + @async_wrap |
| 78 | + def grant_group_role(self, role, users): |
| 79 | + """Grant DB group role to DB users. |
| 80 | +
|
| 81 | + Given a DB group role and a list of DB users, grant the DB role to each user. |
| 82 | +
|
| 83 | + Args: |
| 84 | + role: Name of DB role to grant to users. |
| 85 | + users: List of DB users' usernames. |
| 86 | + """ |
| 87 | + with self.db.connect() as db_connection: |
| 88 | + # if there are users to grant group role to, grant role to users |
| 89 | + if users: |
| 90 | + users = '"' + '", "'.join(users) + '"' |
| 91 | + stmt = sqlalchemy.text(f'GRANT "{role}" TO {users}') |
| 92 | + db_connection.execute(stmt) |
| 93 | + |
| 94 | + @async_wrap |
| 95 | + def revoke_group_role(self, role, users): |
| 96 | + """Revoke DB group role to DB users. |
| 97 | +
|
| 98 | + Given a DB group role and a list of DB users, revoke the DB role from each user. |
| 99 | +
|
| 100 | + Args: |
| 101 | + role: Name of DB role to revoke from users. |
| 102 | + users: List of DB users' usernames. |
| 103 | + """ |
| 104 | + # create connection to db instance |
| 105 | + with self.db.connect() as db_connection: |
| 106 | + # if there are users to revoke group role from, revoke role from users |
| 107 | + if users: |
| 108 | + users = '"' + '", "'.join(users) + '"' |
| 109 | + stmt = sqlalchemy.text(f'REVOKE "{role}" FROM {users}') |
| 110 | + db_connection.execute(stmt) |
| 111 | + |
| 112 | + |
| 113 | +def init_postgres_connection_engine( |
| 114 | + instance_connection_name, creds, ip_type=IPTypes.PUBLIC |
| 115 | +): |
| 116 | + """Configure and initialize Postgres database connection pool. |
| 117 | +
|
| 118 | + Configures the parameters for the database connection pool. Initiliazes the |
| 119 | + database connection pool using the Cloud SQL Python Connector. |
| 120 | +
|
| 121 | + Args: |
| 122 | + instance_connection_name: Instance connection name of Cloud SQL instance. |
| 123 | + (e.g. "<PROJECT-NAME>:<INSTANCE-REGION>:<INSTANCE-NAME>") |
| 124 | + creds: Credentials to get OAuth2 access token from, needed for IAM service |
| 125 | + account authentication to DB. |
| 126 | + ip_type: IP address type for instance connection. |
| 127 | + (IPTypes.PUBLIC or IPTypes.PRIVATE) |
| 128 | + Returns: |
| 129 | + A database connection pool instance. |
| 130 | + """ |
| 131 | + db_config = { |
| 132 | + "pool_size": 2, |
| 133 | + "max_overflow": 2, |
| 134 | + "pool_timeout": 30, # 30 seconds |
| 135 | + "pool_recycle": 1800, # 30 minutes |
| 136 | + } |
| 137 | + # refresh credentials if not valid |
| 138 | + if not creds.valid: |
| 139 | + request = Request() |
| 140 | + creds.refresh(request) |
| 141 | + |
| 142 | + # service account to access DB, postgres removes suffix |
| 143 | + service_account_email = (creds.service_account_email).removesuffix( |
| 144 | + ".gserviceaccount.com" |
| 145 | + ) |
| 146 | + # build connection for db using Python Connector |
| 147 | + connection = lambda: connector.connect( |
| 148 | + instance_connection_name, |
| 149 | + "pg8000", |
| 150 | + ip_types=ip_type, |
| 151 | + user=service_account_email, |
| 152 | + db="postgres", |
| 153 | + enable_iam_auth=True, |
| 154 | + ) |
| 155 | + |
| 156 | + # create connection pool |
| 157 | + pool = sqlalchemy.create_engine( |
| 158 | + "postgresql+pg8000://", creator=connection, **db_config |
| 159 | + ) |
| 160 | + return pool |
0 commit comments