Make OpenArtifact policy application extensible

Move publisher manifests into a dedicated policies directory and mount them
through a separate Kustomize-generated ConfigMap. Apply all mounted YAML files
in filename order instead of hard-coding the WinGet manifest and seven objects.
Require a nonempty successful response for each manifest and fail the PostSync
hook on partial or malformed results. Keep SSO secret substitution separate.

Document registration, ordering and explicit revocation. New publishers require
only a policy file and a ConfigMap files entry, without Python or Job changes.

Validation: four Python unit tests passed, including arbitrary object counts,
manifest discovery and error handling. Rendered ConfigMaps and the PostSync Job
with kubectl kustomize; full Helm chart rendering and live application were not
performed.
This commit is contained in:
ab committed 2026-12-02 03:59:15 +02:00
1 parent 50e3e88387
commit 01b598a285
6 files changed
+150 -35

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
# OpenArtifact access policies
The Helm chart runs OpenArtifact. Kustomize packages the SSO configuration and
publisher policies into ConfigMaps. ArgoCD's PostSync Job applies them through
OpenArtifact's `/api/v1/admin/declarative/apply` API after each sync.
To register another publisher, add a regular `*.yaml` file directly inside
`policies/` and add its path to the `openartifact-policies` ConfigMap generator's
`files` list in `kustomization.yaml`. No Python or Job changes are required.
Kustomize includes the listed files in `openartifact-policies`; the Job
mounts them at `/policies` and applies YAML files in filename order. Group a
publisher's ServiceAccount, PermissionTargets and OIDCTrustPolicy in one manifest,
with the account first. Use globally unique object names; use filename prefixes
if manifests depend on one another.
Every manifest must return a nonempty list of successfully applied objects.
Any failure stops the Job, so ArgoCD reports the sync hook failure. There is no
fixed object count. Existing objects are reapplied on later syncs. Removing a
file or object from Git does not delete it from OpenArtifact: revoke obsolete
access explicitly on the server as well.
Scope permissions to the intended repository, package names and architectures.
Bind OIDC trust to the producer repository, tag/branch, workflow, event and
environment where applicable. Put real credentials in Kubernetes Secrets, never
in policy files. SSO client-secret substitution remains isolated to `sso.yaml`.
Run the local checks with:
```sh
python -m unittest discover -s k8s-ng/apps/openartifact/tests
kubectl kustomize --enable-helm k8s-ng/apps/openartifact
```
Rendering the complete application requires Helm and access to the chart registry.
+48 -34
View File
@@ -1,42 +1,56 @@
"""Apply SSO and all publisher manifests mounted by the GitOps PostSync job."""
import json
from http.cookiejar import CookieJar
from pathlib import Path
from urllib.request import HTTPCookieProcessor, Request, build_opener
server = "https://repo.hexor.cy"
cookies = CookieJar()
session = build_opener(HTTPCookieProcessor(cookies))
headers = {"Content-Type": "application/json", "Origin": server}
def post(path, body):
request = Request(server + "/api/v1/" + path, json.dumps(body).encode(), headers)
with session.open(request, timeout=30) as response:
return response.read()
manifest = Path("/config/sso.yaml").read_text()
credentials = Path("/credentials")
client_secret = (credentials / "client-secret").read_text()
post("auth/login", {"username": "admin", "password": (credentials / "admin-password").read_text()})
try:
headers["X-CSRF-Token"] = next(cookie.value for cookie in cookies if cookie.name == "oa_csrf")
def apply_manifest(post, path, **options):
result = json.loads(post("admin/declarative/apply", {
"manifest": manifest,
"force_secrets": True,
"secrets": {"OIDC_CLIENT_SECRET": client_secret},
"manifest": path.read_text(encoding="utf-8"), **options,
}))
[provider] = result["items"]
if provider["name"] != "keycloak" or provider["result"] != "applied":
raise RuntimeError("OpenArtifact did not apply the Keycloak provider")
print("Keycloak SSO provider applied")
publisher = json.loads(post("admin/declarative/apply", {
"manifest": Path("/config/winget-publisher.yaml").read_text(),
}))
items = publisher["items"]
if len(items) != 7 or any(item["result"] != "applied" for item in items):
raise RuntimeError("OpenArtifact did not apply the OpenArtifact package publisher policy")
print("OpenArtifact package publisher policy applied")
finally:
post("auth/logout", {})
items = result.get("items")
if not isinstance(items, list) or not items or any(
not isinstance(item, dict) or not item.get("name") or item.get("result") != "applied"
for item in items
):
raise RuntimeError(f"OpenArtifact did not apply every object in {path.name}")
print(f"Applied {path.name}: {len(items)} objects")
return items
def apply_policies(post, directory):
manifests = sorted(directory.glob("*.yaml"))
if not manifests:
raise RuntimeError(f"No policy manifests found in {directory}")
for path in manifests:
apply_manifest(post, path)
def main():
server = "https://repo.hexor.cy"
cookies = CookieJar()
session = build_opener(HTTPCookieProcessor(cookies))
headers = {"Content-Type": "application/json", "Origin": server}
def post(path, body):
request = Request(server + "/api/v1/" + path, json.dumps(body).encode(), headers)
with session.open(request, timeout=30) as response:
return response.read()
credentials = Path("/credentials")
client_secret = (credentials / "client-secret").read_text()
post("auth/login", {"username": "admin", "password": (credentials / "admin-password").read_text()})
try:
headers["X-CSRF-Token"] = next(cookie.value for cookie in cookies if cookie.name == "oa_csrf")
providers = apply_manifest(post, Path("/config/sso.yaml"), force_secrets=True,
secrets={"OIDC_CLIENT_SECRET": client_secret})
if [item["name"] for item in providers] != ["keycloak"]:
raise RuntimeError("OpenArtifact did not apply the Keycloak provider")
apply_policies(post, Path("/policies"))
finally:
post("auth/logout", {})
if __name__ == "__main__":
main()
+3 -1
View File
@@ -13,7 +13,9 @@ configMapGenerator:
files:
- sso.yaml
- apply-sso.py
- winget-publisher.yaml
- name: openartifact-policies
files:
- policies/winget-publisher.yaml
helmCharts:
- name: openartifact
+4
View File
@@ -33,8 +33,12 @@ spec:
limits: {memory: 64Mi}
volumeMounts:
- {name: config, mountPath: /config, readOnly: true}
- {name: policies, mountPath: /policies, readOnly: true}
- {name: credentials, mountPath: /credentials, readOnly: true}
volumes:
- name: policies
configMap:
name: openartifact-policies
- name: config
configMap:
name: openartifact-sso
@@ -0,0 +1,61 @@
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock
spec = importlib.util.spec_from_file_location("apply_sso", Path(__file__).resolve().parents[1] / "apply-sso.py")
apply = importlib.util.module_from_spec(spec)
spec.loader.exec_module(apply)
class ApplyPolicyTests(unittest.TestCase):
def test_discovers_added_manifests_and_accepts_any_positive_object_count(self):
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
(directory / "z-new.yaml").write_text("new policy", encoding="utf-8")
(directory / "a-existing.yaml").write_text("existing policies", encoding="utf-8")
(directory / "ignored.txt").write_text("not a policy", encoding="utf-8")
post = Mock(side_effect=[
json.dumps({"items": [{"name": str(i), "result": "applied"} for i in range(9)]}),
json.dumps({"items": [{"name": "new", "result": "applied"}]}),
])
apply.apply_policies(post, directory)
self.assertEqual([call.args for call in post.call_args_list], [
("admin/declarative/apply", {"manifest": "existing policies"}),
("admin/declarative/apply", {"manifest": "new policy"}),
])
def test_failed_or_malformed_response_stops_later_manifests(self):
for response in ({}, {"items": []}, {"items": {}}, {"items": [None]},
{"items": [{"name": "bad", "result": "failed"}]},
{"items": [{"name": "ok", "result": "applied"}, {"name": "bad", "result": "failed"}]}):
with self.subTest(response=response), tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
(directory / "a.yaml").write_text("first", encoding="utf-8")
(directory / "b.yaml").write_text("second", encoding="utf-8")
post = Mock(return_value=json.dumps(response))
with self.assertRaisesRegex(RuntimeError, "a.yaml"):
apply.apply_policies(post, directory)
post.assert_called_once()
def test_empty_directory_is_an_error(self):
with tempfile.TemporaryDirectory() as temp:
post = Mock()
with self.assertRaisesRegex(RuntimeError, "No policy manifests"):
apply.apply_policies(post, Path(temp))
post.assert_not_called()
def test_sso_secret_options_are_only_sent_for_sso(self):
with tempfile.TemporaryDirectory() as temp:
path = Path(temp) / "sso.yaml"
path.write_text("provider", encoding="utf-8")
post = Mock(return_value=json.dumps({"items": [{"name": "keycloak", "result": "applied"}]}))
apply.apply_manifest(post, path, force_secrets=True, secrets={"OIDC_CLIENT_SECRET": "fixture"})
self.assertEqual(post.call_args.args[1], {"manifest": "provider", "force_secrets": True,
"secrets": {"OIDC_CLIENT_SECRET": "fixture"}})
if __name__ == "__main__":
unittest.main()