> For the complete documentation index, see [llms.txt](https://host2host.onibonje.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://host2host.onibonje.com/docs/16-security-library.md).

# Security Library

## 1. Overview

The **Security Library** (`h2h-security`) is a reusable JAR module that centralizes all cryptographic, authentication, and secrets-management operations for the H2H platform. Every other module delegates security concerns here — routes never implement crypto or credential handling directly.

**Module:** `h2h-security`

**Package root:** `com.heirs.h2h.security`

```mermaid
flowchart TB
  subgraph consumers [Consumers]
    FileMgmt[h2h-file-management]
    Routes[h2h-*-routes]
    Admin[h2h-admin-api]
    Gateway[API Gateway plugins]
  end

  subgraph security [h2h-security]
    Vault[VaultClient]
    PGP[PgpService]
    Crypto[CryptoService]
    Sign[SignatureService]
    Cert[CertificateService]
    Mask[DataMaskingService]
    Camel[crypto: Camel component]
  end

  subgraph external [External]
    HashiCorp[HashiCorp Vault]
    HSM[HSM / KMS optional]
  end

  consumers --> security
  Vault --> HashiCorp
  Crypto --> HSM
```

***

## 2. Design Principles

| Principle                  | Implementation                                               |
| -------------------------- | ------------------------------------------------------------ |
| Single security boundary   | All modules use `h2h-security` APIs only                     |
| Secrets never in code/DB   | Vault references resolved at runtime                         |
| Fail secure                | Missing key, bad signature → reject immediately              |
| Algorithm agility          | Configurable algorithms per partner/country                  |
| Audit every crypto op      | Log operation type, key ID, correlation ID — never plaintext |
| Minimal surface in scripts | Script sandbox has no direct security API access             |

***

## 3. Module Structure

```
h2h-security/
├── api/                          # Public interfaces (stable)
│   ├── VaultClient.java
│   ├── PgpService.java
│   ├── CryptoService.java
│   ├── SignatureService.java
│   ├── CertificateService.java
│   └── DataMaskingService.java
├── vault/
│   ├── HashiCorpVaultClient.java
│   └── VaultCredentialResolver.java
├── pgp/
│   ├── BouncyCastlePgpService.java
│   └── PgpKeyCache.java
├── crypto/
│   ├── AesCryptoService.java
│   └── KmsCryptoService.java          # Optional cloud KMS
├── signature/
│   ├── HmacSignatureService.java
│   └── RsaSignatureService.java
├── certificate/
│   ├── CertificateLoader.java
│   └── CertificateValidator.java
├── masking/
│   └── DataMaskingServiceImpl.java
├── camel/
│   ├── CryptoComponent.java           # crypto:pgpDecrypt, crypto:pgpEncrypt
│   ├── CryptoEndpoint.java
│   └── CryptoProducer.java
└── config/
    └── SecurityAutoConfiguration.java
```

***

## 4. Vault Client

### 4.1 VaultClient API

```java
public interface VaultClient {

    String getSecret(String vaultPath, String key);

    byte[] getSecretBytes(String vaultPath, String key);

    void rotateSecret(String vaultPath, Map<String, String> newValues);

    String encrypt(String transitKey, String plaintext);

    String decrypt(String transitKey, String ciphertext);
}
```

### 4.2 Credential Resolution Pattern

Database stores **references only**:

```json
{
  "credentialRef": "vault:secret/sftp/ng/acme/private-key",
  "pgpDecryptKeyRef": "vault:secret/pgp/bank/private",
  "pgpPartnerKeyRef": "vault:secret/pgp/partner/acme/public"
}
```

```java
@Component
public class VaultCredentialResolver {
    public String resolvePrivateKey(String vaultPath) {
        return vaultClient.getSecret(stripPrefix(vaultPath), "key");
    }
}
```

### 4.3 Authentication to Vault

| Environment | Auth method                      |
| ----------- | -------------------------------- |
| Kubernetes  | Service account + Vault K8s auth |
| On-prem     | AppRole                          |
| Local dev   | Dev token (never in production)  |

### 4.4 Secret Caching

| Setting       | Value                  |
| ------------- | ---------------------- |
| Cache TTL     | 5 minutes              |
| Invalidation  | Vault rotation webhook |
| Thread safety | Caffeine cache per pod |

***

## 5. PGP Service

### 5.1 PgpService API

```java
public interface PgpService {

    byte[] encrypt(byte[] plaintext, String publicKeyRef);

    byte[] decrypt(byte[] ciphertext, String privateKeyRef);

    byte[] sign(byte[] data, String signingKeyRef);

    boolean verify(byte[] data, byte[] signature, String publicKeyRef);

    String armoredEncrypt(byte[] plaintext, String publicKeyRef);

    byte[] armoredDecrypt(String armored, String privateKeyRef);
}
```

### 5.2 Inbound File Decryption Flow

```
Partner file (.pgp) → crypto:pgpDecrypt Camel step
    → PgpService.decrypt(ciphertext, profile.pgpDecryptKeyRef)
    → VaultCredentialResolver loads private key
    → Cleartext in memory only → next pipeline step
```

### 5.3 Outbound Encryption Flow

```
ACK file (cleartext) → crypto:pgpEncrypt
    → PgpService.encrypt(plaintext, profile.pgpPartnerKeyRef)
    → Armored output → file-mgmt:deliver
```

### 5.4 PGP Configuration (per partner — database)

| Field                 | Description                |
| --------------------- | -------------------------- |
| `pgpInboundRequired`  | Reject unencrypted inbound |
| `pgpOutboundRequired` | Encrypt all outbound       |
| `pgpSignOutbound`     | Sign with bank key         |
| `pgpVerifyInbound`    | Verify partner signature   |
| `pgpAlgorithm`        | AES-256, ZIP compression   |

***

## 6. Signature Service

### 6.1 HMAC Request Signing (API channel)

For partners authenticating API requests via signed headers.

```java
public interface SignatureService {

    String signHmac(String payload, String keyRef, String algorithm);

    boolean verifyHmac(String payload, String signature, String keyRef, String algorithm);

    String signRsa(String payload, String privateKeyRef);

    boolean verifyRsa(String payload, String signature, String publicKeyRef);
}
```

### 6.2 HMAC Verification Flow

```
Request → API Gateway / Camel intercept
       → extract Signature header
       → SignatureService.verifyHmac(canonicalRequest, signature, partner.signingKeyRef)
       → pass or 401 Unauthorized
```

**Canonical request format:**

```
{HTTP_METHOD}\n{URI_PATH}\n{X-Date}\n{SHA256(body)}
```

### 6.3 File Integrity Signing

Optional **detached signature** file alongside payload:

```
PAY_20260629.csv.pgp          # encrypted payload
PAY_20260629.csv.pgp.sig      # RSA/HMAC signature
```

Verified by `FileIntegrityService` before processing.

***

## 7. Crypto Service (Symmetric)

### 7.1 Use Cases

| Use case                             | Algorithm                     |
| ------------------------------------ | ----------------------------- |
| Idempotency key hashing              | SHA-256                       |
| Field-level encryption (PII at rest) | AES-256-GCM via Vault Transit |
| Temporary token generation           | SecureRandom + Base64URL      |

```java
public interface CryptoService {

    String hashSha256(byte[] data);

    String encryptField(String plaintext, String transitKey);

    String decryptField(String ciphertext, String transitKey);

    String generateSecureToken(int byteLength);
}
```

### 7.2 Vault Transit Engine

Sensitive metadata fields (e.g. account numbers in extension tables) encrypted via Vault Transit — platform never holds master encryption keys.

***

## 8. Certificate Service

### 8.1 CertificateService API

```java
public interface CertificateService {

    X509Certificate loadCertificate(String certRef);

    boolean validateCertificateChain(X509Certificate cert, String trustStoreRef);

    boolean isRevoked(X509Certificate cert);

    int daysUntilExpiry(String certRef);
}
```

### 8.2 Use Cases

| Use case                   | Implementation                                          |
| -------------------------- | ------------------------------------------------------- |
| mTLS partner auth          | Validate client cert against trust store in Vault       |
| SFTP host key verification | Known hosts in Vault                                    |
| API gateway TLS            | cert-manager on Kubernetes (infra)                      |
| Expiry alerting            | Broker-delayed job (`job_def`) checks `daysUntilExpiry` |

### 8.3 Certificate Lifecycle

```mermaid
stateDiagram-v2
  [*] --> ACTIVE: Issued / uploaded
  ACTIVE --> EXPIRING: 30 days to expiry
  EXPIRING --> ROTATED: New cert deployed
  ROTATED --> ACTIVE
  ACTIVE --> REVOKED: Compromise / offboarding
  REVOKED --> [*]
```

Alerts published to `h2h.security.cert.expiring` Kafka topic.

***

## 9. Data Masking Service

### 9.1 Purpose

Mask sensitive data in logs, admin UI, and audit exports based on caller role.

```java
public interface DataMaskingService {

    String maskAccountNumber(String accountNumber, MaskingLevel level);

    String maskPan(String pan, MaskingLevel level);

    String maskForLog(String field, String value, String fieldType);
}
```

### 9.2 Masking Levels

| Level     | Account number | Used by                   |
| --------- | -------------- | ------------------------- |
| `FULL`    | `****1234`     | Ops, logs                 |
| `PARTIAL` | `012****1234`  | Integration analyst       |
| `NONE`    | `0123451234`   | Auditor (with permission) |

***

## 10. Camel Component: `crypto:`

### 10.1 URI Syntax

```
crypto:pgpDecrypt?keyRefHeader=h2h.pgpDecryptKeyRef
crypto:pgpEncrypt?keyRefHeader=h2h.pgpEncryptKeyRef
crypto:sign?keyRefHeader=h2h.signingKeyRef
crypto:verify?keyRefHeader=h2h.verifyKeyRef
```

Key references read from exchange properties set by `ConfigResolverProcessor`.

### 10.2 Example Route Usage

```java
from("file-mgmt:poll")
    .to("crypto:pgpDecrypt")
    .to("direct:validate-and-transform");
```

***

## 11. Security Headers Convention

| Header                | Set by                             | Purpose                          |
| --------------------- | ---------------------------------- | -------------------------------- |
| `X-Correlation-Id`    | Gateway / `CorrelationIdProcessor` | Trace across services            |
| `X-Partner-Id`        | Gateway                            | Partner identification           |
| `X-Request-Signature` | Partner (inbound)                  | HMAC verification                |
| `X-Date`              | Partner (inbound)                  | Replay protection (5 min window) |
| `X-Content-SHA256`    | Partner (file upload)              | Integrity check                  |

### 11.1 Replay Protection

Requests with `X-Date` older than **5 minutes** are rejected (configurable per partner).

***

## 12. Dependency Rules

| Rule                                                           | Enforcement       |
| -------------------------------------------------------------- | ----------------- |
| Only `h2h-security` imports BouncyCastle / crypto SDKs         | Maven enforcer    |
| Route modules use `PgpService` API — not BouncyCastle directly | ArchUnit          |
| No `VaultClient` in admin UI frontend                          | API only          |
| Scripts cannot import security classes                         | Sandbox classpath |

***

## 13. Configuration

```yaml
h2h:
  security:
    vault:
      uri: ${VAULT_URI:https://vault.bank.internal}
      authMethod: kubernetes
      role: h2h-runtime
    pgp:
      keyCacheTtlMinutes: 5
      defaultAlgorithm: AES-256
    signature:
      defaultAlgorithm: HmacSHA256
      replayWindowMinutes: 5
    masking:
      defaultLevel: FULL
```

***

## 14. Audit Events

Every security operation emits an audit event (metadata only):

| Event           | Fields logged                                        |
| --------------- | ---------------------------------------------------- |
| `PGP_DECRYPT`   | correlationId, partnerId, keyRef, fileId, durationMs |
| `PGP_ENCRYPT`   | correlationId, partnerId, keyRef, fileId             |
| `HMAC_VERIFY`   | correlationId, partnerId, result, algorithm          |
| `CERT_VALIDATE` | partnerId, certThumbprint, result                    |
| `VAULT_ACCESS`  | vaultPath (not secret value), operation              |

**Never logged:** Key material, cleartext payloads, signatures, passwords.

***

## 15. Testing

| Test type   | Approach                                               |
| ----------- | ------------------------------------------------------ |
| Unit        | Mock `VaultClient`, test PGP round-trip with test keys |
| Integration | Testcontainers Vault dev mode                          |
| Contract    | Publish test key fixtures for route module consumers   |

Test keys stored in `src/test/resources/keys/` — never in production paths.

***

## 16. Related Documents

* [Universal Library Extensibility](/docs/20-universal-library-extensibility.md)
* [Security and Compliance](/docs/09-security-and-compliance.md) — policies and compliance
* [File Management System](/docs/15-file-management-system.md) — PGP and signed delivery
* [Execution Context](/docs/18-execution-context.md) — correlation and security context
* [Monitoring and Logging](/docs/17-monitoring-and-logging.md) — security event logging
* [Cloud-Agnostic Deployment](/docs/19-cloud-agnostic-deployment.md) — Vault on K8s


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://host2host.onibonje.com/docs/16-security-library.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
