diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..baa77d5 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,190 @@ +name: CI + +# Image build for ins-landing-page, following dynamic-qr's pipeline (build container, DinD, one +# moving tag per profile, per-branch run queue, guarded microk8s rollout, notifications). The k8s +# manifests live in k8s/ and are applied by hand (README "Kubernetes"); CI only rolls the +# Deployment so it pulls the new image, and only from main. Tests run inside the Dockerfile's +# `test` stage, so a failing test stops the image from being pushed. +# +# Tags: main -> ins-landing-page-prd-latest; dev -> ins-landing-page-dev-latest. + +on: + push: + branches: + - main + - dev + +# Do NOT add workflow `concurrency`: Gitea keeps one waiting run per group and cancels the rest. +# Runs queue per branch in the "Wait for older runs" step instead (scripts/waitForOlderRuns.sh). + +jobs: + build: + runs-on: ubuntu-latest + container: + image: gitea.containerverse.dev/solvway/maven-custom-21:latest + credentials: + username: ${{ secrets.PACKAGE_USER }} + password: ${{ secrets.PACKAGE_RW_KEY }} + env: + _REGISTRY: gitea.containerverse.dev + _REGISTRY_PREFIX: solvway + _REPO_NAME: ins-landing-page + _IMAGE_NAME: ins-landing-page + # Images are built against the DinD sidecar (no host docker socket), without TLS. + DOCKER_HOST: tcp://docker:2375 + DOCKER_TLS_VERIFY: "" + # Push a single manifest, not a manifest list with a provenance attestation. + BUILDX_NO_DEFAULT_ATTESTATIONS: "1" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Wait for older runs of this branch + timeout-minutes: 125 + env: + GITEA_TOKEN: ${{ github.token }} + GITEA_API: ${{ github.server_url }}/api/v1 + GITEA_REPO: ${{ github.repository }} + GITEA_BRANCH: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + # Values reach scripts through env:, never as ${{ }} inside run:. + run: | + "$GITHUB_WORKSPACE/scripts/waitForOlderRuns.sh" "$RUN_NUMBER" + + - name: Docker build & push + env: + REGISTRY_USER: ${{ secrets.PACKAGE_USER }} + REGISTRY_PASSWORD: ${{ secrets.PACKAGE_RW_KEY }} + BRANCH: ${{ github.ref_name }} + run: | + case "$BRANCH" in + main) PROFILE=prd ;; + dev) PROFILE=dev ;; + *) echo "Refusing unexpected branch name"; exit 1 ;; + esac + IMAGE_REF="$_REGISTRY/$_REGISTRY_PREFIX/$_IMAGE_NAME:$_REPO_NAME-$PROFILE-latest" + printf '%s' "$REGISTRY_PASSWORD" | docker login "$_REGISTRY" -u "$REGISTRY_USER" --password-stdin + docker build --pull -f Dockerfile --target test . + docker build -f Dockerfile -t "$IMAGE_REF" . + docker push "$IMAGE_REF" + echo "Pushed $IMAGE_REF" + + - name: Rollout to microk8s + if: ${{ github.ref_name == 'main' }} + env: + DEPLOY_USER: ${{ secrets.DRONECICD_SSH_USERNAME }} + DEPLOY_HOST: ${{ secrets.DRONECICD_SSH_HOST }} + DEPLOY_SSH_KEY: ${{ secrets.DRONECICD_SSH_KEY }} + SHA: ${{ github.sha }} + # Same guard as babyboo's emitGuardedRollout.sh: annotate first, and skip when the + # Deployment already runs a newer commit (by committer time), so an older run never rolls + # back a newer image. A missing Deployment (manifests not applied yet) is skipped, not failed. + run: | + case "$SHA" in *[!0-9a-f]*|'') echo "Refusing unexpected sha"; exit 1 ;; esac + COMMIT_TIME="$(git log -1 --format=%ct "$SHA")" + case "$COMMIT_TIME" in ''|*[!0-9]*) echo "cannot resolve the commit time of $SHA"; exit 1 ;; esac + mkdir -p /root/.ssh && chmod 700 /root/.ssh + printf '%s' "$DEPLOY_SSH_KEY" > /root/.ssh/id_rsa + chmod 600 /root/.ssh/id_rsa + ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no "${DEPLOY_USER}@${DEPLOY_HOST}" 'bash -s' </dev/null 2>&1; then + echo "ins-landing-page/ins-landing-page not found: apply k8s/ first (README). Skipping rollout." + exit 0 + fi + cur=\$(k -n ins-landing-page get deployment/ins-landing-page -o 'go-template={{with .metadata.annotations}}{{index . "ins-landing-page/deployed-commit-time"}}{{end}}') + case "\$cur" in ''|*[!0-9]*) cur=0 ;; esac + if [ "\$cur" -gt $COMMIT_TIME ]; then + echo "Skip: ins-landing-page runs a newer commit (commit time \$cur > $COMMIT_TIME)" + else + k -n ins-landing-page annotate --overwrite deployment/ins-landing-page ins-landing-page/deployed-commit-time=$COMMIT_TIME ins-landing-page/deployed-commit=$SHA + ./krrd.sh ins-landing-page ins-landing-page + fi + EOF + + - name: Telegram notification + if: always() + # Uses github.actor (the authenticated pusher) — always populated, so the + # "Commit by " problem from the Drone setup cannot happen here. + env: + TG_TOKEN: ${{ secrets.TELEGRAM_TOKEN }} + TG_TO: ${{ secrets.TELEGRAM_TO }} + BUILD_STATUS: ${{ job.status }} + ACTOR: ${{ github.actor }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + COMMIT_MSG: ${{ github.event.head_commit.message }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [ "$BUILD_STATUS" = "success" ]; then + HEAD="āœ… Build #${RUN_NUMBER} of \`${REPO}\` succeeded." + else + HEAD="āŒ Build #${RUN_NUMBER} of \`${REPO}\` failed." + fi + TEXT="$(printf '%s\n\nšŸ“ Pushed by %s on `%s`:\n\n```\n%s\n```\n\n🌐 %s' \ + "$HEAD" "$ACTOR" "$BRANCH" "$COMMIT_MSG" "$RUN_URL")" + curl -sS "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${TG_TO}" \ + --data-urlencode "parse_mode=Markdown" \ + --data-urlencode "text=${TEXT}" >/dev/null + + - name: Microsoft Teams notification + if: always() + # Independent of the Telegram step: both run on every build regardless of + # the other's outcome. Posts an Adaptive Card, which both Teams Workflows + # webhooks and legacy incoming webhooks accept. + env: + TEAMS_WEBHOOK_URL: ${{ secrets.MICROSOFT_TEAMS_WEBHOOK_URL }} + BUILD_STATUS: ${{ job.status }} + ACTOR: ${{ github.actor }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + COMMIT_MSG: ${{ github.event.head_commit.message }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [ -z "$TEAMS_WEBHOOK_URL" ]; then + echo "MICROSOFT_TEAMS_WEBHOOK_URL not set — skipping." + exit 0 + fi + if [ "$BUILD_STATUS" = "success" ]; then + HEAD="āœ… Build #${RUN_NUMBER} of ${REPO} succeeded." + COLOR="Good" + else + HEAD="āŒ Build #${RUN_NUMBER} of ${REPO} failed." + COLOR="Attention" + fi + # JSON-escape without relying on jq being in the build image. + json_escape() { + printf '%s' "$1" | tr -d '\r' \ + | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/\\t/g' \ + | awk 'NR > 1 { printf "\\n" } { printf "%s", $0 }' + } + BODY="$(cat < --docker-password= + k apply -f k8s/ + k -n ins-landing-page rollout status deployment/ins-landing-page + +Updates: every push to `main` runs the tests and builds `gitea.containerverse.dev/solvway/ins-landing-page:ins-landing-page-prd-latest`. CI then runs `./krrd.sh ins-landing-page ins-landing-page` on the deploy host. Manifest changes are applied by hand (`k apply -f k8s/`). + +CI needs the same repository secrets as dynamic-qr: `PACKAGE_USER`, `PACKAGE_RW_KEY`, `DRONECICD_SSH_*`, `TELEGRAM_*` and, optionally, `MICROSOFT_TEAMS_WEBHOOK_URL`. They come from the `solvway` org once the repo is transferred there. ## Exporting leads To CSV, from the running pod: ```bash -kubectl exec deploy/ins-landing-page -- node --disable-warning=ExperimentalWarning -e " +microk8s kubectl -n ins-landing-page exec deploy/ins-landing-page -- node --disable-warning=ExperimentalWarning -e " const {DatabaseSync}=require('node:sqlite'); const rows=new DatabaseSync(process.env.DB_PATH,{readOnly:true}).prepare('SELECT * FROM leads ORDER BY id').all(); const q=v=>v==null?'':'\"'+String(v).replace(/^[=+\-@]/,\"'\$&\").replace(/\"/g,'\"\"')+'\"'; @@ -45,7 +62,7 @@ for(const r of rows)console.log(Object.values(r).map(q).join(',')); " > leads.csv ``` -Or copy the whole database file: `kubectl cp :/data/leads.db ./leads.db`. +Prefer the CSV export above. The database runs in WAL mode, so copying only `leads.db` can miss the newest leads; if you copy the file, copy `leads.db-wal` with it. Columns: `id, created_at (UTC), name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign`. diff --git a/k8s/00-namespace.yaml b/k8s/00-namespace.yaml new file mode 100644 index 0000000..bd0dcaf --- /dev/null +++ b/k8s/00-namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: ins-landing-page diff --git a/k8s/40-app.yaml b/k8s/40-app.yaml new file mode 100644 index 0000000..deddf0a --- /dev/null +++ b/k8s/40-app.yaml @@ -0,0 +1,95 @@ +# Leads live in a SQLite file on this volume. ReadWriteOnce + 1 replica + Recreate: SQLite has a +# single writer, so two pods must never hold the file at once (not even during a rollout). +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: ins-landing-page-data + namespace: ins-landing-page +spec: + storageClassName: longhorn + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 1Gi +--- +apiVersion: v1 +kind: Service +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + selector: + app: ins-landing-page + ports: + - name: http + port: 3000 +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: ins-landing-page + template: + metadata: + labels: + app: ins-landing-page + spec: + imagePullSecrets: + - name: regcred + terminationGracePeriodSeconds: 10 + securityContext: + runAsNonRoot: true + runAsUser: 1000 # the image's `node` user + runAsGroup: 1000 + fsGroup: 1000 # so the app can write to the Longhorn volume + containers: + - name: ins-landing-page + # One moving tag per profile (CI); the rollout restarts the pod to pull it. + image: gitea.containerverse.dev/solvway/ins-landing-page:ins-landing-page-prd-latest + imagePullPolicy: Always + env: + - name: PORT + value: "3000" + - name: DB_PATH + value: /data/leads.db + ports: + - name: http + containerPort: 3000 + volumeMounts: + - name: data + mountPath: /data + readinessProbe: + httpGet: + path: / + port: http + periodSeconds: 10 + livenessProbe: + httpGet: + path: / + port: http + initialDelaySeconds: 10 + periodSeconds: 30 + failureThreshold: 3 + resources: + requests: + cpu: 20m + memory: 48Mi + limits: + memory: 192Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + volumes: + - name: data + persistentVolumeClaim: + claimName: ins-landing-page-data diff --git a/k8s/50-gateway.yaml b/k8s/50-gateway.yaml new file mode 100644 index 0000000..8de5d21 --- /dev/null +++ b/k8s/50-gateway.yaml @@ -0,0 +1,124 @@ +# Served by Traefik through the Gateway API (GatewayClass `traefik`), the same way as dynamic-qr. +# Cloudflare connects to the origin over HTTPS: port 8443 is Traefik's `websecure` entry point +# (host port 443), 8000 its `web` entry point (host port 80), which only redirects to HTTPS. +# +# Let's Encrypt certificate via cert-manager (ClusterIssuer `lets-encrypt`, HTTP-01). The solver +# pod runs in this namespace and is allowed in by k8s/60-network-policy.yaml. +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: ins-landing-page-tls + namespace: ins-landing-page +spec: + secretName: ins-landing-page-tls + issuerRef: + group: cert-manager.io + kind: ClusterIssuer + name: lets-encrypt + dnsNames: + - ins-landing.containerverse.dev + usages: + - digital signature + - key encipherment +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: Gateway +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + gatewayClassName: traefik + listeners: + - name: http + protocol: HTTP + port: 8000 + allowedRoutes: + namespaces: + from: Same + - name: websecure + protocol: HTTPS + port: 8443 + hostname: ins-landing.containerverse.dev + tls: + mode: Terminate + certificateRefs: + - kind: Secret + group: "" + name: ins-landing-page-tls + allowedRoutes: + namespaces: + from: Same +--- +# Plain HTTP: permanent redirect to HTTPS. +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: https-redirect + namespace: ins-landing-page +spec: + parentRefs: + - name: ins-landing-page + sectionName: http + hostnames: + - ins-landing.containerverse.dev + rules: + - matches: + - path: + type: PathPrefix + value: / + filters: + - type: RequestRedirect + requestRedirect: + scheme: https + port: 443 + statusCode: 301 +--- +# The lead form is public; the honeypot only stops naive bots. Limit form posts per visitor so a +# script cannot fill the volume. depth: 1 takes the right-most X-Forwarded-For entry, which +# Cloudflare sets to the visitor (Traefik keeps that header only from Cloudflare's ranges). +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: lead-rate-limit + namespace: ins-landing-page +spec: + rateLimit: + average: 5 + period: 1m + burst: 5 + sourceCriterion: + ipStrategy: + depth: 1 +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: ins-landing-page + namespace: ins-landing-page +spec: + parentRefs: + - name: ins-landing-page + sectionName: websecure + hostnames: + - ins-landing.containerverse.dev + rules: + - matches: + - path: + type: Exact + value: /api/leads + filters: + - type: ExtensionRef + extensionRef: + group: traefik.io + kind: Middleware + name: lead-rate-limit + backendRefs: + - name: ins-landing-page + port: 3000 + - matches: + - path: + type: PathPrefix + value: / + backendRefs: + - name: ins-landing-page + port: 3000 diff --git a/k8s/60-network-policy.yaml b/k8s/60-network-policy.yaml new file mode 100644 index 0000000..68d7aa9 --- /dev/null +++ b/k8s/60-network-policy.yaml @@ -0,0 +1,61 @@ +# Ingress rules for namespace ins-landing-page (enforced by Calico). Everything is denied unless +# a policy below allows it. The kubelet's probes come from the pod's own node, which Calico always +# allows, so they need no rule. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: default-deny-ingress + namespace: ins-landing-page +spec: + podSelector: {} + policyTypes: + - Ingress +--- +# Traefik (MicroK8s ingress addon, namespace `ingress`) to the app. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: app-from-traefik + namespace: ins-landing-page +spec: + podSelector: + matchLabels: + app: ins-landing-page + policyTypes: + - Ingress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: ingress + podSelector: + matchLabels: + app.kubernetes.io/name: traefik + ports: + - protocol: TCP + port: 3000 +--- +# cert-manager's HTTP-01 solver pod: Traefik must reach it, or the certificate cannot be issued +# or renewed. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: acme-solver-from-traefik + namespace: ins-landing-page +spec: + podSelector: + matchLabels: + acme.cert-manager.io/http01-solver: "true" + policyTypes: + - Ingress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: ingress + podSelector: + matchLabels: + app.kubernetes.io/name: traefik + ports: + - protocol: TCP + port: 8089 diff --git a/scripts/waitForOlderRuns.sh b/scripts/waitForOlderRuns.sh new file mode 100755 index 0000000..445dd61 --- /dev/null +++ b/scripts/waitForOlderRuns.sh @@ -0,0 +1,82 @@ +#!/bin/bash +# Usage: waitForOlderRuns.sh +# Queues deploy runs per branch (openspec ci-pipeline): returns 0 once no OLDER push run of this +# branch is pending, queued or in progress, so runs build and roll out one at a time, in push order. +# Gitea's workflow `concurrency` cannot do this: it keeps one waiting run per group and cancels the +# others, even with cancel-in-progress: false. +# +# It also refuses (exit 1) when a NEWER push run of the branch has already succeeded: that is a manual +# re-run of an old run, which would roll an older image out over a newer one. Push again instead; the +# self-heal (resolveDeployBase.sh) rebuilds whatever the old run missed. +# +# Fails closed: a failed or unreadable API answer counts as "still waiting", and a run still waiting +# after WAIT_TIMEOUT seconds exits 1 rather than build alongside an older run. A refused token (401/403) +# exits 1 at once — waiting would only end in the timeout. +# +# ponytail: reads the newest 50 runs of each kind; an older unfinished run beyond them is not seen. A run +# being cancelled (Gitea "cancelling") is reported in_progress by the API but is not matched by the +# status=in_progress filter; both gaps are seconds-to-minutes wide here — page the API if that changes. +# +# Env: GITEA_TOKEN, GITEA_API (…/api/v1), GITEA_REPO (owner/name), GITEA_BRANCH — for the default fetch. +# WAIT_INTERVAL (s, default 30), WAIT_TIMEOUT (s, default 7200), WAIT_FETCH (a command printing the +# runs JSON; tests replace the API with it). +set -u +own="${1:-}" +if ! [[ "$own" =~ ^[0-9]+$ ]]; then + echo "waitForOlderRuns: own run number must be a number, got '$own'" >&2 + exit 2 +fi +interval="${WAIT_INTERVAL:-30}" +deadline=$(( $(date +%s) + ${WAIT_TIMEOUT:-7200} )) + +fetch() { # $1 = unfinished | succeeded. Prints the runs JSON; exit 3 = token refused, other non-zero = failed. + if [ -n "${WAIT_FETCH:-}" ]; then + "$WAIT_FETCH" "$1" + return + fi + local status=status=success code body + [ "$1" = unfinished ] && status="status=pending&status=queued&status=in_progress" + body="$(mktemp)" + code="$(curl -sS --max-time 20 -o "$body" -w '%{http_code}' -H "Authorization: token $GITEA_TOKEN" \ + "$GITEA_API/repos/$GITEA_REPO/actions/runs?branch=$GITEA_BRANCH&event=push&$status&limit=50")" || code=000 + case "$code" in + 200) cat "$body"; rm -f "$body"; return 0 ;; + 401|403) rm -f "$body"; return 3 ;; + *) rm -f "$body"; return 1 ;; + esac +} + +run_numbers() { # runs JSON on stdin -> its run numbers, one per line. Nested objects carry no run_number. + grep -o '"run_number":[0-9]\+' | cut -d: -f2 +} + +while :; do + json="$(fetch unfinished)"; rc=$? + if [ "$rc" -eq 3 ]; then + echo "Runs API refused the job token (401/403); cannot queue run #$own safely." >&2 + exit 1 + fi + if [ "$rc" -eq 0 ] && [[ "$json" == *'"workflow_runs"'* ]]; then + older="$(printf '%s' "$json" | run_numbers | awk -v own="$own" '$1 < own' | sort -n | tr '\n' ' ')" + if [ -n "$older" ]; then + echo "Run #$own waits for older run(s): ${older% }" + elif done_json="$(fetch succeeded)" && [[ "$done_json" == *'"workflow_runs"'* ]]; then + newer="$(printf '%s' "$done_json" | run_numbers | awk -v own="$own" '$1 > own' | sort -n | tr '\n' ' ')" + if [ -n "$newer" ]; then + echo "Run #$own is older than run(s) ${newer% }, which already deployed; refusing to roll back. Push again instead." >&2 + exit 1 + fi + echo "No older run of this branch is unfinished; starting run #$own." + exit 0 + else + echo "Runs API read failed; run #$own keeps waiting." + fi + else + echo "Runs API read failed; run #$own keeps waiting." + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "Run #$own still waiting after ${WAIT_TIMEOUT:-7200}s; failing rather than building alongside an older run." >&2 + exit 1 + fi + sleep "$interval" +done