-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathllms-full.txt
More file actions
1108 lines (963 loc) · 63 KB
/
Copy pathllms-full.txt
File metadata and controls
1108 lines (963 loc) · 63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Lerian Midaz — Full Reference
> Source-available (Elastic License 2.0) core banking platform in a single Go 1.26.4 monorepo (v4 module path, single root go.mod — no go.work) on `github.com/LerianStudio/lib-commons/v6` v6.2.0 + `lib-observability/v2` v2.1.0. Three deploy units: a unified Ledger HTTP API (onboarding + transaction + CRM holders/instruments + fees, :3002), a Tracer real-time transaction-validation / fraud-prevention API (:4020), plus an Infra docker-compose backing stack. Uses PostgreSQL (primary/replica), MongoDB (metadata + CRM + fees), RabbitMQ (async transactions), and Valkey/Redis (caching). Supports multi-tenant isolation via the lib-commons v6 tenant-manager.
---
## 1. Product Overview
Midaz is a source-available core banking platform in a single Go monorepo: a double-entry
ledger plus real-time transaction validation/fraud prevention (Tracer), CRM (holders/instruments),
and a fee engine — all in one repository, building from one
root `go.mod`. It is no longer "just a ledger"; the consolidation folded the surrounding banking
capabilities into the same repo. Transactional messaging (PIX, cards, wires) and governance
integrations remain external/marketplace. It implements a financial hierarchy:
```
Organization → Ledger → Asset
→ Portfolio → Account
→ Segment → Account
→ Account Type
→ Transaction → Operation → Balance
```
Key capabilities:
- **Double-entry accounting**: Every transaction produces balanced debit/credit operations
- **N:N transactions**: Multiple sources and destinations in a single transaction
- **Multiple creation modes**: JSON, Inflow, Outflow, Annotation
- **Transaction lifecycle**: Create → Commit/Cancel/Revert (pending transactions support)
- **Async processing**: RabbitMQ-based balance updates with bulk recorder (10x throughput)
- **Multi-asset**: Currency (ISO-4217), crypto, commodities, custom asset types
- **Multi-tenant**: Database-per-tenant isolation via the lib-commons v6 tenant-manager
- **Accounting routes**: Configurable operation routes and transaction routes for validation
- **Real-time validation / fraud prevention (Tracer)**: CEL rule engine, multi-scope spending limits, two-phase reservations, and a hash-chained audit log, configurable per-ledger
- **Fees (embedded)**: fee engine + billing packages embedded in the ledger binary; fees applied on transaction create
- **CRM (folded)**: holder/instrument management folded into the ledger binary (host ledger's `midaz` namespace, path-scoped on `/v1/organizations/{organization_id}/...`)
## 2. Architecture
### 2.1 Deploy Units
Three deploy units: two Go services + infra. **CRM and fees are not deploy units** — CRM is a
package tree (`components/ledger/internal/crm`) imported by the ledger binary, and fees are embedded in the
ledger binary. Both are served on the ledger port `:3002`.
| Deploy unit | Port | Description | Data Stores |
|-------------|------|-------------|-------------|
| **Ledger** | 3002 | Unified HTTP API: onboarding + transaction + **CRM** (holders/instruments) + **fees** (engine + billing) | PostgreSQL (onboarding DB + transaction DB), MongoDB (metadata + CRM + fees), Redis/Valkey, RabbitMQ |
| **Tracer** | 4020 | Real-time transaction validation / fraud-prevention API (CEL rule engine, hash-chained audit) | PostgreSQL (own migrations) |
| **Infra** | — | Docker Compose backing stack (single source) | PostgreSQL 17 (primary/replica), MongoDB, RabbitMQ 4.1, Valkey, Grafana/OTEL-LGTM |
### 2.2 Pattern: Hexagonal Architecture with CQRS
```
Handlers (HTTP) → Services (Command/Query) → Repositories (Postgres/Mongo/Redis/RabbitMQ)
↓ ↓ ↓
Models (pkg/mmodel) Models Models
```
Dependencies flow inward. Inner layers must not depend on outer layers. Interfaces defined where used.
### 2.3 Directory Structure
```
midaz/
├── components/
│ ├── ledger/ # DEPLOY UNIT :3002 — onboarding + transaction + CRM + fees
│ │ ├── cmd/app/ # main.go entry point
│ │ ├── internal/
│ │ │ ├── adapters/
│ │ │ │ ├── http/in/ # Fiber HTTP handlers + routes (incl. fees_routes.go, crm_routes.go, holder/instrument handlers)
│ │ │ │ ├── http/out/# Outbound HTTP clients
│ │ │ │ ├── postgres/# PostgreSQL repositories (onboarding + transaction)
│ │ │ │ ├── mongodb/ # MongoDB metadata + fees repositories
│ │ │ │ ├── redis/ # Redis/Valkey cache repositories
│ │ │ │ └── rabbitmq/# RabbitMQ producer/consumer
│ │ │ ├── bootstrap/ # Config, DI, server lifecycle, workers, initCRM, fee wiring
│ │ │ └── services/
│ │ │ ├── command/ # Write operations (CQRS)
│ │ │ ├── query/ # Read operations (CQRS)
│ │ │ └── fees/ # Embedded fee + billing-package use cases
│ │ ├── pkg/
│ │ │ ├── fee/ # Embedded fee engine
│ │ │ └── feeshared/ # Embedded fee shared types/constants (plugin-fees)
│ │ ├── migrations/
│ │ │ ├── onboarding/ # SQL migrations for onboarding DB
│ │ │ └── transaction/ # SQL migrations for transaction DB
│ │ └── api/ # OpenAPI 3.1 spec (openapi.huma.yaml, Huma-generated)
│ ├── crm/ # PACKAGE TREE (not a deploy unit) — imported by ledger
│ │ ├── adapters/
│ │ │ └── mongodb/ # holder/ + instrument/ repositories
│ │ └── services/ # CRM business logic
│ │ # HTTP handlers/routes live in ledger http/in/ (midaz namespace); spec folds into ledger api/
│ ├── tracer/ # DEPLOY UNIT :4020 — real-time validation / fraud-prevention API (CEL, audit log)
│ │ ├── cmd/app/
│ │ ├── internal/
│ │ └── migrations/ # Tracer's own SQL migrations
│ └── infra/ # DEPLOY UNIT — Docker Compose backing stack (single source)
│ ├── docker-compose.yml
│ ├── postgres/ # Init scripts
│ ├── mongo/ # Replica set init
│ ├── rabbitmq/ # Definitions, config
│ └── grafana/ # OTEL collector config
├── pkg/ # Shared packages (root)
│ ├── mmodel/ # Domain models (incl. Holder, Instrument)
│ ├── constant/ # Error codes (ledger 0001+, gap at 0130; 28 CRM-00xx: CRM-0006..CRM-0041), action/module constants
│ ├── errors.go # Typed error structs + ValidateBusinessError
│ ├── net/http/ # Middleware, pagination, protected routes
│ ├── mtransaction/ # Transaction processing utilities (renamed from the old transaction pkg)
│ ├── streaming/ # lib-streaming event modeling
│ ├── crypto/ # CRM crypto primitives: kms/vault/ (Vault Transit KEK), tink/ (DEKs), mode + resolver
│ ├── mongo/ # MongoDB utilities
│ ├── repository/ # Repository interfaces
│ ├── pagination/ # Pagination helpers
│ └── utils/ # General utilities
├── tests/ # Shared test trees (root)
│ ├── chaos/, helpers/, utils/
├── scripts/ # Build/CI scripts
├── mk/ # Makefile includes (coverage, tests, quality)
├── docs/PROJECT_RULES.md # Coding standards
├── docs/auth/RBAC-NAMESPACES.md # The three authz namespaces (R9)
├── docs/api/SCOPING.md # Path-based org scoping on every surface, no exceptions (R22 reversed)
├── Makefile # Root orchestrator
├── go.mod # Module: github.com/LerianStudio/midaz/v4 (single root go.mod)
└── go.sum
```
## 3. Domain Models
All models live in `pkg/mmodel/`. Key entities:
### 3.1 Organization
- Fields: ID, ParentOrganizationID, LegalName, DoingBusinessAs, LegalDocument, Address, Status, Metadata, CreatedAt, UpdatedAt, DeletedAt
- Address follows ISO 3166-1 alpha-2 for country codes
### 3.2 Ledger
- Fields: ID, Name, OrganizationID, Status, Settings, Metadata, CreatedAt, UpdatedAt, DeletedAt
- Settings has two branches: `accounting` validation (validateAccountType, validateRoutes, requireHolder — the last gates CRM holder linkage) and `tracer` (per-ledger tracer/fraud-prevention toggles)
### 3.3 Account
- Fields: ID, Name, ParentAccountID, EntityID, HolderID, AssetCode, OrganizationID, LedgerID, PortfolioID, SegmentID, Status, Alias, Type, Blocked, Metadata, CreatedAt, UpdatedAt, DeletedAt
- HolderID is the CRM ownership link — the formal owner of the account (distinct from EntityID, which is not the ownership link); this field ties CRM holders to ledger accounts
- Alias format: `@<identifier>` (unique per ledger)
- Type: user-defined (e.g., "deposit", "expense", "revenue"); "external" is system-reserved
- Sub-accounts via ParentAccountID
### 3.4 Asset
- Fields: ID, Name, Type, Code, Status, OrganizationID, LedgerID, Metadata, CreatedAt, UpdatedAt, DeletedAt
- Types: currency, crypto, commodities, others
- Code: uppercase alphanumeric; currency codes follow ISO-4217
### 3.5 Transaction
- Persisted fields: ID, ParentTransactionID, Description, Status, Amount (single decimal), AssetCode, ChartOfAccountsGroupName, Source ([]string aliases), Destination ([]string aliases), LedgerID, OrganizationID, Route (deprecated), RouteID, Metadata, CreatedAt, UpdatedAt, DeletedAt
- Status lifecycle: ACTIVE → (revert) | PENDING → COMMIT/CANCEL
- Source/Destination are arrays of account aliases; per-operation amount/share/remaining distribution is expressed in the transaction INPUT (Send) shape, not the persisted record
### 3.6 Balance
- Fields: ID, OrganizationID, LedgerID, AccountID, Alias, Key, AssetCode, Available, OnHold, AccountType, Direction, OverdraftUsed, AllowSending, AllowReceiving, Version, Settings (*BalanceSettings), Metadata, CreatedAt, UpdatedAt, DeletedAt
- Key (max 100) identifies the balance within an account; Direction is the accounting direction; OverdraftUsed tracks consumed overdraft; Settings carries per-balance config (overdraft, etc.)
- Optimistic concurrency via Version field (lock version)
- Supports additional balances per account (e.g., multi-currency)
- Balance history queries via timestamp
### 3.7 Operation Route / Transaction Route
- Operation routes define per-operation rules (source/destination/bidirectional)
- Transaction routes compose multiple operation routes for accounting validation
- Account rules: alias-based or account-type-based validation
### 3.8 Account Type
- Custom account types per organization/ledger
- KeyValue identifier (alphanumeric + underscore + hyphen)
### 3.9 Holder (CRM)
- Fields: ID, ExternalID, Type (NATURAL_PERSON | LEGAL_PERSON), Name, Document, Addresses, Contact, NaturalPerson, LegalPerson, Status, Metadata, CreatedAt, UpdatedAt, DeletedAt
- Customer/entity ownership record; holders are linked to ledger accounts via Account.HolderID
- PII fields (Name, Document, contact details) are persisted via field-level encryption with searchable hashing (lib-commons crypto) — see CRM adapters
### 3.10 Instrument (CRM)
- Fields: ID, Document, Type, LedgerID, AccountID, HolderID, BankingDetails, RegulatoryFields, RelatedParties, Metadata, CreatedAt, UpdatedAt, DeletedAt
- An instrument associates a holder with a ledger account (HolderID + AccountID); carries banking details, regulatory fields, and related parties
## 4. API Reference
The HTTP layer is **Huma v2 (OAS 3.1) over Fiber v3**: Fiber remains the runtime router, auth
chain, and middleware stack, while Huma sits on top to generate the OpenAPI contract and validate
typed request/response structs. API errors serialize as **RFC 9457 `application/problem+json`** — a
`type`/`title`/`status`/`detail`/`instance` document extended with `code` and `entityType`; the
`(code, status)` tuple per business error is preserved (HTTP status codes are unchanged). The native
OpenAPI 3.1 spec and Scalar docs UI are served per contract version — `/v1/openapi.{json,yaml}` and
`/v1/docs` on both components, plus `/v2/openapi.{json,yaml}` and `/v2/docs` on the ledger, which
mounts a v2 contract. Both the ledger and the tracer gate them on `OPENAPI_DOCS_ENABLED`, off by
default — opt in with `OPENAPI_DOCS_ENABLED=true`.
### 4.1 Ledger API (port 3002)
Base path: `/v1`
#### Onboarding Resources
| Method | Path | Description |
|--------|------|-------------|
| POST | /organizations | Create organization |
| GET | /organizations | List organizations |
| GET | /organizations/:id | Get organization |
| PATCH | /organizations/:id | Update organization |
| DELETE | /organizations/:id | Delete organization |
| HEAD | /organizations/metrics/count | Count organizations |
| POST | /organizations/:org_id/ledgers | Create ledger |
| GET | /organizations/:org_id/ledgers | List ledgers |
| GET | /organizations/:org_id/ledgers/:id | Get ledger |
| PATCH | /organizations/:org_id/ledgers/:id | Update ledger |
| DELETE | /organizations/:org_id/ledgers/:id | Delete ledger |
| HEAD | /organizations/:org_id/ledgers/metrics/count | Count ledgers |
| GET | /organizations/:org_id/ledgers/:id/settings | Get ledger settings |
| PATCH | /organizations/:org_id/ledgers/:id/settings | Update ledger settings |
| POST | /organizations/:org_id/ledgers/:lid/assets | Create asset |
| GET | /organizations/:org_id/ledgers/:lid/assets | List assets |
| GET | /organizations/:org_id/ledgers/:lid/assets/:id | Get asset |
| PATCH | /organizations/:org_id/ledgers/:lid/assets/:id | Update asset |
| DELETE | /organizations/:org_id/ledgers/:lid/assets/:id | Delete asset |
| HEAD | /organizations/:org_id/ledgers/:lid/assets/metrics/count | Count assets |
| POST | /organizations/:org_id/ledgers/:lid/portfolios | Create portfolio |
| GET | /organizations/:org_id/ledgers/:lid/portfolios | List portfolios |
| GET | /organizations/:org_id/ledgers/:lid/portfolios/:id | Get portfolio |
| PATCH | /organizations/:org_id/ledgers/:lid/portfolios/:id | Update portfolio |
| DELETE | /organizations/:org_id/ledgers/:lid/portfolios/:id | Delete portfolio |
| HEAD | /organizations/:org_id/ledgers/:lid/portfolios/metrics/count | Count portfolios |
| POST | /organizations/:org_id/ledgers/:lid/segments | Create segment |
| GET | /organizations/:org_id/ledgers/:lid/segments | List segments |
| GET | /organizations/:org_id/ledgers/:lid/segments/:id | Get segment |
| PATCH | /organizations/:org_id/ledgers/:lid/segments/:id | Update segment |
| DELETE | /organizations/:org_id/ledgers/:lid/segments/:id | Delete segment |
| HEAD | /organizations/:org_id/ledgers/:lid/segments/metrics/count | Count segments |
| POST | /organizations/:org_id/ledgers/:lid/accounts | Create account |
| GET | /organizations/:org_id/ledgers/:lid/accounts | List accounts |
| GET | /organizations/:org_id/ledgers/:lid/accounts/:id | Get account |
| GET | /organizations/:org_id/ledgers/:lid/accounts/alias/:alias | Get account by alias |
| GET | /organizations/:org_id/ledgers/:lid/accounts/external/:code | Get external account |
| PATCH | /organizations/:org_id/ledgers/:lid/accounts/:id | Update account |
| DELETE | /organizations/:org_id/ledgers/:lid/accounts/:id | Delete account |
| HEAD | /organizations/:org_id/ledgers/:lid/accounts/metrics/count | Count accounts |
| POST | /organizations/:org_id/ledgers/:lid/account-types | Create account type |
| GET | /organizations/:org_id/ledgers/:lid/account-types | List account types |
| GET | /organizations/:org_id/ledgers/:lid/account-types/:id | Get account type |
| PATCH | /organizations/:org_id/ledgers/:lid/account-types/:id | Update account type |
| DELETE | /organizations/:org_id/ledgers/:lid/account-types/:id | Delete account type |
#### Transaction Resources
| Method | Path | Description |
|--------|------|-------------|
| POST | .../transactions/json | Create transaction (JSON) |
| POST | .../transactions/inflow | Create inflow transaction |
| POST | .../transactions/outflow | Create outflow transaction |
| POST | .../transactions/annotation | Create annotation transaction |
| POST | .../transactions/:tid/commit | Commit pending transaction |
| POST | .../transactions/:tid/cancel | Cancel pending transaction |
| POST | .../transactions/:tid/revert | Revert transaction |
| PATCH | .../transactions/:tid | Update transaction metadata |
| GET | .../transactions | List transactions |
| GET | .../transactions/:tid | Get transaction |
| HEAD | .../transactions/metrics/count | Count transactions |
| GET | .../accounts/:aid/operations | List operations by account |
| GET | .../accounts/:aid/operations/:oid | Get operation |
| PATCH | .../transactions/:tid/operations/:oid | Update operation |
| PUT | .../asset-rates | Create/update asset rate |
| GET | .../asset-rates/:external_id | Get asset rate |
| GET | .../asset-rates/from/:asset_code | List asset rates by code |
| GET | .../balances | List balances |
| GET | .../balances/:bid | Get balance |
| GET | .../balances/:bid/history | Get balance at timestamp |
| PATCH | .../balances/:bid | Update balance |
| DELETE | .../balances/:bid | Delete balance |
| GET | .../accounts/:aid/balances | List balances by account |
| GET | .../accounts/:aid/balances/history | Account balances at timestamp |
| GET | .../accounts/alias/:alias/balances | Balances by alias |
| GET | .../accounts/external/:code/balances | Balances by external code |
| POST | .../accounts/:aid/balances | Create additional balance |
| POST | .../operation-routes | Create operation route |
| GET | .../operation-routes | List operation routes |
| GET | .../operation-routes/:orid | Get operation route |
| PATCH | .../operation-routes/:orid | Update operation route |
| DELETE | .../operation-routes/:orid | Delete operation route |
| POST | .../transaction-routes | Create transaction route |
| GET | .../transaction-routes | List transaction routes |
| GET | .../transaction-routes/:trid | Get transaction route |
| PATCH | .../transaction-routes/:trid | Update transaction route |
| DELETE | .../transaction-routes/:trid | Delete transaction route |
#### Settings / Metadata
| Method | Path | Description |
|--------|------|-------------|
| POST | /v1/settings/metadata-indexes/entities/:entity_name | Create metadata index |
| GET | /v1/settings/metadata-indexes | List metadata indexes |
| DELETE | /v1/settings/metadata-indexes/entities/:entity_name/key/:index_key | Delete metadata index |
#### System
| Method | Path | Description |
|--------|------|-------------|
| GET | /health | Health check |
| GET | /readyz | Readiness probe |
| GET | /version | Version info |
| GET | /v1/openapi.json | v1 OpenAPI 3.1 spec (JSON) — served when `OPENAPI_DOCS_ENABLED=true` |
| GET | /v1/openapi.yaml | v1 OpenAPI 3.1 spec (YAML) — served when `OPENAPI_DOCS_ENABLED=true` |
| GET | /v1/docs | v1 Scalar API docs UI — served when `OPENAPI_DOCS_ENABLED=true` |
| GET | /v2/openapi.json | v2 OpenAPI 3.1 spec (JSON) — served when `OPENAPI_DOCS_ENABLED=true` |
| GET | /v2/openapi.yaml | v2 OpenAPI 3.1 spec (YAML) — served when `OPENAPI_DOCS_ENABLED=true` |
| GET | /v2/docs | v2 Scalar API docs UI — served when `OPENAPI_DOCS_ENABLED=true` |
### 4.2 CRM API (served by the ledger binary on port 3002)
CRM (holders, instruments, related parties) is folded into the ledger binary — it is **not** a
standalone service. The holder/instrument handlers and routes live in the ledger HTTP tree
(`components/ledger/internal/adapters/http/in/`) so the unified Huma OpenAPI spec discovers them; they are
served on `:3002` under the host ledger's `midaz` authz namespace (the resources `holders` and
`instruments`); the standalone CRM plugin namespace was collapsed into `midaz` at v4 (see
`docs/auth/RBAC-NAMESPACES.md`, X1). Uses MongoDB for persistence; holder/instrument PII is encrypted
at rest, alongside deterministic HMAC search tokens that enable equality lookups over ciphertext. The
encryption backend is selected by `KMS_VENDOR`: unset/`none` uses legacy lib-commons symmetric crypto;
`hashicorp-vault` switches to **envelope mode** — a Vault Transit KEK wrapping per-organization Tink
DEKs — which also mounts the provision/status/audit routes below. See section 6.2 and
`docs/architecture/crm-field-encryption.md`.
Scoping is **path-based**: CRM endpoints read the organization from the `:organization_id` path
segment, UUID-validated by the protected-route chain (`ParseUUIDPathParameters`). The former
`X-Organization-Id` header and the `X-Ledger-Id` header were removed; `ledger_id` survives only as
an instrument create-body field and an optional `GET .../instruments` list filter. See
`docs/api/SCOPING.md` (R22 reversed).
| Method | Path | Description |
|--------|------|-------------|
| POST | /v1/organizations/{organization_id}/holders | Create holder |
| GET | /v1/organizations/{organization_id}/holders | List holders |
| GET | /v1/organizations/{organization_id}/holders/:id | Get holder |
| PATCH | /v1/organizations/{organization_id}/holders/:id | Update holder |
| DELETE | /v1/organizations/{organization_id}/holders/:id | Delete holder |
| GET | /v1/organizations/{organization_id}/holders/:id/accounts | List a holder's ledger accounts (mounted only when the holder-accounts handler is wired) |
| POST | /v1/organizations/{organization_id}/ledgers/{ledger_id}/holders/:id/accounts | Create a holder ↔ account association (composition; authz `midaz`/`accounts`; always mounted) |
| GET | /v1/organizations/{organization_id}/instruments | List instruments |
| POST | /v1/organizations/{organization_id}/holders/:holder_id/instruments | Create instrument |
| GET | /v1/organizations/{organization_id}/holders/:holder_id/instruments/:instrument_id | Get instrument |
| PATCH | /v1/organizations/{organization_id}/holders/:holder_id/instruments/:instrument_id | Update instrument |
| DELETE | /v1/organizations/{organization_id}/holders/:holder_id/instruments/:instrument_id | Delete instrument |
| DELETE | /v1/organizations/{organization_id}/holders/:holder_id/instruments/:instrument_id/related-parties/:related_party_id | Delete related party |
| POST | /v1/organizations/{organization_id}/encryption/provision | Provision per-org envelope keyset (envelope mode only; authz `midaz`/`encryption`) |
| GET | /v1/organizations/{organization_id}/encryption/status | Org encryption/protection status (envelope mode only; authz `midaz`/`encryption`) |
| GET | /v1/organizations/{organization_id}/protection/audit | List provisioning audit events, cursor-paged (envelope mode only; authz `midaz`/`protection`) |
The three encryption/protection routes are registered **only in envelope mode** (`KMS_VENDOR=hashicorp-vault`);
in legacy mode their handlers are nil and the routes are never mounted.
The holder-account composition (`POST`) carries an extra `:ledger_id` segment because it creates a
real ledger account; the holder-accounts `GET` (`HolderAccountsHandler.GetAccountsByHolder`, mounted
only when the ledger account-query backing is non-nil) lists a holder's accounts org-wide and needs
no ledger. The `POST` (`CompositionHandler.CreateHolderAccount`, in `composition_routes.go`) is
always mounted. Holder ownership is org-scoped (matching Mongo storage), not ledger-scoped.
CRM error responses carry **canonical midaz codes** (e.g. `0009`, `0046`, `0047`, `0094`) — the
legacy `CRM-00xx` transform shim was removed. The 28 CRM domain sentinels (section 5.1)
are still emitted on their own paths.
### 4.3 Fees API (served by the ledger binary on port 3002)
The fee engine + billing-package surface is embedded in the ledger binary — it is **not** a
standalone service. Routes are registered in `components/ledger/internal/adapters/http/in/fees_routes.go`
(organization-scoped, `/v1`) and `fees_v2_register.go` (ledger-scoped, `/v2`), both under the
`plugin-fees` authz namespace and served on `:3002`.
Scoping is **path-based**: fee endpoints read the organization from the `:organization_id` path
segment, UUID-validated by the protected-route chain (`ParseUUIDPathParameters`) — the same
convention as every other surface in the binary. The former `X-Organization-Id` header was
removed; path-validation errors return the canonical midaz `ErrInvalidPathParameter` envelope
(fee business errors use the canonical numeric error-code registry in `pkg/constant/errors.go` —
the `FEE-` prefixed code family is retired). See `docs/api/SCOPING.md`.
**Two live surfaces.** The same twelve operations are served at two scopes, and neither replaces
the other. On `/v1` the path names only the organization and a read reaches a resource on whichever
ledger of the organization owns it; `ledger_id` there is a create-body field and an optional
`?ledgerId=` list filter, never a scope. On `/v2` the path names the ledger and a read reaches only
what that ledger owns.
| Method | Path | Description |
|--------|------|-------------|
| POST | /v1/organizations/{organization_id}/packages | Create fee package |
| GET | /v1/organizations/{organization_id}/packages | List fee packages |
| GET | /v1/organizations/{organization_id}/packages/:id | Get fee package |
| PATCH | /v1/organizations/{organization_id}/packages/:id | Update fee package |
| DELETE | /v1/organizations/{organization_id}/packages/:id | Delete fee package |
| POST | /v1/organizations/{organization_id}/estimates | Estimate fee calculation (dry run) |
| POST | /v1/organizations/{organization_id}/billing-packages | Create billing package |
| GET | /v1/organizations/{organization_id}/billing-packages | List billing packages |
| GET | /v1/organizations/{organization_id}/billing-packages/:id | Get billing package |
| PATCH | /v1/organizations/{organization_id}/billing-packages/:id | Update billing package |
| DELETE | /v1/organizations/{organization_id}/billing-packages/:id | Delete billing package |
| POST | /v1/organizations/{organization_id}/billing/calculate | Calculate billing |
Ledger-scoped twins on the independent `/v2` contract (`{base}` =
`/v2/organizations/{organization_id}/ledgers/{ledger_id}`):
| Method | Path | Description |
|--------|------|-------------|
| POST | {base}/packages | Create fee package |
| GET | {base}/packages | List the ledger's fee packages |
| GET | {base}/packages/:id | Get fee package |
| PATCH | {base}/packages/:id | Update fee package |
| DELETE | {base}/packages/:id | Delete fee package |
| POST | {base}/estimates | Estimate fee calculation (dry run) |
| POST | {base}/billing-packages | Create billing package |
| GET | {base}/billing-packages | List the ledger's billing packages |
| GET | {base}/billing-packages/:id | Get billing package |
| PATCH | {base}/billing-packages/:id | Update billing package |
| DELETE | {base}/billing-packages/:id | Delete billing package |
| POST | {base}/billing/calculate | Calculate billing |
On the `/v2` paths the path is the sole authority on the ledger: the nil UUID is refused as a
`ledger_id` path value, a request body naming a different ledger is refused (`0234`), and
`?ledgerId=` is refused on the two listings (`0235`) — its empty value would mean "every ledger",
the one scope a ledger-scoped listing must not express. Authz is identical to `/v1`: `plugin-fees` with the
same `(resource, verb)` tuples, so no separate grant is needed for the second surface.
`POST /v1/fees` (live fee calculation) is intentionally **not** exposed — fees run in-process via
the transaction-create seam, not over HTTP. The `/v2` surface omits it for the same reason.
### 4.4 Tracer API (port 4020)
Real-time transaction validation / fraud-prevention API. Hexagonal + CQRS, CEL rule engine,
hash-chained audit log. Ships its own SQL migrations under `components/tracer/migrations`. This is
an INDEPENDENT spec/port/deploy unit — it is not folded into `:3002`. Base path: `/v1`.
The ledger reaches Tracer over a separate reservation seam (not the `:4020` REST API). The seam is
opt-in on both ends: the ledger turns it on by setting `TRACER_BASE_URL` (empty injects a nil
reserver, leaving the transaction-create path unchanged), and the tracer starts the seam only when
`TRACER_GRPC_PORT` is set (distinct from the `:4020` REST/health port). Transport is toggled by
`TRACER_TRANSPORT` — gRPC by default, with REST retained as a selectable fallback. Identity is mutual
TLS, selected by `TRACER_TLS_MODE`: `mtls` makes the seam mutually authenticated with no shared
secret (the ledger presents a client cert, the tracer verifies it against its client CA, and the
ledger verifies the tracer's server cert), while `mesh`/empty runs plaintext and delegates mTLS to a
service-mesh sidecar. Over the verified connection the ledger forwards a trusted `x-tenant-id` that
the tracer's gRPC interceptor uses to resolve the per-tenant pool in multi-tenant mode. See
[docs/architecture/ledger-tracer-topology.md](docs/architecture/ledger-tracer-topology.md).
| Method | Path | Description |
|--------|------|-------------|
| POST | /v1/rules | Create rule |
| GET | /v1/rules | List rules |
| GET | /v1/rules/:id | Get rule |
| PATCH | /v1/rules/:id | Update rule |
| DELETE | /v1/rules/:id | Delete rule |
| POST | /v1/rules/:id/draft | Move rule to draft |
| POST | /v1/rules/:id/activate | Activate rule |
| POST | /v1/rules/:id/deactivate | Deactivate rule |
| POST | /v1/limits | Create limit |
| GET | /v1/limits | List limits |
| GET | /v1/limits/:id | Get limit |
| PATCH | /v1/limits/:id | Update limit |
| DELETE | /v1/limits/:id | Delete limit |
| POST | /v1/limits/:id/draft | Move limit to draft |
| POST | /v1/limits/:id/activate | Activate limit |
| POST | /v1/limits/:id/deactivate | Deactivate limit |
| GET | /v1/limits/:id/usage | Get limit usage |
| POST | /v1/validations | Run validation |
| GET | /v1/validations | List validations |
| GET | /v1/validations/:id | Get validation |
| POST | /v1/reservations | Create reservation (two-phase: reserve) |
| POST | /v1/reservations/:id/confirm | Confirm a reservation by ID |
| POST | /v1/reservations/:id/release | Release a reservation by ID |
| POST | /v1/reservations/transaction/:transaction_id/confirm | Confirm reservations for a transaction |
| POST | /v1/reservations/transaction/:transaction_id/release | Release reservations for a transaction |
| GET | /v1/audit-events | List audit events |
| GET | /v1/audit-events/:id | Get audit event |
| GET | /v1/audit-events/:id/verify | Verify the audit-event hash chain |
The `/v1/reservations` two-phase surface backs the transaction reserve → confirm/release flow:
a reservation holds projected limit usage, then is confirmed (commit) or released (rollback),
either by reservation ID or by the originating transaction ID. The reservation routes are mounted
only when the reservation service is wired (non-nil); they are live in the default/production wiring.
#### System
| Method | Path | Description |
|--------|------|-------------|
| GET | /health | Health check |
| GET | /readyz | Readiness probe |
| GET | /metrics | Prometheus metrics |
| GET | /version | Version info |
| GET | /v1/openapi.{json,yaml} | OpenAPI 3.1 spec — served when `OPENAPI_DOCS_ENABLED=true` |
| GET | /v1/docs | Scalar API docs UI — served when `OPENAPI_DOCS_ENABLED=true` |
## 5. Error System
### 5.1 Error Codes (pkg/constant/errors.go)
Numeric ledger codes starting at 0001 (non-contiguous; gap at 0130). 28 CRM domain codes prefixed
with `CRM-` (CRM-0006..CRM-0041, non-contiguous). The registry is numeric-only for the core; the
`FEE-` / `TRC-` / `TPL-` / `REP-` prefixed families are retired (0 survivors). API errors are
emitted as RFC 9457 `application/problem+json` (§4), preserving each sentinel's `(code, status)`
tuple.
#### Ledger Error Codes (selected key codes)
- `0007` ErrEntityNotFound — entity not found
- `0009` ErrMissingFieldsInRequest — required fields missing
- `0018` ErrInsufficientFunds — insufficient funds
- `0020` ErrAliasUnavailability — alias already in use
- `0041` ErrTokenMissing — no auth token
- `0042` ErrInvalidToken — expired/invalid token
- `0043` ErrInsufficientPrivileges — forbidden
- `0046` ErrInternalServer — unexpected server error
- `0047` ErrBadRequest — malformed request
- `0084` ErrIdempotencyKey — duplicate idempotency key
- `0086` ErrLockVersionAccountBalance — race condition detected
- `0095` ErrMessageBrokerUnavailable — RabbitMQ down
- `0097` ErrOverFlowInt64 — integer overflow
- `0125` ErrInvalidTransactionNonPositiveValue — zero/negative value
- `0146` ErrTenantNotProvisioned — tenant DB not initialized
- `0159` ErrTenantServiceSuspended — tenant service suspended
- `0160` ErrTenantNotFound — tenant does not exist
- `0161` ErrTenantServiceUnavailable — tenant resolution failed
#### Overdraft Feature Error Codes (0167–0176)
- `0167` ErrOverdraftLimitExceeded — transaction exceeds overdraft limit
- `0168` ErrDirectOperationOnInternalBalance — user operation targets internal-scope balance
- `0169` ErrDeletionOfInternalBalance — delete targets internal-scope balance
- `0170` ErrReservedBalanceKey — client used system-managed balance key (e.g. "overdraft")
- `0171` ErrInvalidBalanceDirection — unsupported direction enum value
- `0172` ErrInvalidBalanceSettings — settings payload fails validation
- `0173` ErrOverdraftLimitBelowUsage — cannot reduce limit below current usage
- `0174` ErrStaleBalanceVersion — balance modified between read and write (retry needed)
- `0175` ErrUpdateOfInternalBalance — PATCH targets internal-scope balance
- `0176` ErrOverdraftRouteNotConfigured — overdraft leg's route lacks a direction-specific overdraft accounting entry (route validation enabled)
#### Settings / Reservation Error Codes (0176–0178)
- `0176` ErrInvalidSettingsFieldValue — settings field value fails validation
- `0177` ErrTransactionReservationDenied — tracer reservation denied (limit/rule)
- `0178` ErrTransactionReservationUnavailable — tracer reservation service unavailable
#### CRM Error Codes (all 28)
- `CRM-0006` ErrHolderNotFound — holder not found
- `CRM-0008` ErrInstrumentNotFound — instrument not found
- `CRM-0010` ErrDocumentAssociationError — document association error
- `CRM-0013` ErrAccountAlreadyAssociated — account already associated
- `CRM-0017` ErrHolderHasInstruments — holder has instruments (cannot delete)
- `CRM-0019` ErrMetadataQueryInvalidFormat — metadata query format error
- `CRM-0020` ErrMetadataQueryInvalidKey — metadata query invalid key
- `CRM-0021` ErrMetadataQueryContainsOperator — metadata query contains operator
- `CRM-0022` ErrInvalidHeaderValue — invalid header value
- `CRM-0023` ErrInstrumentClosingDateBeforeCreation — closing date before creation
- `CRM-0024` ErrRelatedPartyNotFound — related party not found
- `CRM-0025` ErrInvalidRelatedPartyRole — invalid related party role
- `CRM-0026` ErrRelatedPartyDocumentRequired — document required
- `CRM-0027` ErrRelatedPartyNameRequired — name required
- `CRM-0028` ErrRelatedPartyStartDateRequired — start date required
- `CRM-0029` ErrRelatedPartyEndDateInvalid — end date before start date
- `CRM-0030` ErrHolderHasAccounts — holder has accounts (cannot delete)
Field-encryption / KMS family (envelope mode; see §6.2 and `docs/architecture/crm-field-encryption.md`):
- `CRM-0031` ErrKeysetNotFound — org encryption keyset not found
- `CRM-0032` ErrKeysetAlreadyExists — org encryption keyset already exists
- `CRM-0033` ErrKeysetRevisionConflict — keyset optimistic-concurrency conflict
- `CRM-0034` ErrRegistryNotFound — protection registry record not found
- `CRM-0035` ErrRegistryAlreadyExists — protection registry record already exists
- `CRM-0036` ErrRegistryRevisionConflict — registry optimistic-concurrency conflict
- `CRM-0037` ErrOrganizationEncryptionFailed — org field encrypt/decrypt failed
- `CRM-0038` ErrProvisioningFailed — key provisioning failed
- `CRM-0039` ErrAuditEventRequired — protection audit event required
- `CRM-0040` ErrAuditWriteFailed — protection audit write failed
- `CRM-0041` ErrReservedTenantID — reserved tenant id (`default`) may not be provisioned externally
### 5.2 Error Types (pkg/errors.go)
| Type | HTTP Status | Use Case |
|------|-------------|----------|
| EntityNotFoundError | 404 | Entity not found |
| ValidationError | 400 | Input validation failures |
| EntityConflictError | 409 | Duplicate entities |
| UnauthorizedError | 401 | Missing/invalid auth |
| ForbiddenError | 403 | Insufficient privileges |
| UnprocessableOperationError | 422 | Business rule violations |
| FailedPreconditionError | 500 | Configuration errors. Despite the name, this maps to 500, not 412: a failed precondition here is a server misconfiguration, not a client-supplied condition |
| ServiceUnavailableError | 503 | Infrastructure failures |
| InternalServerError | 500 | Unexpected errors |
| ValidationKnownFieldsError | 400 | Field-level validation |
| ValidationUnknownFieldsError | 400 | Unexpected fields |
### 5.3 Error Handling Pattern
```go
// Business errors: return directly
if errors.Is(err, constant.ErrEntityNotFound) {
return nil, pkg.ValidateBusinessError(constant.ErrEntityNotFound, "Entity")
}
// Technical errors: wrap with context
return nil, fmt.Errorf("failed to create entity: %w", err)
```
## 6. Environment Variables
Source of truth: `components/ledger/internal/bootstrap/config.go` (the unified Ledger Config
struct — also holds the CRM and fees Mongo config since both are folded into the ledger binary),
plus `components/tracer/.env.example` for the tracer deploy unit. Defaults in parentheses
are set programmatically by `applyConfigDefaults()`.
### 6.1 Ledger Component
#### Application
| Variable | Default | Description |
|----------|---------|-------------|
| APPLICATION_NAME | — | Application identity (tenant-manager service name) |
| ENV_NAME | development | Environment: development, staging, uat, production, local |
| VERSION | v4.0.0 | Application version |
| SERVER_ADDRESS | :3002 | Listen address (single port for all APIs) |
| LOG_LEVEL | debug | Log level |
| DEPLOYMENT_MODE | local | Deployment mode (local toggles relaxed TLS posture; also gates the CRM KMS dev root token to `local` only) |
| ALLOW_INSECURE_TLS | true | Allow insecure TLS (local development; disable in production) |
#### Auth / Casdoor
| Variable | Default | Description |
|----------|---------|-------------|
| PLUGIN_AUTH_ENABLED | false | Enable auth middleware |
| PLUGIN_AUTH_HOST | — | Auth service host |
| CASDOOR_JWK_ADDRESS | — | JWK endpoint for Casdoor JWT validation |
#### PostgreSQL — Onboarding (Primary)
| Variable | Default | Description |
|----------|---------|-------------|
| DB_ONBOARDING_HOST | midaz-postgres-primary | Primary host |
| DB_ONBOARDING_USER | midaz | Username |
| DB_ONBOARDING_PASSWORD | lerian | Password |
| DB_ONBOARDING_NAME | onboarding | Database name |
| DB_ONBOARDING_PORT | 5701 | Port |
| DB_ONBOARDING_SSLMODE | disable | SSL mode |
#### PostgreSQL — Onboarding (Replica)
| Variable | Default | Description |
|----------|---------|-------------|
| DB_ONBOARDING_REPLICA_HOST | midaz-postgres-replica | Replica host |
| DB_ONBOARDING_REPLICA_USER | midaz | Replica username |
| DB_ONBOARDING_REPLICA_PASSWORD | lerian | Replica password |
| DB_ONBOARDING_REPLICA_NAME | onboarding | Replica database name |
| DB_ONBOARDING_REPLICA_PORT | 5702 | Replica port |
| DB_ONBOARDING_REPLICA_SSLMODE | disable | Replica SSL mode |
| DB_ONBOARDING_MAX_OPEN_CONNS | 3000 | Max open connections (shared) |
| DB_ONBOARDING_MAX_IDLE_CONNS | 3000 | Max idle connections (shared) |
#### PostgreSQL — Transaction (Primary)
| Variable | Default | Description |
|----------|---------|-------------|
| DB_TRANSACTION_HOST | midaz-postgres-primary | Primary host |
| DB_TRANSACTION_USER | midaz | Username |
| DB_TRANSACTION_PASSWORD | lerian | Password |
| DB_TRANSACTION_NAME | transaction | Database name |
| DB_TRANSACTION_PORT | 5701 | Port |
| DB_TRANSACTION_SSLMODE | disable | SSL mode |
#### PostgreSQL — Transaction (Replica)
| Variable | Default | Description |
|----------|---------|-------------|
| DB_TRANSACTION_REPLICA_HOST | midaz-postgres-replica | Replica host |
| DB_TRANSACTION_REPLICA_USER | midaz | Replica username |
| DB_TRANSACTION_REPLICA_PASSWORD | lerian | Replica password |
| DB_TRANSACTION_REPLICA_NAME | transaction | Replica database name |
| DB_TRANSACTION_REPLICA_PORT | 5702 | Replica port |
| DB_TRANSACTION_REPLICA_SSLMODE | disable | Replica SSL mode |
| DB_TRANSACTION_MAX_OPEN_CONNS | 3000 | Max open connections (shared) |
| DB_TRANSACTION_MAX_IDLE_CONNS | 3000 | Max idle connections (shared) |
#### MongoDB — Onboarding
| Variable | Default | Description |
|----------|---------|-------------|
| MONGO_ONBOARDING_URI | mongodb | Connection URI scheme |
| MONGO_ONBOARDING_HOST | midaz-mongodb | Host |
| MONGO_ONBOARDING_NAME | onboarding | Database name |
| MONGO_ONBOARDING_USER | midaz | Username |
| MONGO_ONBOARDING_PASSWORD | lerian | Password |
| MONGO_ONBOARDING_PORT | 5703 | Port |
| MONGO_ONBOARDING_PARAMETERS | — | Extra connection params (appended to URI) |
| MONGO_ONBOARDING_MAX_POOL_SIZE | 1000 | Max pool size |
| MONGO_ONBOARDING_TLS_CA_CERT | — | TLS CA cert path |
#### MongoDB — Transaction
| Variable | Default | Description |
|----------|---------|-------------|
| MONGO_TRANSACTION_URI | mongodb | Connection URI scheme |
| MONGO_TRANSACTION_HOST | midaz-mongodb | Host |
| MONGO_TRANSACTION_NAME | transaction | Database name |
| MONGO_TRANSACTION_USER | midaz | Username |
| MONGO_TRANSACTION_PASSWORD | lerian | Password |
| MONGO_TRANSACTION_PORT | 5703 | Port |
| MONGO_TRANSACTION_PARAMETERS | — | Extra connection params |
| MONGO_TRANSACTION_MAX_POOL_SIZE | 1000 | Max pool size |
| MONGO_TRANSACTION_TLS_CA_CERT | — | TLS CA cert path |
#### Redis / Valkey
| Variable | Default | Description |
|----------|---------|-------------|
| REDIS_HOST | midaz-valkey:5704 | Host(s); comma-separated for cluster/sentinel |
| REDIS_MASTER_NAME | — | Sentinel master name (enables sentinel topology) |
| REDIS_PASSWORD | lerian | Password |
| REDIS_DB | 0 | Database index |
| REDIS_PROTOCOL | (3) | RESP protocol version |
| REDIS_TLS | false | Enable TLS |
| REDIS_CA_CERT | — | CA certificate (base64) for TLS |
| REDIS_USE_GCP_IAM | false | Use GCP IAM auth instead of static password |
| REDIS_SERVICE_ACCOUNT | — | GCP service account for IAM auth |
| GOOGLE_APPLICATION_CREDENTIALS | — | GCP credentials (base64) for IAM auth |
| REDIS_TOKEN_LIFETIME | (60) | GCP IAM token lifetime (minutes) |
| REDIS_TOKEN_REFRESH_DURATION | (45) | GCP IAM token refresh interval (minutes) |
| REDIS_POOL_SIZE | (10) | Connection pool size |
| REDIS_MIN_IDLE_CONNS | 0 | Minimum idle connections |
| REDIS_READ_TIMEOUT | (3) | Read timeout (seconds) |
| REDIS_WRITE_TIMEOUT | (3) | Write timeout (seconds) |
| REDIS_DIAL_TIMEOUT | (5) | Dial timeout (seconds) |
| REDIS_POOL_TIMEOUT | (2) | Pool wait timeout (seconds) |
| REDIS_MAX_RETRIES | (3) | Max retries per command |
| REDIS_MIN_RETRY_BACKOFF | (8) | Min retry backoff (milliseconds) |
| REDIS_MAX_RETRY_BACKOFF | (1) | Max retry backoff (seconds) |
#### RabbitMQ
| Variable | Default | Description |
|----------|---------|-------------|
| RABBITMQ_URI | amqp | Protocol scheme (amqp/amqps) |
| RABBITMQ_HOST | midaz-rabbitmq | Host |
| RABBITMQ_PORT_HOST | 3003 | Management port |
| RABBITMQ_PORT_AMQP | 3004 | AMQP port |
| RABBITMQ_DEFAULT_USER | transaction | Producer username |
| RABBITMQ_DEFAULT_PASS | lerian | Producer password |
| RABBITMQ_CONSUMER_USER | consumer | Consumer username |
| RABBITMQ_CONSUMER_PASS | lerian | Consumer password |
| RABBITMQ_VHOST | — | Virtual host (empty = default "/") |
| RABBITMQ_NUMBERS_OF_WORKERS | 5 | Consumer worker count |
| RABBITMQ_NUMBERS_OF_PREFETCH | 10 | Prefetch count per worker |
| RABBITMQ_HEALTH_CHECK_URL | — | Health check URL |
| RABBITMQ_TLS | false | Enable TLS |
| RABBITMQ_TRANSACTION_BALANCE_OPERATION_QUEUE | — | Balance operation queue name |
| RABBITMQ_TRANSACTION_ASYNC | false | Enable async transaction processing |
| RABBITMQ_OPERATION_TIMEOUT | — | Operation timeout (e.g., "30s") |
| RABBITMQ_TRANSACTION_EVENTS_ENABLED | false | Enable transaction event exchange |
| RABBITMQ_TRANSACTION_EVENTS_EXCHANGE | — | Events exchange name |
| RABBITMQ_OVERDRAFT_EVENTS_ENABLED | false | Enable overdraft event publishing |
| RABBITMQ_OVERDRAFT_EVENTS_EXCHANGE | transaction.overdraft_events.exchange | Overdraft events exchange name |
| AUDIT_LOG_ENABLED | false | Enable audit log publishing |
| RABBITMQ_AUDIT_EXCHANGE | — | Audit exchange name |
| RABBITMQ_AUDIT_KEY | — | Audit routing key |
#### RabbitMQ Circuit Breaker
| Variable | Default | Description |
|----------|---------|-------------|
| RABBITMQ_CIRCUIT_BREAKER_CONSECUTIVE_FAILURES | 15 | Consecutive failures before open |
| RABBITMQ_CIRCUIT_BREAKER_FAILURE_RATIO | 50 | Failure % to trigger open (0-100) |
| RABBITMQ_CIRCUIT_BREAKER_INTERVAL | 120 | Failure counting window (seconds) |
| RABBITMQ_CIRCUIT_BREAKER_MAX_REQUESTS | 3 | Requests allowed in half-open state |
| RABBITMQ_CIRCUIT_BREAKER_MIN_REQUESTS | 10 | Min requests before ratio evaluated |
| RABBITMQ_CIRCUIT_BREAKER_TIMEOUT | 30 | Open → half-open wait (seconds) |
| RABBITMQ_CIRCUIT_BREAKER_HEALTH_CHECK_INTERVAL | 30 | Health check interval (seconds) |
| RABBITMQ_CIRCUIT_BREAKER_HEALTH_CHECK_TIMEOUT | 10 | Health check timeout (seconds) |
#### Bulk Recorder
| Variable | Default | Description |
|----------|---------|-------------|
| BULK_RECORDER_ENABLED | (true) | Enable bulk mode |
| BULK_RECORDER_SIZE | (workers×prefetch) | Batch size (0 = auto-calculated) |
| BULK_RECORDER_FLUSH_TIMEOUT_MS | (100) | Flush timeout (ms) |
| BULK_RECORDER_MAX_ROWS_PER_INSERT | (1000) | Max rows per INSERT |
#### OpenTelemetry
| Variable | Default | Description |
|----------|---------|-------------|
| OTEL_RESOURCE_SERVICE_NAME | ledger | Service name in traces |
| OTEL_LIBRARY_NAME | — | Instrumentation library name |
| OTEL_RESOURCE_SERVICE_VERSION | — | Service version in traces |
| OTEL_RESOURCE_DEPLOYMENT_ENVIRONMENT | — | Deployment environment in traces |
| OTEL_EXPORTER_OTLP_ENDPOINT | http://midaz-otel-lgtm:4317 | OTLP collector endpoint (includes scheme) |
| ENABLE_TELEMETRY | false | Enable telemetry export |
#### Multi-Tenant
| Variable | Default | Description |
|----------|---------|-------------|
| MULTI_TENANT_ENABLED | false | Enable multi-tenant mode |
| MULTI_TENANT_URL | — | Tenant Manager API URL |
| MULTI_TENANT_SERVICE_API_KEY | — | Service API key for tenant-manager |
| MULTI_TENANT_CIRCUIT_BREAKER_THRESHOLD | (5) | CB failures before open |
| MULTI_TENANT_CIRCUIT_BREAKER_TIMEOUT_SEC | (30) | CB open → half-open (seconds) |
| MULTI_TENANT_CONNECTIONS_CHECK_INTERVAL_SEC | — | Revalidation check interval (seconds) |
| MULTI_TENANT_CACHE_TTL_SEC | (120) | Tenant config cache TTL (seconds, 0=disabled) |
| MULTI_TENANT_REDIS_HOST | — | Redis for tenant Pub/Sub events |
| MULTI_TENANT_REDIS_PORT | 6379 | Redis port for Pub/Sub |
| MULTI_TENANT_REDIS_PASSWORD | — | Redis password for Pub/Sub |
| MULTI_TENANT_REDIS_TLS | false | Enable TLS for Pub/Sub Redis |
#### Pagination
| Variable | Default | Description |
|----------|---------|-------------|
| MAX_PAGINATION_LIMIT | 100 | Max items per page |
| MAX_PAGINATION_MONTH_DATE_RANGE | 3 | Max date range (months) |
#### Balance Sync
| Variable | Default | Description |
|----------|---------|-------------|
| BALANCE_SYNC_BATCH_SIZE | 50 | Keys accumulated before flush (SIZE trigger) |
| BALANCE_SYNC_FLUSH_TIMEOUT_MS | 500 | Max ms before flush (TIMEOUT trigger) |
| BALANCE_SYNC_POLL_INTERVAL_MS | 50 | ZSET polling interval (ms) when draining |
#### Streaming (lib-streaming/v2 v2.0.0 / Kafka)
The master flag is `STREAMING_ENABLED`; when false, a no-op emitter is injected. The rest are
loaded by `libStreaming.LoadConfig()` with franz-go defaults. Wire format: CloudEvents 1.0 binary
mode on Kafka.
| Variable | Default | Description |
|----------|---------|-------------|
| STREAMING_ENABLED | false | Enable streaming producer |
| STREAMING_BROKERS | — | Kafka-compatible broker list |
| STREAMING_CLIENT_ID | — | Producer client ID |
| STREAMING_CLOUDEVENTS_SOURCE | — | CloudEvents source (set explicitly per component) |
| STREAMING_COMPRESSION | — | Producer compression codec |
| STREAMING_REQUIRED_ACKS | — | Producer required acks |
| STREAMING_BATCH_LINGER_MS | — | Producer batch linger (ms) |
| STREAMING_SASL_MECHANISM | — | SASL mechanism |
| STREAMING_SASL_USERNAME | — | SASL username |
| STREAMING_SASL_PASSWORD | — | SASL password |
| STREAMING_ALLOW_PLAINTEXT_SASL | — | Allow SASL over plaintext |
| STREAMING_IMPORTANT_EMIT_TIMEOUT_MS | 5000 | Bound on direct IMPORTANT-event emit latency |
#### Service Discovery (opt-in; no-op when SD_ENABLED=false)
Consul-backed registration + host resolution. Read by `libsd.ConfigFromEnv()`.
Disabled by default: a no-op Manager is wired and `Resolve` returns the static
fallback host. When `SD_ENABLED=true`, `SD_ADVERTISE_ADDRESS` is required —
enabling discovery with an empty advertise address aborts boot
(`ErrEmptyAdvertiseAddr`).
| Variable | Default | Description |
|----------|---------|-------------|
| SD_ENABLED | false | Enable Consul-backed discovery (no-op when false) |
| SD_ADDRESS | localhost:8500 | Consul HTTPS API (host:port); :8501 on central agents |
| SD_ADVERTISE_ADDRESS | — | Required when enabled; hostname or full URL. Empty + enabled aborts boot |
| SD_ADVERTISE_PORT | 0 | Advertised port override; 0 = use Register port (SERVER_ADDRESS) |
| SD_WORKLOAD | — | Workload scope for tag-based isolation per environment |
| SD_TLS | false | Enable HTTPS to the discovery server |
| SD_TLS_SKIP_VERIFY | false | Skip discovery-server cert verification (dev/self-signed) |
| SD_TOKEN | — | ACL token sent to the discovery server |
#### Tracer Client (ledger → tracer)
| Variable | Default | Description |
|----------|---------|-------------|
| TRACER_BASE_URL | — | Tracer service base URL (enables reservation calls) |
| TRACER_TIMEOUT_MS | — | Per-reservation-call timeout (ms) |
| TRACER_TRANSPORT | grpc | Seam transport: `grpc` (default) or `rest` fallback |
| TRACER_TLS_MODE | — | Seam identity: `mtls` (mutual TLS) or `mesh`/empty (plaintext, sidecar mTLS) |
| TRACER_TLS_CERT_FILE | — | Ledger client cert presented under `mtls` |
| TRACER_TLS_KEY_FILE | — | Ledger client key under `mtls` |
| TRACER_TLS_CA_FILE | — | CA used to verify the tracer's server cert under `mtls` |
Seam topology and TLS posture: [docs/architecture/ledger-tracer-topology.md](docs/architecture/ledger-tracer-topology.md).
#### Fee Engine
| Variable | Default | Description |
|----------|---------|-------------|
| DEFAULT_CURRENCY | USD | Default currency for fee calculation |
### 6.2 CRM + Fees (folded into the ledger binary)
Since CRM and fees are served by the ledger binary, their config lives in the unified ledger
Config struct (`components/ledger/internal/bootstrap/config.go`) and `components/ledger/.env.example`.
They use **namespaced** Mongo env vars so they do not collide with the ledger's onboarding /
transaction Mongo. They MAY point at the same Mongo deployment (separate logical DBs).
CRM Mongo (`MONGO_CRM_*`, read by `initCRM` via the `CrmPrefixed*` config fields):
| Variable | Default | Description |
|----------|---------|-------------|
| MONGO_CRM_URI | mongodb | Connection URI scheme |
| MONGO_CRM_HOST | midaz-mongodb | MongoDB host |
| MONGO_CRM_NAME | crm | Database name |
| MONGO_CRM_USER | midaz | Username |
| MONGO_CRM_PASSWORD | lerian | Password |
| MONGO_CRM_PORT | 5703 | Port |
| MONGO_CRM_PARAMETERS | — | Extra connection parameters |
| MONGO_CRM_MAX_POOL_SIZE | 1000 | Max pool size |
| MONGO_CRM_TLS_CA_CERT | — | TLS CA cert path |
| LCRYPTO_HASH_SECRET_KEY | — | Legacy CRM PII HMAC secret — live in legacy mode; imported for legacy reads in envelope mode |
| LCRYPTO_ENCRYPT_SECRET_KEY | — | Legacy CRM PII AES key — live in legacy mode; imported for legacy reads in envelope mode |
##### CRM Field Encryption (KMS / envelope)
`KMS_VENDOR` selects the encryption backend for holder/instrument PII: unset/`none` → **legacy**
(the `LCRYPTO_*` symmetric keys above, no Vault); `hashicorp-vault` → **envelope** (a shared,
mode-derived Vault Transit engine — `transit-mt`/`transit-st` — whose KEK wraps per-organization
Tink DEKs; tenant isolation lives in the key **name** `{tenant}_org-{id}`, not per-tenant mounts).
The `FieldEncryptor` seam (`components/ledger/internal/crm/services/encryption`) is non-nil in both
modes; the keyset/registry/audit repos, Vault client, and provision/status/audit routes wire up only
in envelope mode. Key rotation is scaffolded, not yet active. Full design:
`docs/architecture/crm-field-encryption.md`.
| Variable | Default | Description |
|----------|---------|-------------|
| KMS_VENDOR | none | Mode selector: unset/`none` → legacy; `hashicorp-vault` → envelope; anything else fails boot |
| KMS_VAULT_ADDR | — | Vault server address (envelope only) |
| KMS_VAULT_AUTH_METHOD | — | `approle` \| `token`; sole driver of Vault auth; fails closed if unset/invalid in envelope mode |
| KMS_VAULT_ROLE_ID | — | AppRole role ID (when `KMS_VAULT_AUTH_METHOD=approle`) |
| KMS_VAULT_SECRET_ID | — | AppRole secret ID (when `KMS_VAULT_AUTH_METHOD=approle`) |
`token` auth uses the hardcoded dev root token and is permitted only when `DEPLOYMENT_MODE=local`;
`MULTI_TENANT_ENABLED` selects `transit-mt` vs `transit-st` and the MT key-naming / reserved-tenant
rules. New dependencies for envelope mode: `hashicorp/vault/api`, `tink-crypto/tink-go/v2`.
Fees Mongo (`MONGO_FEES_*`):
| Variable | Default | Description |
|----------|---------|-------------|
| MONGO_FEES_URI | mongodb | Connection URI scheme |
| MONGO_FEES_HOST | midaz-mongodb | MongoDB host |
| MONGO_FEES_NAME | fees | Database name |
| MONGO_FEES_USER | midaz | Username |
| MONGO_FEES_PASSWORD | lerian | Password |
| MONGO_FEES_PORT | 5703 | Port |
| MONGO_FEES_PARAMETERS | — | Extra connection parameters |
| MONGO_FEES_MAX_POOL_SIZE | 100 | Max pool size |
| MONGO_FEES_TLS_CA_CERT | — | TLS CA cert path |
Auth and multi-tenant env vars (`PLUGIN_AUTH_*`, `MULTI_TENANT_*`) are shared across the whole
ledger binary (one set governs onboarding, transaction, CRM, and fees) — see section 6.1.
### 6.3 Tracer (port 4020)
Source: `components/tracer/.env.example`. Key vars: `SERVER_PORT` (4020), `SERVER_ADDRESS`,
`DEPLOYMENT_MODE`, `ALLOW_INSECURE_TLS`, `API_KEY` / `API_KEY_ENABLED`, `CORS_ALLOWED_ORIGINS`,
`DB_HOST` / `DB_USER` / `DB_PASSWORD` / `DB_NAME` / `DB_PORT` / `DB_SSL_MODE` (its own PostgreSQL),
plus the standard OTEL exporter vars. The ledger→tracer reservation seam (separate from the `:4020`
REST API) is governed server-side by `TRACER_GRPC_PORT` (starts the gRPC seam; distinct from
`SERVER_PORT`) and the `TRACER_TLS_*` certs — `TRACER_TLS_CERT_FILE` / `TRACER_TLS_KEY_FILE` for the
server identity and `TRACER_TLS_CLIENT_CA_FILE` to verify the ledger's client cert under
`TRACER_TLS_MODE=mtls`; see
[docs/architecture/ledger-tracer-topology.md](docs/architecture/ledger-tracer-topology.md).
### 6.4 Infrastructure
| Variable | Default | Description |
|----------|---------|-------------|
| DB_HOST | midaz-postgres-primary | PostgreSQL primary |
| DB_USER | midaz | PostgreSQL username |
| DB_PASSWORD | lerian | PostgreSQL password |
| DB_PORT | 5701 | PostgreSQL port |
| MAX_CONNECTIONS | 3000 | PostgreSQL max connections |
| SHARED_BUFFERS | 1GB | PostgreSQL shared buffers |
| DB_REPLICA_HOST | midaz-postgres-replica | Replica host |
| DB_REPLICA_PORT | 5702 | Replica port |
| REPLICATION_USER | replicator | Replication username |
| REPLICATION_PASSWORD | replicator_password | Replication password |
| MONGO_HOST | midaz-mongodb | MongoDB host |
| MONGO_USER | midaz | MongoDB username |
| MONGO_PASSWORD | lerian | MongoDB password |
| MONGO_PORT | 5703 | MongoDB port |
| REDIS_HOST | midaz-valkey | Valkey/Redis host |
| REDIS_PORT | 5704 | Valkey/Redis port |
| REDIS_USER | midaz | Redis username |
| REDIS_PASSWORD | lerian | Redis password |
| RABBITMQ_PORT_HOST | 3003 | RabbitMQ management port |
| RABBITMQ_PORT_AMQP | 3004 | RabbitMQ AMQP port |
| RABBITMQ_DEFAULT_USER | midaz | RabbitMQ username |
| RABBITMQ_DEFAULT_PASS | lerian | RabbitMQ password |
| OTEL_LGTM_INTERNAL_PORT | 3000 | Grafana internal port |
| OTEL_LGTM_EXTERNAL_PORT | 3100 | Grafana external port |
| OTEL_LGTM_RECEIVER_GRPC_PORT | 4317 | OTLP gRPC receiver port |
| OTEL_LGTM_RECEIVER_HTTP_PORT | 4318 | OTLP HTTP receiver port |
| OTEL_LGTM_ADMIN_USER | midaz | Grafana admin username |
| OTEL_LGTM_ADMIN_PASSWORD | lerian | Grafana admin password |
## 7. Build & Development
### 7.1 Prerequisites
- Go 1.26.4 (`go.mod` `go 1.26.4`; component Docker builders use `golang:1.26.3-alpine`)
- Docker (with `docker compose`)
- golangci-lint v2.12.2
### 7.2 Makefile Commands
```bash
# Setup
make set-env # Copy .env.example → .env for all components
make dev-setup # Install tools + git hooks + env files
make setup-git-hooks # Configure git hooks
# Build & Run
make build # Build the deploy-unit binaries
make up # Start all services (infra → ledger → tracer)
make down # Stop all services
make restart # Restart all services
make rebuild-up # Rebuild and restart
make logs # Show logs
# Quality
make lint # Lint all components
make format # Format code
make tidy # go mod tidy
make sec # Security checks (gosec + govulncheck)
# Testing
make test # Run all tests
make test-unit # Unit tests