CJVT updates August and September 2026
This commit is contained in:
@@ -61,6 +61,54 @@ CONCORDANCER_LISTEN_PORT=3003
|
||||
# The origin, where the portal will be made available.
|
||||
URL_ORIGIN="https://mywebportal.com"
|
||||
|
||||
# OIDC/SSO federation with the University of Ljubljana (backed by Microsoft Entra ID). Register
|
||||
# the portal as a confidential OIDC client in the target environment's University of
|
||||
# Ljubljana/Entra app registration, with redirect URI "${URL_ORIGIN}/users/oidc/callback", then
|
||||
# fill in the real values below. Not used in dev - dev/docker-compose.yml instead derives dev's
|
||||
# OIDC_UNI_LJ_* values automatically from AUTHENTIK_OIDC_CLIENT_ID/_SECRET further down this file.
|
||||
OIDC_UNI_LJ_CLIENT_ID="changeme"
|
||||
OIDC_UNI_LJ_CLIENT_SECRET="changeme"
|
||||
OIDC_UNI_LJ_DISCOVERY_URL="https://login.microsoftonline.com/<tenant-id>/v2.0/.well-known/openid-configuration"
|
||||
|
||||
# Container image registry prefix, read only by docker-compose.prod.yml.
|
||||
# Leave empty for a local `up --build` (images get a local name); for a registry-based CI/CD
|
||||
# deploy set it to <gitea-host>/<owner-lowercase>, e.g. gitea.example.tld/myorg. The image tag is
|
||||
# not set here — the deploy wrapper exports IMAGE_TAG per deploy.
|
||||
REGISTRY=""
|
||||
|
||||
|
||||
# Development only settings (not used in production)
|
||||
MAILDEV_WEB_GUI_PORT=3001
|
||||
|
||||
# Throwaway Authentik OIDC Identity Provider, used only for local SSO/OIDC login testing.
|
||||
# Started with `docker compose --profile develop-idp up -d`. See dev/authentik/README.md.
|
||||
# It stands in for the single real University of Ljubljana OIDC federation ('uni_lj' in the
|
||||
# auth_provider enum) - it is not a production identity provider and none of its state is meant
|
||||
# to be kept.
|
||||
|
||||
# Exposed on host's localhost to reach the Authentik admin UI and the test IdP's login pages.
|
||||
AUTHENTIK_LISTEN_PORT=9000
|
||||
# Used only by Authentik's own internal Postgres database - a separate, throwaway database
|
||||
# dedicated to this test IdP, not the portal's own database.
|
||||
AUTHENTIK_POSTGRES_PASSWORD="weak_authentik_postgres_password"
|
||||
# Used by Authentik for its own cookie signing/encryption and unique user IDs. Generate a real
|
||||
# random 50+ char value for anything beyond throwaway local testing, e.g.:
|
||||
# openssl rand -base64 60 | tr -d '\n'
|
||||
AUTHENTIK_SECRET_KEY="weak_authentik_secret_key_please_generate_a_real_one"
|
||||
|
||||
# Credentials for Authentik's own built-in "akadmin" superuser, created automatically on first
|
||||
# startup (Authentik's non-interactive/automated-install feature). Used to log into the Authentik
|
||||
# admin UI at http://localhost:${AUTHENTIK_LISTEN_PORT}/if/admin/ - unrelated to the portal's own
|
||||
# PORTAL_ADMIN_INITIAL_EMAIL/PASSWORD above, which is a completely separate account/app.
|
||||
AUTHENTIK_BOOTSTRAP_EMAIL="admin@authentik.test"
|
||||
AUTHENTIK_BOOTSTRAP_PASSWORD="weak_authentik_admin_password"
|
||||
# API token for the akadmin user, also created on first startup. Not needed for manual UI use;
|
||||
# documented here in case future scripted setup/debugging needs direct Authentik API access.
|
||||
AUTHENTIK_BOOTSTRAP_TOKEN="weak_authentik_bootstrap_api_token"
|
||||
|
||||
# Fixed OIDC client credentials for the single University-of-Ljubljana-stand-in test application
|
||||
# that the blueprint in dev/authentik/blueprints/ registers in Authentik. Being dev-only throwaway
|
||||
# values for a testing IdP, committing them is fine (same "weak_" pattern as EXPRESS_SECRET
|
||||
# above). The express-side OIDC client needs these two values (see OIDC_UNI_LJ_* above).
|
||||
AUTHENTIK_OIDC_CLIENT_ID="weak_uni_lj_test_client_id"
|
||||
AUTHENTIK_OIDC_CLIENT_SECRET="weak_uni_lj_test_client_secret"
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# Authentik — throwaway local OIDC Identity Provider
|
||||
|
||||
This directory holds a throwaway [Authentik](https://goauthentik.io/) instance, added to the dev
|
||||
Docker Compose stack purely for **local testing of SSO/OIDC login**. It stands in for the single
|
||||
real external identity federation the portal integrates with — the **University of Ljubljana**
|
||||
(itself backed by Microsoft Entra ID) — which in the portal's schema is the one non-`local` value
|
||||
of the `auth_provider` enum: `uni_lj`.
|
||||
|
||||
This is infrastructure/dev-setup only. For the bigger picture of running the portal locally, see
|
||||
the main [README](../../README.md). **Wiring the express app itself up as an OIDC client against
|
||||
this (or the real University of Ljubljana) is a separate, later task** — nothing here touches
|
||||
`express/`.
|
||||
|
||||
> **Note:** This Authentik instance, its database, and every seeded user are throwaway. Nothing
|
||||
> here is meant to be backed up, migrated, or taken into production.
|
||||
|
||||
## What's here
|
||||
|
||||
- `blueprints/uni-lj-stand-in.yaml` — a declarative [Authentik blueprint](https://docs.goauthentik.io/customize/blueprints/)
|
||||
that, on every startup, seeds: one OIDC Provider + Application
|
||||
(`Univerza v Ljubljani (test stand-in)`), two custom claim (scope) mappings restricted to the
|
||||
business-relevant claims the University of Ljubljana/Entra actually sends — `email`, `name`,
|
||||
`preferred_username` on the ID token, `given_name`, `family_name`, `picture` via `/userinfo`
|
||||
(plus `sub`, which authentik always includes automatically) — and three test users (see below).
|
||||
|
||||
## Bringing it up
|
||||
|
||||
This is behind the `develop-idp` Docker Compose profile, so it's off by default:
|
||||
|
||||
docker compose --profile develop-idp up -d
|
||||
|
||||
(Combine with other profiles as needed, e.g. `docker compose --profile develop-idp --profile develop-concordancer up -d --build` if you're also working on the concordancer.)
|
||||
|
||||
First startup takes a little longer than the rest of the stack: Authentik runs its own database
|
||||
migrations and then applies the blueprint in `blueprints/`. Watch it with:
|
||||
|
||||
docker compose logs -f authentik-server authentik-worker
|
||||
|
||||
> **Note:** the blueprint is re-applied automatically roughly every 60 minutes, on container
|
||||
> restart, and whenever the blueprint file changes — so if you ever poke at a seeded provider,
|
||||
> application, mapping, or user through the admin UI, expect your changes to be silently reverted.
|
||||
> Treat that as a feature: it's the reset mechanism (see _Resetting test data_ below).
|
||||
|
||||
## Reaching the admin UI
|
||||
|
||||
Once up, the Authentik admin UI is at `http://localhost:${AUTHENTIK_LISTEN_PORT}` (default
|
||||
`9000`, from the root `.env`) — e.g. `http://localhost:9000/if/admin/`.
|
||||
|
||||
Log in with the bootstrap admin account, created automatically on first startup from the root
|
||||
`.env`:
|
||||
|
||||
| | value (from `.env`) |
|
||||
| -------- | ------------------------------------------------------------------------ |
|
||||
| Email | `AUTHENTIK_BOOTSTRAP_EMAIL` (default `admin@authentik.test`) |
|
||||
| Password | `AUTHENTIK_BOOTSTRAP_PASSWORD` (default `weak_authentik_admin_password`) |
|
||||
|
||||
This account is Authentik's own superuser — unrelated to the portal's own
|
||||
`PORTAL_ADMIN_INITIAL_EMAIL`/`PORTAL_ADMIN_INITIAL_PASSWORD` admin account, which is a completely
|
||||
separate application.
|
||||
|
||||
## The registered test application
|
||||
|
||||
- **Application slug:** `uni-lj-test`
|
||||
- **Redirect URI:** `http://localhost:${EXPRESS_LISTEN_PORT}/users/oidc/callback` (the portal's
|
||||
planned generic OIDC callback route — provider selection is carried via session, not the URL)
|
||||
- **Client ID / secret:** `AUTHENTIK_OIDC_CLIENT_ID` / `AUTHENTIK_OIDC_CLIENT_SECRET` in `.env`
|
||||
(fixed, non-secret dev defaults — safe to commit, same pattern as `EXPRESS_SECRET`)
|
||||
- **Scopes to request:** `openid email profile`
|
||||
- **Discovery document:**
|
||||
|
||||
- from your host/browser: `http://localhost:${AUTHENTIK_LISTEN_PORT}/application/o/uni-lj-test/.well-known/openid-configuration`
|
||||
- from inside another container on the compose network (e.g. the future express OIDC client):
|
||||
`http://authentik-server:9000/application/o/uni-lj-test/.well-known/openid-configuration`
|
||||
|
||||
These are two different hosts on purpose: the authorization/redirect legs happen in the user's
|
||||
browser (needs the `localhost` URL), while token/JWKS/userinfo calls happen server-to-server
|
||||
(can use the internal `authentik-server` compose hostname). The future express-side OIDC client
|
||||
task will need to account for this split.
|
||||
|
||||
Only one provider/application is registered, matching the single `uni_lj` value in the
|
||||
portal's `auth_provider` enum — this is not meant to model multiple external IdPs.
|
||||
|
||||
## Test users
|
||||
|
||||
All seeded users share the password **`IdpTest123!`** (log in with it on Authentik's own login
|
||||
page during the OIDC redirect flow — this is _not_ a portal password).
|
||||
|
||||
| Authentik username | Claims sent (ID token) / userinfo | Portal-side scenario it exercises |
|
||||
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ana.novak` | `name="Novak, Ana"`, `email=ana.novak@ff.uni-lj.si`, `preferred_username=novaka@ff.uni-lj.si` / userinfo: `given_name=Ana`, `family_name=Novak`, `picture=<Graph API constant>` | **(A) Brand new user, all claims present.** No pre-existing local account needed — log in via SSO, review the read-only data on `/users/create-profile`, and confirm to create the new portal account exactly as shown (nothing on that page is editable). |
|
||||
| `berta.kolar.idp` | `name="Kolar, Berta"`, `email=berta.kolar@fri.uni-lj.si`, `preferred_username=kolarb@fri.uni-lj.si` / userinfo: `given_name=Berta`, `family_name=Kolar`, `picture=<Graph API constant>` | **(B) Email matches an existing LOCAL account → account conversion.** See below — you must register a matching local account first. Confirming with that account's password permanently overwrites its username/first/last name with the IdP data and removes its password — sign-in from then on is SSO-only. |
|
||||
| `brez.imena` | `email=brez.imena@fri.uni-lj.si`, `preferred_username=brez.imena@fri.uni-lj.si` — **`given_name`/`family_name`/`name` absent** | **(C) Missing given_name/family_name claims → account creation/conversion is refused.** The claims are entirely absent from the ID token/userinfo response (not blank strings) — since there's nothing to review or persist, the portal shows a clear error and never renders a create/convert page. |
|
||||
|
||||
> **Note on claim placement:** the real University of Ljubljana/Entra ID token never carries
|
||||
> `given_name`/`family_name`/`picture` — only the `/userinfo` endpoint does (`name` and
|
||||
> `preferred_username`, by contrast, _are_ on the real ID token). Authentik has no per-field way to
|
||||
> split claims between the ID token and userinfo response — a single provider-level toggle either
|
||||
> includes everything in both, or restricts the ID token to bare-minimum standard fields (which
|
||||
> would also strip `email`/`preferred_username`, breaking parity there). This blueprint leaves that
|
||||
> toggle at its default (`include_claims_in_id_token: true`), so Authentik's ID token ends up a
|
||||
> harmless superset of the real one — it also carries `given_name`/`family_name`/`picture`. This is
|
||||
> intentional and documented, not a bug: the app code (`express/middleware/auth.js`) only ever reads
|
||||
> `given_name`/`family_name` from the `/userinfo` response, never from ID-token claims, so the extra
|
||||
> keys in Authentik's ID token are inert.
|
||||
|
||||
> **Note:** there is no seeded/default local user in this app's dev DB — registration is always
|
||||
> manual, via the normal `/register` flow. So for scenario B, before testing SSO login as
|
||||
> `berta.kolar.idp`, first manually register a local portal account with email exactly
|
||||
> `berta.kolar@fri.uni-lj.si` (any other field can be anything you like), then log in via SSO as
|
||||
> `berta.kolar.idp` and confirm the portal lands on `/users/convert-account`, showing that local
|
||||
> account's current username alongside the (locked) IdP-derived data. Confirming with that local
|
||||
> account's password converts it: username/first/last name are overwritten with the IdP data, its
|
||||
> password is removed, and a subsequent local-password login attempt should fail with the usual
|
||||
> "created via University of Ljubljana, no password" message.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
> **Note:** On a genuinely first-ever startup (empty `authentik-postgres-data` volume), the custom
|
||||
> blueprint's very first apply attempt can race against Authentik's own built-in self-signed
|
||||
> certificate being created (the blueprint's OIDC provider references that certificate as its
|
||||
> signing key) — if the blueprint applies first, that one attempt fails and the provider ends up
|
||||
> without a working configuration. Authentik retries blueprints roughly every 60 minutes on its
|
||||
> own, but you don't need to wait: just re-apply it manually once, which always succeeds once the
|
||||
> certificate exists (by then, well under a minute after startup):
|
||||
>
|
||||
> docker compose --profile develop-idp exec authentik-worker ak apply_blueprint /blueprints/custom/uni-lj-stand-in.yaml
|
||||
>
|
||||
> You can confirm whether this happened via the admin UI (System → Blueprints) or the API:
|
||||
>
|
||||
> curl -s -H "Authorization: Bearer ${AUTHENTIK_BOOTSTRAP_TOKEN}" \
|
||||
> "http://localhost:${AUTHENTIK_LISTEN_PORT}/api/v3/managed/blueprints/?search=Ljubljana" \
|
||||
> | grep -o '"status": *"[a-z]*"'
|
||||
>
|
||||
> A `"successful"` status means it's fine; `"error"` means run the manual re-apply above.
|
||||
|
||||
## Resetting test data
|
||||
|
||||
Because the blueprint uses `state: present`, Authentik reconciles all of the above back to these
|
||||
exact values automatically (on restart, on blueprint file changes, and roughly every 60 minutes
|
||||
regardless). So for most purposes, just wait or restart:
|
||||
|
||||
docker compose --profile develop-idp restart authentik-server authentik-worker
|
||||
|
||||
For a full wipe (new admin bootstrap, fresh database, blueprint re-applied from scratch):
|
||||
|
||||
docker compose --profile develop-idp down
|
||||
docker volume rm terminoloski_portal_authentik-postgres-data terminoloski_portal_authentik-data
|
||||
docker compose --profile develop-idp up -d
|
||||
|
||||
(Adjust the volume name prefix if your Compose project name differs from the directory name.)
|
||||
|
||||
## Tearing it down
|
||||
|
||||
docker compose --profile develop-idp down
|
||||
|
||||
This only stops/removes the `authentik-postgres`, `authentik-server` and `authentik-worker`
|
||||
containers — it never touches the portal's own `postgres`/`express`/etc. services or data.
|
||||
@@ -0,0 +1,166 @@
|
||||
version: 1
|
||||
metadata:
|
||||
name: University of Ljubljana test stand-in - provider, application, claim mappings and test users
|
||||
labels:
|
||||
blueprints.goauthentik.io/description: |
|
||||
Throwaway local Identity Provider setup for the Terminoloski portal's dev stack. Registers
|
||||
ONE OIDC provider + application standing in for the single real University of Ljubljana/
|
||||
Entra ID federation (the portal's `auth_provider` enum only ever has one external value:
|
||||
'uni_lj'), whose claim set is deliberately restricted to the business-relevant fields the
|
||||
University of Ljubljana actually sends: sub, email, name, preferred_username (ID token) and
|
||||
given_name, family_name, picture (userinfo) - deliberately NOT Microsoft/Entra-proprietary
|
||||
protocol claims (rh, aud, exp, iat, iss, nbf, oid, sid, tid, uti, ver), which app code never
|
||||
reads and which authentik already has its own standard-OIDC equivalents for. authentik has
|
||||
no way to split claims between the ID token and userinfo per-field, so (with
|
||||
include_claims_in_id_token left at its default true) authentik's ID token ends up a harmless
|
||||
superset of the real Entra one (it also carries given_name/family_name/picture) - see
|
||||
dev/authentik/README.md. See dev/authentik/README.md for what each seeded test user is for.
|
||||
entries:
|
||||
# --- Claim (scope) mappings -------------------------------------------------------------
|
||||
# authentik's own built-in "email"/"profile" scopes emit extra claims (email_verified,
|
||||
# nickname, groups) that the real University of Ljubljana/Entra federation does NOT send in
|
||||
# this combination. These two replace them for this provider only, so dev testing matches
|
||||
# production claims exactly. (name and picture ARE now included deliberately, in real-Entra
|
||||
# shape - see below - unlike authentik's own defaults, which format them differently.)
|
||||
- model: authentik_providers_oauth2.scopemapping
|
||||
id: uni-lj-scope-email
|
||||
state: present
|
||||
identifiers:
|
||||
name: "Univerza v Ljubljani test mapping: email"
|
||||
attrs:
|
||||
name: "Univerza v Ljubljani test mapping: email"
|
||||
scope_name: email
|
||||
description: "Only 'email' - no email_verified (the University of Ljubljana/Entra doesn't send it either)."
|
||||
expression: |
|
||||
return {
|
||||
"email": request.user.email,
|
||||
}
|
||||
|
||||
- model: authentik_providers_oauth2.scopemapping
|
||||
id: uni-lj-scope-profile
|
||||
state: present
|
||||
identifiers:
|
||||
name: "Univerza v Ljubljani test mapping: profile"
|
||||
attrs:
|
||||
name: "Univerza v Ljubljani test mapping: profile"
|
||||
scope_name: profile
|
||||
description: >
|
||||
given_name, family_name, name, preferred_username, picture - no nickname/groups. Mirrors
|
||||
the real University of Ljubljana/Entra shape: given_name/family_name come from the user's
|
||||
own attributes with NO fallback (delete_none_values() drops them entirely when unset, so a
|
||||
test user can simulate the IdP omitting those claims); name is derived from those same two
|
||||
attributes as "<family_name>, <given_name>" (also dropped, not just blank, when either is
|
||||
missing - real Entra's ID token has no given_name/family_name at all, but DOES have name in
|
||||
that exact format); preferred_username comes from a dedicated "preferred_username"
|
||||
attribute (NOT request.user.username, which must stay the authentik login name) in the real
|
||||
IdP's UPN-style "<lastname><first-letter-of-firstname>@<domain>" format; picture is the
|
||||
fixed, non-user-specific Graph API URL every real account was observed to return.
|
||||
expression: |
|
||||
given_name = ak_obj_attr(request.user, "given_name")
|
||||
family_name = ak_obj_attr(request.user, "family_name")
|
||||
name = f"{family_name}, {given_name}" if given_name and family_name else None
|
||||
|
||||
return delete_none_values({
|
||||
"given_name": given_name,
|
||||
"family_name": family_name,
|
||||
"name": name,
|
||||
"preferred_username": ak_obj_attr(request.user, "preferred_username"),
|
||||
"picture": "https://graph.microsoft.com/v1.0/me/photo/$value",
|
||||
})
|
||||
|
||||
# --- Provider + Application --------------------------------------------------------------
|
||||
- model: authentik_providers_oauth2.oauth2provider
|
||||
id: uni-lj-provider
|
||||
state: present
|
||||
identifiers:
|
||||
name: "Univerza v Ljubljani (test stand-in)"
|
||||
attrs:
|
||||
name: "Univerza v Ljubljani (test stand-in)"
|
||||
authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]]
|
||||
invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
|
||||
client_type: confidential
|
||||
client_id: !Env AUTHENTIK_OIDC_CLIENT_ID
|
||||
client_secret: !Env AUTHENTIK_OIDC_CLIENT_SECRET
|
||||
# Not populated by any default when created via blueprint - without it the authorization
|
||||
# endpoint rejects every request with "Invalid grant_type for provider" (verified locally).
|
||||
grant_types:
|
||||
- authorization_code
|
||||
- refresh_token
|
||||
redirect_uris:
|
||||
- url: !Format ["http://localhost:%s/users/oidc/callback", !Env [IDP_REDIRECT_PORT, "3000"]]
|
||||
matching_mode: strict
|
||||
signing_key: !Find [authentik_crypto.certificatekeypair, [name, "authentik Self-signed Certificate"]]
|
||||
property_mappings:
|
||||
- !Find [authentik_providers_oauth2.scopemapping, [managed, "goauthentik.io/providers/oauth2/scope-openid"]]
|
||||
- !KeyOf uni-lj-scope-email
|
||||
- !KeyOf uni-lj-scope-profile
|
||||
|
||||
- model: authentik_core.application
|
||||
id: uni-lj-application
|
||||
state: present
|
||||
identifiers:
|
||||
slug: uni-lj-test
|
||||
attrs:
|
||||
name: "Univerza v Ljubljani (test stand-in)"
|
||||
slug: uni-lj-test
|
||||
provider: !KeyOf uni-lj-provider
|
||||
policy_engine_mode: any
|
||||
meta_description: >
|
||||
Throwaway local test application standing in for the single real University of Ljubljana
|
||||
OIDC federation. Not a real IdP - dev/testing use only.
|
||||
|
||||
# --- Test users --------------------------------------------------------------------------
|
||||
# All seeded users share the same fixed password so a tester can log in without hunting for
|
||||
# per-user credentials. See dev/authentik/README.md for what portal-side scenario each covers,
|
||||
# and for the exact local-account value scenario B requires you to register first.
|
||||
|
||||
# (A) Brand new user via IdP only, every claim present.
|
||||
- model: authentik_core.user
|
||||
id: uni-lj-user-full
|
||||
state: present
|
||||
identifiers:
|
||||
username: ana.novak
|
||||
attrs:
|
||||
name: "Ana Novak"
|
||||
email: ana.novak@ff.uni-lj.si
|
||||
is_active: true
|
||||
attributes:
|
||||
given_name: Ana
|
||||
family_name: Novak
|
||||
preferred_username: novaka@ff.uni-lj.si
|
||||
password: "IdpTest123!"
|
||||
|
||||
# (B) email claim matches a pre-existing LOCAL portal account -> account-conversion test.
|
||||
- model: authentik_core.user
|
||||
id: uni-lj-user-email-match
|
||||
state: present
|
||||
identifiers:
|
||||
username: berta.kolar.idp
|
||||
attrs:
|
||||
name: "Berta Kolar"
|
||||
email: berta.kolar@fri.uni-lj.si
|
||||
is_active: true
|
||||
attributes:
|
||||
given_name: Berta
|
||||
family_name: Kolar
|
||||
preferred_username: kolarb@fri.uni-lj.si
|
||||
password: "IdpTest123!"
|
||||
|
||||
# (C) given_name/family_name attributes deliberately left unset -> those claims (and the derived
|
||||
# `name`) are entirely absent from the ID token/userinfo response (not blank strings) -> the
|
||||
# portal refuses to create/convert an account without a name (nothing to review or persist),
|
||||
# with a clear error message rather than a blank editable form. No real first/last name
|
||||
# exists to build a proper email/preferred_username from, so both deliberately reuse the same
|
||||
# "brez.imena" placeholder local-part (only the domain suffix is updated for consistency).
|
||||
- model: authentik_core.user
|
||||
id: uni-lj-user-missing-name
|
||||
state: present
|
||||
identifiers:
|
||||
username: brez.imena
|
||||
attrs:
|
||||
name: "Brez imena (missing given_name/family_name claims)"
|
||||
email: brez.imena@fri.uni-lj.si
|
||||
is_active: true
|
||||
attributes:
|
||||
preferred_username: brez.imena@fri.uni-lj.si
|
||||
password: "IdpTest123!"
|
||||
@@ -0,0 +1,352 @@
|
||||
# CI/CD — pipeline internals
|
||||
|
||||
This directory holds the runner-side scripts the Gitea Actions workflows in
|
||||
`.gitea/workflows/` call:
|
||||
|
||||
- `build.sh` — `docker buildx` build + push of the three custom images, with registry layer cache.
|
||||
- `promote.sh` — retag an already-built image set to a new tag (no rebuild), for staging→prod promotion.
|
||||
- `deploy.sh` — runner side: SSH the target host the tag to deploy (nothing more).
|
||||
- `ci-deploy-wrapper.sh` — host side: the forced command that validates the tag and runs
|
||||
`git checkout` + `run-prod.sh pull` + `up -d`.
|
||||
|
||||
The end-to-end pipeline (what triggers what, the registry model, rollback) is documented in the
|
||||
main [README](../../README.md#automated-deployment-cicd). This file covers two operational tasks in
|
||||
depth: **standing up the runner on a build host**, and **hardening deploy access** to each host.
|
||||
|
||||
## Setting up the Gitea Runner on a VPS
|
||||
|
||||
The runner formerly known as `act_runner` was rebranded to **Gitea Runner** at the runner project's
|
||||
own **v1.0.0** (separate versioning from the Gitea *server*). Use the `gitea/runner` image;
|
||||
`gitea/act_runner` still works but is deprecated.
|
||||
|
||||
Pick a build host that is **not** your public production server but has Docker, disk, and internet
|
||||
(the concordancer build downloads a large lexicon). Our own choice is the private ~24/7 VPS. The
|
||||
runner needs **outbound HTTPS** to Gitea, and later **outbound SSH** to the deploy targets.
|
||||
|
||||
### 0. Prerequisites (on the VPS)
|
||||
|
||||
```bash
|
||||
docker --version && docker ps # Docker present, your user can reach the daemon
|
||||
```
|
||||
|
||||
### 1. Get a registration token
|
||||
|
||||
In Gitea: **repository → Settings → Actions → Runners → Create new runner**. Note your Gitea URL
|
||||
and the (single-use, short-lived) **registration token**. Using the *repo's* runner page — not the
|
||||
admin/org one — makes the runner **repo-scoped**, so no Gitea admin access is needed.
|
||||
|
||||
### 2. Create the runner (Docker Compose)
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /opt/gitea-runner/data
|
||||
cd /opt/gitea-runner
|
||||
```
|
||||
|
||||
`/opt/gitea-runner/docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
runner:
|
||||
image: gitea/runner:latest # NOT gitea/act_runner (deprecated)
|
||||
restart: always
|
||||
environment:
|
||||
GITEA_INSTANCE_URL: https://gitea.example.tld # ← your Gitea
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN: "PASTE_TOKEN_HERE" # ← from step 1
|
||||
GITEA_RUNNER_NAME: vps-builder
|
||||
# Maps the `self-hosted` label our workflows target to an image that already
|
||||
# ships git, node, docker CLI and ssh.
|
||||
GITEA_RUNNER_LABELS: "self-hosted:docker://catthehacker/ubuntu:act-latest"
|
||||
volumes:
|
||||
- ./data:/data
|
||||
- /var/run/docker.sock:/var/run/docker.sock # jobs run docker/buildx on the host daemon
|
||||
```
|
||||
|
||||
Two details that matter for this pipeline:
|
||||
|
||||
- `self-hosted:docker://…` runs each job inside that image, which supplies `node` (required by
|
||||
`actions/checkout`) plus `git`, `docker`, `ssh`.
|
||||
- The socket mount is what lets the `docker buildx` / `docker login` calls in `build.sh` and
|
||||
`promote.sh` reach a real daemon.
|
||||
|
||||
### 3. Start and confirm registration
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose logs -f
|
||||
```
|
||||
|
||||
Wait for `runner registered successfully` → `waiting for tasks…`. The token is now consumed; the
|
||||
runner identity persists in `./data/.runner`. To re-register later, wipe `./data` and use a fresh
|
||||
token.
|
||||
|
||||
### 4. Confirm in Gitea
|
||||
|
||||
Back on **Settings → Actions → Runners**, `vps-builder` should show **Idle / online** (green) with
|
||||
the `self-hosted` label.
|
||||
|
||||
> **Binary / systemd alternative.** Instead of Docker, fetch the `gitea/runner` release binary and
|
||||
> run `./runner register --no-interactive --instance <url> --token <token> --name vps-builder
|
||||
> --labels "self-hosted:host"` then `./runner daemon`. Simpler socket story, but the VPS itself must
|
||||
> then have `git`, `node`, `docker`, and `ssh` installed, since jobs won't inherit them from an image.
|
||||
|
||||
## Smoke tests
|
||||
|
||||
**A — online status (step 4).** Green = registration + Gitea↔runner networking are good.
|
||||
|
||||
**B — it claims a job and has the toolchain (the real test).** On a scratch branch add
|
||||
`.gitea/workflows/smoke.yml`, push it, watch the **Actions** tab, then delete it:
|
||||
|
||||
```yaml
|
||||
name: smoke
|
||||
on: [push]
|
||||
jobs:
|
||||
check:
|
||||
runs-on: [self-hosted]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: |
|
||||
git --version && node --version && ssh -V
|
||||
docker version && docker buildx version
|
||||
docker ps # proves the socket mount reaches the host daemon
|
||||
echo OK
|
||||
```
|
||||
|
||||
Green proves the runner runs jobs, `checkout` works, and `docker`/`buildx`/`ssh` + host socket are
|
||||
all present — exactly what `build.sh`, `promote.sh`, and `deploy.sh` rely on.
|
||||
|
||||
**C — registry push path (optional, once `REGISTRY_TOKEN` is set).** Validates registry auth
|
||||
**and** the buildx `docker-container` cache driver together — the two things most likely to bite:
|
||||
|
||||
```yaml
|
||||
- run: |
|
||||
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login gitea.example.tld -u "${{ github.actor }}" --password-stdin
|
||||
docker buildx create --name ci --driver docker-container --use 2>/dev/null || docker buildx use ci
|
||||
printf 'FROM alpine\nRUN echo hi\n' > /tmp/Dockerfile
|
||||
docker buildx build -f /tmp/Dockerfile -t gitea.example.tld/<owner>/smoke:test --push /tmp
|
||||
```
|
||||
|
||||
Notes learned the hard way (validated against a real Gitea instance):
|
||||
|
||||
- **`REGISTRY_TOKEN`, not the automatic `GITEA_TOKEN`.** The auto token is repo-scoped and returns
|
||||
`unauthorized` at the registry; you need a PAT with `write:package`.
|
||||
- **The registry ignores the username** — it authenticates on the token alone, so `github.actor`
|
||||
is safe (works whoever triggers the run).
|
||||
- **Don't add a job-level `permissions:` block** — on Gitea it becomes a complete allow-list and
|
||||
drops `contents: read`, breaking `actions/checkout` with `Repository not found`.
|
||||
- **`<owner>` must be lowercase** — OCI repository paths reject uppercase, so a mixed-case Gitea
|
||||
org/user (e.g. `Amebis`) must be lowercased (`amebis`). The real workflows do this in their
|
||||
`meta` step via `${owner,,}`.
|
||||
|
||||
## Troubleshooting quick hits
|
||||
|
||||
- **Never turns green:** wrong `GITEA_INSTANCE_URL`, blocked outbound 443, or a reused token
|
||||
(regenerate, wipe `./data`, retry) — check `docker compose logs`.
|
||||
- **`docker ps` fails in-job / permission denied:** socket mount missing or host socket perms too tight.
|
||||
- **`--cache-to type=registry` errors:** the default docker driver doesn't support registry cache —
|
||||
that's why the workflow creates the `docker-container` builder first.
|
||||
- **Config errors on first `up`:** verify env var names against the current `gitea/runner` docs and
|
||||
`docker run --rm gitea/runner:latest --help`.
|
||||
|
||||
## Hardened deploy access
|
||||
|
||||
Gitea Actions secrets are **encrypted, not hashed** — they must be decryptable to be injected into
|
||||
jobs. So the SSH private key you store is recoverable by anyone holding the Gitea server's
|
||||
`SECRET_KEY` (a Gitea admin) and by anyone with write access to this repo (a workflow can print a
|
||||
secret). You cannot hide it. The strategy is instead: **expose a key that is worth as little as
|
||||
possible and is trivial to revoke.** Three measures, in priority order.
|
||||
|
||||
### 1. A dedicated CI keypair (do this)
|
||||
|
||||
Never put your personal key in Gitea. Generate a passphraseless key used only by this pipeline, so
|
||||
a leak is revoked in isolation:
|
||||
|
||||
```bash
|
||||
ssh-keygen -t ed25519 -f ci_deploy_key -N "" -C "gitea-ci-deploy"
|
||||
# private half (ci_deploy_key) -> Gitea secret STAGING_SSH_KEY / PROD_SSH_KEY
|
||||
# public half (ci_deploy_key.pub) -> the deploy user's authorized_keys on each host (step 3)
|
||||
```
|
||||
|
||||
Paste the **entire** `ci_deploy_key` file into `STAGING_SSH_KEY` / `PROD_SSH_KEY` — **including**
|
||||
the `-----BEGIN OPENSSH PRIVATE KEY-----` and `-----END OPENSSH PRIVATE KEY-----` lines and the
|
||||
trailing newline. Stripping the armor lines makes the key unparseable (`error in libcrypto` /
|
||||
`invalid format` at deploy time).
|
||||
|
||||
### 2. A dedicated `deploy` user per host
|
||||
|
||||
Keeps automation out of your personal account → clean audit logs and clean revocation (delete the
|
||||
user, the access is gone). It needs Docker, which means the `docker` group — and **docker group ≈
|
||||
root**, so this is about isolation/auditability, not privilege reduction.
|
||||
|
||||
```bash
|
||||
export DEPLOY_USER=deploy # the account these steps create — pick your own
|
||||
export DEPLOY_DIR=/opt/termportal-prod # this host's repo checkout path — pick your own
|
||||
sudo adduser --disabled-password --gecos "" "$DEPLOY_USER" # no password login (key/console only)
|
||||
sudo usermod -aG docker "$DEPLOY_USER" # lets it run docker/compose without sudo
|
||||
export DEPLOY_HOME="$(getent passwd "$DEPLOY_USER" | cut -d: -f6)" # its home, e.g. /home/deploy
|
||||
```
|
||||
|
||||
> `DEPLOY_USER`, `DEPLOY_DIR`, and `DEPLOY_HOME` live in **this admin shell**. The commands below run
|
||||
> as the deploy user via `sudo -H -u "$DEPLOY_USER"` — your shell expands these vars *before* the
|
||||
> user switch, and `-H` sets the deploy user's `$HOME` so git/docker write their credentials under
|
||||
> that account, not yours.
|
||||
|
||||
> **This host involves two credentials — don't mix them up:**
|
||||
> - the **CI SSH key** from step 1 (runner → this host): its *public* half goes into the deploy
|
||||
> user's `authorized_keys` in step 3; its private half is the Gitea secret.
|
||||
> - a **read-only PAT** (this host → Gitea, over HTTPS): lets the deploy user `clone`/`fetch` the
|
||||
> repo **and** `docker pull` images. Created just below.
|
||||
|
||||
**Create one read-only token** for the deploy user in Gitea → **Settings → Applications → Generate
|
||||
New Token**, with scopes **`read:repository`** + **`read:package`** (older Gitea: `repo` + `package`
|
||||
read). One token covers both git and the registry, so there's a single low-value credential to
|
||||
rotate.
|
||||
|
||||
**Clone the repo over HTTPS** to this host's checkout path, owned by the deploy user (`/opt` needs
|
||||
root just to create the directory):
|
||||
|
||||
```bash
|
||||
sudo mkdir -p "$DEPLOY_DIR"
|
||||
sudo chown "$DEPLOY_USER:$DEPLOY_USER" "$DEPLOY_DIR"
|
||||
sudo -H -u "$DEPLOY_USER" git config --global credential.helper store # cache creds in ~deploy/.git-credentials (mode 600)
|
||||
sudo -H -u "$DEPLOY_USER" git clone https://gitea.example.tld/<owner>/<repo>.git "$DEPLOY_DIR"
|
||||
# Username: <your-gitea-user>
|
||||
# Password: <the read PAT> -> stored, so the wrapper's `git fetch` runs non-interactively later
|
||||
```
|
||||
|
||||
**Place host-only files and log in to the registry** as the deploy user, reusing the same token:
|
||||
|
||||
```bash
|
||||
sudo -H -u "$DEPLOY_USER" cp "$DEPLOY_DIR/dev/.env" "$DEPLOY_DIR/.env"
|
||||
sudo -H -u "$DEPLOY_USER" "${EDITOR:-nano}" "$DEPLOY_DIR/.env" # fill in real secrets, incl. the REGISTRY line (gitea.example.tld/<owner-lowercase>)
|
||||
# optional per-host tweaks:
|
||||
# sudo -H -u "$DEPLOY_USER" cp "$DEPLOY_DIR/docker-compose.prod.override.example.yml" "$DEPLOY_DIR/docker-compose.prod.override.yml"
|
||||
sudo -H -u "$DEPLOY_USER" docker login gitea.example.tld -u <your-gitea-user> # paste the SAME read PAT at the prompt
|
||||
```
|
||||
|
||||
`.env` and `docker-compose.prod.override.yml` are gitignored, so the deploy-time `git checkout`
|
||||
never touches them. The stored git credential and the cached `docker login` (in the deploy user's
|
||||
`~/.git-credentials` and `~/.docker/config.json`, both mode 600) let deploy-time `git fetch` and
|
||||
`docker pull` run without prompts.
|
||||
|
||||
`docker login` prints a "credentials are stored unencrypted … Configure a credential helper"
|
||||
warning — that's expected and fine here: the value is a read-only `read:package` token in a
|
||||
mode-600 file under a dedicated account. A credential helper isn't worth the `pass`/GPG or
|
||||
secret-service plumbing on a headless host.
|
||||
|
||||
> **SSH instead of HTTPS (only if your Gitea has SSH enabled).** If the instance allows it, you can
|
||||
> use a read-only **Deploy Key** rather than a PAT for git: as the deploy user,
|
||||
> `ssh-keygen -t ed25519 -f ~/.ssh/gitea_ro -N ""`, add the `.pub` under repo → Settings → Deploy
|
||||
> Keys (write access off), add a `Host` stanza in `~/.ssh/config` pointing at `gitea_ro`, and clone
|
||||
> `git@gitea.example.tld:<owner>/<repo>.git`. You'd still need a `read:package` token for
|
||||
> `docker login`. If Deploy Keys show "SSH Disabled", the admin has turned SSH off instance-wide —
|
||||
> use the HTTPS path above.
|
||||
|
||||
### 3. Pin the key to a forced command (this is what shrinks a leaked key)
|
||||
|
||||
Install the wrapper **outside the git checkout** (so `git checkout` never rewrites the running
|
||||
script) and tell it this host's checkout path:
|
||||
|
||||
```bash
|
||||
sudo -u "$DEPLOY_USER" cp "$DEPLOY_DIR/dev/ci/ci-deploy-wrapper.sh" "$DEPLOY_HOME/ci-deploy-wrapper.sh"
|
||||
sudo -u "$DEPLOY_USER" chmod 755 "$DEPLOY_HOME/ci-deploy-wrapper.sh"
|
||||
echo "DEPLOY_DIR=$DEPLOY_DIR" | sudo -u "$DEPLOY_USER" tee "$DEPLOY_HOME/ci-deploy.conf" # the wrapper reads this
|
||||
```
|
||||
|
||||
Then add the pinned CI key to the deploy user's `authorized_keys`. Open it in an editor (creating
|
||||
the `.ssh` dir first if needed) — that way you can paste the key now and reopen the same file to add
|
||||
`from=` later:
|
||||
|
||||
```bash
|
||||
sudo -u "$DEPLOY_USER" install -d -m 700 "$DEPLOY_HOME/.ssh"
|
||||
sudo -H -u "$DEPLOY_USER" "${EDITOR:-nano}" "$DEPLOY_HOME/.ssh/authorized_keys"
|
||||
```
|
||||
|
||||
Paste the CI **public** key as one line, prefixed with the forced-command options. The paths here
|
||||
are **literal** (`authorized_keys` doesn't expand variables), so use the deploy user's real home for
|
||||
`command=` — print it with `echo "$DEPLOY_HOME"`. Leave `from=` off for now (you add it once you
|
||||
know the runner's source IP — see *Verify it*):
|
||||
|
||||
```
|
||||
restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA...CI-public-key... gitea-ci-deploy
|
||||
```
|
||||
|
||||
Later, reopen the file with the same editor command and prepend `from="<source>",`:
|
||||
|
||||
```
|
||||
from="<source>",restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA...CI-public-key... gitea-ci-deploy
|
||||
```
|
||||
|
||||
- `command="…"` — a **forced command**: this key can *only* run the wrapper. The tag the runner
|
||||
sends arrives as `$SSH_ORIGINAL_COMMAND`; the wrapper allow-lists it to `[A-Za-z0-9._-]`, so even
|
||||
a fully compromised Gitea/workflow can at most deploy some existing tag — never a shell.
|
||||
- `from="<source>"` — the key works only from the address the **target's** `sshd` sees for the
|
||||
runner's connection, so a leaked key is useless elsewhere. That address depends on topology:
|
||||
- **Runner reaches this host over the network** (e.g. remote prod): it's the runner's public
|
||||
egress IP — `curl -s ifconfig.me` from the runner.
|
||||
- **Runner and this host are the same machine** (e.g. co-located staging): jobs run in a
|
||||
container, so `sshd` sees a Docker-network address, not the public IP — and it can vary per
|
||||
job, so pin the subnet, e.g. `from="172.16.0.0/12"`. (`DEPLOY_HOST` for such a host must also
|
||||
be an address the container can reach — its routable IP, **not** `127.0.0.1`.)
|
||||
When unsure, read the real value from the target after one test connection (see *Verify it*):
|
||||
`sudo journalctl -u ssh | grep Accepted` (or `/var/log/auth.log`) shows `… from <IP> …`.
|
||||
- `restrict` — no PTY, no port/agent forwarding, nothing but the command.
|
||||
|
||||
Because you can't make the key un-leakable, keep rotation cheap: to revoke, delete the
|
||||
`authorized_keys` line (and/or the `deploy` user) and replace the Gitea secret with a fresh key.
|
||||
|
||||
### Verify it
|
||||
|
||||
The private key lives in the Gitea secret, so drive the checks from the runner via the
|
||||
**`deploy-dispatch`** workflow (Actions → Run workflow), not a local `ssh`.
|
||||
|
||||
1. **Probe — no deploy.** Run `deploy-dispatch` with `environment` set to this host and
|
||||
`image_tag = probe/invalid` (any character outside `[A-Za-z0-9._-]`). The job **should go red at
|
||||
the deploy step, and that is the pass**: the key authenticates, then the wrapper refuses the
|
||||
invalid tag *before* any `git fetch`/`pull`/`up`, so nothing deploys — one run verifies both auth
|
||||
and the allow-list lock.
|
||||
2. **Read the source IP** the target saw and pin it in `from=` (reopen `authorized_keys` with the
|
||||
editor command above; use the subnet CIDR if it's a per-job Docker address):
|
||||
```bash
|
||||
sudo journalctl -u ssh | grep 'Accepted publickey' | tail -1 # -> ... from <IP> port ...
|
||||
```
|
||||
3. **Full path.** When you actually want to deploy, run `deploy-dispatch` with a **valid** existing
|
||||
tag (e.g. a `sha-…` already in the registry) to exercise checkout → pull → `up -d`.
|
||||
|
||||
> **Stronger option if the admin threat is the real concern.** All of the above still exposes the
|
||||
> key to the Gitea admin. If that is unacceptable, switch to **pull-based** deploy: the host pulls
|
||||
> images itself (a cron or webhook running the wrapper), and Gitea holds only a read-only registry
|
||||
> token — far lower value than an SSH key into prod. More setup, but no deploy key in Gitea at all.
|
||||
|
||||
## Registry retention
|
||||
|
||||
Every push to the default branch mints three `sha-<short>` image tags (one per service), forever —
|
||||
so without a policy the registry grows unbounded. The `v*` release tags grow slowly and are
|
||||
meaningful, and `buildcache` is a single tag that is *overwritten* each build (it doesn't pile up).
|
||||
So the only thing worth pruning is **old `sha-*` tags**.
|
||||
|
||||
Use Gitea's built-in package **Cleanup Rules** (no scripting; runs on Gitea's package-cleanup cron):
|
||||
org → **Settings → Packages → Cleanup Rules → Add Cleanup Rule** (needs org-owner access). Recommended:
|
||||
|
||||
| Field (labels vary slightly by Gitea version) | Value |
|
||||
|---|---|
|
||||
| Package type | **Container** |
|
||||
| Keep the most recent | **10** |
|
||||
| Remove versions older than | **30 days** |
|
||||
| **Keep** versions matching (regex) | `^(v.*\|buildcache\|latest)$` |
|
||||
| **Remove** versions matching (regex) | `^sha-` |
|
||||
|
||||
A version is deleted only if it matches **Remove** (`^sha-…`), is **not** among the 10 newest, is
|
||||
older than 30 days, **and** doesn't match **Keep** — the patterns match the full tag name. Rationale:
|
||||
|
||||
- **`v*` kept forever** — release tags are rollback targets; never let one you might revert to be
|
||||
reaped. The `Keep` pattern protects them absolutely.
|
||||
- **`buildcache` kept** — it warms rebuilds (notably the ~5-min concordancer); pruning it just makes
|
||||
the next build cold.
|
||||
- **`sha-*` bounded** — keeping ~10 recent (and anything under 30 days) still lets you roll a few
|
||||
commits back while capping growth. Tune the two numbers to how often you deploy.
|
||||
- **`Remove` restricted to `^sha-`** — belt-and-suspenders so the rule can only ever touch CI
|
||||
artifacts, never a release or the cache.
|
||||
|
||||
Caveat: a container tag also has underlying `sha256:…` manifest entries. `^sha-` doesn't match
|
||||
`sha256:…`, so after the first cleanup run, check the package list — if orphaned `sha256:` digests
|
||||
visibly accumulate, revisit it (carefully; don't delete a digest a kept tag still references).
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and push the three custom images to the registry. Runs on the CI runner.
|
||||
# Requires a buildx builder that supports registry cache export (docker-container driver);
|
||||
# the workflow sets one up. Uses registry-backed layer cache so unchanged images (notably
|
||||
# the concordancer, whose build downloads a large lexicon from clarin.si) are near-instant.
|
||||
#
|
||||
# Required environment:
|
||||
# REGISTRY image name prefix, e.g. gitea.example.tld/luka
|
||||
# TAG tag to build, e.g. sha-abc1234
|
||||
set -euo pipefail
|
||||
: "${REGISTRY:?}" "${TAG:?}"
|
||||
|
||||
# service | context | dockerfile
|
||||
builds=(
|
||||
"termportal-express|express|express/Dockerfile.prod"
|
||||
"termportal-opensearch|opensearch|opensearch/Dockerfile"
|
||||
"termportal-concordancer|concordancer|concordancer/Dockerfile.prod"
|
||||
)
|
||||
|
||||
for spec in "${builds[@]}"; do
|
||||
IFS='|' read -r name context dockerfile <<<"$spec"
|
||||
ref="$REGISTRY/$name"
|
||||
echo "+ build $ref:$TAG (context=$context, dockerfile=$dockerfile)" >&2
|
||||
docker buildx build \
|
||||
--file "$dockerfile" \
|
||||
--tag "$ref:$TAG" \
|
||||
--cache-from "type=registry,ref=$ref:buildcache" \
|
||||
--cache-to "type=registry,ref=$ref:buildcache,mode=max" \
|
||||
--push \
|
||||
"$context"
|
||||
done
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
# Forced-command deploy wrapper — the ONLY thing the CI deploy key is allowed to run on a
|
||||
# target host. Install it OUTSIDE the git checkout (so `git checkout` here can never rewrite
|
||||
# the running script) and pin it as the forced command for the CI key in authorized_keys:
|
||||
#
|
||||
# from="<runner-ip>",restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA... gitea-ci-deploy
|
||||
#
|
||||
# With that line, the CI runner can only ever trigger a deploy of a validated image tag on
|
||||
# THIS host — never an arbitrary shell command, port-forward, or PTY. The tag the runner asks
|
||||
# for arrives as $SSH_ORIGINAL_COMMAND (ignored as a command, read here as data).
|
||||
#
|
||||
# Also runnable by hand for break-glass deploys / rollbacks: ./ci-deploy-wrapper.sh v1.2.3
|
||||
set -euo pipefail
|
||||
|
||||
# Host-specific config lives next to the installed wrapper, so this script stays byte-identical
|
||||
# across hosts. Create it once, e.g.: echo 'DEPLOY_DIR=/opt/termportal-prod' > ci-deploy.conf
|
||||
conf="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/ci-deploy.conf"
|
||||
# shellcheck source=/dev/null
|
||||
[[ -f "$conf" ]] && source "$conf"
|
||||
: "${DEPLOY_DIR:?set DEPLOY_DIR in ci-deploy.conf next to the wrapper}"
|
||||
|
||||
# Tag from the argument (manual use) or the forced-command's SSH_ORIGINAL_COMMAND (CI use).
|
||||
tag="${1:-${SSH_ORIGINAL_COMMAND:-}}"
|
||||
|
||||
# Strict allow-list, matched against the WHOLE value (no tokenizing) so multi-token or
|
||||
# metacharacter input fails closed and loud. Registry tags are [A-Za-z0-9._-]; the leading-char
|
||||
# anchor also blocks option injection (a tag can't start with '-'). This stops a compromised
|
||||
# Gitea/workflow from smuggling anything but a bare tag through SSH_ORIGINAL_COMMAND.
|
||||
if [[ ! "$tag" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
|
||||
echo "ci-deploy-wrapper: refusing invalid tag: '${tag}'" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
ref="${tag#sha-}" # sha-abc1234 -> abc1234 ; v1.2.3 stays v1.2.3
|
||||
|
||||
echo "+ deploy tag=${tag} ref=${ref} dir=${DEPLOY_DIR}" >&2
|
||||
cd "$DEPLOY_DIR"
|
||||
git fetch --tags --prune origin
|
||||
git checkout --force "$ref"
|
||||
export IMAGE_TAG="$tag" # picked up by docker compose via run-prod.sh
|
||||
echo "$tag" >.deployed_tag # small audit trail of what is running
|
||||
./run-prod.sh pull
|
||||
./run-prod.sh up -d
|
||||
docker image prune -f
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runner-side deploy trigger used by the Gitea Actions workflows in .gitea/workflows/.
|
||||
#
|
||||
# The target host's CI deploy key is pinned to a forced command (dev/ci/ci-deploy-wrapper.sh,
|
||||
# installed on the host — see dev/ci/README.md). So the ONLY thing we send over SSH is the
|
||||
# image tag: it arrives on the host as $SSH_ORIGINAL_COMMAND, the wrapper validates it and runs
|
||||
# the deploy. The runner can never execute an arbitrary command on the target, and the host —
|
||||
# not this script — owns its checkout path (DEPLOY_DIR in the host's ci-deploy.conf).
|
||||
#
|
||||
# Required environment:
|
||||
# DEPLOY_HOST target hostname / IP
|
||||
# DEPLOY_USER SSH user on the target (e.g. the dedicated `deploy` user)
|
||||
# DEPLOY_SSH_KEY private SSH key contents (the CI deploy key)
|
||||
# IMAGE_TAG image tag to deploy, e.g. v1.2.3 or sha-abc1234
|
||||
# Optional environment:
|
||||
# DEPLOY_SSH_PORT SSH port on the target, if not the default 22
|
||||
set -euo pipefail
|
||||
: "${DEPLOY_HOST:?}" "${DEPLOY_USER:?}" "${DEPLOY_SSH_KEY:?}" "${IMAGE_TAG:?}"
|
||||
DEPLOY_SSH_PORT="${DEPLOY_SSH_PORT:-22}"
|
||||
|
||||
key_file="$(mktemp)"
|
||||
trap 'rm -f "$key_file"' EXIT
|
||||
printf '%s\n' "$DEPLOY_SSH_KEY" >"$key_file"
|
||||
chmod 600 "$key_file"
|
||||
|
||||
echo "+ deploy ${DEPLOY_USER}@${DEPLOY_HOST}:${DEPLOY_SSH_PORT} tag=${IMAGE_TAG}" >&2
|
||||
|
||||
# StrictHostKeyChecking=accept-new trusts the host key on first connection and pins it after.
|
||||
# The "command" we pass is delivered to the host's forced-command wrapper as
|
||||
# $SSH_ORIGINAL_COMMAND — it is a tag, not a shell command.
|
||||
exec ssh -i "$key_file" -p "$DEPLOY_SSH_PORT" -o StrictHostKeyChecking=accept-new -o BatchMode=yes \
|
||||
"${DEPLOY_USER}@${DEPLOY_HOST}" "$IMAGE_TAG"
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Promote an already-built set of images to a new tag WITHOUT rebuilding, by copying the
|
||||
# registry manifest. Guarantees production runs the exact bytes staging tested. Runs on the
|
||||
# CI runner. Fails clearly if the source tag does not exist (e.g. the commit was never built
|
||||
# on the default branch before being tagged).
|
||||
#
|
||||
# Required environment:
|
||||
# REGISTRY image name prefix, e.g. gitea.example.tld/luka
|
||||
# SRC_TAG existing tag to promote from, e.g. sha-abc1234
|
||||
# DST_TAG new tag to create, e.g. v1.2.3
|
||||
set -euo pipefail
|
||||
: "${REGISTRY:?}" "${SRC_TAG:?}" "${DST_TAG:?}"
|
||||
|
||||
for name in termportal-express termportal-opensearch termportal-concordancer; do
|
||||
ref="$REGISTRY/$name"
|
||||
echo "+ promote $ref:$SRC_TAG -> :$DST_TAG" >&2
|
||||
docker buildx imagetools create --tag "$ref:$DST_TAG" "$ref:$SRC_TAG"
|
||||
done
|
||||
Executable
+61
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
# Compares the fully resolved config of an old, full docker-compose file against a new
|
||||
# base compose file + override compose file, to confirm a migration from "one full compose
|
||||
# file per environment" to "one shared base + small per-environment override files"
|
||||
# (see: https://github.com/compose-spec/compose-spec/blob/master/13-merge.md) produced an
|
||||
# identical stack. Generic - not tied to this project; copy it wherever you're doing the
|
||||
# same kind of migration, or keep one copy and point to it from any project's directory.
|
||||
#
|
||||
# Usage: compose-config-diff.sh [OLD_FILE] [NEW_FILE] [OVERRIDE_FILE]
|
||||
# OLD_FILE defaults to docker-compose.prod.old.yml
|
||||
# NEW_FILE defaults to docker-compose.prod.yml
|
||||
# OVERRIDE_FILE defaults to docker-compose.prod.override.yml (optional - if missing,
|
||||
# NEW_FILE is compared on its own, with a warning)
|
||||
#
|
||||
# Run from the directory containing these files (and .env, if the project uses one -
|
||||
# docker compose picks it up from the current directory as usual, same as any other
|
||||
# `docker compose` invocation there).
|
||||
#
|
||||
# Writes nothing to disk - both configs are held in memory and diffed via process
|
||||
# substitution.
|
||||
set -uo pipefail
|
||||
|
||||
OLD="${1:-docker-compose.prod.old.yml}"
|
||||
NEW="${2:-docker-compose.prod.yml}"
|
||||
OVERRIDE="${3:-docker-compose.prod.override.yml}"
|
||||
|
||||
if [[ ! -f "$OLD" ]]; then
|
||||
echo "Missing $OLD - run this from the directory containing it, or pass its path as \$1." >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ ! -f "$NEW" ]]; then
|
||||
echo "Missing $NEW - run this from the directory containing it, or pass its path as \$2." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
new_files=(-f "$NEW")
|
||||
new_desc="$NEW"
|
||||
if [[ -f "$OVERRIDE" ]]; then
|
||||
new_files+=(-f "$OVERRIDE")
|
||||
new_desc="$NEW + $OVERRIDE"
|
||||
else
|
||||
echo "Note: $OVERRIDE not found - comparing against $NEW on its own." >&2
|
||||
fi
|
||||
|
||||
old_config="$(docker compose -f "$OLD" config)"
|
||||
old_status=$?
|
||||
new_config="$(docker compose "${new_files[@]}" config)"
|
||||
new_status=$?
|
||||
|
||||
if [[ $old_status -ne 0 || $new_status -ne 0 ]]; then
|
||||
echo "FAILED: docker compose config errored (see messages above) - cannot compare." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if diff -u <(printf '%s\n' "$old_config") <(printf '%s\n' "$new_config"); then
|
||||
echo "OK: resolved config is identical between $OLD and $new_desc."
|
||||
exit 0
|
||||
else
|
||||
echo "MISMATCH: resolved config differs (diff above) between $OLD and $new_desc." >&2
|
||||
exit 1
|
||||
fi
|
||||
Reference in New Issue
Block a user