Debian Codegraph @

ansible_collections/community/postgresql/plugins/modules/postgresql_privs.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # Copyright: (c) 2019, Tobias Birkefeld (@tcraxs) <[email protected]>
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 DOCUMENTATION = r'''
13 ---
14 module: postgresql_privs
15 short_description: Grant or revoke privileges on PostgreSQL database objects
16 description:
17 - Grant or revoke privileges on PostgreSQL database objects.
18 - This module is basically a wrapper around most of the functionality of
19 PostgreSQL's GRANT and REVOKE statements with detection of changes
20 (GRANT/REVOKE I(privs) ON I(type) I(objs) TO/FROM I(roles)).
21 options:
22 login_db:
23 description:
24 - Name of database to connect to.
25 - The V(db) and V(database) aliases are deprecated and will be removed in version 5.0.0.
26 required: true
27 type: str
28 aliases:
29 - db
30 - database
31 state:
32 description:
33 - If C(present), the specified privileges are granted, if C(absent) they are revoked.
34 type: str
35 default: present
36 choices: [ absent, present ]
37 privs:
38 description:
39 - Comma separated list of privileges to grant/revoke.
40 type: str
41 aliases:
42 - priv
43 type:
44 description:
45 - Type of database object to set privileges on.
46 - The C(default_privs) choice is available starting at version 2.7.
47 - The C(foreign_data_wrapper) and C(foreign_server) object types are available since Ansible version 2.8.
48 - The C(type) choice is available since Ansible version 2.10.
49 - The C(procedure) is supported since collection version 1.3.0 and PostgreSQL 11.
50 - The C(parameter) is supported since collection version 3.1.0 and PostgreSQL 15.
51 - The C(table) also includes views and materialized views. It is inclusive of foreign tables since collection version 3.6.0.
52 type: str
53 default: table
54 choices: [ database, default_privs, foreign_data_wrapper, foreign_server, function,
55 group, language, table, tablespace, schema, sequence, type, procedure, parameter ]
56 objs:
57 description:
58 - Comma separated list of database objects to set privileges on.
59 - If I(type) is C(table), C(partition table), C(sequence), C(function) or C(procedure),
60 the special value C(ALL_IN_SCHEMA) can be provided instead to specify all
61 database objects of I(type) in the schema specified via I(schema).
62 (This also works with PostgreSQL < 9.0.) (C(ALL_IN_SCHEMA) is available
63 for C(function) and C(partition table) since Ansible 2.8).
64 - C(procedure) is supported since PostgreSQL 11 and community.postgresql collection 1.3.0.
65 - C(parameter) is supported since PostgreSQL 15 and community.postgresql collection 3.1.0.
66 - If I(type) is C(database), this parameter can be omitted, in which case
67 privileges are set for the database specified via I(database).
68 - If I(type) is C(function) or C(procedure), colons (":") in object names will be
69 replaced with commas (needed to specify signatures, see examples).
70 type: str
71 aliases:
72 - obj
73 schema:
74 description:
75 - Schema that contains the database objects specified via I(objs).
76 - May only be provided if I(type) is C(table), C(sequence), C(function), C(procedure), C(type),
77 or C(default_privs). Defaults to C(public) in these cases.
78 - Pay attention, for embedded types when I(type=type)
79 I(schema) can be C(pg_catalog) or C(information_schema) respectively.
80 - If not specified, uses C(public). Not to pass any schema, use C(not-specified).
81 type: str
82 roles:
83 description:
84 - Comma separated list of role (user/group) names to set permissions for.
85 - Roles C(PUBLIC), C(CURRENT_ROLE), C(CURRENT_USER), C(SESSION_USER) are implicitly defined in PostgreSQL.
86 - C(CURRENT_USER) and C(SESSION_USER) implicit roles are supported since collection version 3.1.0 and PostgreSQL 9.5.
87 - C(CURRENT_ROLE) implicit role is supported since collection version 3.1.0 and PostgreSQL 14.
88 type: str
89 required: true
90 aliases:
91 - role
92 fail_on_role:
93 description:
94 - If C(true), fail when target role (for whom privs need to be granted) does not exist.
95 Otherwise just warn and continue.
96 default: true
97 type: bool
98 session_role:
99 description:
100 - Switch to session_role after connecting.
101 - The specified session_role must be a role that the current login_user is a member of.
102 - Permissions checking for SQL commands is carried out as though the session_role were the one that had logged in originally.
103 type: str
104 target_roles:
105 description:
106 - A list of existing role (user/group) names to set as the
107 default permissions for database objects subsequently created by them.
108 - Parameter I(target_roles) is only available with C(type=default_privs).
109 type: str
110 grant_option:
111 description:
112 - Whether C(role) may grant/revoke the specified privileges/group memberships to others.
113 - Set to C(false) to revoke GRANT OPTION, leave unspecified to make no changes.
114 - I(grant_option) only has an effect if I(state) is C(present).
115 type: bool
116 aliases:
117 - admin_option
118 trust_input:
119 description:
120 - If C(false), check whether values of parameters I(roles), I(target_roles), I(session_role),
121 I(schema) are potentially dangerous.
122 - It makes sense to use C(false) only when SQL injections via the parameters are possible.
123 type: bool
124 default: true
125 version_added: '0.2.0'
126
127 notes:
128 - Parameters that accept comma separated lists (I(privs), I(objs), I(roles))
129 have singular alias names (I(priv), I(obj), I(role)).
130 - To revoke only C(GRANT OPTION) for a specific object, set I(state) to
131 C(present) and I(grant_option) to C(false) (see examples).
132 - Note that when revoking privileges from a role R, this role may still have
133 access via privileges granted to any role R is a member of including C(PUBLIC).
134 - Note that when revoking privileges from a role R, you do so as the user
135 specified via I(login_user). If R has been granted the same privileges by
136 another user also, R can still access database objects via these privileges.
137 - When revoking privileges, C(RESTRICT) is assumed (see PostgreSQL docs).
138
139 seealso:
140 - module: community.postgresql.postgresql_user
141 - module: community.postgresql.postgresql_owner
142 - module: community.postgresql.postgresql_membership
143 - name: PostgreSQL privileges
144 description: General information about PostgreSQL privileges.
145 link: https://www.postgresql.org/docs/current/ddl-priv.html
146 - name: PostgreSQL GRANT command reference
147 description: Complete reference of the PostgreSQL GRANT command documentation.
148 link: https://www.postgresql.org/docs/current/sql-grant.html
149 - name: PostgreSQL REVOKE command reference
150 description: Complete reference of the PostgreSQL REVOKE command documentation.
151 link: https://www.postgresql.org/docs/current/sql-revoke.html
152
153 attributes:
154 check_mode:
155 support: full
156
157 extends_documentation_fragment:
158 - community.postgresql.postgres
159
160 author:
161 - Bernhard Weitzhofer (@b6d)
162 - Tobias Birkefeld (@tcraxs)
163 - Daniele Giudice (@RealGreenDragon)
164 '''
165
166 EXAMPLES = r'''
167 # On database "library":
168 # GRANT SELECT, INSERT, UPDATE ON TABLE public.books, public.authors
169 # TO librarian, reader WITH GRANT OPTION
170 - name: Grant privs to librarian and reader on database library
171 community.postgresql.postgresql_privs:
172 login_db: library
173 state: present
174 privs: SELECT,INSERT,UPDATE
175 type: table
176 objs: books,authors
177 schema: public
178 roles: librarian,reader
179 grant_option: true
180
181 - name: Same as above leveraging default values
182 community.postgresql.postgresql_privs:
183 login_db: library
184 privs: SELECT,INSERT,UPDATE
185 objs: books,authors
186 roles: librarian,reader
187 grant_option: true
188
189 # REVOKE GRANT OPTION FOR INSERT ON TABLE books FROM reader
190 # Note that role "reader" will be *granted* INSERT privilege itself if this
191 # isn't already the case (since state: present).
192 - name: Revoke privs from reader
193 community.postgresql.postgresql_privs:
194 login_db: library
195 state: present
196 priv: INSERT
197 obj: books
198 role: reader
199 grant_option: false
200
201 # "public" is the default schema. This also works for PostgreSQL 8.x.
202 - name: REVOKE INSERT, UPDATE ON ALL TABLES IN SCHEMA public FROM reader
203 community.postgresql.postgresql_privs:
204 login_db: library
205 state: absent
206 privs: INSERT,UPDATE
207 objs: ALL_IN_SCHEMA
208 role: reader
209
210 - name: GRANT ALL PRIVILEGES ON SCHEMA public, math TO librarian
211 community.postgresql.postgresql_privs:
212 login_db: library
213 privs: ALL
214 type: schema
215 objs: public,math
216 role: librarian
217
218 # Note the separation of arguments with colons.
219 - name: GRANT ALL PRIVILEGES ON FUNCTION math.add(int, int) TO librarian, reader
220 community.postgresql.postgresql_privs:
221 login_db: library
222 privs: ALL
223 type: function
224 obj: add(int:int)
225 schema: math
226 roles: librarian,reader
227
228 # Note that group role memberships apply cluster-wide and therefore are not
229 # restricted to database "library" here.
230 - name: GRANT librarian, reader TO alice, bob WITH ADMIN OPTION
231 community.postgresql.postgresql_privs:
232 login_db: library
233 type: group
234 objs: librarian,reader
235 roles: alice,bob
236 admin_option: true
237
238 # Note that here "db: postgres" specifies the database to connect to, not the
239 # database to grant privileges on (which is specified via the "objs" param)
240 - name: GRANT ALL PRIVILEGES ON DATABASE library TO librarian
241 community.postgresql.postgresql_privs:
242 login_db: postgres
243 privs: ALL
244 type: database
245 obj: library
246 role: librarian
247
248 # If objs is omitted for type "database", it defaults to the database
249 # to which the connection is established
250 - name: GRANT ALL PRIVILEGES ON DATABASE library TO librarian
251 community.postgresql.postgresql_privs:
252 login_db: library
253 privs: ALL
254 type: database
255 role: librarian
256
257 # Available since version 2.7
258 # Objs must be set, ALL_DEFAULT to TABLES/SEQUENCES/TYPES/FUNCTIONS
259 # ALL_DEFAULT works only with privs=ALL
260 # For specific
261 - name: ALTER DEFAULT PRIVILEGES ON DATABASE library TO librarian
262 community.postgresql.postgresql_privs:
263 login_db: library
264 objs: ALL_DEFAULT
265 privs: ALL
266 type: default_privs
267 role: librarian
268 grant_option: true
269
270 # Available since version 2.7
271 # Objs must be set, ALL_DEFAULT to TABLES/SEQUENCES/TYPES/FUNCTIONS
272 # ALL_DEFAULT works only with privs=ALL
273 # For specific
274 - name: ALTER DEFAULT PRIVILEGES ON DATABASE library TO reader, step 1
275 community.postgresql.postgresql_privs:
276 login_db: library
277 objs: TABLES,SEQUENCES
278 privs: SELECT
279 type: default_privs
280 role: reader
281
282 - name: ALTER DEFAULT PRIVILEGES ON DATABASE library TO reader, step 2
283 community.postgresql.postgresql_privs:
284 login_db: library
285 objs: TYPES
286 privs: USAGE
287 type: default_privs
288 role: reader
289
290 # Available since version 2.8
291 - name: GRANT ALL PRIVILEGES ON FOREIGN DATA WRAPPER fdw TO reader
292 community.postgresql.postgresql_privs:
293 login_db: library
294 objs: fdw
295 privs: ALL
296 type: foreign_data_wrapper
297 role: reader
298
299 # Available since community.postgresql 0.2.0
300 - name: GRANT ALL PRIVILEGES ON TYPE customtype TO reader
301 community.postgresql.postgresql_privs:
302 login_db: library
303 objs: customtype
304 privs: ALL
305 type: type
306 role: reader
307
308 # Available since version 2.8
309 - name: GRANT ALL PRIVILEGES ON FOREIGN SERVER fdw_server TO reader
310 community.postgresql.postgresql_privs:
311 login_db: test
312 objs: fdw_server
313 privs: ALL
314 type: foreign_server
315 role: reader
316
317 # Available since version 2.8
318 # Grant 'execute' permissions on all functions in schema 'common' to role 'caller'
319 - name: GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA common TO caller
320 community.postgresql.postgresql_privs:
321 type: function
322 state: present
323 privs: EXECUTE
324 roles: caller
325 objs: ALL_IN_SCHEMA
326 schema: common
327
328 # Available since collection version 1.3.0
329 # Grant 'execute' permissions on all procedures in schema 'common' to role 'caller'
330 # Needs PostreSQL 11 or higher and community.postgresql 1.3.0 or higher
331 - name: GRANT EXECUTE ON ALL PROCEDURES IN SCHEMA common TO caller
332 community.postgresql.postgresql_privs:
333 type: procedure
334 state: present
335 privs: EXECUTE
336 roles: caller
337 objs: ALL_IN_SCHEMA
338 schema: common
339
340 # Available since version 2.8
341 # ALTER DEFAULT PRIVILEGES FOR ROLE librarian IN SCHEMA library GRANT SELECT ON TABLES TO reader
342 # GRANT SELECT privileges for new TABLES objects created by librarian as
343 # default to the role reader.
344 # For specific
345 - name: ALTER privs
346 community.postgresql.postgresql_privs:
347 login_db: library
348 schema: library
349 objs: TABLES
350 privs: SELECT
351 type: default_privs
352 role: reader
353 target_roles: librarian
354
355 # Available since version 2.8
356 # ALTER DEFAULT PRIVILEGES FOR ROLE librarian IN SCHEMA library REVOKE SELECT ON TABLES FROM reader
357 # REVOKE SELECT privileges for new TABLES objects created by librarian as
358 # default from the role reader.
359 # For specific
360 - name: ALTER privs
361 community.postgresql.postgresql_privs:
362 login_db: library
363 state: absent
364 schema: library
365 objs: TABLES
366 privs: SELECT
367 type: default_privs
368 role: reader
369 target_roles: librarian
370
371 # Available since community.postgresql 0.2.0
372 - name: Grant type privileges for pg_catalog.numeric type to alice
373 community.postgresql.postgresql_privs:
374 type: type
375 roles: alice
376 privs: ALL
377 objs: numeric
378 schema: pg_catalog
379 login_db: acme
380
381 - name: Alter default privileges grant usage on schemas to datascience
382 community.postgresql.postgresql_privs:
383 login_db: test
384 type: default_privs
385 privs: usage
386 objs: schemas
387 role: datascience
388
389 # Available since community.postgresql 3.1.0
390 # Needs PostgreSQL 15 or higher
391 - name: GRANT SET ON PARAMETER log_destination,log_line_prefix TO logtest
392 community.postgresql.postgresql_privs:
393 login_db: logtest
394 state: present
395 privs: SET
396 type: parameter
397 objs: log_destination,log_line_prefix
398 roles: logtest
399
400 - name: GRANT ALTER SYSTEM ON PARAMETER primary_conninfo,synchronous_standby_names TO replicamgr
401 community.postgresql.postgresql_privs:
402 login_db: replicamgr
403 state: present
404 privs: ALTER_SYSTEM
405 type: parameter
406 objs: primary_conninfo,synchronous_standby_names
407 roles: replicamgr
408 '''
409
410 RETURN = r'''
411 queries:
412 description: List of executed queries.
413 returned: success
414 type: list
415 sample: ['REVOKE GRANT OPTION FOR INSERT ON TABLE "books" FROM "reader";']
416 '''
417
418 import traceback
419
420 from ansible.module_utils.common.text.converters import to_native
421 # import module snippets
422 from ansible.module_utils.basic import AnsibleModule
423 from ansible_collections.community.postgresql.plugins.module_utils.database import (
424 check_input,
425 pg_quote_identifier,
426 )
427 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
428 HAS_PSYCOPG,
429 PSYCOPG_VERSION,
430 connect_to_db,
431 ensure_required_libs,
432 get_conn_params,
433 get_server_version,
434 pg_cursor_args,
435 postgres_common_argument_spec,
436 )
437 from ansible_collections.community.postgresql.plugins.module_utils.version import \
438 LooseVersion
439
440 if HAS_PSYCOPG and PSYCOPG_VERSION < LooseVersion("3.0"):
441 from psycopg2 import Error as PsycopgError
442 elif HAS_PSYCOPG:
443 from psycopg import Error as PsycopgError
444
445 VALID_PRIVS = frozenset(('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER', 'CREATE',
446 'CONNECT', 'TEMPORARY', 'TEMP', 'EXECUTE', 'USAGE', 'ALL', 'SET', 'ALTER_SYSTEM',
447 'MAINTAIN'))
448 VALID_DEFAULT_OBJS = {'TABLES': ('ALL', 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER', 'MAINTAIN'),
449 'SEQUENCES': ('ALL', 'SELECT', 'UPDATE', 'USAGE'),
450 'FUNCTIONS': ('ALL', 'EXECUTE'),
451 'TYPES': ('ALL', 'USAGE'),
452 'SCHEMAS': ('CREATE', 'USAGE'), }
453 VALID_IMPLICIT_ROLES = {'PUBLIC': 0,
454 'CURRENT_USER': 95000,
455 'SESSION_USER': 95000,
456 'CURRENT_ROLE': 140000, }
457
458 executed_queries = []
459
460
461 class Error(Exception):
462 pass
463
464
465 # We don't have functools.partial in Python < 2.5
466 def partial(f, *args, **kwargs):
467 """Partial function application"""
468
469 def g(*g_args, **g_kwargs):
470 new_kwargs = kwargs.copy()
471 new_kwargs.update(g_kwargs)
472 return f(*(args + g_args), **g_kwargs)
473
474 g.f = f
475 g.args = args
476 g.kwargs = kwargs
477 return g
478
479
480 class Connection(object):
481 """Wrapper around a psycopg connection with some convenience methods"""
482
483 def __init__(self, params, module):
484 self.database = params.login_db
485 self.module = module
486
487 # Ensure psycopg libraries are available before connecting to DB:
488 ensure_required_libs(module)
489 conn_params = get_conn_params(module, params.__dict__, warn_db_default=False)
490
491 self.connection, dummy = connect_to_db(module, conn_params, autocommit=False)
492 self.cursor = self.connection.cursor(**pg_cursor_args)
493 self.pg_version = get_server_version(self.connection)
494
495 # implicit roles in current pg version
496 self.pg_implicit_roles = tuple(
497 implicit_role for implicit_role, version_min in VALID_IMPLICIT_ROLES.items() if self.pg_version >= version_min
498 )
499
500 def execute(self, query, input_vars=None):
501 try:
502 self.cursor.execute(query, input_vars)
503 except Exception as e:
504 self.module.fail_json(msg="Cannot execute SQL '%s': %s" % (query, to_native(e)))
505
506 def commit(self):
507 self.connection.commit()
508
509 def rollback(self):
510 self.connection.rollback()
511
512 # Methods for implicit roles managements
513
514 def is_implicit_role(self, rolname):
515 return rolname.upper() in self.pg_implicit_roles
516
517 # Methods for querying database objects
518
519 def role_exists(self, rolname):
520 # check if rolname is a implicit role
521 if self.is_implicit_role(rolname):
522 return True
523
524 # check if rolname is present in pg_catalog.pg_roles
525 query = "SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = %s"
526 self.execute(query, (rolname,))
527 return self.cursor.rowcount > 0
528
529 # PostgreSQL < 9.0 doesn't support "ALL TABLES IN SCHEMA schema"-like
530 # phrases in GRANT or REVOKE statements, therefore alternative methods are
531 # provided here.
532
533 def schema_exists(self, schema):
534 query = """SELECT count(*) c
535 FROM pg_catalog.pg_namespace WHERE nspname = %s"""
536 self.execute(query, (schema,))
537 return self.cursor.fetchone()["c"] > 0
538
539 def get_all_tables_in_schema(self, schema):
540 if schema:
541 if not self.schema_exists(schema):
542 raise Error('Schema "%s" does not exist.' % schema)
543
544 query = """SELECT relname
545 FROM pg_catalog.pg_class c
546 JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
547 WHERE nspname = %s AND relkind in ('r', 'v', 'm', 'p', 'f')"""
548 self.execute(query, (schema,))
549 else:
550 query = ("SELECT relname FROM pg_catalog.pg_class "
551 "WHERE relkind in ('r', 'v', 'm', 'p', 'f')")
552 self.execute(query)
553 return [t["relname"] for t in self.cursor.fetchall()]
554
555 def get_all_sequences_in_schema(self, schema):
556 if schema:
557 if not self.schema_exists(schema):
558 raise Error('Schema "%s" does not exist.' % schema)
559 query = """SELECT relname
560 FROM pg_catalog.pg_class c
561 JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
562 WHERE nspname = %s AND relkind = 'S'"""
563 self.execute(query, (schema,))
564 else:
565 self.execute("SELECT relname FROM pg_catalog.pg_class WHERE relkind = 'S'")
566 return [t["relname"] for t in self.cursor.fetchall()]
567
568 def get_all_functions_in_schema(self, schema):
569 if schema:
570 if not self.schema_exists(schema):
571 raise Error('Schema "%s" does not exist.' % schema)
572
573 query = ("SELECT p.proname, oidvectortypes(p.proargtypes) ptypes "
574 "FROM pg_catalog.pg_proc p "
575 "JOIN pg_namespace n ON n.oid = p.pronamespace "
576 "WHERE nspname = %s")
577
578 if self.pg_version >= 110000:
579 query += " and p.prokind = 'f'"
580
581 self.execute(query, (schema,))
582 else:
583 self.execute("SELECT p.proname, oidvectortypes(p.proargtypes) ptypes FROM pg_catalog.pg_proc p")
584 return ["%s(%s)" % (t["proname"], t["ptypes"]) for t in self.cursor.fetchall()]
585
586 def get_all_procedures_in_schema(self, schema):
587 if self.pg_version < 110000:
588 raise Error("PostgreSQL version must be >= 11 for type=procedure. Exit")
589
590 if schema:
591 if not self.schema_exists(schema):
592 raise Error('Schema "%s" does not exist.' % schema)
593
594 query = ("SELECT p.proname, oidvectortypes(p.proargtypes) ptypes "
595 "FROM pg_catalog.pg_proc p "
596 "JOIN pg_namespace n ON n.oid = p.pronamespace "
597 "WHERE nspname = %s and p.prokind = 'p'")
598
599 self.execute(query, (schema,))
600 else:
601 query = ("SELECT p.proname, oidvectortypes(p.proargtypes) ptypes "
602 "FROM pg_catalog.pg_proc p WHERE p.prokind = 'p'")
603 self.execute(query)
604 return ["%s(%s)" % (t["proname"], t["ptypes"]) for t in self.cursor.fetchall()]
605
606 # Methods for getting access control lists and group membership info
607
608 # To determine whether anything has changed after granting/revoking
609 # privileges, we compare the access control lists of the specified database
610 # objects before and afterwards. Python's list/string comparison should
611 # suffice for change detection, we should not actually have to parse ACLs.
612 # The same should apply to group membership information.
613
614 def get_table_acls(self, schema, tables):
615 if schema:
616 query = """SELECT relacl::text
617 FROM pg_catalog.pg_class c
618 JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
619 WHERE nspname = %s AND relkind in ('r','p','v','m','f') AND relname = ANY (%s)
620 ORDER BY relname"""
621 self.execute(query, (schema, tables))
622 else:
623 query = ("SELECT relacl::text FROM pg_catalog.pg_class "
624 "WHERE relkind in ('r','p','v','m','f') AND relname = ANY (%s) "
625 "ORDER BY relname")
626 self.execute(query)
627 return [t["relacl"] for t in self.cursor.fetchall()]
628
629 def get_sequence_acls(self, schema, sequences):
630 if schema:
631 query = """SELECT relacl::text
632 FROM pg_catalog.pg_class c
633 JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
634 WHERE nspname = %s AND relkind = 'S' AND relname = ANY (%s)
635 ORDER BY relname"""
636 self.execute(query, (schema, sequences))
637 else:
638 query = ("SELECT relacl::text FROM pg_catalog.pg_class "
639 "WHERE relkind = 'S' AND relname = ANY (%s) ORDER BY relname")
640 self.execute(query)
641 return [t["relacl"] for t in self.cursor.fetchall()]
642
643 def get_function_acls(self, schema, function_signatures):
644 funcnames = [f.split('(', 1)[0] for f in function_signatures]
645 if schema:
646 query = """SELECT proacl::text
647 FROM pg_catalog.pg_proc p
648 JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
649 WHERE nspname = %s AND proname = ANY (%s)
650 ORDER BY proname, proargtypes"""
651 self.execute(query, (schema, funcnames))
652 else:
653 query = ("SELECT proacl::text FROM pg_catalog.pg_proc WHERE proname = ANY (%s) "
654 "ORDER BY proname, proargtypes")
655 self.execute(query, (funcnames))
656 return [t["proacl"] for t in self.cursor.fetchall()]
657
658 def get_schema_acls(self, schemas):
659 query = """SELECT nspacl::text FROM pg_catalog.pg_namespace
660 WHERE nspname = ANY (%s) ORDER BY nspname"""
661 self.execute(query, (schemas,))
662 return [t["nspacl"] for t in self.cursor.fetchall()]
663
664 def get_language_acls(self, languages):
665 query = """SELECT lanacl::text FROM pg_catalog.pg_language
666 WHERE lanname = ANY (%s) ORDER BY lanname"""
667 self.execute(query, (languages,))
668 return [t["lanacl"] for t in self.cursor.fetchall()]
669
670 def get_tablespace_acls(self, tablespaces):
671 query = """SELECT spcacl::text FROM pg_catalog.pg_tablespace
672 WHERE spcname = ANY (%s) ORDER BY spcname"""
673 self.execute(query, (tablespaces,))
674 return [t["spcacl"] for t in self.cursor.fetchall()]
675
676 def get_database_acls(self, databases):
677 query = """SELECT datacl::text FROM pg_catalog.pg_database
678 WHERE datname = ANY (%s) ORDER BY datname"""
679 self.execute(query, (databases,))
680 return [t["datacl"] for t in self.cursor.fetchall()]
681
682 def get_group_memberships(self, groups):
683 query = """SELECT roleid, grantor, member, admin_option
684 FROM pg_catalog.pg_auth_members am
685 JOIN pg_catalog.pg_roles r ON r.oid = am.roleid
686 WHERE r.rolname = ANY(%s)
687 ORDER BY roleid, grantor, member"""
688 self.execute(query, (groups,))
689 return self.cursor.fetchall()
690
691 def get_default_privs(self, schema, *args):
692 if schema:
693 query = """SELECT defaclacl::text
694 FROM pg_default_acl a
695 JOIN pg_namespace b ON a.defaclnamespace=b.oid
696 WHERE b.nspname = %s;"""
697 self.execute(query, (schema,))
698 else:
699 self.execute("SELECT defaclacl::text FROM pg_default_acl;")
700 return [t["defaclacl"] for t in self.cursor.fetchall()]
701
702 def get_foreign_data_wrapper_acls(self, fdws):
703 query = """SELECT fdwacl::text FROM pg_catalog.pg_foreign_data_wrapper
704 WHERE fdwname = ANY (%s) ORDER BY fdwname"""
705 self.execute(query, (fdws,))
706 return [t["fdwacl"] for t in self.cursor.fetchall()]
707
708 def get_foreign_server_acls(self, fs):
709 query = """SELECT srvacl::text FROM pg_catalog.pg_foreign_server
710 WHERE srvname = ANY (%s) ORDER BY srvname"""
711 self.execute(query, (fs,))
712 return [t["srvacl"] for t in self.cursor.fetchall()]
713
714 def get_type_acls(self, schema, types):
715 if schema:
716 query = """SELECT t.typacl::text FROM pg_catalog.pg_type t
717 JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
718 WHERE n.nspname = %s AND t.typname = ANY (%s) ORDER BY typname"""
719 self.execute(query, (schema, types))
720 else:
721 query = "SELECT typacl::text FROM pg_catalog.pg_type WHERE typname = ANY (%s) ORDER BY typname"
722 self.execute(query)
723 return [t["typacl"] for t in self.cursor.fetchall()]
724
725 def get_parameter_acls(self, parameters):
726 if self.pg_version < 150000:
727 raise Error("PostgreSQL version must be >= 15 for type=parameter. Exit")
728
729 query = """SELECT paracl::text FROM pg_catalog.pg_parameter_acl
730 WHERE parname = ANY (%s) ORDER BY parname"""
731 self.cursor.execute(query, (parameters,))
732 return [t["paracl"] for t in self.cursor.fetchall()]
733
734 # Manipulating privileges
735
736 def manipulate_privs(self, obj_type, privs, objs, orig_objs, roles, target_roles,
737 state, grant_option, schema_qualifier=None, fail_on_role=True):
738 """Manipulate database object privileges.
739
740 :param obj_type: Type of database object to grant/revoke
741 privileges for.
742 :param privs: Either a list of privileges to grant/revoke
743 or None if type is "group".
744 :param objs: List of database objects to grant/revoke
745 privileges for.
746 :param orig_objs: ALL_IN_SCHEMA or None.
747 :param roles: List of role names.
748 :param target_roles: List of role names to grant/revoke
749 default privileges as.
750 :param state: "present" to grant privileges, "absent" to revoke.
751 :param grant_option: Only for state "present": If True, set
752 grant/admin option. If False, revoke it.
753 If None, don't change grant option.
754 :param schema_qualifier: Some object types ("TABLE", "SEQUENCE",
755 "FUNCTION") must be qualified by schema.
756 Ignored for other Types.
757 """
758 # get_status: function to get current status
759 if obj_type == 'table':
760 get_status = partial(self.get_table_acls, schema_qualifier)
761 elif obj_type == 'sequence':
762 get_status = partial(self.get_sequence_acls, schema_qualifier)
763 elif obj_type in ('function', 'procedure'):
764 get_status = partial(self.get_function_acls, schema_qualifier)
765 elif obj_type == 'schema':
766 get_status = self.get_schema_acls
767 elif obj_type == 'language':
768 get_status = self.get_language_acls
769 elif obj_type == 'tablespace':
770 get_status = self.get_tablespace_acls
771 elif obj_type == 'database':
772 get_status = self.get_database_acls
773 elif obj_type == 'group':
774 get_status = self.get_group_memberships
775 elif obj_type == 'default_privs':
776 get_status = partial(self.get_default_privs, schema_qualifier)
777 elif obj_type == 'foreign_data_wrapper':
778 get_status = self.get_foreign_data_wrapper_acls
779 elif obj_type == 'foreign_server':
780 get_status = self.get_foreign_server_acls
781 elif obj_type == 'type':
782 get_status = partial(self.get_type_acls, schema_qualifier)
783 elif obj_type == 'parameter':
784 get_status = self.get_parameter_acls
785 else:
786 raise Error('Unsupported database object type "%s".' % obj_type)
787
788 # Return False (nothing has changed) if there are no objs to work on.
789 if not objs:
790 return False
791
792 quoted_schema_qualifier = '"%s"' % schema_qualifier.replace('"', '""') if schema_qualifier else None
793 # obj_ids: quoted db object identifiers (sometimes schema-qualified)
794 if obj_type in ('function', 'procedure'):
795 obj_ids = []
796 for obj in objs:
797 try:
798 f, args = obj.split('(', 1)
799 except Exception:
800 raise Error('Illegal function / procedure signature: "%s".' % obj)
801 obj_ids.append('%s."%s"(%s' % (quoted_schema_qualifier, f, args))
802 elif obj_type in ['table', 'sequence', 'type']:
803 obj_ids = ['%s."%s"' % (quoted_schema_qualifier, o) for o in objs]
804 else:
805 obj_ids = ['"%s"' % o for o in objs]
806
807 # set_what: SQL-fragment specifying what to set for the target roles:
808 # Either group membership or privileges on objects of a certain type
809 if obj_type == 'group':
810 set_what = ','.join(obj_ids)
811 elif obj_type == 'default_privs':
812 # We don't want privs to be quoted here
813 set_what = ','.join(privs)
814 else:
815 # function types are already quoted above
816 if obj_type not in ('function', 'procedure'):
817 obj_ids = [pg_quote_identifier(i, 'table') for i in obj_ids]
818 # Note: obj_type has been checked against a set of string literals
819 # and privs was escaped when it was parsed
820 # Note: Underscores are replaced with spaces to support multi-word privs and obj_type
821 if orig_objs is not None:
822 set_what = '%s ON %s %s' % (','.join(privs).replace('_', ' '), orig_objs, quoted_schema_qualifier)
823 else:
824 set_what = '%s ON %s %s' % (','.join(privs).replace('_', ' '), obj_type.replace('_', ' '), ','.join(obj_ids))
825
826 # for_whom: SQL-fragment specifying for whom to set the above
827 if not roles:
828 return False
829 for_whom = ','.join(roles)
830
831 # as_who: SQL-fragment specifying to who to set the above
832 as_who = None
833 if target_roles:
834 as_who = ','.join('"%s"' % r for r in target_roles)
835
836 status_before = get_status(objs)
837
838 query = QueryBuilder(state) \
839 .for_objtype(obj_type) \
840 .with_grant_option(grant_option) \
841 .for_whom(for_whom) \
842 .as_who(as_who) \
843 .for_schema(quoted_schema_qualifier) \
844 .set_what(set_what) \
845 .for_objs(objs) \
846 .build()
847
848 executed_queries.append(query)
849 self.execute(query)
850
851 status_after = get_status(objs)
852
853 def nonesorted(e):
854 # For python 3+ that can fail trying
855 # to compare NoneType elements by sort method.
856 if e is None:
857 return ''
858 # With Psycopg 3 we get a list of dicts, it is easier to sort it as strings
859 return str(e)
860
861 status_before.sort(key=nonesorted)
862 status_after.sort(key=nonesorted)
863 return status_before != status_after
864
865
866 class QueryBuilder(object):
867 def __init__(self, state):
868 self._grant_option = None
869 self._for_whom = None
870 self._as_who = None
871 self._set_what = None
872 self._obj_type = None
873 self._state = state
874 self._schema = None
875 self._objs = None
876 self.query = []
877
878 def for_objs(self, objs):
879 self._objs = objs
880 return self
881
882 def for_schema(self, schema):
883 self._schema = ' IN SCHEMA %s' % schema if schema is not None else ''
884 return self
885
886 def with_grant_option(self, option):
887 self._grant_option = option
888 return self
889
890 def for_whom(self, who):
891 self._for_whom = who
892 return self
893
894 def as_who(self, target_roles):
895 self._as_who = target_roles
896 return self
897
898 def set_what(self, what):
899 self._set_what = what
900 return self
901
902 def for_objtype(self, objtype):
903 self._obj_type = objtype
904 return self
905
906 def build(self):
907 if self._state == 'present':
908 self.build_present()
909 elif self._state == 'absent':
910 self.build_absent()
911 else:
912 self.build_absent()
913 return '\n'.join(self.query)
914
915 def add_default_revoke(self):
916 for obj in self._objs:
917 if self._as_who:
918 self.query.append(
919 'ALTER DEFAULT PRIVILEGES FOR ROLE {0}{1} REVOKE ALL ON {2} FROM {3};'.format(self._as_who,
920 self._schema, obj,
921 self._for_whom))
922 else:
923 self.query.append(
924 'ALTER DEFAULT PRIVILEGES{0} REVOKE ALL ON {1} FROM {2};'.format(self._schema, obj,
925 self._for_whom))
926
927 def add_grant_option(self):
928 if self._grant_option:
929 if self._obj_type == 'group':
930 self.query[-1] += ' WITH ADMIN OPTION;'
931 else:
932 self.query[-1] += ' WITH GRANT OPTION;'
933 elif self._grant_option is False:
934 self.query[-1] += ';'
935 if self._obj_type == 'group':
936 self.query.append('REVOKE ADMIN OPTION FOR {0} FROM {1};'.format(self._set_what, self._for_whom))
937 elif not self._obj_type == 'default_privs':
938 self.query.append('REVOKE GRANT OPTION FOR {0} FROM {1};'.format(self._set_what, self._for_whom))
939 else:
940 self.query[-1] += ';'
941
942 def add_default_priv(self):
943 for obj in self._objs:
944 if self._as_who:
945 self.query.append(
946 'ALTER DEFAULT PRIVILEGES FOR ROLE {0}{1} GRANT {2} ON {3} TO {4}'.format(self._as_who,
947 self._schema,
948 self._set_what,
949 obj,
950 self._for_whom))
951 else:
952 self.query.append(
953 'ALTER DEFAULT PRIVILEGES{0} GRANT {1} ON {2} TO {3}'.format(self._schema,
954 self._set_what,
955 obj,
956 self._for_whom))
957 self.add_grant_option()
958
959 def build_present(self):
960 if self._obj_type == 'default_privs':
961 self.add_default_revoke()
962 self.add_default_priv()
963 else:
964 self.query.append('GRANT {0} TO {1}'.format(self._set_what, self._for_whom))
965 self.add_grant_option()
966
967 def build_absent(self):
968 if self._obj_type == 'default_privs':
969 self.query = []
970 for obj in ['TABLES', 'FUNCTIONS', 'SEQUENCES', 'TYPES']:
971 if self._as_who:
972 self.query.append(
973 'ALTER DEFAULT PRIVILEGES FOR ROLE {0}{1} REVOKE ALL ON {2} FROM {3};'.format(self._as_who,
974 self._schema, obj,
975 self._for_whom))
976 else:
977 self.query.append(
978 'ALTER DEFAULT PRIVILEGES{0} REVOKE ALL ON {1} FROM {2};'.format(self._schema, obj,
979 self._for_whom))
980 else:
981 self.query.append('REVOKE {0} FROM {1};'.format(self._set_what, self._for_whom))
982
983
984 def main():
985 argument_spec = postgres_common_argument_spec()
986 argument_spec.update(
987 login_db=dict(type='str', required=True, aliases=['db', 'database'], deprecated_aliases=[
988 {
989 'name': 'db',
990 'version': '5.0.0',
991 'collection_name': 'community.postgresql',
992 },
993 {
994 'name': 'database',
995 'version': '5.0.0',
996 'collection_name': 'community.postgresql',
997 }],
998 ),
999 state=dict(default='present', choices=['present', 'absent']),
1000 privs=dict(required=False, aliases=['priv']),
1001 type=dict(default='table',
1002 choices=['table',
1003 'sequence',
1004 'function',
1005 'procedure',
1006 'database',
1007 'schema',
1008 'language',
1009 'tablespace',
1010 'group',
1011 'default_privs',
1012 'foreign_data_wrapper',
1013 'foreign_server',
1014 'type',
1015 'parameter', ]),
1016 objs=dict(required=False, aliases=['obj']),
1017 schema=dict(required=False),
1018 roles=dict(required=True, aliases=['role']),
1019 session_role=dict(required=False),
1020 target_roles=dict(required=False),
1021 grant_option=dict(required=False, type='bool',
1022 aliases=['admin_option']),
1023 fail_on_role=dict(type='bool', default=True),
1024 trust_input=dict(type='bool', default=True),
1025 )
1026
1027 module = AnsibleModule(
1028 argument_spec=argument_spec,
1029 supports_check_mode=True,
1030 )
1031
1032 fail_on_role = module.params['fail_on_role']
1033
1034 # Create type object as namespace for module params
1035 p = type('Params', (), module.params)
1036
1037 # param "schema": default, allowed depends on param "type"
1038 if p.type in ['table', 'sequence', 'function', 'procedure', 'type', 'default_privs']:
1039 if p.objs == 'schemas' or p.schema == 'not-specified':
1040 p.schema = None
1041 else:
1042 p.schema = p.schema or 'public'
1043 elif p.schema:
1044 module.fail_json(msg='Argument "schema" is not allowed '
1045 'for type "%s".' % p.type)
1046
1047 # param "objs": ALL_IN_SCHEMA can be used only
1048 # when param "type" is table, sequence, function or procedure
1049 if p.objs == 'ALL_IN_SCHEMA' and p.type not in ('table', 'sequence', 'function', 'procedure'):
1050 module.fail_json(msg='Argument "objs": ALL_IN_SCHEMA can be used only for '
1051 'type: table, sequence, function or procedure, '
1052 '%s was passed.' % p.type)
1053
1054 # param "objs": default, required depends on param "type"
1055 if p.type == 'database':
1056 p.objs = p.objs or p.login_db
1057 elif not p.objs:
1058 module.fail_json(msg='Argument "objs" is required '
1059 'for type "%s".' % p.type)
1060
1061 # param "privs": allowed, required depends on param "type"
1062 if p.type == 'group':
1063 if p.privs:
1064 module.fail_json(msg='Argument "privs" is not allowed '
1065 'for type "group".')
1066 elif not p.privs:
1067 module.fail_json(msg='Argument "privs" is required '
1068 'for type "%s".' % p.type)
1069
1070 # Check input
1071 if not p.trust_input:
1072 # Check input for potentially dangerous elements:
1073 check_input(module, p.roles, p.target_roles, p.session_role, p.schema)
1074
1075 # Connect to Database
1076 conn = Connection(p, module)
1077
1078 if p.session_role:
1079 try:
1080 conn.cursor.execute('SET ROLE "%s"' % p.session_role)
1081 except Exception as e:
1082 module.fail_json(msg="Could not switch to role %s: %s" % (p.session_role, to_native(e)), exception=traceback.format_exc())
1083
1084 try:
1085 # privs
1086 if p.privs:
1087 privs = frozenset(pr.upper() for pr in p.privs.split(','))
1088 if not privs.issubset(VALID_PRIVS):
1089 module.fail_json(msg='Invalid privileges specified: %s' % privs.difference(VALID_PRIVS))
1090 else:
1091 privs = None
1092 # objs:
1093 orig_objs = None
1094 if p.objs == 'ALL_IN_SCHEMA':
1095 if p.type == 'table':
1096 objs = conn.get_all_tables_in_schema(p.schema)
1097 elif p.type == 'sequence':
1098 objs = conn.get_all_sequences_in_schema(p.schema)
1099 elif p.type == 'function':
1100 objs = conn.get_all_functions_in_schema(p.schema)
1101 elif p.type == 'procedure':
1102 objs = conn.get_all_procedures_in_schema(p.schema)
1103
1104 if conn.pg_version >= 90000:
1105 if p.type == 'table':
1106 orig_objs = 'ALL TABLES IN SCHEMA'
1107 elif p.type == 'sequence':
1108 orig_objs = 'ALL SEQUENCES IN SCHEMA'
1109 elif p.type == 'function':
1110 orig_objs = 'ALL FUNCTIONS IN SCHEMA'
1111 elif p.type == 'procedure':
1112 orig_objs = 'ALL PROCEDURES IN SCHEMA'
1113
1114 elif p.type == 'default_privs':
1115 if p.objs == 'ALL_DEFAULT':
1116 VALID_DEFAULT_OBJS.pop('SCHEMAS')
1117 objs = frozenset(VALID_DEFAULT_OBJS.keys())
1118 else:
1119 objs = frozenset(obj.upper() for obj in p.objs.split(','))
1120 if not objs.issubset(VALID_DEFAULT_OBJS):
1121 module.fail_json(
1122 msg='Invalid Object set specified: %s' % objs.difference(VALID_DEFAULT_OBJS.keys()))
1123 # Again, do we have valid privs specified for object type:
1124 valid_objects_for_priv = frozenset(obj for obj in objs if privs.issubset(VALID_DEFAULT_OBJS[obj]))
1125 if not valid_objects_for_priv == objs:
1126 module.fail_json(
1127 msg='Invalid priv specified. Valid object for priv: {0}. Objects: {1}'.format(
1128 valid_objects_for_priv, objs))
1129 else:
1130 objs = p.objs.split(',')
1131
1132 # function signatures are encoded using ':' to separate args
1133 if p.type in ('function', 'procedure'):
1134 objs = [obj.replace(':', ',') for obj in objs]
1135
1136 # roles
1137 roles = []
1138 roles_raw = p.roles.split(',')
1139 for r in roles_raw:
1140 if conn.role_exists(r):
1141 if conn.is_implicit_role(r):
1142 # Some implicit roles (as PUBLIC) works in uppercase without double quotes and in lowercase with double quotes.
1143 # Other implicit roles (as SESSION_USER) works only in uppercase without double quotes.
1144 # So the approach that works for all implicit roles is uppercase without double quotes.
1145 roles.append('%s' % r.upper())
1146 else:
1147 roles.append('"%s"' % r.replace('"', '""'))
1148 else:
1149 if fail_on_role:
1150 module.fail_json(msg="Role '%s' does not exist" % r)
1151 else:
1152 module.warn("Role '%s' does not exist, pass it" % r)
1153 if not roles:
1154 module.warn("No valid roles provided, nothing to do")
1155 module.exit_json(changed=False, queries=executed_queries)
1156
1157 # check if target_roles is set with type: default_privs
1158 if p.target_roles and not p.type == 'default_privs':
1159 module.warn('"target_roles" will be ignored '
1160 'Argument "type: default_privs" is required for usage of "target_roles".')
1161
1162 # target roles
1163 if p.target_roles:
1164 target_roles = p.target_roles.split(',')
1165 else:
1166 target_roles = None
1167
1168 changed = conn.manipulate_privs(
1169 obj_type=p.type,
1170 privs=privs,
1171 objs=objs,
1172 orig_objs=orig_objs,
1173 roles=roles,
1174 target_roles=target_roles,
1175 state=p.state,
1176 grant_option=p.grant_option,
1177 schema_qualifier=p.schema,
1178 fail_on_role=fail_on_role,
1179 )
1180
1181 except Error as e:
1182 conn.rollback()
1183 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
1184
1185 except PsycopgError as e:
1186 conn.rollback()
1187 module.fail_json(msg=to_native(e))
1188
1189 if module.check_mode or not changed:
1190 conn.rollback()
1191 else:
1192 conn.commit()
1193
1194 conn.cursor.close()
1195 conn.connection.close()
1196
1197 module.exit_json(changed=changed, queries=executed_queries)
1198
1199
1200 if __name__ == '__main__':
1201 main()