HUB
Sign inSign up
kavic-mock logo

vkakama/kavic-mock

By vkakama

•Updated 2 months ago

Stub HTTP mock server for end-to-end tests. Mocks external providers: payment rails, KYC, APIs.

Image
Integration & delivery
API management
Developer tools
3

391

vkakama/kavic-mock repository overview

⁠Kavic Mock

A stub HTTP server for end-to-end tests. It stands in for the external providers your system talks to — a payment rail, a KYC vendor, a fund administrator — decides what to answer from the request it was given, and, where the real provider would call back, calls back. It is driven entirely over HTTP with JSON, so any language, framework or CI system can use it, and it ships as a container image, so using it costs your project no dependency.

The one thing to know: when two of your stubs both match a request, Kavic Mock answers 409 naming both. It does not pick one. An ambiguous stub set is a defect in the test, and a server that guesses turns that defect into a failure three steps downstream.

Why not an in-process double? A fake client bean replaces the code being proved — no line of the HTTP layer runs, so the suite can be green while the URL paths, auth headers, serialisation, response parsing and 4xx/5xx mapping are all wrong. And an asynchronous provider cannot be tested end-to-end without something that calls your callback back.

⁠What a harness needs
GET  /__kavic/api/v1/journal            what your client actually sent
POST /__kavic/api/v1/reset?namespace=…  back to the baseline, per test
KAVIC_ADMIN_AUTH_ENABLED=false          no token plumbing inside the suite
KAVIC_STUBS_SEED_DIR                    the read-only baseline a reset returns to

One set of stub definitions serves local development and CI, which is what most mock servers cannot offer. A library the suite starts keeps its stubs in that suite's code, so they run there and nowhere else. Here the baseline is a directory of files: mounted on a laptop, committed to a repository, mounted again in the pipeline. When a provider's contract drifts, a build fails instead of somebody finding it by hand.


⁠Quick start

docker pull vkakama/kavic-mock:0.2.0

Every commit to main also publishes 0.3.0-snapshot-<short-sha>, so a fix is pullable before it is tagged; those are pruned after 30 days. There is no latest and no moving tag of any name — a mutable tag makes a running server unidentifiable to whoever pinned it.

docker run -d --name kavic-mock -p 9898:9898 --read-only --tmpfs /tmp \
  -e KAVIC_ADMIN_AUTH_ENABLED=false vkakama/kavic-mock:0.2.0

That runs in memory, which is enough to try it. To keep stubs across restarts, mount a data directory — and note the image runs as uid 1000, so the directory has to be writable by it or every registration is refused with a 503 naming exactly that. See Running it with Docker Compose.

Three commands and you have a stubbed provider — create the namespace, register a stub, drive it:

curl -X PUT http://localhost:9898/__kavic/api/v1/namespaces/daraja \
  -H 'Content-Type: application/json' -d '{"description":"Safaricom M-PESA Daraja sandbox"}'
curl -X POST http://localhost:9898/__kavic/api/v1/stubs -H 'Content-Type: application/json' -d '{
  "namespace":"daraja","name":"stk-push","description":"STK push accepted",
  "method":"POST","path":"/mpesa/stkpush/v1/processrequest",
  "response":{"status":200,"json_body":{"ResponseCode":"0","CustomerMessage":"Success. Request accepted for processing"}}}'
curl -X POST http://localhost:9898/daraja/mpesa/stkpush/v1/processrequest
{"ResponseCode":"0","CustomerMessage":"Success. Request accepted for processing"}

Byte for byte what you declared — no envelope, no added fields, no reordered keys.


⁠Running it with Docker Compose

Kavic Mock is deployed once and left running — not started by a suite and not scoped to a test run. Automated suites drive it, and so do people testing by hand against the same environment.

⁠One thing to get right first

Same rule as above: the data directory must be writable by uid 1000, and neither Docker default gives you that.

⁠Method A — bind mount (simplest; the usual choice for local development)
services:
  kavic-mock:
    image: vkakama/kavic-mock:0.2.0
    container_name: kavic-mock
    ports:
      - "9898:9898"
    environment:
      # The ONE configuration decision the server requires — see Authentication below.
      KAVIC_ADMIN_AUTH_ENABLED: "false"
      KAVIC_STUBS_DATA_DIR: /data
      KAVIC_STUBS_SEED_DIR: /seed
    volumes:
      - ./data:/data
      - ./seed:/seed:ro
    read_only: true
    tmpfs:
      - /tmp
    healthcheck:                                   # health needs no token
      test: ["CMD", "wget", "-qO-", "http://localhost:9898/__kavic/actuator/health"]
mkdir -p data seed && docker compose up -d

On Docker Desktop (macOS, Windows) this works as-is; its file-sharing layer maps ownership. On Linux there is no such mapping, so chown the host directory once, before the first up:

mkdir -p data && sudo chown -R 1000:1000 data

A one-off — the directory keeps its ownership. Nicer locally on two counts: the project is one container, and stub files land in ./data, where promoting one to your baseline is a cp.

⁠Method B — named volume with an init container (portable; the usual choice for a deployment)

Where the volume is managed rather than mounted — CI, a shared environment. Take the file above, swap ./data:/data for kavic-data:/data, and add:

services:
  # Makes the data volume writable by uid 1000, then exits.
  kavic-init:
    image: alpine:3
    command: chown -R 1000:1000 /data
    user: root
    volumes:
      - kavic-data:/data

  kavic-mock:
    depends_on:
      kavic-init:
        condition: service_completed_successfully

volumes:
  kavic-data:

The same one-off chown, inside the volume where you have no shell.

kavic-init will show as stopped, and that is correct. It exits 0 and gets out of the way, but Docker Desktop lights a project by how many containers run, so this one reads as partly running for ever. Check docker compose ps -a.

A volume keeps its ownership, so after the first successful up you can delete kavic-init and its depends_on — keep it only if the same file must stand up a fresh volume elsewhere.

If your system under test also runs in Compose, put both on the same network and point the callback base URL at its service name (http://my-service:8080), not localhost, which inside a container means the container itself.

⁠Environment variables
VariableDefaultNotes
KAVIC_PORT9898One port serves both surfaces
KAVIC_ADMIN_PREFIX/__kavicMust begin with an underscore
KAVIC_ADMIN_BIND_ADDRESS0.0.0.0Binds the whole server, not only the admin API
KAVIC_ADMIN_AUTH_ENABLEDtrueWith no realm configured, the server refuses to start
KAVIC_ADMIN_AUTH_KEYCLOAK_URL, ..._REALM, ..._REQUIRED_ROLE—, —, KAVIC_ADMINThe realm to validate against, and the role a token must carry
KAVIC_STUBS_SEED_DIRunsetRead-only baseline
KAVIC_STUBS_DATA_DIRunsetRead-write; unset means in-memory only
KAVIC_CALLBACK_TRUST_STOREunsetPEM bundle for an internal CA

⁠Concepts

Namespace — one stubbed provider. It is the first path segment of every request routed to it, so it takes the place of the provider's host in your test configuration:

https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest becomes http://kavic:9898/daraja/mpesa/stkpush/v1/processrequest.

You change one base URL per provider and nothing else. Paths below the namespace are written exactly as the provider documents them, in your client and in the stub alike. A namespace is created deliberately: registering a stub into one that does not exist is a 404 listing the ones that do, since a mistyped name silently creating a second would leave your stub invisible to every request going to the right one.

Two surfaces, one port. /__kavic/api/v1/** is the admin API, answering a standard envelope (status, message, data); everything else is the mock surface. The prefix must begin with an underscore — namespace names exclude _, which is what stops one shadowing the admin API.

Stub — conditions plus a response. Exactly one must match: zero is a 404 with a diff, two or more a 409 naming both. Journal — what arrived, what matched, what was answered, which is how you assert "my client sent exactly this".


⁠A worked example: standing in for M-PESA Daraja

Daraja exercises everything: bearer auth, body matching, an acknowledge-then-callback flow, and a token that expires.

1. Create the namespace as in the quick start: PUT answers 201 the first time and 200 after, so setup can call it unconditionally.

2. Set the config your callbacks interpolate — where your system listens. Per-namespace, never global, so one deployment serves several systems under test.

curl -X PUT http://localhost:9898/__kavic/api/v1/namespaces/daraja/config/callback-base-url \
  -H 'Content-Type: text/plain' --data-binary 'http://my-service:8080'

Ordering matters. Config must be set before the stubs referencing it; a stub naming an unset key is refused at registration. Deferring that to dispatch turns a setup mistake into a callback that silently never arrives, diagnosed hours later and nowhere near its cause.

3. The token endpoint — expired once, then fresh. A responses array answers 401 then 200, so "it refreshed correctly" and "it never refreshed" stop being indistinguishable. See Order sequences.

4. STK push — acknowledge, then call back.

curl -X POST http://localhost:9898/__kavic/api/v1/stubs -H 'Content-Type: application/json' -d '{
  "namespace": "daraja",
  "name": "stk-push-accepted",
  "description": "STK push accepted for a known test handset",
  "method": "POST",
  "path": "/mpesa/stkpush/v1/processrequest",
  "headers": { "Authorization": { "matches": "^Bearer .+$" } },
  "body_fields": [
    { "json_path": "$.PhoneNumber", "value": { "anyOf": ["254708374149", "254711111111"] } }
  ],
  "response": {
    "status": 200,
    "json_body": {
      "CheckoutRequestID": "ws_CO_191220191020363925",
      "ResponseCode": "0",
      "CustomerMessage": "Success. Request accepted for processing"
    }
  },
  "callback": {
    "method": "POST",
    "url": "${config:callback-base-url}/api/v1/callbacks/mpesa",
    "headers": { "Content-Type": "application/json" },
    "delay_ms": 300,
    "body": "{\"Body\":{\"stkCallback\":{\"ResultCode\":0,\"CallbackMetadata\":{\"Item\":[{\"Name\":\"Amount\",\"Value\":${request.body:$.Amount}},{\"Name\":\"PhoneNumber\",\"Value\":${request.body:$.PhoneNumber}}]}}}}"
  }
}'

Drive it:

curl -X POST http://localhost:9898/daraja/mpesa/stkpush/v1/processrequest \
  -H 'Authorization: Bearer c2VjcmV0LXRva2Vu' -H 'Content-Type: application/json' \
  -d '{"TransactionType":"CustomerPayBillOnline","Amount":1,"PhoneNumber":254708374149}'

Your service is acknowledged immediately, and 300 ms later a real HTTP POST arrives at its callback endpoint carrying the amount and phone number from the request it just made — so your correlation logic is exercised rather than assumed.


⁠Matching reference

A stub may carry any combination, and all must hold. No priority field, no specificity ranking, no registration-order effect.

Method and path — exact unless the path declares variables, and relative to the namespace: a path repeating its namespace is refused at registration. An unconstrained {segment} matches any single non-empty segment; wildcards are unsupported, since a * copied from documentation matches more than its author can see.

{ "method": "GET", "path": "/mpesa/stkpushquery/{version}/query/{checkoutId}",
  "path_variables": { "version": { "equalTo": "v1" } } }

Headers are matched case-insensitively by name per RFC 9110 and case-sensitively by value unless the matcher says otherwise. For query parameters, a repeated parameter matches if any of its values satisfies the condition. Each named header or parameter is an independent condition.

{ "headers": { "Authorization": { "matches": "^Bearer .+$" }, "X-Trace": { "absent": true } },
  "query_params": { "shortcode": { "equalTo": "174379" }, "ref": { "contains": "INV-" } } }

The whole body — exactly one of equalToJson (key order and insignificant whitespace ignored), matchesJsonPath, equalTo (literal string) or matches (regular expression).

{ "body": { "equalToJson": { "TransactionID": "NLJ7RT61SV", "Amount": 1 } } }
{ "body": { "matchesJsonPath": "$[?(@.Amount > 70000)]" } }

A field inside the body, where the full matcher vocabulary applies. A path resolving to nothing satisfies absent and fails every other matcher.

{ "body_fields": [
    { "json_path": "$.PhoneNumber", "value": { "anyOf": ["254708374149", "254711111111"] } },
    { "json_path": "$.TransactionType", "value": { "equalTo": "CustomerPayBillOnline" } } ] }
⁠The seven matchers
MatcherHolds when
{"equalTo": "v1"}exactly equal, case-sensitive
{"equalToIgnoreCase": "v1"}equal ignoring case
{"contains": "INV-"}the value contains that substring
{"matches": "^Bearer .+$"}the whole value matches the expression
{"absent": true}the field was not sent
{"present": true}the field was sent, with any value
{"anyOf": [...]}any entry holds — 2 to 50 entries

anyOf entries are literal values or any of the other six: {"anyOf": [{"matches": "^2547[0-9]{8}$"}, {"equalTo": "254711111111"}]}.

anyOf is OR within one field only. OR across fields is deliberately not expressible — it would make the no-match diagnostic unexplainable. Two stubs express that choice.

Note the key casing: the seven matchers are camelCase, every structural key snake_case (json_path, body_fields, delay_ms) — the spelling WireMock users already know.


⁠Responses

{ "response": { "status": 200, "json_body": { "ResponseCode": "0" },
                "headers": { "X-Request-Id": "abc" }, "delay_ms": 300 } }
FieldNotes
statusAny code 100–599 — a provider that answers 418 must be reproducible
json_bodyA JSON value; Content-Type defaults to application/json
bodyA literal string. Content-Type is then mandatory — guessing would put a header on the wire the provider never sends
headersSent exactly as declared
delay_ms0–30000, for exercising your client's timeout

Nothing is added to a served response — no envelope, no error page, no security headers, only Content-Type, Content-Length and Date.


⁠Interpolation

Five sources, and no expression syntax at all — no defaults, no functions, no nesting:

ExpressionReads
${request.body:$.PhoneNumber}a JSONPath into the matched request's body
${request.header:X-Request-Id}a header from the matched request
${request.query:orderId}a query parameter
${request.path:checkoutId}a path variable your template declared
${config:callback-base-url}a value from the namespace's config

Usable in a response body, response headers, and a callback's URL, headers and body. An expression resolving to nothing renders as an empty string and is recorded — null is how a client dereferences it and fails somewhere unrelated. $${ escapes a literal ${.


⁠Callbacks

{ "callback": { "method": "POST", "url": "${config:callback-base-url}/api/v1/callbacks/mpesa",
    "headers": { "Content-Type": "application/json", "Authorization": "Bearer ${config:callback-token}" },
    "body": "{\"ResultCode\":0}", "delay_ms": 300 } }

The stub's own response is written first; the callback dispatches afterwards from another thread. delay_ms: 0 means "as soon as the response has been written", never before — a callback overtaking its own acknowledgement would be a race you could not reproduce.

Kavic Mock never authenticates its outbound callbacks — it holds no credential of its own. If your endpoint needs one, declare it as an ordinary header sourced from config.

Never retried: a retry the real provider would not perform teaches your test a false lesson about its own idempotency. One not completing in 10 s is abandoned as TIMED_OUT.

Every attempt is recorded at GET /__kavic/api/v1/callbacks?namespace=daraja — a callback that silently failed to fire is indistinguishable from a system under test that ignored it:

OutcomeMeans
COMPLETEDReached the endpoint and got a status back — any status. A 500 from your service means the callback landed
TIMED_OUTAbandoned after 10 s
CONNECT_FAILEDNothing listening, or the host did not resolve
TLS_FAILEDCertificate did not validate — mount an internal CA at KAVIC_CALLBACK_TRUST_STORE
BLOCKEDDenied by the egress list, which by default covers link-local addresses
INVALID_URLNot absolute after interpolation

Poll for a callback; never sleep for a guessed duration.


⁠Order sequences

A sequence answers differently on successive calls — which is what makes a token refresh, a retry or a poll testable.

{ "responses": [
    { "status": 200, "json_body": { "ResponseDescription": "Success" } },
    { "status": 500, "json_body": { "errorMessage": "ShortCode already registered" } } ],
  "on_exhaustion": "fail" }

on_exhaustion is repeat_last by default — the last entry repeats, which is what a poll or refresh test wants. fail answers 409 naming the stub and its response count, which is what a retry test wants, where a third call means the code under test is wrong.

A sequence advances the response, never the match: which stub matches is decided entirely by the request, so a sequenced stub is no likelier to be ambiguous than any other.

⁠Per-entity positions

A shared counter is wrong when two entities are in flight; sequence_key gives each its own:

{ "method": "GET", "path": "/mpesa/stkpushquery/v1/query/{checkoutId}",
  "sequence_key": { "path": "checkoutId" },
  "responses": [ { "status": 200, "json_body": { "ResultCode": "1032" } },
                 { "status": 200, "json_body": { "ResultCode": "0" } } ] }

Polling one checkout does not advance another's. Extract the key from path, header, query or json_path; at most 1000 per stub, least recently used evicted. A key resolving to nothing answers 409 rather than falling back to a shared position, which would hide a broken setup.

POST /__kavic/api/v1/stubs/{id}/rewind resets one stub's position, which is narrower than a reset.

Without a sequence_key, a sequence is shared state. Two suites driving one namespace interleave positions and both read the wrong answers.


⁠Asserting with the journal

curl "http://localhost:9898/__kavic/api/v1/journal?namespace=daraja"
{ "status": "SUCCESS",
  "data": [ { "sequence": 3, "received_at": "2026-09-11T21:19:42Z",
      "method": "POST", "path": "/mpesa/stkpush/v1/processrequest",
      "headers": { "authorization": ["[REDACTED]"] },
      "body": "{\"Amount\":1,\"PhoneNumber\":254708374149}",
      "outcome": "MATCHED", "matched_stub_id": "2549...ad98",
      "status": 200, "response_index": 0 } ],
  "meta": { "page_info": { "total": 1, "current_page": 1, "total_pages": 1 } } }

Filter by namespace, method, path_like (case-insensitive substring), outcome (MATCHED, AMBIGUOUS, UNMATCHED), stub_id, received_at_gte and received_at_lte.

Credentials are redacted as they are stored, not on the way out — Authorization, Proxy-Authorization, Cookie and Set-Cookie by default. A journal holding a bearer token is a credential incident even if nothing reads it. A request naming no namespace is never journalled; its only record is the server's ERROR log.


⁠Reset and teardown

curl -X POST "http://localhost:9898/__kavic/api/v1/reset?namespace=daraja"

One call, because a teardown needing two will be half-written: it removes the namespace's stubs and config values, rewinds every sequence, and clears its journal. The namespace itself always survives — removing it would destroy its own precondition and fail the next test's first registration.

?all=true is the only form that removes namespaces: run-created ones go, seed-declared ones stay. There is no default: on a shared deployment an unscoped reset takes away somebody else's work.

A harness resets per test, then re-PUTs config before posting stubs — a reset leaves a run-created namespace with no config.


⁠Stubs on disk

Two directories, different lifecycles: KAVIC_STUBS_SEED_DIR is the read-only baseline kept in a repository and reloaded on every reset; KAVIC_STUBS_DATA_DIR is where the server writes what has been registered since, and is emptied by a reset.

seed/
  daraja/
    _namespace.json         {"description": "Safaricom M-PESA Daraja sandbox"}
    _config.json            {"callback-base-url": "http://my-service:8080"}
    stk-push-accepted.json

The namespace is the directory and the name is the filename — neither is repeated inside the file, so neither can disagree with where it sits, and a file the server wrote is committable to your seed directory unedited. A directory under either root declares a namespace, so it exists from startup even empty, and _config.json loads before the stub files.

A file that fails validation fails startup, naming every bad file at once: a stub silently skipped at boot becomes a test that fails later for an unrelated-looking reason.


⁠Authentication

The admin API is a resource server: it validates Keycloak-issued tokens and never issues one. The mock surface is never gated — your system believes it is talking to a third party, so a token there would be one it would never send in production.

Point it at a realm with KAVIC_ADMIN_AUTH_KEYCLOAK_URL, KAVIC_ADMIN_AUTH_REALM and KAVIC_ADMIN_AUTH_REQUIRED_ROLE; your harness sends a client-credentials token as Authorization: Bearer …. One confidential client per consuming team — the server records who changed what, and that record is worth nothing when every team is one principal.

With authentication on and no realm configured, the server refuses to start — a fixture that came up silently unprotected is worse than one that did not come up. KAVIC_ADMIN_AUTH_ENABLED=false is the deliberate opt-out, which the server warns about loudly at startup.

GET /__kavic/actuator/health needs no token, so a container wait strategy works before one exists.


⁠Reading the diagnostics

Every mock-surface failure answers a bare kavic_mock_error document — deliberately not the admin envelope, since no real provider wraps errors in a key named after this server — and repeats the code in an X-Kavic-Mock-Error response header.

NO_STUB_MATCHED lists every stub in the namespace closest miss first, with its first failing condition — the stub that satisfied the most conditions is almost always the one you meant, and that condition is almost always your bug:

- transaction list, filtered    query[shortcode] | expected equal to "174379" | actual 000000
- reversal for an exact payload method           | expected POST | actual GET
CodeMeans
UNKNOWN_NAMESPACEA base URL or a namespace PUT was missed. Names the segment given, the path, and the namespaces that exist
NO_STUB_MATCHEDThe namespace is right, no stub is — with the diff above
AMBIGUOUS_MATCHTwo stubs matched, so neither was served. candidates names both by description — which is why a description is mandatory. Narrow one stub or delete the other
SEQUENCE_EXHAUSTEDA sequence declaring on_exhaustion: fail was called past its end
SEQUENCE_KEY_UNRESOLVEDA partitioned stub matched a request not carrying its key

⁠Limits

Namespaces200
Stubs per namespace100
Stubs across the deployment2000
anyOf entries2–50
Responses in a sequence2–20
Partition keys per stub1000, least recently used evicted
Response delay0–30 s
Callback delay0–60 s
Callback timeout10 s, never retried
Journal1000 entries per namespace
Journalled body32 KB, then truncated with a flag

The per-namespace ceiling doubles as a leak detector: a teardown not removing what it registered meets it first.


Tag summary

Content type

Image

Digest

sha256:789d3600f…

Size

97.1 MB

Last updated

2 months ago

docker pull vkakama/kavic-mock:0.3.0-snapshot-5684395b