Secrets & Policy Exercises
The first four exercises are small pieces of the logic inside Vault, CI runners, policy engines and SOPS, written as pure Python functions with the calls already in place. Run the starter first: it prints placeholder answers. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last two are real Vault and OPA sessions to fix.
Exercise 1: Evaluate a Vault policy
Topics: Policies
Return the capabilities a policy grants on a path. Rules: a trailing * matches any suffix; + matches exactly one path segment; if any matching rule has deny, the answer is ["deny"]; no match also means ["deny"]; otherwise an exact path (no * or +) wins over patterns, and among patterns the longest wins. Return capabilities sorted.
POLICY = {
"secret/data/linkly/*": ["read"],
"secret/data/linkly/admin": ["deny"],
"secret/data/+/shared": ["read", "list"],
"secret/data/linkly/config": ["read", "update"],
}
def matches(pattern, path):
# TODO: turn the pattern into a regex: "+" -> one segment, trailing "*" -> anything
return False
def capabilities(policy, path):
# TODO: collect matching rules, apply deny, then pick the most specific
return ["?"]
for path in ["secret/data/linkly/db", "secret/data/linkly/admin", "secret/data/billing/shared",
"secret/data/billing/db", "secret/data/linkly/config", "secret/data/a/b/shared"]:
print(f"{path:28} {capabilities(POLICY, path)}")secret/data/linkly/db ['?']
secret/data/linkly/admin ['?']
secret/data/billing/shared ['?']
secret/data/billing/db ['?']
secret/data/linkly/config ['?']
secret/data/a/b/shared ['?']
Expected output:
secret/data/linkly/db ['read']
secret/data/linkly/admin ['deny']
secret/data/billing/shared ['list', 'read']
secret/data/billing/db ['deny']
secret/data/linkly/config ['read', 'update']
secret/data/a/b/shared ['deny']Show solution
import re
def matches(pattern, path):
rx = re.escape(pattern).replace(r"\+", "[^/]+")
if rx.endswith(r"\*"):
rx = rx[:-2] + ".*"
return re.fullmatch(rx, path) is not None
def capabilities(policy, path):
hits = {pat: caps for pat, caps in policy.items() if matches(pat, path)}
if not hits or any("deny" in caps for caps in hits.values()):
return ["deny"]
exact = [p for p in hits if not p.endswith("*") and "+" not in p]
best = exact[0] if exact else max(hits, key=len)
return sorted(hits[best])secret/data/linkly/config matches both the glob and the exact rule; the exact rule wins, so the token may also update it. Real Vault's priority rules have more detail (position of the first wildcard, number of +), but deny-wins and most-specific-wins are the parts that matter in practice.
Exercise 2: Mask derived secret forms
Topics: How Secrets Leak
A CI runner masks only exact values. Make mask also hide the base64, URL-encoded and JSON-escaped forms of each secret.
import base64, urllib.parse, json
def variants(secret):
# TODO: return the set of forms to mask: the secret, its base64, URL-encoding (safe="") and JSON-escaped form
return {secret}
def mask(line, secrets):
for s in secrets:
for v in sorted(variants(s), key=len, reverse=True):
line = line.replace(v, "***")
return line
SECRETS = ["p@ss/w0rd", 'quote"me']
LOG = [
"password=p@ss/w0rd",
"b64=cEBzcy93MHJk",
"url=postgres://u:p%40ss%2Fw0rd@db/x",
'json={"token": "quote\\"me"}',
"nothing to hide here",
]
for line in LOG:
print(mask(line, SECRETS))password=***
b64=cEBzcy93MHJk
url=postgres://u:p%40ss%2Fw0rd@db/x
json={"token": "quote\"me"}
nothing to hide here
Expected output:
password=***
b64=***
url=postgres://u:***@db/x
json={"token": "***"}
nothing to hide hereShow solution
def variants(secret):
return {secret,
base64.b64encode(secret.encode()).decode(),
urllib.parse.quote(secret, safe=""),
json.dumps(secret)[1:-1]}This is what ::add-mask:: for derived values does by hand in GitHub Actions. It still can't catch every transformation, which is why the real fix is not printing secrets at all.
Exercise 3: A plan policy for open ports
Topics: Conftest on Terraform Plans
Report every security group being created or updated whose ingress rules open a sensitive port to 0.0.0.0/0. A rule covers a port if from_port <= port <= to_port. Report ports in ascending order per rule. Ignore deletions.
PLAN = {"resource_changes": [
{"address": "aws_security_group.db", "type": "aws_security_group", "change": {"actions": ["create"], "after": {
"ingress": [{"from_port": 5432, "to_port": 5432, "cidr_blocks": ["10.20.0.0/16"]},
{"from_port": 0, "to_port": 65535, "cidr_blocks": ["0.0.0.0/0"]}]}}},
{"address": "aws_security_group.web", "type": "aws_security_group", "change": {"actions": ["update"], "after": {
"ingress": [{"from_port": 443, "to_port": 443, "cidr_blocks": ["0.0.0.0/0"]},
{"from_port": 22, "to_port": 22, "cidr_blocks": ["0.0.0.0/0"]}]}}},
{"address": "aws_security_group.old", "type": "aws_security_group", "change": {"actions": ["delete"], "after": None}},
]}
SENSITIVE_PORTS = {22: "SSH", 3389: "RDP", 5432: "PostgreSQL", 6379: "Redis"}
def deny(plan):
out = []
# TODO: loop over resource_changes, skip non-SG and delete-only changes, check each ingress rule
return out
print("\n".join(deny(PLAN)) or "no violations")no violations
Expected output:
aws_security_group.db: SSH (22) open to 0.0.0.0/0
aws_security_group.db: RDP (3389) open to 0.0.0.0/0
aws_security_group.db: PostgreSQL (5432) open to 0.0.0.0/0
aws_security_group.db: Redis (6379) open to 0.0.0.0/0
aws_security_group.web: SSH (22) open to 0.0.0.0/0Show solution
def deny(plan):
out = []
for rc in plan["resource_changes"]:
if rc["type"] != "aws_security_group" or not ({"create", "update"} & set(rc["change"]["actions"])):
continue
for rule in rc["change"]["after"].get("ingress", []):
if "0.0.0.0/0" not in rule["cidr_blocks"]:
continue
for port, name in sorted(SENSITIVE_PORTS.items()):
if rule["from_port"] <= port <= rule["to_port"]:
out.append(f"{rc['address']}: {name} ({port}) open to 0.0.0.0/0")
return outThe "all ports" rule (0–65535) is the dangerous one: a check that only compares from_port == 5432 would miss it. In Rego the same logic is rule.from_port <= port; port <= rule.to_port. Note after is None for deletions, which is why they must be skipped first.
Exercise 4: Which SOPS rule applies?
Topics: SOPS for Teams
SOPS uses the first creation rule whose path_regex matches (re.search). Return the rule index and its recipients, or None and an error message. Then look at the output for envs/prod/shared.yaml: is that what the rule author wanted?
import re
RULES = [
{"path_regex": r"envs/prod/.*\.yamlquot;, "age": ["ci-prod", "breakglass"]},
{"path_regex": r"envs/.*/shared\.yamlquot;, "age": ["everyone"]},
{"path_regex": r"envs/dev/.*\.yamlquot;, "age": ["ada", "grace", "ci-dev"]},
]
def recipients(path):
# TODO: first matching rule wins
return None, "?"
for path in ["envs/prod/db.yaml", "envs/dev/db.yaml", "envs/dev/shared.yaml", "envs/prod/shared.yaml", "README.md"]:
idx, who = recipients(path)
print(f"{path:22} -> rule {idx}: {who}")envs/prod/db.yaml -> rule None: ?
envs/dev/db.yaml -> rule None: ?
envs/dev/shared.yaml -> rule None: ?
envs/prod/shared.yaml -> rule None: ?
README.md -> rule None: ?
Expected output:
envs/prod/db.yaml -> rule 0: ['ci-prod', 'breakglass']
envs/dev/db.yaml -> rule 2: ['ada', 'grace', 'ci-dev']
envs/dev/shared.yaml -> rule 1: ['everyone']
envs/prod/shared.yaml -> rule 0: ['ci-prod', 'breakglass']
README.md -> rule None: error: no matching creation ruleShow solution
def recipients(path):
for i, r in enumerate(RULES):
if re.search(r["path_regex"], path):
return i, r["age"]
return None, "error: no matching creation rule"envs/prod/shared.yaml hits the prod rule first, so "everyone" can't read it. If that was intended, fine; if not, move the shared rule above the prod rule. Order is policy: review .sops.yaml changes as carefully as IAM changes.
Exercise 5: The KV v2 policy that grants nothing
The CI token should read secret/linkly/db and list the keys under secret/linkly/, but every request is denied. Fix only the policy file so the session prints the password and the key list.
vault server -dev -dev-root-token-id=root -dev-listen-address=127.0.0.1:8200 > vault.log 2>&1 &
for i in $(seq 50); do vault status > /dev/null 2>&1 && break; sleep 0.2; done
export VAULT_TOKEN=root
vault kv put -mount=secret linkly/db password='c0rrect-h0rse' > /dev/null
vault kv put -mount=secret linkly/api-key value='k1' > /dev/null
cat > ci.hcl <<'HCL'
path "secret/linkly/*" {
capabilities = ["read", "list"]
}
HCL
vault policy write ci ci.hcl > /dev/null
CI=$(vault token create -policy=ci -field=token)
if VAULT_TOKEN=$CI vault kv get -mount=secret -field=password linkly/db > pw 2> /dev/null; then cat pw; echo; else echo "read: permission denied"; fi
if VAULT_TOKEN=$CI vault kv list -mount=secret -format=json linkly > keys 2> /dev/null; then jq -r '.[]' keys; else echo "list: permission denied"; firead: permission denied
list: permission denied
Expected output:
c0rrect-h0rse
api-key
dbShow solution
path "secret/data/linkly/*" {
capabilities = ["read"]
}
path "secret/metadata/linkly/*" {
capabilities = ["list"]
}KV v2 serves values under data/ and listings under metadata/. vault token capabilities $CI secret/data/linkly/db would have shown deny for the original policy before anyone ran the pipeline.
Exercise 6: The policy that never fires
Topics: Testing Policies with opa test, Rego: Iteration, Sets & Functions
The rule should deny Deployments with privileged containers, and its tests fail. Find the bug in policy/privileged.rego (not in the tests) and fix it so opa test passes.
mkdir -p policy && cd policy
cat > privileged.rego <<'REGO'
package k8s.privileged
deny contains msg if {
input.kind == "Deployment"
some c in input.spec.containers
c.securityContext.privileged == true
msg := sprintf("%s: container %q is privileged", [input.metadata.name, c.name])
}
REGO
cat > privileged_test.rego <<'REGO'
package k8s.privileged_test
import data.k8s.privileged
deployment(sc) := {"kind": "Deployment", "metadata": {"name": "linkly"},
"spec": {"template": {"spec": {"containers": [{"name": "app", "securityContext": sc}]}}}}
test_privileged_denied if {
privileged.deny == {"linkly: container \"app\" is privileged"} with input as deployment({"privileged": true})
}
test_unprivileged_allowed if {
count(privileged.deny) == 0 with input as deployment({"privileged": false})
}
REGO
opa test . 2>&1 | grep -E '^(data|PASS|FAIL)'data.k8s.privileged_test.test_privileged_denied: FAIL (508.068µs)
PASS: 1/2
FAIL: 1/2
Expected output:
PASS: 2/2Show solution
some c in input.spec.template.spec.containersinput.spec.containers is where a Pod keeps its containers; a Deployment has them under spec.template.spec. The wrong path is simply undefined, so the rule never fires and, without the test, every privileged Deployment would have passed. Note that the "allowed" test passed even with the bug: always test that a rule fires, not only that it stays quiet.
Test yourself
In Exercise 6, why did test_unprivileged_allowed pass even with the bug?
- The test was wrong
- A rule that never fires always produces an empty deny set, so 'no violations' tests can't detect it
- OPA skipped it
- privileged was false
In Exercise 1, what does secret/data/+/shared match?
secret/data/a/b/sharedsecret/data/billing/sharedsecret/data/shared- All of them