No description
  • JavaScript 69.3%
  • Elixir 25.3%
  • Shell 2.6%
  • HTML 2.6%
  • Dockerfile 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
amiryahaya 53bf5063be
All checks were successful
Lint / lint (push) Successful in 1m34s
Security / Dependency advisories (mix hex.audit) (push) Successful in 25s
Security / Secret scan (gitleaks) (push) Successful in 10s
Unit tests / test (push) Successful in 2m27s
Merge pull request 'fix: renew the OCSP responder certificate before it expires (#64)' (#66) from fix/64-ocsp-responder-renewal into main
2026-11-15 20:50:17 +01:00
.forgejo/workflows ci: use prebuilt ci-elixir image (elixir+node+jq) for beam jobs 2026-11-15 00:46:48 +08:00
assets chore: B7 — drop unused dark variant 2026-11-16 00:22:16 +08:00
config fix: #26 review — blank seed env vars fall back to defaults, test cleanup order, docs 2026-11-16 00:47:09 +08:00
docs fix: renew the OCSP responder certificate before it expires (#64) 2026-11-16 03:37:35 +08:00
lib fix: renew the OCSP responder certificate before it expires (#64) 2026-11-16 03:37:35 +08:00
priv fix(security): opaque error responses, DTD rejection, OCSP nonce, HSTS, vendored swagger 2026-11-15 09:36:51 +08:00
scripts fix: B6 pass-1 review — token format guard, exact schema match, banner helper, store tests 2026-11-16 00:02:36 +08:00
test test: avoid type warning in renewal republisher test 2026-11-16 03:38:56 +08:00
.dockerignore fix: B2 review — restore procedure, backup script safety, https-only URLs, dev start_period, hide /healthz at Caddy 2026-11-15 19:12:27 +08:00
.env.example fix: #26 review — blank seed env vars fall back to defaults, test cleanup order, docs 2026-11-16 00:47:09 +08:00
.formatter.exs chore: initial import from chris/CA-MDID @ d85e2ee (clean snapshot, credentials redacted) 2026-11-12 16:45:41 +08:00
.gitignore chore: initial import from chris/CA-MDID @ d85e2ee (clean snapshot, credentials redacted) 2026-11-12 16:45:41 +08:00
.gitleaks.toml ci: fix private-dep auth (user:token), hex.audit needs deps, gitleaks allowlist config 2026-11-15 00:11:41 +08:00
AGENTS.md fix: renew the OCSP responder certificate before it expires (#64) 2026-11-16 03:37:35 +08:00
Caddyfile fix: B2 review — restore procedure, backup script safety, https-only URLs, dev start_period, hide /healthz at Caddy 2026-11-15 19:12:27 +08:00
docker-compose.dev.yml fix: Batch B3 — hardening nits (#31), doc fixes (#32), gate live Trustgate tests (#33), PII redaction + telemetry (#34), crypto nits (#35) 2026-11-15 19:36:23 +08:00
docker-compose.yml fix: Batch B3 — hardening nits (#31), doc fixes (#32), gate live Trustgate tests (#33), PII redaction + telemetry (#34), crypto nits (#35) 2026-11-15 19:36:23 +08:00
Dockerfile fix: Batch B3 — hardening nits (#31), doc fixes (#32), gate live Trustgate tests (#33), PII redaction + telemetry (#34), crypto nits (#35) 2026-11-15 19:36:23 +08:00
Dockerfile.ci ci: use prebuilt ci-elixir image (elixir+node+jq) for beam jobs 2026-11-15 00:46:48 +08:00
mix.exs chore: B7 — remove unused daisyUI/heroicons plugins, vendored files and :heroicons dep 2026-11-16 00:21:29 +08:00
mix.lock chore: B7 — remove unused daisyUI/heroicons plugins, vendored files and :heroicons dep 2026-11-16 00:21:29 +08:00
README.md fix: #26 review — blank seed env vars fall back to defaults, test cleanup order, docs 2026-11-16 00:47:09 +08:00

MdidWs

Phoenix-based certificate management web service exposing RESTful APIs for enrollment, renewal, revocation, and status checking. Uses Mnesia for persistence, ECDSA P-256 for JWT signing, and a 2-tier ECC CA (Root + Sub) for certificate issuance.

Quick Start

Mnesia disc_copies requires a named node. Always start with --sname:

# Development
iex --sname mdid_ws -S mix phx.server

# Or non-interactive
elixir --sname mdid_ws -S mix phx.server

Visit localhost:4000 for the developer documentation portal.

An Mnesia directory is bound to the node name that created it. Reuse the same named node for an existing directory; when switching node names, use a new MNESIA_DIR instead.

For disposable local integration work, use a fresh Mnesia directory instead of deleting or relying on the existing mnesia.db state:

MNESIA_DIR="$(mktemp -d)" elixir --sname mdid_ws -S mix phx.server

Setup

mix setup        # install deps + assets
mix precommit    # compile (warnings as errors), format, and run tests

Testing

Tests require a named node because Mnesia disc_copies is used. Use the provided alias:

mix test_named

This clears /tmp/mdid_ws_test_mnesia and runs elixir --sname test@localhost -S mix test.

Architecture Overview

Authentication

  • OAuth2 Client Credentials flow at POST /api/v1/cert_mgmt/oauth/token
  • Development seed client: client_id=mdid_ws_client, client_secret=mdid_ws_secret
  • Unknown client_id values are rejected with 401 {"error":"invalid_client"}; they are not auto-created
  • JWT access tokens signed with ECDSA P-256 keypair stored in Mnesia (:oauth_signing_key)
  • Access tokens are persisted in :oauth_access_token table

Certificate Authority

  • 2-tier ECC P-256 CA
  • Root CA: self-signed, 25-year validity
  • Sub CA: signed by Root CA — build_owner must set public_key on the CertOwner for CA-signed certs so the certificate's Subject Public Key Info matches the signing keypair
  • Leaf certificates use their issuance path's default validity unless preview configuration overrides it.
  • Public CA download endpoints (no auth required):
    • GET /api/v1/cert_mgmt/issuer/root
    • GET /api/v1/cert_mgmt/issuer/sub
  • Issuers are auto-generated on startup if missing (see MdidWs.Application.ensure_issuers/0)

Certificate Validity Configuration

  • Runtime config :license comes from the MDID_LICENSE environment variable (preview or released); it defaults to :preview when unset, in every environment.
  • Callers may pass an optional cert_validity field ([amount, unit], e.g. [1, "year"]) in the enrollment and renewal request bodies. It is honored only when the server runs with the :preview license and takes precedence over the configured :cert_validity. Under the :released license a provided cert_validity is silently ignored. Invalid cert_validity values are rejected with 400 (invalid cert_validity for enrollment, iErrorCode: "600" for renewal) under :preview.
  • Only :preview reads the optional :cert_validity server setting. Add it in config/runtime.exs, for example: config :mdid_ws, :cert_validity, [1, :year].
  • Accepted formats are [positive_integer, :year | :month | :week | :day | :hour | :min | :second] (units may also be given as strings in the request). Weeks are converted to days before certificate generation.
  • Invalid server-configured preview values fail issuance rather than falling back silently. :released ignores :cert_validity and preserves the existing issuance rules.

CRL

  • Local revocations regenerate the Sub CA CRL via MdidWs.CertManagement.CrlPublisher, published as a static DER file at /revocation/<sub CA cert serial hex>/crl.crl (served from priv/static, no auth required).
  • All leaf certificates issued during enrollment and renewal include a non-critical CRL Distribution Points extension (OID 2.5.29.31) with URI <crl_base_url>/revocation/<sub CA cert serial hex>/crl.crl.
  • The CDP base URL is configurable: config :mdid_ws, :crl_base_url, "https://mdidws.mypqc.com.my" (default shown; prod sets MDID_PUBLIC_BASE_URL).

OCSP

  • The public OCSP responder accepts POST /services/ocsp and Base64url GET /services/ocsp/:request requests. It returns DER with content type application/ocsp-response.
  • A delegated P-256 responder certificate is generated on startup when absent. It is issued by the Sub CA and includes the OCSPSigning EKU and OCSP nocheck extension.
  • The responder accepts SHA-1 and SHA-256 CertID hashes for compatibility and signs responses with ECDSA P-256/SHA-384.
  • Enrollment and both renewal paths include an OCSP Authority Information Access entry using <ocsp_base_url>/services/ocsp. The default base URL is configurable with config :mdid_ws, :ocsp_base_url, "https://mdidws.mypqc.com.my".

Certificate Management API (/api/v1/cert_mgmt)

All endpoints below require a valid Bearer JWT (via MdidWsWeb.Plugs.RequireJwt), except oauth/token and issuer/*.

Method Endpoint Description
POST /api/v1/cert_mgmt/ Enroll — CSR
POST /api/v1/cert_mgmt/renew Renew — CSR
POST /api/v1/cert_mgmt/revoke Revoke by certSerialNumber hex or subject serialNumber / icNumber
POST /api/v1/cert_mgmt/revoke-by-ic Revoke by icNumber (+ optional fullname and issuerCN)
POST /api/v1/cert_mgmt/status Check status by icNumber (+ optional issuerCN)
POST /api/v1/cert_mgmt/admin/tokens/revoke Revoke an access token by jti (admin scope)
POST /api/v1/cert_mgmt/admin/clients/suspend Suspend a client by client_id; its tokens stop working at once (admin scope)
POST /api/v1/cert_mgmt/admin/clients/reactivate Reactivate a suspended client (admin scope)

Each client holds scopes (enroll, renew, revoke, status, status_full, admin); a call without the matching scope returns 403 {"iErrorCode":"403"}. /status includes the x509Cert only for clients with status_full, and returns 429 with retry-after past 60 requests/minute per client. Issued certificates carry only the CSR's CN, serialNumber and C: organisation, OU, email and SubjectAltName are ignored.

Key Business Rules

  • MyKad IC validation: Enrollment and renewal validate the CSR subject serialNumber against the 12-digit MyKad structure (dashed YYMMDD-PB-###G form is normalized; no checksum exists, so only the structural rule is enforced; see SubjectValidator). Failures return 400 with iErrorCode: "600" / sErrorMessage: "serialNumber must be a 12-digit MyKad number".
  • OCSP and expiry: an expired certificate that was never revoked is answered good (RFC 6960 reports non-revocation only). Relying parties must check notAfter. Responses are signed with ECDSA/SHA-256 (the P-256 responder key).
  • Errors: every /api/v1/cert_mgmt error (including admin endpoints) is {"iErrorCode","sErrorMessage"}: 600 bad/missing parameter, 602 active certificate exists, 500 server failure, otherwise the HTTP status (401, 403, 404, 409, 429). Only oauth/token uses RFC 6749 {"error":...}.
  • Enrollment: Before issuing locally, enrollment checks Trustgate SOAP status by CSR serialNumber / icNumber first without issuerCN, then retries with the local Sub CA issuer CN when available. A SOAP -101 (not found) result allows enrollment to proceed; a SOAP fault or other non-000 result returns 503 {"iErrorCode":"500","sErrorMessage":"certificate status unavailable"}. Any valid SOAP or local certificate blocks enrollment.
  • Renewal: Revoked/Expired certificates can always be renewed. Valid certificates can only be renewed if they are ≤ 30 days from expiry (renewal_threshold_days). Remaining validity is carried over.
  • Renewal SOAP check: Standalone renewal runs the same SOAP-first lookup order as enrollment before local Mnesia lookup. A SOAP-valid certificate is renewable only when it is already within the 30-day grace period.
  • Renewal remote source: When no local certificate exists for the IC number, renewal falls back to the Trustgate SOAP certificate as the renewal source. If that remote certificate is still valid, it is revoked remotely first (by certificate serial, or by IC with fullname when no serial is available) before the new certificate is issued; a remote revocation failure blocks renewal.
  • Status: /api/v1/cert_mgmt/status requires icNumber; client issuerCN is optional. SOAP is queried on every request with the caller value when supplied, otherwise the configured default issuer CN (MDID_DEFAULT_ISSUER_CN, default MyTrust Digital ID Class 3 CA). A matching local Mnesia certificate takes response priority and is filtered by issuer only when the caller supplied one; otherwise a successful SOAP response is returned; if neither exists, -101 is returned. The SOAP x509Cert response falls back to the base64 field when x509Cert is absent.
  • Revoke by certificate serial: /api/v1/cert_mgmt/revoke accepts the actual certificate serial hex in certSerialNumber. SOAP revoke is attempted first and local state is the fallback. Local serial lookup normalizes input and tries both lowercase and uppercase stored variants for compatibility.
  • Revoke by IC: /api/v1/cert_mgmt/revoke-by-ic and the serialNumber / icNumber branch of /api/v1/cert_mgmt/revoke accept optional fullname and client issuerCN. The default Trustgate test-site RevokeByIcNumber SOAP contract accepts only optional fullname and required icNumber; when fullname is omitted, the controller uses it from a matching local record when available, otherwise omits it from SOAP. Trustgate may return its own 600 error for a remote-only record without a name, and the API returns that response unchanged. issuerCN filters local Mnesia records; the signed ICD profile includes it in its SOAP request. Local state remains synchronized after the SOAP revocation attempt.
  • Revocation by IC state rules:
    • Valid → Revoked (000 success)
    • Revoked → unchanged (000 success)
    • Expired → unchanged (000 success)
  • Enrollment extracts serialNumber from CSR → ic_number, commonName → fullname, issuer CN from sub CA → issuer_cn.
  • certSerialnumber in responses is the actual certificate serial normalized to lowercase hex. When certificate PEM or DER is available, the API derives this value from the certificate payload itself instead of trusting stored or SOAP serial strings. It is distinct from the subject DN serialNumber used as the IC identifier.

Error Codes

Code Meaning
000 Success
-101 Get Cert detail failed (not found)
600 Missing parameter value {X} from local validation or Trustgate; also used for an invalid MyKad serialNumber on renewal
RN102 Renewal failed (not within period)
RV200 Get Cert detail failed (revoke target not found)

Mnesia Tables

Table Module
:oauth_client MdidWs.OAuth.Client
:oauth_signing_key MdidWs.OAuth.SigningKey
:oauth_access_token MdidWs.OAuth.AccessToken
:certificate_request MdidWs.CertManagement.CertificateRequest
:issuer MdidWs.CertManagement.Issuer
:login_attempt MdidWs.Auth.LoginAttempt

Shell Scripts

The scripts/ directory contains API testing and Docker helper scripts:

API Testing

  • 01_enroll.sh — enrollment; writes a successful x509Cert response to ./new_cert.crt
  • 02_renew.sh — renewal
  • 04_revoke_by_ic.sh — revoke by IC; extracts subject serialNumber and commonName from a CSR
  • 06_check_status.sh — status check; accepts IC number and optional issuer CN
  • 07_full_workflow.sh — end-to-end workflow
  • 08_revoke_by_serial.sh — revoke by the actual X.509 serial extracted from an issued certificate PEM
  • 09_ocsp.sh — verify public OCSP POST and GET operations for an issued leaf PEM
  • 10_soap_enroll.sh — call Trustgate's test-site SOAP enrollment operation with a CSR; writes ./soap_new_cert.crt

04_revoke_by_ic.sh accepts a CSR path or prompts for one. It requires the CSR subject to contain both serialNumber and commonName, which it sends as icNumber and fullname to avoid Trustgate's remote-only 600 fullname error. The issuer CN remains an optional second argument:

./scripts/04_revoke_by_ic.sh ./request.csr
./scripts/04_revoke_by_ic.sh ./request.csr "My Sub CA"

08_revoke_by_serial.sh accepts an issued certificate PEM path or prompts for one, then extracts the actual X.509 certificate serial. A CSR cannot be used for this operation because the CA assigns the certificate serial after issuing the certificate:

./scripts/08_revoke_by_serial.sh ./new_cert.crt

OCSP Operation Check

09_ocsp.sh downloads the current Root and Sub CA certificates, then checks SHA-1 and SHA-256 CertID requests through both raw POST and Base64url GET. It checks the response content type and uses OpenSSL to validate the responder chain and certificate status.

BASE_URL=http://localhost:4000 ./scripts/09_ocsp.sh /path/to/issued-leaf.pem

The public OCSP endpoint does not require an OAuth token. The helper requires curl, openssl, base64, and tr. Set EXPECTED_STATUS to assert a status other than good, or CURL_INSECURE=1 for a local self-signed HTTPS endpoint.

SOAP Test-Site Enrollment

10_soap_enroll.sh calls the Trustgate mobilePKI test-site SOAP 1.1 enroll operation. It sends only the XML-escaped CSR element required by that endpoint; it does not use a private key or send CAPayload.

./scripts/10_soap_enroll.sh /path/to/request.csr

Set SOAP_ENDPOINT to override the endpoint, CURL_INSECURE=1 for a local self-signed HTTPS endpoint, or DRY_RUN=1 to print the generated envelope without sending it. On success, the helper converts the returned Base64 DER certificate (base64 or x509Cert) to PEM at ./soap_new_cert.crt. The signed ICD enrollment contract is intentionally not implemented by this helper.

Docker Helpers

  • start-docker-dev.sh — build and start the Docker stack in development mode (localhost, self-signed TLS)
  • start-docker-prod.sh — build and start the Docker stack in production mode (Let's Encrypt TLS for a public domain)
  • start-docker.sh — deprecated, delegates to start-docker-dev.sh
  • docker-shell.sh — attach an IEx remote console to the running release
  • docker-sh.sh — open a plain /bin/sh shell inside the running container

These helper scripts are also copied into the Docker image at /app/scripts/.

Dependencies

  • Phoenix 1.8 + LiveView 1.1
  • strap_data_store — Mnesia persistence protocol
  • strap_certificate_manager + ex_ccrypto_ext — ECC CA and certificate operations
  • jose — JWT signing/verification
  • x509 — X.509 utilities
  • uniq — UUID generation

Docker

A multi-stage Dockerfile and docker-compose.yml are included for containerized deployment. The stack includes a Caddy reverse proxy that provides automatic HTTPS via Let's Encrypt.

Requirements:

  • Docker + Docker Compose
  • Build context must be the workspace root (parent of mdid_ws/) so sibling local dependencies are accessible
  • For production TLS: a public domain name pointing to your server

Quick start:

# Quick start with helper script
./scripts/start-docker-dev.sh

# Or manually:
cp .env.example .env
# Edit .env and set SECRET_KEY_BASE, MDID_DOMAIN, and CADDY_EMAIL
docker compose up -d --build

TLS / Let's Encrypt

The Docker Compose stack includes a Caddy reverse proxy that automatically handles HTTPS:

Production (public domain):

  1. Point your domain's DNS A record to your server's IP
  2. Set MDID_DOMAIN=your-domain.com and CADDY_EMAIL=your@email.com in .env
  3. Run docker compose up -d --build
  4. Caddy automatically obtains and renews Let's Encrypt certificates
  5. Access your service at https://your-domain.com

Local development (localhost):

  • Set MDID_DOMAIN=localhost in .env
  • Caddy will use a self-signed certificate
  • Access via https://localhost (accept the browser warning)

Ports exposed by Caddy:

  • 80 → HTTP (redirects to HTTPS)
  • 443 → HTTPS

Docker details:

  • Base image: elixir:1.20.2 (Debian; same image for builder + runtime so NIFs match)
  • Runtime packages: libstdc++6, openssl, libncurses6, curl (healthcheck)
  • Runs as non-root user (mdid)
  • Mnesia disc_copies persisted via Docker volume mdid_mnesia
  • Named node (mdid_ws@localhost) for Mnesia compatibility
  • Production release built with mix release
  • scripts/ directory copied into the image at /app/scripts/
  • Issuers (Root + Sub CAs) are auto-generated on first startup if not present in Mnesia
  • Caddy certificates persisted via caddy_data volume

Environment variables (via .env):

  • SECRET_KEY_BASE — required; generate with mix phx.gen.secret
  • MDID_KEY_ENCRYPTION_KEY — required in prod; base64 of 32 bytes (openssl rand -base64 32), encrypts stored CA and JWT signing keys. See docs/key-management.md
  • PHX_HOST — defaults to localhost
  • RELEASE_COOKIE — required; generate with openssl rand -base64 32
  • MDID_DOMAIN — domain for TLS (e.g., localhost or your-domain.com)
  • CADDY_EMAIL — email for Let's Encrypt account (optional for local dev)

Deployment

Ready to run in production? Please check our deployment guides.