r/devops7 • • 7h ago

One script, one chore: rotating the orders-db password. grep finds 3 deployments; one graph walk finds 9 that must restart and 9 more to warn, with owners (real output)

Short one this week: one script, one chore, real output. (This sub is run by the SynapCores team.)

The chore

The orders-db password gets rotated tonight. Before anyone types the new value: which services must restart to pick it up, and who else sees errors while they do? Today the answer is a grep over the manifests:

$ grep -l orders-db-password manifests/*.yaml
manifests/inventory-sync.yaml
manifests/orders-api.yaml
manifests/orders-worker.yaml

Three deployments name the secret. Six more get it without naming it: two mount orders-env, a shared env template that includes it; two mount batch-env, which includes orders-env; payments-gateway comes from a chart that bundles it; fraud-scorer reads the vault alias kv/db/orders. Nothing a grep can follow, so those six keep the old password and page you at 2 a.m.

The payoff: one walk, one join

secretwalk.py load turns the manifests, includes.csv and deps.csv into a graph and owners.csv (team, Slack channel, tier) into a SQL table, same SynapCores database. The SynapCores step: one Cypher walk from the secret, 1 to 6 hops over the three ways a secret travels, however many bundles sit in between:

MATCH p = (s:d11_Secret {name: 'orders-db-password'})-[:INCLUDED_IN|MOUNTED_BY|READ_BY*1..6]->(v:d11_Service)
RETURN v.name AS service, length(p) AS hops, [n IN nodes(p) | n.name] AS via

The script keeps the shortest path per service, saves it into d11_restart, and one join adds the owners:

SELECT o.tier, r.service, o.team, o.channel, r.via
FROM d11_restart r JOIN d11_owners o ON o.service = r.service
ORDER BY o.tier, r.hops, r.service

orders-db-password is named in 3 manifests (what grep finds): inventory-sync, orders-api, orders-worker

  tier  service               team           channel           how it gets the secret
  1     orders-api            orders         #orders-oncall    by name
  1     orders-worker         orders         #orders-oncall    by name
  1     payments-gateway      payments       #payments-oncall  payments-chart
  1     refund-service        payments       #payments-oncall  orders-env
  2     inventory-sync        inventory      #inventory        by name
  2     fraud-scorer          risk           #risk-oncall      kv/db/orders
  2     order-search-indexer  search         #search           orders-env
  2     invoice-export        finance-eng    #finance-eng      orders-env > batch-env
  3     nightly-report        data-platform  #data-oncall      orders-env > batch-env

Two lines grep cannot give you: invoice-export gets the secret two includes away (orders-env > batch-env), and fraud-scorer's manifest never contains the string orders-db-password, only the alias.

Who to warn

Same graph, second walk: everything that calls one of those nine, directly or through other services. They do not restart, they see errors while their dependency does, so their channel gets a heads-up (same join, against d11_warn):

MATCH (s:d11_Secret {name: 'orders-db-password'})-[:INCLUDED_IN|MOUNTED_BY|READ_BY*1..6]->(r:d11_Service)
MATCH p = (w:d11_Service)-[:DEPENDS_ON*1..6]->(r)
RETURN w.name AS service, r.name AS restarts, [n IN nodes(p) | n.name] AS via

  tier  service               team           channel           calls
  1     checkout-web          web            #web-oncall       orders-api
  1     mobile-bff            mobile         #mobile           orders-api, payments-gateway
...
  3     support-console       support-eng    #support-eng      refund-service

restart 9 (grep found 3), warn 9; tell 13 channels: #orders-oncall, #payments-oncall, #inventory, #risk-oncall, #search, #finance-eng, #data-oncall, #web-oncall, #mobile, #partners, #logistics, #growth, #support-eng

Ran on SynapCores 2.5.1 on a Mac mini (Apple M4); 2.3.2 gave the same output. Script, sample files and run commands are in the first two comments. SynapCores is free to download: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-one-script-11

How do you answer "where is this secret used" today: a grep like the one above, a label on each deployment, the vault's own lease list, or whoever rotated it last time?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 7h ago

Graph hops and the rest of the Cypher used here, one concept per lesson: SQLv2 Lesson 5, graph hops + meaning search (https://www.reddit.com/r/SQLv2/comments/1xq8g8l/).

secretwalk.py, part 1 of 2 (standard library only; set SC_URL and SC_TOKEN). Part 2, the sample files and the run commands are in the reply below.

"""secretwalk.py: rotating one secret. Who has to restart, and who has to be warned?
grep finds the manifests that name the secret. It cannot follow an env template that includes it, a chart that
bundles it, or a vault alias for it. A graph can: secret > bundle > service is one walk, and the owners table
(team, Slack channel, tier) is one SQL join, in the same SynapCores database.
usage: python3 secretwalk.py load manifests includes.csv deps.csv owners.csv
       python3 secretwalk.py rotate orders-db-password
  manifests/*.yaml  one per service: kind, name, then secretRef / envFrom / chart / vaultPath
  includes.csv      bundle,includes      (an env template, chart or vault alias, and the secret or bundle inside it)
  deps.csv          service,depends_on   (runtime calls: the left side sees errors when the right side restarts)
  owners.csv        service,team,channel,tier
"""
import csv, glob, json, os, sys, time, urllib.error, urllib.request

BASE = os.environ["SC_URL"]      # e.g. http://localhost:<port> of your SynapCores
TOKEN = os.environ["SC_TOKEN"]   # from POST /v1/auth/login


def run(q, tries=5):
    req = urllib.request.Request(BASE + "/v1/query/execute", method="POST",
                                 data=json.dumps({"sql": q, "database": "main"}).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            return json.load(r)["data"].get("rows", [])
    except urllib.error.HTTPError as e:  # server busy: wait a second, try again
        if tries > 1 and (e.code in (429, 503) or "retry" in e.read().decode().lower()):
            time.sleep(1)
            return run(q, tries - 1)
        raise


def load(mdir, includes, deps, owners):
    # what the bundles hold: the secret, or another bundle (an env template that includes an env template)
    bundles = {}
    for b, inc in csv.reader(open(includes)):
        bundles.setdefault(b, []).append(inc)
    for b, incs in bundles.items():
        for inc in incs:
            lab = "d11_Bundle" if inc in bundles else "d11_Secret"
            run(f'MERGE (a:{lab} {{name: "{inc}"}}) MERGE (b:d11_Bundle {{name: "{b}"}}) MERGE (a)-[:INCLUDED_IN]->(b)')
    # the manifests: a service reads a secret by name, or mounts a bundle (env template, chart, vault path)
    files = sorted(glob.glob(os.path.join(mdir, "*.yaml")))
    for f in files:
        kv = dict(l.strip().split(": ", 1) for l in open(f) if ": " in l)
        svc = kv["name"]
        if "secretRef" in kv:
            run(f'MERGE (s:d11_Secret {{name: "{kv["secretRef"]}"}}) MERGE (v:d11_Service {{name: "{svc}"}}) MERGE (s)-[:READ_BY]->(v)')
        else:
            b = kv.get("envFrom") or kv.get("chart") or kv.get("vaultPath")
            run(f'MERGE (b:d11_Bundle {{name: "{b}"}}) MERGE (v:d11_Service {{name: "{svc}"}}) MERGE (b)-[:MOUNTED_BY]->(v)')
    # who calls whom at runtime
    for a, b in csv.reader(open(deps)):
        run(f'MERGE (a:d11_Service {{name: "{a}"}}) MERGE (b:d11_Service {{name: "{b}"}}) MERGE (a)-[:DEPENDS_ON]->(b)')
    # the owners: a plain SQL table
    run("CREATE TABLE d11_owners (service TEXT PRIMARY KEY, team TEXT, channel TEXT, tier INTEGER)")
    rows = list(csv.reader(open(owners)))
    run("INSERT INTO d11_owners VALUES " + ",".join(f"('{s}', '{t}', '{c}', {tier})" for s, t, c, tier in rows))
    run("CREATE TABLE d11_restart (service TEXT, hops INTEGER, via TEXT)")
    run("CREATE TABLE d11_warn (service TEXT, restarts TEXT, via TEXT)")
    print(f"loaded {len(files)} manifests, {len(bundles)} bundles with includes, {len(rows)} owners")


# 1. the walk: every service the secret reaches in 1 to 6 hops, by name or through bundles inside bundles
WALK = """MATCH p = (s:d11_Secret {{name: '{secret}'}})-[:INCLUDED_IN|MOUNTED_BY|READ_BY*1..6]->(v:d11_Service)
RETURN v.name AS service, length(p) AS hops, [n IN nodes(p) | n.name] AS via"""

# 2. one SQL join: the walk against the owners table, tier 1 first
RESTART = """SELECT o.tier, r.service, o.team, o.channel, r.via
FROM d11_restart r JOIN d11_owners o ON o.service = r.service
ORDER BY o.tier, r.hops, r.service"""

1

u/Alternative_Pin9598 7h ago

secretwalk.py, part 2 of 2

# 3. the second walk: who depends, directly or through other services, on something that restarts
DOWNSTREAM = """MATCH (s:d11_Secret {{name: '{secret}'}})-[:INCLUDED_IN|MOUNTED_BY|READ_BY*1..6]->(r:d11_Service)
MATCH p = (w:d11_Service)-[:DEPENDS_ON*1..6]->(r)
RETURN w.name AS service, r.name AS restarts, [n IN nodes(p) | n.name] AS via"""

WARN = """SELECT o.tier, w.service, o.team, o.channel, w.via
FROM d11_warn w JOIN d11_owners o ON o.service = w.service
ORDER BY o.tier, w.service"""


def table(rows, last):
    print(f"  {'tier':<5} {'service':<21} {'team':<14} {'channel':<17} {last}")
    for tier, service, team, channel, via in rows:
        print(f"  {tier:<5} {service:<21} {team:<14} {channel:<17} {via}")


def rotate(secret):
    walk = run(WALK.format(secret=secret))
    byname = sorted(r[0] for r in walk if r[1] == 1)
    print(f"{secret} is named in {len(byname)} manifests (what grep finds): {', '.join(byname)}")
    shortest = {}  # the shortest chain to each service: the bundles between the secret and it
    for service, hops, via in sorted(walk, key=lambda r: r[1]):
        shortest.setdefault(service, (hops, " > ".join(via[1:-1]) or "by name"))
    run("DELETE FROM d11_restart")
    run("INSERT INTO d11_restart VALUES " + ",".join(f"('{s}', {h}, '{v}')" for s, (h, v) in shortest.items()))
    print(f"\ngraph walk from the secret, 1 to 6 hops: {len(shortest)} services get it. RESTART:\n")
    restart = run(RESTART)
    table(restart, "how it gets the secret")
    down = {}  # the services that call one of those, minus the ones that restart anyway (and paths through those)
    for service, restarts, via in run(DOWNSTREAM.format(secret=secret)):
        if service not in shortest and not any(n in shortest for n in via[1:-1]):
            down.setdefault(service, {})[restarts] = " > ".join(via[1:])
    run("DELETE FROM d11_warn")
    run("INSERT INTO d11_warn VALUES " + ",".join(f"('{s}', '{', '.join(sorted(v))}', '{', '.join(sorted(v.values()))}')" for s, v in down.items()))
    print(f"\n{len(down)} services depend on one of those. They do not restart, they see errors while it does. WARN:\n")
    warn = run(WARN)
    table(warn, "calls")
    channels = list(dict.fromkeys(r[3] for r in restart + warn))
    print(f"\nrestart {len(restart)} (grep found {len(byname)}), warn {len(warn)}; tell {len(channels)} channels: {', '.join(channels)}")


if __name__ == "__main__":
    if sys.argv[1] == "load":
        load(*sys.argv[2:6])
    else:
        rotate(sys.argv[2])

Sample files. manifests/<service>.yaml, 20 files of three lines: kind: Deployment, name: <service>, then the line after the colon here:

analytics-dash: envFrom: dash-env
auth-service: secretRef: auth-signing-key
cdn-purger: envFrom: web-env
checkout-web: envFrom: web-env
email-sender: secretRef: sendgrid-api-key
erp-bridge: envFrom: finance-env
fraud-scorer: vaultPath: kv/db/orders
inventory-sync: secretRef: orders-db-password
invoice-export: envFrom: batch-env
mobile-bff: envFrom: web-env
nightly-report: envFrom: batch-env
order-search-indexer: envFrom: orders-env
orders-api: secretRef: orders-db-password
orders-worker: secretRef: orders-db-password
partner-api: envFrom: partner-env
payments-gateway: chart: payments-chart
refund-service: envFrom: orders-env
shipping-labeler: envFrom: logistics-env
storefront: envFrom: web-env
support-console: envFrom: web-env

includes.csv (bundle,includes):

orders-env,orders-db-password
batch-env,orders-env
payments-chart,orders-db-password
kv/db/orders,orders-db-password

deps.csv (service,depends_on):

checkout-web,orders-api
storefront,checkout-web
mobile-bff,orders-api
mobile-bff,payments-gateway
mobile-bff,auth-service
partner-api,orders-api
support-console,refund-service
analytics-dash,nightly-report
shipping-labeler,inventory-sync
email-sender,orders-worker
erp-bridge,invoice-export
refund-service,payments-gateway
order-search-indexer,orders-api

owners.csv (service,team,channel,tier):

orders-api,orders,#orders-oncall,1
orders-worker,orders,#orders-oncall,1
inventory-sync,inventory,#inventory,2
refund-service,payments,#payments-oncall,1
order-search-indexer,search,#search,2
nightly-report,data-platform,#data-oncall,3
invoice-export,finance-eng,#finance-eng,2
payments-gateway,payments,#payments-oncall,1
fraud-scorer,risk,#risk-oncall,2
checkout-web,web,#web-oncall,1
storefront,web,#web-oncall,1
mobile-bff,mobile,#mobile,1
partner-api,partners,#partners,2
support-console,support-eng,#support-eng,3
analytics-dash,data-platform,#data-oncall,3
shipping-labeler,logistics,#logistics,2
email-sender,growth,#growth,3
erp-bridge,finance-eng,#finance-eng,2
auth-service,identity,#identity,1
cdn-purger,web,#web-oncall,3

Run:

grep -l orders-db-password manifests/*.yaml
python3 secretwalk.py load manifests includes.csv deps.csv owners.csv
python3 secretwalk.py rotate orders-db-password

Everything the script creates starts with d11_ (three node labels, three tables), easy to drop afterwards.