- JavaScript 69.3%
- Elixir 25.3%
- Shell 2.6%
- HTML 2.6%
- Dockerfile 0.2%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .forgejo/workflows | ||
| assets | ||
| config | ||
| docs | ||
| lib | ||
| priv | ||
| scripts | ||
| test | ||
| .dockerignore | ||
| .env.example | ||
| .formatter.exs | ||
| .gitignore | ||
| .gitleaks.toml | ||
| AGENTS.md | ||
| Caddyfile | ||
| docker-compose.dev.yml | ||
| docker-compose.yml | ||
| Dockerfile | ||
| Dockerfile.ci | ||
| mix.exs | ||
| mix.lock | ||
| README.md | ||
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_idvalues are rejected with401 {"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_tokentable
Certificate Authority
- 2-tier ECC P-256 CA
- Root CA: self-signed, 25-year validity
- Sub CA: signed by Root CA —
build_ownermust setpublic_keyon theCertOwnerfor 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/rootGET /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
:licensecomes from theMDID_LICENSEenvironment variable (previeworreleased); it defaults to:previewwhen unset, in every environment. - Callers may pass an optional
cert_validityfield ([amount, unit], e.g.[1, "year"]) in the enrollment and renewal request bodies. It is honored only when the server runs with the:previewlicense and takes precedence over the configured:cert_validity. Under the:releasedlicense a providedcert_validityis silently ignored. Invalidcert_validityvalues are rejected with400(invalid cert_validityfor enrollment,iErrorCode: "600"for renewal) under:preview. - Only
:previewreads the optional:cert_validityserver setting. Add it inconfig/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.
:releasedignores:cert_validityand 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 frompriv/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 setsMDID_PUBLIC_BASE_URL).
OCSP
- The public OCSP responder accepts
POST /services/ocspand Base64urlGET /services/ocsp/:requestrequests. It returns DER with content typeapplication/ocsp-response. - A delegated P-256 responder certificate is generated on startup when absent. It is issued by the Sub CA and includes the
OCSPSigningEKU 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 withconfig :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
serialNumberagainst the 12-digit MyKad structure (dashedYYMMDD-PB-###Gform is normalized; no checksum exists, so only the structural rule is enforced; seeSubjectValidator). Failures return400withiErrorCode: "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 checknotAfter. Responses are signed with ECDSA/SHA-256 (the P-256 responder key). - Errors: every
/api/v1/cert_mgmterror (including admin endpoints) is{"iErrorCode","sErrorMessage"}:600bad/missing parameter,602active certificate exists,500server failure, otherwise the HTTP status (401,403,404,409,429). Onlyoauth/tokenuses RFC 6749{"error":...}. - Enrollment: Before issuing locally, enrollment checks Trustgate SOAP status by CSR
serialNumber/icNumberfirst withoutissuerCN, 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-000result returns503 {"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
fullnamewhen no serial is available) before the new certificate is issued; a remote revocation failure blocks renewal. - Status:
/api/v1/cert_mgmt/statusrequiresicNumber; clientissuerCNis optional. SOAP is queried on every request with the caller value when supplied, otherwise the configured default issuer CN (MDID_DEFAULT_ISSUER_CN, defaultMyTrust 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,-101is returned. The SOAPx509Certresponse falls back to thebase64field whenx509Certis absent. - Revoke by certificate serial:
/api/v1/cert_mgmt/revokeaccepts the actual certificate serial hex incertSerialNumber. 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-icand theserialNumber/icNumberbranch of/api/v1/cert_mgmt/revokeaccept optionalfullnameand clientissuerCN. The default Trustgate test-siteRevokeByIcNumberSOAP contract accepts only optionalfullnameand requiredicNumber; whenfullnameis omitted, the controller uses it from a matching local record when available, otherwise omits it from SOAP. Trustgate may return its own600error for a remote-only record without a name, and the API returns that response unchanged.issuerCNfilters 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
serialNumberfrom CSR →ic_number,commonName→fullname, issuer CN from sub CA →issuer_cn. certSerialnumberin 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 DNserialNumberused 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 successfulx509Certresponse to./new_cert.crt02_renew.sh— renewal04_revoke_by_ic.sh— revoke by IC; extracts subjectserialNumberandcommonNamefrom a CSR06_check_status.sh— status check; accepts IC number and optional issuer CN07_full_workflow.sh— end-to-end workflow08_revoke_by_serial.sh— revoke by the actual X.509 serial extracted from an issued certificate PEM09_ocsp.sh— verify public OCSP POST and GET operations for an issued leaf PEM10_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 tostart-docker-dev.shdocker-shell.sh— attach an IEx remote console to the running releasedocker-sh.sh— open a plain/bin/shshell 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 protocolstrap_certificate_manager+ex_ccrypto_ext— ECC CA and certificate operationsjose— JWT signing/verificationx509— X.509 utilitiesuniq— 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):
- Point your domain's DNS A record to your server's IP
- Set
MDID_DOMAIN=your-domain.comandCADDY_EMAIL=your@email.comin.env - Run
docker compose up -d --build - Caddy automatically obtains and renews Let's Encrypt certificates
- Access your service at
https://your-domain.com
Local development (localhost):
- Set
MDID_DOMAIN=localhostin.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_copiespersisted via Docker volumemdid_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_datavolume
Environment variables (via .env):
SECRET_KEY_BASE— required; generate withmix phx.gen.secretMDID_KEY_ENCRYPTION_KEY— required in prod; base64 of 32 bytes (openssl rand -base64 32), encrypts stored CA and JWT signing keys. Seedocs/key-management.mdPHX_HOST— defaults tolocalhostRELEASE_COOKIE— required; generate withopenssl rand -base64 32MDID_DOMAIN— domain for TLS (e.g.,localhostoryour-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.