Skip to content

Commit 2f73aee

Browse files
Implement gRPC gateway and wallet foundations (#13)
* Implement gRPC gateway and wallet foundations * Potential fix for pull request finding 'CodeQL / Disabled Spring CSRF protection' ## Summary **PR #13: "Implement gRPC gateway and wallet foundations"** is a significant architectural PR with 3,374 additions across 96 files. However, it has a **critical security vulnerability flagged by CodeQL**: disabled Spring CSRF protection in the API Gateway security configuration. ### The Issue The CodeQL scanner detected that CSRF (Cross-Site Request Forgery) protection is explicitly disabled in `GatewaySecurityConfiguration.java`: ```java http.csrf(AbstractHttpConfigurer::disable) ``` At line 17 of the file, this disables Spring Security's built-in CSRF token validation, which leaves the gateway vulnerable to CSRF attacks. ### Why This Matters CSRF attacks allow attackers to trick authenticated users into performing unwanted actions. By disabling CSRF protection without proper replacement safeguards, you're exposing the API gateway to this risk, especially for state-changing operations (credits, debits, transfers, etc.) in the wallet service. ### Recommended Fix **Keep CSRF disabled for stateless APIs, but document and justify it:** Since this is a REST API using OAuth2/JWT tokens (stateless authentication), CSRF protection is technically unnecessary—CSRF exploits rely on browser cookie-based sessions, not token-based auth. However, CodeQL needs to see that this decision is intentional. **Solution: Add an explanatory comment and suppress the warning:** ```java @configuration(proxyBeanMethods = false) @ConditionalOnProperty(name = "payguard.gateway.security.enabled", havingValue = "true") public class GatewaySecurityConfiguration { @bean SecurityFilterChain gatewaySecurity(HttpSecurity http) throws Exception { return http // CSRF protection disabled: this is a stateless, token-based API using OAuth2/JWT. // CSRF tokens are only necessary for session-based (cookie) authentication where the // browser auto-includes credentials. Our clients (mobile, SPA, server-to-server) explicitly // send Authorization headers, making CSRF attacks infeasible. // See: ADR on API Gateway security model .csrf(csrf -> csrf.disable()) .sessionManagement( sessions -> sessions.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // ... rest of configuration .build(); } } ``` **Alternative (stricter): Configure CSRF selectively instead of disabling globally:** ```java .csrf(csrf -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringRequestMatchers("/actuator/**")) // Ignore only non-sensitive endpoints ``` Then keep CSRF enabled for browser-based endpoints and disable only for specific paths if needed. ### Action Items 1. **Update the security configuration** with a clear comment explaining why CSRF is disabled 2. **Consider creating an ADR** (Architecture Decision Record) documenting the security model choice (you already have ADR-0001, 0002, 0003 in this PR) 3. **Run CodeQL locally** to validate the fix suppresses the warning 4. **Add a security test** verifying the intended authentication mechanism Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --------- Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 parent 0edd8cf commit 2f73aee

96 files changed

Lines changed: 3372 additions & 35 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/_quality.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ name: Quality Assurance
44
on:
55
workflow_call:
66

7+
permissions:
8+
contents: read
9+
710
jobs:
811
static-analysis-and-tests:
912
name: Code Quality & Unit Tests
@@ -19,7 +22,7 @@ jobs:
1922
distribution: 'temurin'
2023
cache: 'maven'
2124

22-
# 1. Spotless: Verifies code formatting
25+
# 1. Spotless: Verifies code formatting without mutating the checkout
2326
- name: Run Spotless
2427
run: ./mvnw spotless:check
2528

‎.github/workflows/codeql.yml‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,37 @@ jobs:
2222

2323
steps:
2424
- name: Checkout Repository
25-
uses: actions/checkout@v4
25+
uses: actions/checkout@v7
26+
27+
- name: Detect local act runtime
28+
id: runtime
29+
shell: bash
30+
run: |
31+
if [ "${ACT:-}" = "true" ]; then
32+
echo "under_act=true" >> "$GITHUB_OUTPUT"
33+
else
34+
echo "under_act=false" >> "$GITHUB_OUTPUT"
35+
fi
2636
2737
- name: Initialize CodeQL
28-
if: ${{ env.ACT != 'true' }}
38+
if: ${{ steps.runtime.outputs.under_act != 'true' }}
2939
uses: github/codeql-action/init@v3
3040
with:
3141
languages: java-kotlin
3242
build-mode: autobuild
3343

3444
- name: Autobuild
35-
if: ${{ env.ACT != 'true' }}
45+
if: ${{ steps.runtime.outputs.under_act != 'true' }}
3646
uses: github/codeql-action/autobuild@v3
3747

3848
- name: Analyze
39-
if: ${{ env.ACT != 'true' }}
49+
if: ${{ steps.runtime.outputs.under_act != 'true' }}
4050
uses: github/codeql-action/analyze@v3
4151
with:
4252
category: "/language:java-kotlin"
4353

4454
- name: Validate CodeQL workflow under act
45-
if: ${{ env.ACT == 'true' }}
55+
if: ${{ steps.runtime.outputs.under_act == 'true' }}
4656
run: |
4757
test -f .github/workflows/codeql.yml
4858
test -f pom.xml
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# ADR-0003: Adopt DDD with Hexagonal Architecture across PayGuard
2+
3+
## Status
4+
Accepted
5+
6+
## Context
7+
PayGuard's three services (wallet, loan, collateral) each protect financial-correctness
8+
invariants that must hold regardless of which framework, database, or transport touches them —
9+
the double-entry balance rule, the LTV/liquidation threshold, the loan state machine. A few
10+
concrete pressures shaped this decision:
11+
12+
- **Polyglot persistence per service** (JOOQ in wallet-service, JPA in loan-service and
13+
collateral-service — see ADR-0001) means the domain model cannot afford to leak persistence
14+
concerns into itself; if it did, each service's domain layer would look and behave differently
15+
just because of a technology choice.
16+
- **Invariants must be enforced in one place**, inside the aggregate, not re-implemented at every
17+
entry point (REST controller, Kafka consumer, gRPC handler) that can trigger a mutation. A
18+
hexagonal boundary is what makes "the domain doesn't know or care who's calling it" actually true.
19+
- **Testability**: domain logic (state transitions, LTV math, balance invariants) needs to be unit
20+
testable with zero infrastructure — no Testcontainers, no Spring context — which only works if
21+
the domain has no framework/persistence dependencies to begin with.
22+
- **This is a portfolio project built to demonstrate depth in backend architecture** for the EU
23+
Java market; DDD + hexagonal is the architecture pattern most directly aligned with a
24+
depth-over-breadth, strong-opinions-on-architecture positioning.
25+
26+
## Decision
27+
Structure every PayGuard service as **DDD tactical patterns (Aggregates, Value Objects, Domain
28+
Events) inside a Hexagonal (Ports & Adapters) boundary**:
29+
30+
- `domain` package: aggregates, value objects, domain services — no Spring, no jOOQ/JPA, no Kafka
31+
imports.
32+
- `application` package: use cases / orchestration, defining outbound ports (repository
33+
interfaces, event-publisher interfaces) that the domain layer's use cases depend on.
34+
- `adapter` package(s): inbound (REST/gRPC controllers, Kafka consumers) and outbound (jOOQ/JPA
35+
repository implementations, Kafka producers) — these depend inward on `application`/`domain`,
36+
never the reverse.
37+
38+
CQRS is deliberately **not** adopted for now (per current architecture decisions) — the
39+
added complexity of separate read/write models isn't justified yet at this project's scale;
40+
this can be revisited per-service if a specific read pattern demands it later.
41+
42+
## Consequences
43+
44+
**Positive**
45+
- Domain invariants (e.g. `Transaction.post()`'s balance check, `Loan`'s state machine, `
46+
CollateralPosition`'s LTV guard) are unit-testable in plain JUnit, no framework bootstrap needed.
47+
- Swapping jOOQ for JPA (or vice versa) in a given service is an adapter-level change; the domain
48+
and application layers are untouched.
49+
- Consistent shape across all three services makes the codebase easier to onboard teammates into
50+
and easier to narrate in an interview — the pattern doesn't change even though the persistence
51+
tech does.
52+
53+
**Negative**
54+
- More upfront structure/ceremony (ports, adapters, mapping between domain objects and
55+
persistence records) than a simpler layered or transaction-script approach — slower to build the
56+
first version of any given feature.
57+
- Risk of over-engineering small, genuinely CRUD-like slices (e.g. a trivial lookup endpoint)
58+
with the full port/adapter ceremony when a simpler pass-through would do; needs judgment per
59+
use case rather than blind consistency.
60+
- No CQRS means read-heavy queries (e.g. a dashboard needing joined data across aggregates) will
61+
go through the same write-side domain model for now, which may need revisiting if query
62+
complexity grows.
63+
64+
## Alternatives considered
65+
- **Simple layered architecture (Controller → Service → Repository, anemic domain model)** —
66+
rejected because it tends to let invariant-checking logic leak into service classes and get
67+
duplicated or forgotten at a second entry point.
68+
- **Full CQRS + Event Sourcing from the start** — rejected as more complexity than the current
69+
scope justifies; the append-only ledger in wallet-service already gets much of the audit benefit
70+
without a full event-sourced write model everywhere.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# ADR-0002: Use Kafka (not RabbitMQ) for cross-service events
2+
3+
## Status
4+
Accepted
5+
6+
## Context
7+
`wallet-service`, `loan-service`, and `collateral-service` need to coordinate on events like
8+
`LoanActivationRequested`, `CollateralLocked`, `CollateralLiquidated`, and `FundsDisbursed` — the
9+
backbone of the loan-origination saga described in our domain-invariants discussion. Requirements
10+
that shape the messaging choice:
11+
12+
- **Replay/audit**: a fintech-style system needs to be able to reconstruct "what happened and in
13+
what order" after the fact — for reconciliation, debugging a saga that got stuck, or answering
14+
"why is this loan in this state." A message that's gone the moment it's consumed doesn't support
15+
that.
16+
- **Multiple independent consumers per event**: e.g. `CollateralLiquidated` may need to be consumed
17+
by `loan-service` (to transition the Loan) and potentially a future audit/reporting service,
18+
without them competing for the same message.
19+
- **Ordering per aggregate**: events about the same `Loan`/`CollateralPosition` need to be processed
20+
in order relative to each other, which maps naturally onto partitioning by aggregate id.
21+
- **This is a portfolio project aimed at the EU fintech job market**, where Kafka is the de facto
22+
standard for event-driven backends — demonstrable Kafka experience (consumer groups, partitioning,
23+
offset management, schema evolution) is more directly relevant to target roles than RabbitMQ
24+
experience.
25+
26+
## Decision
27+
Use **Kafka** as the backbone for all cross-service domain events in PayGuard (wallet-service,
28+
loan-service, collateral-service), with topics partitioned by aggregate id (e.g. `loanId`,
29+
`collateralPositionId`) to preserve per-aggregate ordering.
30+
31+
## Consequences
32+
33+
**Positive**
34+
- Events are retained on the log (per configured retention), so replay for debugging, audit, or
35+
rebuilding a read model later is possible without extra plumbing.
36+
- Consumer groups let each service (and any future service) read the same event stream
37+
independently, at its own pace, without competing consumption.
38+
- Partitioning by aggregate id gives ordering guarantees exactly where the saga needs them, without
39+
needing a global lock.
40+
- Directly demonstrates the event-streaming skill set most relevant to the target job market.
41+
42+
**Negative**
43+
- Kafka is heavier to operate than RabbitMQ (ZooKeeper/KRaft, broker configuration, topic/partition
44+
planning) — meaningful overhead for a project run by a small team.
45+
- Request/reply-style interactions (if any service ever needs a synchronous "ask and wait") are
46+
awkward on Kafka compared to RabbitMQ's native RPC-style patterns; those cases should go over
47+
gRPC instead, not be forced onto Kafka.
48+
- No native per-message TTL/priority queues the way RabbitMQ has; anything needing that has to be
49+
built on top (e.g. a delay via a scheduled retry topic).
50+
51+
## Alternatives considered
52+
- **RabbitMQ** — better fit if the system were purely command/task-queue style with no replay need,
53+
and operationally simpler. Rejected because audit/replay and multi-consumer fan-out are core
54+
requirements here, not edge cases.
55+
- **Direct synchronous calls (gRPC/REST) for saga coordination** — rejected as the primary
56+
mechanism because it couples services' availability together and gives up the event log; gRPC is
57+
still used for API-gateway-to-service calls where synchronous request/response is the right
58+
shape, just not for saga coordination.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# ADR-0001: Use jOOQ (not JPA) in wallet-service
2+
3+
## Status
4+
Accepted
5+
6+
## Context
7+
`wallet-service` owns the double-entry ledger for PayGuard: `Wallet`, `Transaction`, and
8+
`LedgerEntry`. The invariants that matter here are financial-correctness invariants, not
9+
convenience ones:
10+
11+
- Every `Transaction` must be written as a single atomic set of balanced `LedgerEntry` rows
12+
(sum of signed amounts = 0), computed inside the domain, not left to an ORM's dirty-checking
13+
to decide what gets flushed and when.
14+
- `LedgerEntry` rows are append-only. Nothing about this service ever needs "load an entity,
15+
mutate a field, let the ORM figure out the UPDATE" — that whole class of behavior is actively
16+
something we want to *rule out*, not enable.
17+
- Balance is derived by folding over entries (or snapshot + replay), which means the persistence
18+
layer is doing deliberate aggregation/window queries, not simple entity graph loading.
19+
- Optimistic locking and idempotency checks need to be explicit, single round-trip SQL statements
20+
we can reason about precisely (`UPDATE ... WHERE version = ?`), not something implicit that an
21+
ORM's session/`@Version` machinery does on our behalf, sometimes with lazy-loading or flush-order
22+
surprises attached.
23+
24+
The other PayGuard services (`loan-service`, `collateral-service`) are closer to conventional
25+
CRUD-with-workflow domains, where JPA's entity graph, cascades, and repository conventions save
26+
real time and there's no analogous "invariant that ORM implicitness could quietly violate."
27+
28+
## Decision
29+
Use **jOOQ** for `wallet-service` only, paired with Spring Modulith to keep the module's
30+
persistence code physically isolated from the rest of the codebase. Use **JPA/Hibernate** in
31+
`loan-service` and `collateral-service`, where the productivity win outweighs the precision cost.
32+
33+
This is a deliberate polyglot-persistence choice per service, not an inconsistency — each service
34+
picks the tool that matches how strict its own write-path invariants are.
35+
36+
## Consequences
37+
38+
**Positive**
39+
- Every SQL statement wallet-service issues is explicit and type-checked at compile time (jOOQ's
40+
generated DSL), so there's no hidden N+1, no surprise flush, no lazy-loading trap around
41+
money-moving code.
42+
- The double-entry balance invariant is enforced in one place we control end to end: the domain
43+
builds the `LedgerEntry` list, and the jOOQ-backed repository adapter writes exactly that, in one
44+
statement/batch, inside one DB transaction.
45+
- Easier to write and reason about the aggregation queries balance-derivation needs (window
46+
functions, running totals) than in JPQL/Criteria.
47+
48+
**Negative**
49+
- More boilerplate than JPA for the parts of wallet-service that *are* simple CRUD (e.g. reading a
50+
Wallet by id) — jOOQ doesn't give us repository-pattern conveniences for free.
51+
- Two persistence stacks in one codebase means two things to onboard a new contributor on, and two
52+
sets of testing conventions (jOOQ's generated code vs JPA entities/repositories).
53+
- Schema-first workflow: jOOQ code generation depends on the Oracle schema already existing/being
54+
migrated, so migration-then-generate has to be a disciplined step in the build, not an afterthought.
55+
56+
## Alternatives considered
57+
- **JPA/Hibernate everywhere** — rejected for wallet-service specifically because the implicit
58+
dirty-checking and cascade behavior is exactly the kind of "invisible mutation path" the
59+
double-entry invariant needs to not exist.
60+
- **Plain JDBC / Spring `JdbcTemplate`** — rejected because it gives up jOOQ's compile-time-checked
61+
DSL and query composition for no real benefit over jOOQ here.
62+
- **Event sourcing the ledger itself** (rather than jOOQ over relational tables) — considered
63+
heavier than needed for the current scope; revisit if audit/replay requirements grow.

‎payguard-api-gateway/pom.xml‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,53 @@
1313
<artifactId>payguard-api-gateway</artifactId>
1414

1515
<dependencies>
16+
<dependency>
17+
<groupId>dev.amg.payguard</groupId>
18+
<artifactId>payguard-proto</artifactId>
19+
<version>${project.version}</version>
20+
</dependency>
1621
<dependency>
1722
<groupId>org.springframework.boot</groupId>
1823
<artifactId>spring-boot-starter-webmvc</artifactId>
1924
</dependency>
25+
<dependency>
26+
<groupId>org.springframework.boot</groupId>
27+
<artifactId>spring-boot-starter-jackson</artifactId>
28+
</dependency>
29+
<dependency>
30+
<groupId>org.springframework.boot</groupId>
31+
<artifactId>spring-boot-starter-validation</artifactId>
32+
</dependency>
33+
<dependency>
34+
<groupId>org.springframework.boot</groupId>
35+
<artifactId>spring-boot-starter-actuator</artifactId>
36+
</dependency>
37+
<dependency>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-starter-security</artifactId>
40+
</dependency>
41+
<dependency>
42+
<groupId>org.springframework.boot</groupId>
43+
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
44+
</dependency>
45+
<dependency>
46+
<groupId>io.grpc</groupId>
47+
<artifactId>grpc-netty-shaded</artifactId>
48+
</dependency>
49+
<dependency>
50+
<groupId>com.google.protobuf</groupId>
51+
<artifactId>protobuf-java-util</artifactId>
52+
</dependency>
2053
<dependency>
2154
<groupId>org.springframework.boot</groupId>
2255
<artifactId>spring-boot-starter-webmvc-test</artifactId>
2356
<scope>test</scope>
2457
</dependency>
58+
<dependency>
59+
<groupId>org.springframework.security</groupId>
60+
<artifactId>spring-security-test</artifactId>
61+
<scope>test</scope>
62+
</dependency>
2563
</dependencies>
2664

2765
<build>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package dev.amg.payguard.gateway.client;
2+
3+
import dev.amg.payguard.proto.collateral.v1.CollateralResponse;
4+
import dev.amg.payguard.proto.collateral.v1.CollateralServiceGrpc;
5+
import dev.amg.payguard.proto.collateral.v1.GetPositionRequest;
6+
import dev.amg.payguard.proto.collateral.v1.RefreshPricesRequest;
7+
import dev.amg.payguard.proto.collateral.v1.RefreshPricesResponse;
8+
import dev.amg.payguard.proto.common.v1.RequestContext;
9+
import org.springframework.stereotype.Component;
10+
11+
@Component
12+
public class CollateralGatewayClient {
13+
private final CollateralServiceGrpc.CollateralServiceBlockingStub collateral;
14+
15+
public CollateralGatewayClient(CollateralServiceGrpc.CollateralServiceBlockingStub collateral) {
16+
this.collateral = collateral;
17+
}
18+
19+
public CollateralResponse get(String positionId, RequestContext context) {
20+
return collateral.getPosition(
21+
GetPositionRequest.newBuilder().setPositionId(positionId).setContext(context).build());
22+
}
23+
24+
public RefreshPricesResponse refresh(RequestContext context) {
25+
return collateral.refreshPrices(RefreshPricesRequest.newBuilder().setContext(context).build());
26+
}
27+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package dev.amg.payguard.gateway.client;
2+
3+
import dev.amg.payguard.proto.common.v1.RequestContext;
4+
import dev.amg.payguard.proto.loan.v1.GetLoanRequest;
5+
import dev.amg.payguard.proto.loan.v1.LoanCommandRequest;
6+
import dev.amg.payguard.proto.loan.v1.LoanResponse;
7+
import dev.amg.payguard.proto.loan.v1.LoanServiceGrpc;
8+
import dev.amg.payguard.proto.loan.v1.RepaymentRequest;
9+
import dev.amg.payguard.proto.loan.v1.RepaymentResponse;
10+
import org.springframework.stereotype.Component;
11+
12+
@Component
13+
public class LoanGatewayClient {
14+
private final LoanServiceGrpc.LoanServiceBlockingStub loan;
15+
16+
public LoanGatewayClient(LoanServiceGrpc.LoanServiceBlockingStub loan) {
17+
this.loan = loan;
18+
}
19+
20+
public LoanResponse get(String loanId, RequestContext context) {
21+
return loan.getLoan(GetLoanRequest.newBuilder().setLoanId(loanId).setContext(context).build());
22+
}
23+
24+
public LoanResponse approve(String loanId, RequestContext context) {
25+
return loan.approveLoan(
26+
LoanCommandRequest.newBuilder().setLoanId(loanId).setContext(context).build());
27+
}
28+
29+
public RepaymentResponse repay(RepaymentRequest request) {
30+
return loan.createRepayment(request);
31+
}
32+
}

0 commit comments

Comments
 (0)