ЛР 7: Безопасность, mTLS и OpenBao
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create non-owner database accounts with API and worker table grants."""
|
||||
import os
|
||||
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
|
||||
|
||||
def main():
|
||||
ca_file = os.environ["INTERNAL_CA_CERT"]
|
||||
conninfo = psycopg.conninfo.make_conninfo(
|
||||
host=os.environ["PGHOST"],
|
||||
port=os.environ.get("PGPORT", "5432"),
|
||||
dbname=os.environ["PGDATABASE"],
|
||||
user=os.environ["PGUSER"],
|
||||
password=os.environ["PGPASSWORD"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert=ca_file,
|
||||
connect_timeout=5,
|
||||
)
|
||||
accounts = (
|
||||
(os.environ["API_DB_USER"], os.environ["API_DB_PASSWORD"]),
|
||||
(os.environ["WORKER_DB_USER"], os.environ["WORKER_DB_PASSWORD"]),
|
||||
)
|
||||
with psycopg.connect(conninfo, autocommit=True) as conn:
|
||||
conn.execute(
|
||||
sql.SQL("REVOKE CREATE ON SCHEMA public FROM PUBLIC")
|
||||
)
|
||||
for username, password in accounts:
|
||||
found = conn.execute(
|
||||
"SELECT 1 FROM pg_roles WHERE rolname = %s",
|
||||
(username,),
|
||||
).fetchone()
|
||||
if found:
|
||||
conn.execute(
|
||||
sql.SQL("ALTER ROLE {} LOGIN PASSWORD {}").format(
|
||||
sql.Identifier(username),
|
||||
sql.Literal(password),
|
||||
)
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
sql.SQL("CREATE ROLE {} LOGIN PASSWORD {}").format(
|
||||
sql.Identifier(username),
|
||||
sql.Literal(password),
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(
|
||||
sql.Identifier(os.environ["PGDATABASE"]),
|
||||
sql.Identifier(username),
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(
|
||||
sql.Identifier(username),
|
||||
)
|
||||
)
|
||||
|
||||
api_user = sql.Identifier(accounts[0][0])
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}"
|
||||
).format(api_user)
|
||||
)
|
||||
worker_user = sql.Identifier(accounts[1][0])
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"GRANT SELECT, UPDATE ON TABLE attachments, image_jobs TO {}"
|
||||
).format(worker_user)
|
||||
)
|
||||
print("PASS: database service roles provisioned with separate grants")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user