# Odoo provisioning, run as an initContainer on every pod start — idempotent by # construction, so a restart never re-initialises a live database. # # 1. wait for Postgres # 2. if the `odoo` database has no tables: `odoo -i base,web # --without-demo=all --stop-after-init` (the "init once" step, done by the # pod rather than by a separate Job so there is exactly one thing to wait # on and no ordering race between a Job and the Deployment) # 3. CREATE EXTENSION unaccent, as the database owner # 4. (re)apply the read-only BI grants over every table Odoo just created, # including revoking the tables that carry credentials # 5. set the admin login/password from Secret `farrisilk/odoo-admin` # # Step 4 runs unconditionally, not only on first install: it is what picks up # tables added by a later module install (`-i`/`-u` from /mnt/extra-addons), and # `ALTER DEFAULT PRIVILEGES` alone does not cover tables created before the # grant. Nothing here writes a credential to stdout. apiVersion: v1 kind: ConfigMap metadata: name: odoo-init namespace: farrisilk data: init_db.py: | #!/usr/bin/env python3 """Idempotent first-run provisioning of the Farrisilk lab Odoo database.""" import os import subprocess import sys import time import psycopg2 HOST = os.environ["DB_HOST"] PORT = int(os.environ.get("DB_PORT", "5432")) SUPER_USER = os.environ["PG_SUPERUSER"] SUPER_PW = os.environ["PG_SUPERPASS"] DB = os.environ.get("ODOO_DB_NAME", "odoo") CONF = "/etc/odoo-runtime/odoo.conf" ADMIN_LOGIN = os.environ["ODOO_ADMIN_LOGIN"] ADMIN_PASSWORD = os.environ["ODOO_ADMIN_PASSWORD"] # Tables that hold credentials looking like data. `ir_config_parameter` is # the one the card calls out (API keys/tokens for integrations); the rest # are the same class of column. `res_users` is deliberately NOT in this # list: it carries a password *hash* only, and Metabase needs it for user # counts. Everything found by inspection at runtime is added and logged. CREDENTIAL_TABLES = [ "ir_config_parameter", "ir_mail_server", "fetchmail_server", "res_users_apikeys", "payment_provider", "res_users_identitycheck", ] def connect(dbname, user, password): conn = psycopg2.connect( host=HOST, port=PORT, dbname=dbname, user=user, password=password, connect_timeout=10, ) conn.autocommit = True return conn def wait_for_pg(): for _ in range(90): try: connect("postgres", SUPER_USER, SUPER_PW).close() return except psycopg2.Error: time.sleep(2) sys.exit("postgres unreachable") def tables(cur): cur.execute( "select table_name from information_schema.tables " "where table_schema = 'public' and table_type = 'BASE TABLE'" ) return {r[0] for r in cur.fetchall()} def run(cmd, **kw): print("+ " + " ".join(cmd), flush=True) subprocess.run(cmd, check=True, **kw) wait_for_pg() conn = connect("postgres", SUPER_USER, SUPER_PW) cur = conn.cursor() cur.execute("select 1 from pg_database where datname = %s", (DB,)) exists = cur.fetchone() is not None conn.close() have_tables = False if exists: dconn = connect(DB, SUPER_USER, SUPER_PW) dcur = dconn.cursor() have_tables = bool(tables(dcur)) dconn.close() if not have_tables: print(f"== initialising {DB}: base,web (no demo data) ==", flush=True) run(["odoo", "-c", CONF, "-d", DB, "-i", "base,web", "--without-demo=all", "--stop-after-init", "--no-http"]) else: print(f"== {DB} already initialised: skipping -i base ==", flush=True) # unaccent as the database owner (trusted extension in PG16). Odoo uses it # for accent-insensitive search in the web client. oconn = connect(DB, "odoo", os.environ["ODOO_DB_PASSWORD"]) ocur = oconn.cursor() ocur.execute("CREATE EXTENSION IF NOT EXISTS unaccent") ocur.execute("select extname, extowner::regrole::text from pg_extension where extname = 'unaccent'") print("unaccent:", ocur.fetchone(), flush=True) oconn.close() # Read-only BI grants + credential-table revokes. gconn = connect(DB, SUPER_USER, SUPER_PW) gcur = gconn.cursor() # PostgreSQL 16 leaves CREATE on schema public granted to PUBLIC in a # database created by a NON-SUPERUSER (Odoo creates its own database as # `odoo`), so `default_transaction_read_only` is the only thing stopping # metabase_ro from creating tables — and a role may lift its own default # with `SET default_transaction_read_only = off`. Privileges are the real # guard: PUBLIC loses CREATE, metabase_ro gets USAGE only. gcur.execute("REVOKE CREATE ON SCHEMA public FROM PUBLIC") gcur.execute("REVOKE ALL ON SCHEMA public FROM metabase_ro") gcur.execute("GRANT USAGE ON SCHEMA public TO metabase_ro") gcur.execute("GRANT SELECT ON ALL TABLES IN SCHEMA public TO metabase_ro") gcur.execute( "ALTER DEFAULT PRIVILEGES FOR ROLE odoo IN SCHEMA public " "GRANT SELECT ON TABLES TO metabase_ro" ) present = tables(gcur) revoked = sorted({t for t in CREDENTIAL_TABLES if t in present}) # Inspect rather than assume the static list is complete: anything whose # columns look like credentials is added to the revoke set (logged below). gcur.execute( "select distinct table_name from information_schema.columns " "where table_schema = 'public' and (" " column_name ~ '(^|_)(password|secret|token)($|_)' or " " column_name ~ '(api_key|access_key|private_key)'" ") and table_name not in ('res_users', 'res_partner')" ) for (t,) in gcur.fetchall(): if t in present and t not in revoked: revoked.append(t) revoked = sorted(revoked) for t in revoked: gcur.execute("REVOKE SELECT ON public.%s FROM metabase_ro" % t) gcur.execute( "select table_name from information_schema.table_privileges " "where grantee = 'metabase_ro' and privilege_type = 'SELECT' " "and table_schema = 'public' order by 1" ) readable = len(gcur.fetchall()) gconn.close() print(f"metabase_ro: SELECT granted on {readable} tables; " f"revoked on {revoked}", flush=True) # Admin login/password from Secret farrisilk/odoo-admin. `odoo shell` is # the supported way to set a res.users password without hand-rolling a # pbkdf2 hash. Re-writing the same value on every start is harmless. payload = ( "u = env.ref('base.user_admin')\n" f"u.write({{'login': {ADMIN_LOGIN!r}, 'password': {ADMIN_PASSWORD!r}}})\n" "env.cr.commit()\n" "print('admin uid', u.id, 'login', u.login)\n" ) run(["odoo", "shell", "-c", CONF, "-d", DB, "--no-http", "--shell-interface=python"], input=payload, text=True) print("== provisioning complete ==", flush=True)