Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: postgresql_user
14 short_description: Create, alter, or remove a user (role) from a PostgreSQL server instance
15 description:
16 - Creates, alters, or removes a user (role) from a PostgreSQL server instance
17 ("cluster" in PostgreSQL terminology) and, optionally,
18 grants the user access to an existing database or tables.
19 - A user is a role with login privilege.
20 - You cannot remove a user while it still has any privileges granted to it in any database.
21 - Set I(fail_on_user) to C(false) to make the module ignore failures when trying to remove a user.
22 In this case, the module reports if changes happened as usual and separately reports
23 whether the user has been removed or not.
24 options:
25 name:
26 description:
27 - Name of the user (role) to add or remove.
28 type: str
29 required: true
30 aliases:
31 - user
32 password:
33 description:
34 - Set the user's password, before 1.4 this was required.
35 - Password can be passed unhashed or hashed (MD5-hashed).
36 - An unhashed password is automatically hashed when saved into the
37 database if I(encrypted) is set, otherwise it is saved in
38 plain text format.
39 - When passing an MD5-hashed password, you must generate it with the format
40 C('str["md5"] + md5[ password + username ]'), resulting in a total of
41 35 characters. An easy way to do this is
42 C(echo "md5`echo -n 'verysecretpasswordJOE' | md5sum | awk '{print $1}'`").
43 - Note that if the provided password string is already in MD5-hashed
44 format, then it is used as-is, regardless of I(encrypted) option.
45 type: str
46 login_db:
47 description:
48 - Name of database to connect to and where user's permissions are granted.
49 - The V(db) alias is deprecated and will be removed in version 5.0.0.
50 type: str
51 default: ''
52 aliases:
53 - db
54 fail_on_user:
55 description:
56 - If C(true), fails when the user (role) cannot be removed. Otherwise just log and continue.
57 default: true
58 type: bool
59 aliases:
60 - fail_on_role
61 role_attr_flags:
62 description:
63 - "PostgreSQL user attributes string in the format: CREATEDB,CREATEROLE,SUPERUSER."
64 - Note that '[NO]CREATEUSER' is deprecated.
65 - To create a simple role for using it like a group, use C(NOLOGIN) flag.
66 - See the full list of supported flags in documentation for your PostgreSQL version.
67 type: str
68 default: ''
69 session_role:
70 description:
71 - Switch to session role after connecting.
72 - The specified session role must be a role that the current login_user is a member of.
73 - Permissions checking for SQL commands is carried out as though the session role
74 were the one that had logged in originally.
75 type: str
76 state:
77 description:
78 - The user (role) state.
79 type: str
80 default: present
81 choices: [ absent, present ]
82 encrypted:
83 description:
84 - Whether the password is stored hashed in the database.
85 - You can specify an unhashed password, and PostgreSQL ensures
86 the stored password is hashed when I(encrypted=true) is set.
87 If you specify a hashed password, the module uses it as-is,
88 regardless of the setting of I(encrypted).
89 - "Note: Postgresql 10 and newer does not support unhashed passwords."
90 - Previous to Ansible 2.6, this was C(false) by default.
91 default: true
92 type: bool
93 expires:
94 description:
95 - The date at which the user's password is to expire.
96 - If set to C('infinity'), user's password never expires.
97 - Note that this value must be a valid SQL date and time type.
98 type: str
99 no_password_changes:
100 description:
101 - If C(true), does not inspect the database for password changes.
102 If the user already exists, skips all password related checks.
103 Useful when C(pg_authid) is not accessible (such as in AWS RDS).
104 Otherwise, makes password changes as necessary.
105 default: false
106 type: bool
107 conn_limit:
108 description:
109 - Specifies the user (role) connection limit.
110 type: int
111 ssl_mode:
112 description:
113 - Determines how an SSL session is negotiated with the server.
114 - See U(https://www.postgresql.org/docs/current/static/libpq-ssl.html) for more information on the modes.
115 - Default of C(prefer) matches libpq default.
116 type: str
117 default: prefer
118 choices: [ allow, disable, prefer, require, verify-ca, verify-full ]
119 ca_cert:
120 description:
121 - Specifies the name of a file containing SSL certificate authority (CA) certificate(s).
122 - If the file exists, verifies that the server's certificate is signed by one of these authorities.
123 type: str
124 aliases: [ ssl_rootcert ]
125 comment:
126 description:
127 - Adds a comment on the user (equivalent to the C(COMMENT ON ROLE) statement).
128 - To reset the comment, pass an empty string.
129 type: str
130 version_added: '0.2.0'
131 trust_input:
132 description:
133 - If C(false), checks whether values of options I(name), I(password), I(expires),
134 I(role_attr_flags), I(comment), I(session_role) are potentially dangerous.
135 - It makes sense to use C(false) only when SQL injections through the options are possible.
136 type: bool
137 default: true
138 version_added: '0.2.0'
139 configuration:
140 description:
141 - Role-specific configuration parameters that would otherwise be set by C(ALTER ROLE user SET variable TO value;).
142 - Takes a dict where the key is the name of the configuration parameter. If the key includes special characters
143 like C(.) and C(-), it needs to be quoted to ensure the YAML is valid.
144 - Sets or updates any parameter in the list that is not present or has the wrong value in the database.
145 - Removes any parameter from the user that is not listed here.
146 - Parameters that are present in the database but are not included in this list will only be reset, if
147 O(reset_unspecified_configuration=true).
148 - Inputs to O(user) as well as keys and values in this parameter are quoted by the module. If you require the
149 user to contain a C("), you need to double it, otherwise the module will fail. C(") and C(') are not allowed in
150 configuration keys and any C(') in the value of a configuration will be escaped by this module.
151 Additionally, parameters and values are checked if O(trust_input) is C(false).
152 type: dict
153 default: {}
154 version_added: '3.5.0'
155 reset_unspecified_configuration:
156 description:
157 - If set to C(true), the user's default configuration parameters will be reset in case they are not included in
158 O(configuration), otherwise existing parameters will not be modified if not included in O(configuration).
159 type: bool
160 default: false
161 version_added: '3.5.0'
162 quote_configuration_values:
163 description:
164 - Automatically quote the values of configuration variables added via I(configuration). The default is C(true)
165 and setting this to C(false) leaves these options open to SQL-injections and makes the user responsible for
166 properly quoting values.
167 - This is required to be C(false) to modify settings like C(search_path), that need to be unquoted.
168 - If this is C(false) you will also need to make sure that strings are properly quoted.
169 For example C("'16MB'") for C(work_mem).
170 - Set this only to C(false) if you know what you are doing!
171 type: bool
172 default: true
173 version_added: '3.11.0'
174 notes:
175 - The module creates a user (role) with login privilege by default.
176 Use C(NOLOGIN) I(role_attr_flags) to change this behaviour.
177 - If you specify C(PUBLIC) as the user (role), then the privilege changes apply to all users (roles).
178 You may not specify password or role_attr_flags when the C(PUBLIC) user is specified.
179 - SCRAM-SHA-256-hashed passwords (SASL Authentication) require PostgreSQL version 10 or newer.
180 On the previous versions the whole hashed string is used as a password.
181 - 'Working with SCRAM-SHA-256-hashed passwords, be sure you use the I(environment:) variable
182 C(PGOPTIONS: "-c password_encryption=scram-sha-256") when it is not default
183 for your PostgreSQL version (see the provided example).'
184 - On some systems (such as AWS RDS), C(pg_authid) is not accessible, thus, the module cannot compare
185 the current and desired C(password). In this case, the module assumes that the passwords are
186 different and changes it reporting that the state has been changed.
187 To skip all password related checks for existing users, use I(no_password_changes=true).
188 - On some systems (such as AWS RDS), C(SUPERUSER) is unavailable. This means the C(SUPERUSER) and
189 C(NOSUPERUSER) I(role_attr_flags) should not be specified to preserve idempotency and avoid
190 InsufficientPrivilege errors.
191
192 attributes:
193 check_mode:
194 support: full
195
196 seealso:
197 - module: community.postgresql.postgresql_privs
198 - module: community.postgresql.postgresql_membership
199 - module: community.postgresql.postgresql_owner
200 - name: PostgreSQL database roles
201 description: Complete reference of the PostgreSQL database roles documentation.
202 link: https://www.postgresql.org/docs/current/user-manag.html
203 - name: PostgreSQL SASL Authentication
204 description: Complete reference of the PostgreSQL SASL Authentication.
205 link: https://www.postgresql.org/docs/current/sasl-authentication.html
206 author:
207 - Ansible Core Team
208 extends_documentation_fragment:
209 - community.postgresql.postgres
210 '''
211
212 EXAMPLES = r'''
213 - name: Connect to acme database, create django user
214 community.postgresql.postgresql_user:
215 login_db: acme
216 name: django
217 password: ceec4eif7ya
218 expires: "Jan 31 2020"
219
220 - name: Add a comment on django user
221 community.postgresql.postgresql_user:
222 login_db: acme
223 name: django
224 comment: This is a test user
225
226 # Connect to default database, create rails user, set its password (MD5- or SHA256-hashed),
227 # and set flags to allow the user to create databases
228 # and demote rails from super user status if user exists
229 # the hash from the corresponding pg_authid entry.
230 - name: Create rails user, set MD5-hashed password, set flags
231 community.postgresql.postgresql_user:
232 name: rails
233 password: md59543f1d82624df2b31672ec0f7050460
234 # password: SCRAM-SHA-256$4096:zFuajwIVdli9mK=NJkcv1Q++$JC4gWIrEHmF6sqRbEiZw5FFW45HUPrpVzNdoM72o730+;fqA4vLN3mCZGbhcbQyvNYY7anCrUTsem1eCh/4YA94=
235 role_attr_flags: CREATEDB,NOSUPERUSER
236 # When using sha256-hashed password:
237 # environment:
238 # PGOPTIONS: "-c password_encryption=scram-sha-256"
239
240 - name: Connect to test database, remove test user from cluster
241 community.postgresql.postgresql_user:
242 login_db: test
243 name: test
244 state: absent
245
246 - name: Connect to acme database and set user's password with no expire date
247 community.postgresql.postgresql_user:
248 login_db: acme
249 name: django
250 password: mysupersecretword
251 expires: infinity
252
253 - name: Connect to test database and remove an existing user's password
254 community.postgresql.postgresql_user:
255 login_db: test
256 user: test
257 password: ""
258
259 # Create user with a cleartext password if it does not exist or update its password.
260 # The password will be encrypted with SCRAM algorithm (available since PostgreSQL 10)
261 - name: Create appclient user with SCRAM-hashed password
262 community.postgresql.postgresql_user:
263 name: appclient
264 password: "secret123"
265 environment:
266 PGOPTIONS: "-c password_encryption=scram-sha-256"
267
268 # Create a user and set a default-configuration that is active when they start a session
269 - name: Create a user with config-parameter
270 community.postgresql.postgresql_user:
271 name: appclient
272 password: "secret123"
273 configuration:
274 work_mem: "16MB"
275
276 # Make sure user has only specified default configuration parameters
277 - name: Clear all configuration that is not explicitly defined for user
278 community.postgresql.postgresql_user:
279 name: appclient
280 password: "secret123"
281 configuration:
282 work_mem: "16MB"
283 reset_unspecified_configuration: true
284
285 - name: Set search_path for user
286 community.postgresql.postgresql_user:
287 name: postgres_exporter
288 quote_configuration_values: false
289 configuration:
290 search_path: postgres_exporter, pg_catalog, public
291 '''
292
293 RETURN = r'''
294 queries:
295 description: List of executed queries.
296 returned: success
297 type: list
298 sample: ['CREATE USER "alice"', 'GRANT CONNECT ON DATABASE "acme" TO "alice"']
299 '''
300
301 import hmac
302 import itertools
303 import re
304 import traceback
305 from base64 import b64decode
306 from hashlib import md5, sha256
307
308 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
309 from ansible.module_utils.basic import AnsibleModule
310 from ansible_collections.community.postgresql.plugins.module_utils import \
311 saslprep
312 from ansible_collections.community.postgresql.plugins.module_utils.database import (
313 SQLParseError,
314 check_input,
315 pg_quote_identifier,
316 )
317 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
318 HAS_PSYCOPG,
319 PSYCOPG_VERSION,
320 connect_to_db,
321 ensure_required_libs,
322 get_comment,
323 get_conn_params,
324 get_server_version,
325 pg_cursor_args,
326 postgres_common_argument_spec,
327 set_comment,
328 )
329 from ansible_collections.community.postgresql.plugins.module_utils.version import \
330 LooseVersion
331
332 if HAS_PSYCOPG and PSYCOPG_VERSION < LooseVersion("3.0"):
333 import psycopg2 as psycopg
334 elif HAS_PSYCOPG:
335 import psycopg
336
337 try:
338 # pbkdf2_hmac is missing on python 2.6, we can safely assume,
339 # that postresql 10 capable instance have at least python 2.7 installed
340 from hashlib import pbkdf2_hmac
341 pbkdf2_found = True
342 except ImportError:
343 pbkdf2_found = False
344
345
346 FLAGS = ('SUPERUSER', 'CREATEROLE', 'CREATEDB', 'INHERIT', 'LOGIN', 'REPLICATION')
347 FLAGS_BY_VERSION = {'BYPASSRLS': 90500}
348
349 SCRAM_SHA256_REGEX = r'^SCRAM-SHA-256\$(\d+):([A-Za-z0-9+\/=]+)\$([A-Za-z0-9+\/=]+):([A-Za-z0-9+\/=]+)$'
350
351 # map to cope with idiosyncrasies of SUPERUSER and LOGIN
352 PRIV_TO_AUTHID_COLUMN = dict(SUPERUSER='rolsuper', CREATEROLE='rolcreaterole',
353 CREATEDB='rolcreatedb', INHERIT='rolinherit', LOGIN='rolcanlogin',
354 REPLICATION='rolreplication', BYPASSRLS='rolbypassrls')
355
356 executed_queries = []
357
358 # This is a special list for debugging.
359 # If you need to fetch information (e.g. results of cursor.fetchall(),
360 # queries built with cursor.mogrify(), vars values, etc.):
361 # 1. Put debug_info.append(<information_you_need>) as many times as you need.
362 # 2. Run integration tests or you playbook with -vvv
363 # 3. If it's not empty, you'll see the list in the returned json.
364 debug_info = []
365
366
367 class InvalidFlagsError(Exception):
368 pass
369
370
371 class InvalidPrivsError(Exception):
372 pass
373
374 # ===========================================
375 # PostgreSQL module specific support methods.
376 #
377
378
379 def user_exists(cursor, user):
380 # The PUBLIC user is a special case that is always there
381 if user == 'PUBLIC':
382 return True
383 query = "SELECT rolname FROM pg_roles WHERE rolname=%(user)s"
384 cursor.execute(query, {'user': user})
385 return cursor.rowcount > 0
386
387
388 def user_add(cursor, user, password, role_attr_flags, encrypted, expires, conn_limit, module):
389 """Create a new database user (role)."""
390 # Note: role_attr_flags escaped by parse_role_attrs and encrypted is a
391 # literal
392 query_password_data = dict(password=password, expires=expires)
393 query = ['CREATE USER %(user)s' %
394 {"user": _pg_quote_user(user, module)}]
395 if password is not None and password != '':
396 query.append("WITH %(crypt)s" % {"crypt": encrypted})
397 query.append("PASSWORD %(password)s")
398 if expires is not None:
399 query.append("VALID UNTIL %(expires)s")
400 if conn_limit is not None:
401 query.append("CONNECTION LIMIT %(conn_limit)s" % {"conn_limit": conn_limit})
402 query.append(role_attr_flags)
403 query = ' '.join(query)
404 executed_queries.append(query)
405 cursor.execute(query, query_password_data)
406 return True
407
408
409 def get_passwd_encryption(cursor):
410 cursor.execute("SHOW password_encryption")
411 return cursor.fetchone()["password_encryption"]
412
413
414 def user_should_we_change_password(cursor, current_role_attrs, user, password, encrypted):
415 """Check if we should change the user's password.
416
417 Compare the proposed password with the existing one, comparing
418 hashes if encrypted. If we can't access it assume yes.
419 """
420
421 if current_role_attrs is None:
422 # on some databases, E.g. AWS RDS instances, there is no access to
423 # the pg_authid relation to check the pre-existing password, so we
424 # just assume password is different
425 return True
426
427 # Do we actually need to do anything?
428 pwchanging = False
429 if password is not None:
430 current_password = current_role_attrs['rolpassword']
431 # Handle SQL_ASCII encoded databases
432 if isinstance(current_password, bytes):
433 current_password = current_password.decode('ascii')
434
435 # Empty password means that the role shouldn't have a password, which
436 # means we need to check if the current password is None.
437 if password == '':
438 if current_password is not None:
439 pwchanging = True
440 # If the provided password is a SCRAM hash, compare it directly to the current password
441 elif re.match(SCRAM_SHA256_REGEX, password):
442 if password != current_password:
443 pwchanging = True
444
445 # SCRAM hashes are represented as a special object, containing hash data:
446 # `SCRAM-SHA-256$<iteration count>:<salt>$<StoredKey>:<ServerKey>`
447 # for reference, see https://www.postgresql.org/docs/current/catalog-pg-authid.html
448 elif current_password is not None \
449 and pbkdf2_found \
450 and re.match(SCRAM_SHA256_REGEX, current_password):
451
452 r = re.match(SCRAM_SHA256_REGEX, current_password)
453 try:
454 # extract SCRAM params from rolpassword
455 it = int(r.group(1))
456 salt = b64decode(r.group(2))
457 server_key = b64decode(r.group(4))
458 # we'll never need `storedKey` as it is only used for server auth in SCRAM
459 # storedKey = b64decode(r.group(3))
460
461 # from RFC5802 https://tools.ietf.org/html/rfc5802#section-3
462 # SaltedPassword := Hi(Normalize(password), salt, i)
463 # ServerKey := HMAC(SaltedPassword, "Server Key")
464 normalized_password = saslprep.saslprep(to_text(password))
465 salted_password = pbkdf2_hmac('sha256', to_bytes(normalized_password), salt, it)
466
467 server_key_verifier = hmac.new(salted_password, digestmod=sha256)
468 server_key_verifier.update(b'Server Key')
469
470 if server_key_verifier.digest() != server_key:
471 pwchanging = True
472 except Exception:
473 # We assume the password is not scram encrypted
474 # or we cannot check it properly, e.g. due to missing dependencies
475 pwchanging = True
476
477 # When the provided password looks like a MD5-hash, value of
478 # 'encrypted' is ignored.
479 elif is_pg_passwd_md5(password) or encrypted == 'UNENCRYPTED':
480 if password != current_password:
481 pwchanging = True
482 elif encrypted == 'ENCRYPTED':
483 default_pw_encryption = get_passwd_encryption(cursor)
484
485 if default_pw_encryption == 'md5':
486 hashed_password = 'md5{0}'.format(md5(to_bytes(password) + to_bytes(user)).hexdigest())
487 if hashed_password != current_password:
488 pwchanging = True
489 elif default_pw_encryption == 'scram-sha-256':
490 # https://github.com/ansible-collections/community.postgresql/issues/688
491 # When the current password is not none and is not
492 # hashed as scram-sha-256 / not explicitly declared as plain text
493 # (if we are here, these conditions should be met)
494 # but the default password encryption is scram-sha-256, update the password.
495 # Can be relevant when migrating from older version of postgres.
496 pwchanging = True
497
498 return pwchanging
499
500
501 def is_pg_passwd_md5(password):
502 # 32: MD5 hashes are represented as a sequence of 32 hexadecimal digits
503 # 3: The size of the 'md5' prefix
504 return True if password.startswith('md5') and len(password) == 32 + 3 else False
505
506
507 def get_role_attrs(db_connection, module, cursor, user):
508 current_role_attrs = None
509
510 # Let's first try to get the attrs from pg_authid.
511 # Some systems like AWS RDS instances
512 # do not allow user to access pg_authid
513 try:
514 query = "SELECT * FROM pg_authid where rolname=%(user)s"
515 cursor.execute(query, {"user": user})
516 current_role_attrs = cursor.fetchone()
517 except psycopg.ProgrammingError:
518 db_connection.rollback()
519
520 # If we succeeded, return it
521 if current_role_attrs is not None:
522 return current_role_attrs
523
524 # If we haven't succeeded, like in case of AWS RDS,
525 # try to get the attrs from the pg_roles table
526 try:
527 query = "SELECT * FROM pg_roles where rolname=%(user)s"
528 cursor.execute(query, {"user": user})
529 current_role_attrs = cursor.fetchone()
530 except psycopg.ProgrammingError as e:
531 db_connection.rollback()
532 module.fail_json(msg="Failed to get role details for current user %s: %s" % (user, e))
533
534 return current_role_attrs
535
536
537 def need_to_change_role_attr_flags(role_attr_flags, current_role_attrs):
538 # Compare the desired role_attr_flags and current ones.
539 # If they don't match, return True which means
540 # they need to be updated, False otherwise.
541
542 role_attr_flags_changing = False
543 if role_attr_flags:
544 role_attr_flags_dict = {}
545 for r in role_attr_flags.split(' '):
546 if r.startswith('NO'):
547 role_attr_flags_dict[r.replace('NO', '', 1)] = False
548 else:
549 role_attr_flags_dict[r] = True
550
551 for role_attr_name, role_attr_value in role_attr_flags_dict.items():
552 if current_role_attrs[PRIV_TO_AUTHID_COLUMN[role_attr_name]] != role_attr_value:
553 role_attr_flags_changing = True
554
555 return role_attr_flags_changing
556
557
558 def need_to_change_role_expiration(cursor, expires, current_role_attrs):
559 expires_changing = False
560
561 if expires is not None:
562 cursor.execute("SELECT %s::timestamptz exp_timestamp", (expires,))
563 expires_with_tz = cursor.fetchone()["exp_timestamp"]
564 # If the desired expiration date is not equal to
565 # what is already set for the role, set this to True
566 expires_changing = expires_with_tz != current_role_attrs.get('rolvaliduntil')
567
568 return expires_changing
569
570
571 def need_to_change_conn_limit(conn_limit, current_role_attrs):
572 return (conn_limit is not None and conn_limit != current_role_attrs['rolconnlimit'])
573
574
575 def exec_alter_user(module, cursor, statement, params=None):
576 changed = False
577
578 if params is None:
579 params = {}
580
581 try:
582 cursor.execute(statement, params)
583 executed_queries.append(statement)
584 changed = True
585 # We could catch psycopg.errors.ReadOnlySqlTransaction directly,
586 # but that was added only in Psycopg 2.8
587 except psycopg.InternalError as e:
588 if e.diag.sqlstate == "25006":
589 # Handle errors due to read-only transactions indicated by pgcode 25006
590 # ERROR: cannot execute ALTER ROLE in a read-only transaction
591 changed = False
592 module.fail_json(msg=e.diag.message_primary, exception=traceback.format_exc())
593 return changed
594 else:
595 raise psycopg.InternalError(e)
596 except psycopg.NotSupportedError as e:
597 module.fail_json(msg=e.diag.message_primary, exception=traceback.format_exc())
598
599 return changed
600
601
602 def user_alter(db_connection, module, user, password, role_attr_flags, encrypted, expires, no_password_changes, conn_limit):
603 """Change user password and/or attributes. Return True if changed, False otherwise."""
604 changed = False
605
606 cursor = db_connection.cursor(**pg_cursor_args)
607 # Note: role_attr_flags escaped by parse_role_attrs and encrypted is a literal
608 if user == 'PUBLIC':
609 if password is not None:
610 module.fail_json(msg="cannot change the password for PUBLIC user")
611 elif role_attr_flags != '':
612 module.fail_json(msg="cannot change the role_attr_flags for PUBLIC user")
613 else:
614 return False
615
616 # Handle passwords.
617 if not no_password_changes and (password is not None or role_attr_flags != '' or expires is not None or conn_limit is not None):
618 # Get role's current attributes to check if they match with the desired state
619 current_role_attrs = get_role_attrs(db_connection, module, cursor, user)
620
621 # Does password need to changed?
622 pwchanging = user_should_we_change_password(cursor, current_role_attrs, user, password, encrypted)
623
624 # Do role attributes need to changed?
625 role_attr_flags_changing = need_to_change_role_attr_flags(role_attr_flags, current_role_attrs)
626
627 # Does role expiration date need to changed?
628 expires_changing = need_to_change_role_expiration(cursor, expires, current_role_attrs)
629
630 # Does role connection limit need to change?
631 conn_limit_changing = need_to_change_conn_limit(conn_limit, current_role_attrs)
632
633 # Now let's check if anything needs to changed. If nothing, just return False
634 if not pwchanging and not role_attr_flags_changing and not expires_changing and not conn_limit_changing:
635 return False
636
637 # If we are here, something does need to change.
638 # Compose a statement and execute it
639 alter = ['ALTER USER %(user)s' % {"user": _pg_quote_user(user, module)}]
640 if pwchanging:
641 if password != '':
642 alter.append("WITH %(crypt)s" % {"crypt": encrypted})
643 alter.append("PASSWORD %(password)s")
644 else:
645 alter.append("WITH PASSWORD NULL")
646 alter.append(role_attr_flags)
647 elif role_attr_flags:
648 alter.append('WITH %s' % role_attr_flags)
649 if expires is not None:
650 alter.append("VALID UNTIL %(expires)s")
651 if conn_limit is not None:
652 alter.append("CONNECTION LIMIT %(conn_limit)s" % {"conn_limit": conn_limit})
653
654 query_password_data = dict(password=password, expires=expires)
655 statement = ' '.join(alter)
656 changed = exec_alter_user(module, cursor, statement, query_password_data)
657
658 elif no_password_changes and role_attr_flags != '':
659 # Get role's current attributes to check if they match with the desired state
660 current_role_attrs = get_role_attrs(db_connection, module, cursor, user)
661
662 # Do role attributes need to changed? If not, just return False right away
663 role_attr_flags_changing = need_to_change_role_attr_flags(role_attr_flags, current_role_attrs)
664 if not role_attr_flags_changing:
665 return False
666
667 # If they need, compose a statement and execute
668 alter = ['ALTER USER %(user)s' %
669 {"user": _pg_quote_user(user, module)}]
670 if role_attr_flags:
671 alter.append('WITH %s' % role_attr_flags)
672
673 statement = ' '.join(alter)
674
675 changed = exec_alter_user(module, cursor, statement)
676
677 # Fetch new role attributes.
678 new_role_attrs = get_role_attrs(db_connection, module, cursor, user)
679
680 # Detect any differences between current_ and new_role_attrs.
681 changed = current_role_attrs != new_role_attrs
682
683 return changed
684
685
686 def user_delete(cursor, user, module):
687 """Try to remove a user. Returns True if successful otherwise False"""
688 cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
689 try:
690 query = 'DROP USER %s' % _pg_quote_user(user, module)
691 executed_queries.append(query)
692 cursor.execute(query)
693 except Exception as e:
694 cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
695 cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
696 return False, e
697
698 cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
699 return True, None
700
701
702 def parse_role_attrs(role_attr_flags, srv_version):
703 """
704 Parse role attributes string for user creation.
705 Format:
706
707 attributes[,attributes,...]
708
709 Where:
710
711 attributes := CREATEDB,CREATEROLE,NOSUPERUSER,...
712 [ "[NO]SUPERUSER","[NO]CREATEROLE", "[NO]CREATEDB",
713 "[NO]INHERIT", "[NO]LOGIN", "[NO]REPLICATION",
714 "[NO]BYPASSRLS" ]
715
716 Note: "[NO]BYPASSRLS" role attribute introduced in 9.5
717 Note: "[NO]CREATEUSER" role attribute is deprecated.
718
719 """
720 flags = frozenset(role.upper() for role in role_attr_flags.split(',') if role)
721
722 valid_flags = frozenset(itertools.chain(FLAGS, get_valid_flags_by_version(srv_version)))
723 valid_flags = frozenset(itertools.chain(valid_flags, ('NO%s' % flag for flag in valid_flags)))
724
725 if not flags.issubset(valid_flags):
726 raise InvalidFlagsError('Invalid role_attr_flags specified: %s' %
727 ' '.join(flags.difference(valid_flags)))
728
729 return ' '.join(flags)
730
731
732 def get_valid_flags_by_version(srv_version):
733 """
734 Some role attributes were introduced after certain versions. We want to
735 compile a list of valid flags against the current Postgres version.
736 """
737 return [
738 flag
739 for flag, version_introduced in FLAGS_BY_VERSION.items()
740 if srv_version >= version_introduced
741 ]
742
743
744 def add_comment(cursor, user, comment, check_mode):
745 """Add comment on user."""
746 current_comment = get_comment(cursor, 'role', user)
747 # For the resetting comment feature (comment: '') to work correctly
748 current_comment = current_comment if current_comment is not None else ''
749 if comment != current_comment:
750 set_comment(cursor, comment, 'role', user, check_mode, executed_queries)
751 return True
752 else:
753 return False
754
755
756 def compare_user_configurations(current, desired, reset_unspec_config):
757 """Compares two configurations and returns a list of values to reset as well as a dict of parameters to update."""
758 reset = []
759 update = desired.copy()
760
761 # check each item in the current configuration
762 for key, value in current.items():
763 # we already have the correct setting
764 if key in desired and value == desired[key]:
765 # so we can remove it from the list
766 del update[key]
767 # if the key is not in the list of settings we want, and we reset unspecified parameters
768 elif key not in desired and reset_unspec_config:
769 # we will reset it on the database
770 reset.append(key)
771 # if the setting is not in the db or has the wrong value, it will get updated
772
773 return {"reset": reset, "update": update}
774
775
776 def parse_user_configuration(module, configs):
777 """Parses configuration from a list of 'key=value' strings like returned from the database to a dict."""
778 if configs is not None:
779 try:
780 # parses a list of "key=value" strings to a dict
781 return {t[0]: t[1] for t in map(lambda s: s.split("=", 1), configs)}
782 except IndexError:
783 module.fail_json(
784 msg="Expecting a list of strings where each string has the format 'key=value'.")
785 else:
786 return {}
787
788
789 def user_configuration(cursor, module, user, configuration, reset_unspec_config, quote_values):
790 """Updates the user's configuration parameters if necessary."""
791 current_config_query = "SELECT rolconfig FROM pg_roles WHERE rolname = %(user)s;"
792 cursor.execute(current_config_query, {"user": user})
793 current_config = cursor.fetchone()
794 changed = False
795
796 if current_config is None:
797 module.fail_json(msg="Can't find user %(user)s in 'pg_roles'" % {"user": user})
798
799 current_config_dict = parse_user_configuration(module, current_config['rolconfig'])
800 config_updates = compare_user_configurations(current_config_dict, configuration, reset_unspec_config)
801
802 try:
803 # It seems psycopg's prepared statements don't work with 'ALTER ROLE' at this point.
804 # This is vulnerable to SQL-injections (added to docs) but I don't see a better way to do this.
805 for item in config_updates["reset"]:
806 query = 'ALTER ROLE %(user)s RESET "%(key)s";' % {"user": _pg_quote_user(user, module), "key": item}
807 executed_queries.append(query)
808 cursor.execute(query)
809 changed = True
810 for key, value in config_updates["update"].items():
811 if quote_values:
812 query = ('ALTER ROLE %(user)s SET "%(key)s" TO \'%(value)s\';' %
813 {"user": _pg_quote_user(user, module), "key": key, "value": value})
814 else:
815 query = ('ALTER ROLE %(user)s SET "%(key)s" TO %(value)s;' %
816 {"user": _pg_quote_user(user, module), "key": key, "value": value})
817 executed_queries.append(query)
818 cursor.execute(query)
819 changed = True
820 except psycopg.ProgrammingError as e:
821 module.fail_json("Unable to update configuration for '%(user)s' due to: %(exception)s" %
822 {"user": user, "exception": e})
823 return changed
824
825
826 def _pg_quote_user(user, module):
827 """correctly escape users, pg_quote_identifiers will fail if the user contains a dot but is not pre-quoted"""
828 if user[0] != '"' and user[-1] != '"':
829 # we pre-quote users to make sure pg_quote_identifiers doesn't fail on dots
830 return pg_quote_identifier('"%s"' % user, 'role')
831 elif (user[0] == '"' and user[-1] != '"') or (user[0] != '"' and user[-1] == '"'):
832 module.fail_json("The value of the user-field can't contain a double-quote in the end "
833 "if it doesn't start with one and vice-versa.")
834 else:
835 # user is already quoted, we run it through pg_quote_identifiers to make sure it doesn't contain any lonely
836 # double-quotes to prevent SQL-injections
837 return pg_quote_identifier(user, 'role')
838
839
840 # ===========================================
841 # Module execution.
842 #
843
844 def main():
845 argument_spec = postgres_common_argument_spec()
846 argument_spec.update(
847 user=dict(type='str', required=True, aliases=['name']),
848 password=dict(type='str', default=None, no_log=True),
849 state=dict(type='str', default='present', choices=['absent', 'present']),
850 login_db=dict(type='str', default="", aliases=['db'], deprecated_aliases=[
851 {
852 'name': 'db',
853 'version': '5.0.0',
854 'collection_name': 'community.postgresql',
855 }],
856 ),
857 fail_on_user=dict(type='bool', default=True, aliases=['fail_on_role']),
858 role_attr_flags=dict(type='str', default=''),
859 encrypted=dict(type='bool', default=True),
860 no_password_changes=dict(type='bool', default=False, no_log=False),
861 expires=dict(type='str', default=None),
862 conn_limit=dict(type='int', default=None),
863 session_role=dict(type='str'),
864 comment=dict(type='str', default=None),
865 trust_input=dict(type='bool', default=True),
866 configuration=dict(type='dict', default={}),
867 reset_unspecified_configuration=dict(type='bool', default=False),
868 quote_configuration_values=dict(type='bool', default=True),
869 )
870 module = AnsibleModule(
871 argument_spec=argument_spec,
872 supports_check_mode=True
873 )
874
875 user = module.params["user"]
876 password = module.params["password"]
877 state = module.params["state"]
878 fail_on_user = module.params["fail_on_user"]
879 no_password_changes = module.params["no_password_changes"]
880 if module.params["encrypted"]:
881 encrypted = "ENCRYPTED"
882 else:
883 encrypted = "UNENCRYPTED"
884 expires = module.params["expires"]
885 conn_limit = module.params["conn_limit"]
886 role_attr_flags = module.params["role_attr_flags"]
887 comment = module.params["comment"]
888 session_role = module.params['session_role']
889 configuration = module.params['configuration']
890 reset_unspec_config = module.params['reset_unspecified_configuration']
891 quote_configuration_values = module.params['quote_configuration_values']
892
893 trust_input = module.params['trust_input']
894 if not trust_input:
895 # Check input for potentially dangerous elements:
896 check_input(module, user, password, expires,
897 role_attr_flags, comment, session_role, comment, configuration)
898
899 # Ensure psycopg libraries are available before connecting to DB:
900 ensure_required_libs(module)
901 conn_params = get_conn_params(module, module.params, warn_db_default=False)
902 db_connection, dummy = connect_to_db(module, conn_params)
903 cursor = db_connection.cursor(**pg_cursor_args)
904
905 srv_version = get_server_version(db_connection)
906
907 # sanitize configuration
908 if quote_configuration_values:
909 for key, value in configuration.items():
910 if '"' in key or '\'' in key:
911 module.fail_json("The key of a configuration may not contain single or double quotes")
912 configuration[key] = value.replace("'", "''")
913
914 try:
915 role_attr_flags = parse_role_attrs(role_attr_flags, srv_version)
916 except InvalidFlagsError as e:
917 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
918
919 kw = dict(user=user)
920 changed = False
921
922 if state == "present":
923 if user_exists(cursor, user):
924 try:
925 changed = user_alter(db_connection, module, user, password,
926 role_attr_flags, encrypted, expires, no_password_changes, conn_limit)
927 except SQLParseError as e:
928 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
929 else:
930 try:
931 changed = user_add(cursor, user, password,
932 role_attr_flags, encrypted, expires, conn_limit, module)
933 except psycopg.ProgrammingError as e:
934 module.fail_json(msg="Unable to add user with given requirement "
935 "due to : %s" % to_native(e),
936 exception=traceback.format_exc())
937 except SQLParseError as e:
938 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
939
940 if comment is not None:
941 try:
942 changed = add_comment(cursor, user, comment, module.check_mode) or changed
943 except Exception as e:
944 module.fail_json(msg='Unable to add comment on role: %s' % to_native(e),
945 exception=traceback.format_exc())
946
947 # handle user-specific configuration-defaults
948 changed = user_configuration(cursor, module, user, configuration, reset_unspec_config,
949 quote_configuration_values) or changed
950
951 else:
952 if user_exists(cursor, user):
953 if module.check_mode:
954 changed = True
955 kw['user_removed'] = True
956 else:
957 try:
958 changed, err = user_delete(cursor, user, module)
959 except SQLParseError as e:
960 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
961
962 if fail_on_user and not changed:
963 msg = "Unable to remove user: %s" % err
964 module.fail_json(msg=msg)
965 kw['user_removed'] = changed
966
967 if module.check_mode:
968 db_connection.rollback()
969 else:
970 db_connection.commit()
971
972 cursor.close()
973 db_connection.close()
974
975 kw['changed'] = changed
976 kw['queries'] = executed_queries
977 if debug_info:
978 kw['debug_info'] = debug_info
979 module.exit_json(**kw)
980
981
982 if __name__ == '__main__':
983 main()