Repository navigation
feat(chart): add the foca-common library chart - #357
Conversation
Add a Helm library chart for FOCA apps, extracted from the chart of cloud-registry (version 3): the app Deployment, the config overlay ConfigMap, Service, Ingress or OpenShift Route, NetworkPolicies and an optional MongoDB with credentials from an existing Secret. Templates take the root context and the app settings (values key, databases, generated config), so that app charts keep their values structure. Includes a JSON schema of the values for app charts to copy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add a thin chart for the petstore example on top of the library chart, and pytest tests rendering it with helm template: snapshot tests of a few sets of values and tests of the behavior of the templates. The tests need Helm, so the default test paths exclude them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add a workflow that lints the library and petstore charts and runs their tests with a pinned Helm version. Exclude Helm templates and snapshots from check-yaml. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe how to build an app chart on the library chart: settings, templates, values and schema, deployment notes and development. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Install Gunicorn in the petstore image and serve the app with it via a WSGI app factory (wsgi.py), so that the image works with the thin chart; Docker Compose still runs the development server. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fail without config.db.host if the bundled MongoDB is disabled, with the parse error if the app settings are not valid YAML, and clearly if the values lack the mongodb map; do not panic on null security sections in the audience check. Make the pull policy of MongoDB configurable, and default the petstore chart to the locally built image (foca-petstore, IfNotPresent). Add tests of probes, grace periods, Gunicorn settings, Services and MongoDB settings, and document the Helm version of the snapshots. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pin a Gunicorn version that exists on PyPI, give the commands to build and load the petstore image, and document external MongoDB settings and the pull policy of MongoDB. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAdds a reusable, schema-validated Sequence diagram for config overlay and application startupsequenceDiagram
participant Helm
participant ConfigMap
participant Deployment
participant App
Helm->>ConfigMap: foca-common.configMap
Helm->>Deployment: foca-common.deployment
Deployment->>ConfigMap: Mount overlay.yaml
Deployment->>App: Set FOCA_CONFIG_OVERLAY
App->>ConfigMap: Read merged configuration
Helm->>Deployment: Set checksum/config annotation
Sequence diagram for optional bundled MongoDB provisioningsequenceDiagram
participant Helm
participant Secret
participant MongoDB
participant App
Helm->>MongoDB: foca-common.mongodbDeployment
Helm->>MongoDB: foca-common.mongodbInitScript
MongoDB->>Secret: Read root and app credentials
MongoDB->>MongoDB: createUser
Helm->>App: Configure MongoDB Service host
App->>MongoDB: Connect with MONGO_USERNAME and MONGO_PASSWORD
Flow diagram for thin app chart renderingflowchart TD
Values["App values and copied schema"] --> Settings["App settings: valuesKey, databases, generated config"]
Settings --> Calls["One template call per resource"]
Calls --> Validation["foca-common validation"]
Validation --> Render["Helm renders app and optional MongoDB manifests"]
Render --> Deploy["Kubernetes or OpenShift deployment"]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #357 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 24 24
Lines 1796 1796
=========================================
Hits 1796 1796
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="charts/foca-common/templates/_mongodb.tpl" line_range="151-154" />
<code_context>
+ // Create the app user with access to the app's databases only; FOCA puts
+ // the first database in the connection string, so the app authenticates
+ // against it.
+ db.getSiblingDB({{ first $databases | squote }}).createUser({
+ user: process.env.MONGO_APP_USERNAME,
+ pwd: process.env.MONGO_APP_PASSWORD,
+ roles: [{{ join ", " $roles }}],
+ });
+{{ end -}}
</code_context>
<issue_to_address>
**New databases lack user grants**
When an app adds a database after bundled MongoDB has initialized its persistent data directory, mongoDB runs the generated `createUser` script only for an empty data directory, so the existing app user keeps grants for the old database list and FOCA operations against the new database fail with authorization errors.
Ensure app-user grants are updated when the configured database list changes, including when MongoDB reuses an initialized data directory.
Also at `charts/foca-common/templates/_mongodb.tpl:138-139`.
</issue_to_address>
### Comment 2
<location path="charts/foca-common/templates/_deployment.tpl" line_range="59-62" />
<code_context>
+ value: {{ include "foca-common.gunicornArgs" . | quote }}
+ {{- end }}
+ {{- if $root.Values.mongodb.auth.enabled }}
+ {{- include "foca-common.mongodbSecretEnv" (dict "root" $root "vars" (dict
+ "MONGO_USERNAME" "username"
+ "MONGO_PASSWORD" "password"
+ )) | trim | nindent 8 }}
+ {{- end }}
+ ports:
</code_context>
<issue_to_address>
**Rotated credentials break MongoDB authentication**
When the app user's Secret password is changed after MongoDB has initialized and the app pods are subsequently restarted or rolled, the app Deployment reads the updated password from the Secret, but the bundled MongoDB user retains the password set when its data directory was empty; after the app pods restart, their new credentials do not authenticate and database operations fail.
Provide and document a coordinated credential-rotation procedure that updates the persisted MongoDB user before rolling the app pods.
Also at `charts/foca-common/templates/_mongodb.tpl:128-151`.
</issue_to_address>
### Comment 3
<location path="charts/foca-common/templates/_deployment.tpl" line_range="79-84" />
<code_context>
+ # (no authentication, no database access)
+ # Up to 5 minutes are allowed for the start before liveness checks
+ startupProbe:
+ httpGet:
+ path: {{ $values.probePath | quote }}
+ port: 8080
+ periodSeconds: 10
+ timeoutSeconds: 5
+ failureThreshold: 30
+ readinessProbe:
+ httpGet:
+ path: {{ $values.probePath | quote }}
+ port: 8080
+ periodSeconds: 10
+ timeoutSeconds: 5
+ failureThreshold: 3
+ livenessProbe:
+ httpGet:
</code_context>
<issue_to_address>
**Database outages leave pods ready**
When mongoDB is unavailable after the app pod starts, the readiness probe requests the configured UI path, which does not access MongoDB, so Kubernetes keeps routing traffic to the app while its database is unavailable; database-dependent requests fail instead of the pod being removed from Service endpoints.
Use a readiness check that reflects the app's ability to serve database-dependent traffic, or document and implement an explicit degraded-service policy.
</issue_to_address>
### Comment 4
<location path="charts/foca-common/templates/_mongodb.tpl" line_range="151" />
<code_context>
+ // Create the app user with access to the app's databases only; FOCA puts
+ // the first database in the connection string, so the app authenticates
+ // against it.
+ db.getSiblingDB({{ first $databases | squote }}).createUser({
+ user: process.env.MONGO_APP_USERNAME,
+ pwd: process.env.MONGO_APP_PASSWORD,
</code_context>
<issue_to_address>
**Interrupted MongoDB bootstrap stays broken**
When the MongoDB pod is terminated after initializing its data directory but before `createUser` completes, mongoDB restarts with a non-empty data directory and skips its first-start init scripts, leaving the app user absent; the app then fails authentication without any chart mechanism to recreate the user.
Provision the app user through an idempotent reconciliation step that runs independently of MongoDB's empty-directory initialization scripts.
</issue_to_address>
### Comment 5
<location path="charts/foca-common/templates/_deployment.tpl" line_range="58" />
<code_context>
+ - name: GUNICORN_CMD_ARGS
+ value: {{ include "foca-common.gunicornArgs" . | quote }}
+ {{- end }}
+ {{- if $root.Values.mongodb.auth.enabled }}
+ {{- include "foca-common.mongodbSecretEnv" (dict "root" $root "vars" (dict
+ "MONGO_USERNAME" "username"
</code_context>
<issue_to_address>
**Missing auth settings crash rendering**
When `mongodb` is present but `mongodb.auth` is omitted or set to null, the templates dereference `mongodb.auth.enabled` without checking that `mongodb.auth` exists, so Helm aborts rendering with a nil-pointer error instead of a clear validation message.
Require and validate the `mongodb.auth` map before rendering, or make the templates safely handle its absence.
Also at `charts/foca-common/templates/_mongodb.tpl:48`, `charts/foca-common/templates/_mongodb.tpl:131`.
</issue_to_address>
### Comment 6
<location path="charts/foca-common/templates/_helpers.tpl" line_range="138-142" />
<code_context>
+{{- fail (printf "the app and MongoDB resources would both be named %s: choose a fullnameOverride that does not end in -mongodb" $fullname) -}}
+{{- end -}}
+{{- if not (include "foca-common.mongodbEnabled" .root) -}}
+{{- $db := get (.root.Values.config | default dict) "db" -}}
+{{- $host := and (kindIs "map" $db) (get $db "host") -}}
+{{- if not (and (kindIs "string" $host) (trim $host)) -}}
+{{- fail "config.db.host must be set to the host of the external MongoDB if mongodb.enabled is false" -}}
+{{- end -}}
+{{- end -}}
+{{- if .settings.requireAudience -}}
</code_context>
<issue_to_address>
**Generated config is ignored**
When an app chart supplies `db.host`, `security.auth.audience`, or `server.max_content_length` through its generated settings config instead of the `config` values, `validate`, `checkAudience`, and `maxContentLength` read `.Values.config` but not `.settings.config`, even though `configOverlay` merges both. A chart that generates an external database host or token audience in its settings fails rendering, and a generated body-size limit is missing from the ingress annotation, so the ingress controller can reject requests the app accepts.
Have these checks derive their inputs from the effective merged overlay, including `.settings.config` and user values.
Also at `charts/foca-common/templates/_helpers.tpl:160-173`, `charts/foca-common/templates/_helpers.tpl:249-256`.
</issue_to_address>
### Comment 7
<location path="charts/foca-common/templates/_helpers.tpl" line_range="59" />
<code_context>
+{{- define "foca-common.labels" -}}
+helm.sh/chart: {{ printf "%s-%s" .root.Chart.Name .root.Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
+{{ include "foca-common.selectorLabels" . }}
+app.kubernetes.io/version: {{ .root.Chart.AppVersion | quote }}
+app.kubernetes.io/managed-by: {{ .root.Release.Service }}
+{{- end -}}
</code_context>
<issue_to_address>
**Build metadata breaks resource labels**
When .Chart.AppVersion contains SemVer build metadata (`+...`), `foca-common.labels` emits `.root.Chart.AppVersion` unchanged as `app.kubernetes.io/version`; Kubernetes rejects label values containing `+`, so installs or upgrades using SemVer build metadata fail when the API server validates the resources.
Replace `+` with `_` in `.root.Chart.AppVersion` before emitting the label.
</issue_to_address>
### Comment 8
<location path="examples/petstore/chart/values.yaml" line_range="60" />
<code_context>
+ https:
+ # Request a certificate from cert-manager (via `issuer`, a
+ # ClusterIssuer) and serve HTTPS
+ enabled: false
+ issuer: letsencrypt-prod
+ # NetworkPolicy allowing connections to the app only from `ingressFrom`
</code_context>
<issue_to_address>
**Notes advertise unavailable HTTPS**
When the app is exposed through the default Ingress with HTTPS disabled, `NOTES.txt` displays an `https://` URL while the Ingress has no TLS configuration, so users following the link encounter a TLS error instead of the app.
Make the displayed URL scheme reflect whether HTTPS is enabled.
</issue_to_address>
### Comment 9
<location path="charts/foca-common/tests/test_templates.py" line_range="373" />
<code_context>
+def test_gunicorn_extra_args_quoted(render: Callable[..., Docs]) -> None:
+ docs = render("--set-json", 'petstore.gunicorn.extraArgs=["--access-logfile", "-"]')
+ args = _env(_container(docs))["GUNICORN_CMD_ARGS"]
+ assert args.endswith(" '--access-logfile' '-'")
+
+
</code_context>
<issue_to_address>
**Extra arguments can replace defaults**
When `petstore.gunicorn.extraArgs` is nonempty and the rendered command contains the quoted extras but drops the configured options, `test_gunicorn_extra_args_quoted` checks only the suffix, so `GUNICORN_CMD_ARGS` can omit the configured worker and timeout options whenever extra arguments are set and still pass; the app then runs with Gunicorn defaults.
Assert the complete expected command, including the configured options and the quoted extras.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 9 findings to address first, and the chart provisions an authenticated MongoDB and a PVC for app data; uninstalling a release removes the PVC, and whether the underlying data survives depends on the storage class. Reverting the chart cannot restore data already deleted or recover access changes made in a deployed cluster.
Blocking findings: charts/foca-common/templates/_mongodb.tpl:154, charts/foca-common/templates/_deployment.tpl:62, charts/foca-common/templates/_deployment.tpl:84, charts/foca-common/templates/_mongodb.tpl:151, charts/foca-common/templates/_deployment.tpl:58, and 4 more
Derive the external MongoDB host, audience and body size checks from the merged overlay (generated and values config), require the mongodb.auth map, strip build metadata from the version label, note missing TLS in the petstore notes, and document the limits of the MongoDB init script (Sourcery review). Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # .pre-commit-config.yaml # pyproject.toml
Add docstrings and return types to the chart tests and justify the subprocess call, as the shared ruff standard (#358) requires. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds
foca-common, a Helm library chart for FOCA apps (charts/foca-common), extracted from cloud-registry's chart (v3), so that cloud-registry (elixir-cloud-aai/cloud-registry#158), proTES and other apps can use thin charts over one implementation.Deployment(non-root security contexts with OpenShift ID handling, read-only root FS with/tmpemptyDir, probes,preStopdelay,enableServiceLinks: false, optional Gunicorn settings viaGUNICORN_CMD_ARGS), config overlayConfigMap(FOCA_CONFIG_OVERLAY,checksum/configannotation),Service,Ingress(cert-manager, ingress-nginx body size) or OpenShiftRoute, appNetworkPolicy(opt-in,ingressFrom), and an optional MongoDB (Deployment,Service, PVC, init script creating the app user,NetworkPolicyenabled by default, credentials fromexistingSecret); external MongoDB withmongodb.enabled: false.(dict "root" . "settings" ...), where the app chart's settings (valuesKey, databases, generated config, body size limit, audience requirement) are a small YAML helper. This keeps each app's values structure: the app's container values live under its own key (e.g.cloudRegistry).app-values.schema.json(with$defs) for app charts to copy asvalues.schema.json; a test keeps the petstore copy in sync.examples/petstore/chart); the petstore image now serves the app with Gunicorn (wsgi.py), Docker Compose still runs the dev server.charts/foca-common/tests(Helm convention: tests inside the chart dir, excluded by.helmignore): snapshot tests of 4 sets of values plus behavior tests of the templates (92 tests, ruff line length 88); excluded from the package's defaulttestpaths.charts.yml(lint both charts, checkChart.lock, run the chart tests with Helm v3.22.1 pinned). Separate file to avoid conflicts withchecks.ymlchanges in flight.docs/helm-chart.md), linked from the Kubernetes section of the deployment guide.Split: the kind install test (chart-testing) and the GHCR release workflow on
chart-v*tags moved to #356 (follow-up PR stacked on this one); #350's body was updated accordingly.cloud-registry litmus test
A thin cloud-registry chart over the library (cloud-registry's
deployment/with one-line templates, its ownvalidatechecks for removed keys, legacy releases and the admin mapping, and settingsvaluesKey: cloudRegistry,maxContentLength: 1048576,requireAudience: true,mongodb.databases: [serviceStore], generatedcustom.endpoints.service) renders the same manifests as cloud-registry's chart for its CI values and 22 variations (no auth, Route, OpenShift, HTTPS, annotations incl.null, network policies, Gunicorn args, name overrides, tmp size limits,preStopSleepSeconds: 0, body size,custom: null/server: null, image tag/digest, db port, audience disabled, ...), including thechecksum/configvalue. Only comments differ: one YAML comment in the Deployment, and the JS comment in the MongoDB init script (it now describes several databases), which changes the init-script ConfigMap's data text but not its behavior. The same 16 failure cases fail in both (messages are app-neutral now, withoutdeployment/README.mdreferences).Verification
pytest charts/foca-common/tests(Helm v3.22.1): 92 passedhelm lint --strict charts/foca-common;helm lint --strict examples/petstore/chart -f examples/petstore/chart/ci/test-values.yaml: passedpytest -m "not mongodb"(package tests,testpaths = ["tests"]): 1036 passedruff check,ruff format --check: passedmkdocs build --strict: passedactionlint .github/workflows/charts.yml: passedhelm package charts/foca-common: contains only Chart.yaml, values.yaml, templates, .helmignore and the schemaintegrationjob ofchecks.ymlin CIdevwith the shared ruff standard, style: adopt the shared ruff standard #358, and Python 3.10 dropped, build!: drop Python 3.10 support #360; the chart tests got docstrings for it), incl. codecov and the Sourcery re-review; all 9 Sourcery threads answered and resolvedDeclined review findings
Snapshot comparison as parsed YAML instead of raw text (quality reviewer): kept raw, as snapshots are meant to catch any change of the output, incl. comments and whitespace; the Helm version is pinned in CI and documented, and the failure message says how to update.
paths:filter forcharts.yml(quality reviewer): a workflow-level filter makes required checks hang on other PRs; the job is short.Replacing the
requiredflag of the test helpers (quality reviewer): kept; it is explicit and used in a few tests only.Sourcery: app-user grants for databases added later, password rotation and an interrupted first MongoDB start (init scripts only run on an empty data directory): documented in the deployment notes (manual
mongoshsteps) rather than adding a reconciliation job, keeping cloud-registry's behavior.Sourcery: readiness probe without database access: deliberate, as in cloud-registry (a MongoDB outage shouldn't remove all app pods from the Service).
Open questions
None.
Closes #350
🤖 Generated with Claude Code