Coverage for dak/import_users_from_passwd.py: 28%

73 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2026-11-21 08:51 +0000

1"""Sync PostgreSQL users with system users""" 

2 

3# Copyright (C) 2001, 2002, 2006 James Troup <james@nocrew.org> 

4 

5# This program is free software; you can redistribute it and/or modify 

6# it under the terms of the GNU General Public License as published by 

7# the Free Software Foundation; either version 2 of the License, or 

8# (at your option) any later version. 

9 

10# This program is distributed in the hope that it will be useful, 

11# but WITHOUT ANY WARRANTY; without even the implied warranty of 

12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

13# GNU General Public License for more details. 

14 

15# You should have received a copy of the GNU General Public License 

16# along with this program; if not, write to the Free Software 

17# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 

18 

19################################################################################ 

20 

21import grp 

22import pwd 

23import re 

24import sys 

25from contextlib import closing 

26 

27import apt_pkg 

28from psycopg2 import sql as pgsql 

29from sqlalchemy import sql 

30from sqlalchemy.orm import Session 

31 

32from daklib import utils 

33from daklib.config import Config 

34from daklib.dbconn import DBConn 

35 

36################################################################################ 

37 

38 

39def usage(exit_code=0): 

40 print( 

41 """Usage: dak import-users-from-passwd [OPTION]... 

42Sync PostgreSQL's users with system users. 

43 

44 -h, --help show this help and exit 

45 -n, --no-action don't do anything 

46 -q, --quiet be quiet about what is being done 

47 -v, --verbose explain what is being done""" 

48 ) 

49 sys.exit(exit_code) 

50 

51 

52################################################################################ 

53 

54 

55def execute_composed(session: Session, query: pgsql.Composable) -> None: 

56 """Execute a query composed with psycopg2.sql in the session's transaction""" 

57 with closing(session.connection().connection.cursor()) as cursor: 

58 cursor.execute(query) 

59 

60 

61################################################################################ 

62 

63 

64def main(): 

65 cnf = Config() 

66 

67 Arguments = [ 

68 ("n", "no-action", "Import-Users-From-Passwd::Options::No-Action"), 

69 ("q", "quiet", "Import-Users-From-Passwd::Options::Quiet"), 

70 ("v", "verbose", "Import-Users-From-Passwd::Options::Verbose"), 

71 ("h", "help", "Import-Users-From-Passwd::Options::Help"), 

72 ] 

73 for i in ["no-action", "quiet", "verbose", "help"]: 

74 key = "Import-Users-From-Passwd::Options::%s" % i 

75 if key not in cnf: 75 ↛ 73line 75 didn't jump to line 73 because the condition on line 75 was always true

76 cnf[key] = "" 

77 

78 arguments = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv) # type: ignore[attr-defined] 

79 Options = cnf.subtree("Import-Users-From-Passwd::Options") 

80 

81 if Options["Help"]: 81 ↛ 83line 81 didn't jump to line 83 because the condition on line 81 was always true

82 usage() 

83 elif arguments: 

84 utils.warn("dak import-users-from-passwd takes no non-option arguments.") 

85 usage(1) 

86 

87 session = DBConn().session() 

88 valid_gid = cnf.get("Import-Users-From-Passwd::ValidGID", "") 

89 if valid_gid: 

90 debiangrp = grp.getgrnam(valid_gid).gr_mem 

91 else: 

92 debiangrp = [] 

93 

94 passwd_unames = {} 

95 for entry in pwd.getpwall(): 

96 uname = entry[0] 

97 if uname not in debiangrp: 

98 if Options["Verbose"]: 

99 print("Skipping %s (Not in group %s)." % (uname, valid_gid)) 

100 continue 

101 passwd_unames[uname] = "" 

102 

103 postgres_unames = {} 

104 q = session.execute(sql.text("SELECT usename FROM pg_user")) 

105 for j in q.fetchall(): 

106 uname = j[0] 

107 postgres_unames[uname] = "" 

108 

109 known_postgres_unames = {} 

110 for i in cnf.get("Import-Users-From-Passwd::KnownPostgres", "").split(","): 

111 uname = i.strip() 

112 known_postgres_unames[uname] = "" 

113 

114 for uname in sorted(postgres_unames): 

115 if uname not in passwd_unames and uname not in known_postgres_unames: 

116 print( 

117 "I: Deleting %s from Postgres, no longer in passwd or list of known Postgres users" 

118 % (uname) 

119 ) 

120 execute_composed( 

121 session, pgsql.SQL("DROP USER {}").format(pgsql.Identifier(uname)) 

122 ) 

123 

124 safe_name = re.compile("^[A-Za-z0-9]+$") 

125 for uname in sorted(passwd_unames): 

126 if uname not in postgres_unames: 

127 if not Options["Quiet"]: 

128 print("Creating %s user in Postgres." % (uname)) 

129 if not Options["No-Action"]: 

130 if safe_name.match(uname): 

131 try: 

132 execute_composed( 

133 session, 

134 pgsql.SQL("CREATE USER {}").format(pgsql.Identifier(uname)), 

135 ) 

136 session.commit() 

137 except Exception as e: 

138 utils.warn("Could not create user %s (%s)" % (uname, str(e))) 

139 session.rollback() 

140 else: 

141 print("NOT CREATING USER %s. Doesn't match safety regex" % uname) 

142 

143 session.commit()