Skip to content

Feature: Add API-Based Signatures for B2C Flows #42

@DibranMulder

Description

@DibranMulder

Summary

Add API-based signature support to PostGuard, enabling Business-to-Consumer (B2C) flows where systems/organizations can send end-to-end encrypted files without requiring human authentication via Yivi/IRMA.

Scope: API-based authentication applies only to senders, not recipients. Recipients continue using Identity-Based Encryption (IBE) with Yivi authentication.

Full Design Document: See API_SIGNATURES_DESIGN.md


Motivation

Current Limitation

The existing PostGuard system requires all senders to authenticate via Yivi, which is designed for human users. This prevents automated systems, backend services, or organizations from sending encrypted files programmatically.

Use Cases

  • Healthcare systems sending encrypted patient records to individuals
  • Government agencies distributing encrypted documents to citizens
  • Financial institutions transmitting secure statements to customers
  • SaaS platforms sending encrypted data exports to users

Architecture Overview

High-Level Components

graph TB
    subgraph "Senders"
        Human[Human User<br/>Yivi Auth]
        System[Organization/System<br/>API Key Auth]
    end

    subgraph "PKG Server"
        APIKeyStore[(API Key Store)]
        KeyIssuer[Key Issuer]
        YiviValidator[Yivi Validator]
        APIValidator[API Key Validator]
    end

    subgraph "Recipients"
        Recipient[Human Recipient<br/>Yivi Auth]
    end

    Human -->|Yivi Session| YiviValidator
    System -->|API Key| APIValidator

    YiviValidator --> KeyIssuer
    APIValidator --> KeyIssuer
    APIKeyStore --> APIValidator

    KeyIssuer -->|IBS Keys| Human
    KeyIssuer -->|IBS Keys| System

    Human -->|Encrypted File| Recipient
    System -->|Encrypted File| Recipient
    Recipient -->|Decrypt via Yivi| PKG
Loading

Key Features

1. API Key Management

API Key Format: `pg_live_<base64url(32_random_bytes)>_`

CLI Commands:
```bash

Generate a new API key

cargo run --release --bin pg-pkg api-key create
--org-name "Healthcare Provider Inc."
--org-id "org_abc123"
--contact "security@healthprovider.com"
--expires-in-days 365

List all API keys

cargo run --release --bin pg-pkg api-key list

Revoke an API key

cargo run --release --bin pg-pkg api-key revoke apk_7x8y9z10abc

Show API key details

cargo run --release --bin pg-pkg api-key info apk_7x8y9z10abc

Rotate an API key

cargo run --release --bin pg-pkg api-key rotate apk_7x8y9z10abc
```

2. New API Endpoints

`POST /v2/api/sign/key`: Request signing keys using API authentication

Request:
```http
POST /v2/api/sign/key HTTP/1.1
Authorization: Bearer pg_live_xK9mP2vL4nQ8rT6wY1zA5bD3cF7gH0jM_c4a9
Content-Type: application/json

{
"pubSignId": [{ "t": "api.organization.name" }],
"privSignId": [{ "t": "api.organization.id" }]
}
```

Response:
```json
{
"status": "SUCCESS",
"pubSignKey": { "key": "...", "policy": {...} },
"privSignKey": { "key": "...", "policy": {...} },
"api_key_metadata": {
"org_name": "Healthcare Provider Inc.",
"org_id": "org_abc123",
"key_id": "apk_7x8y9z10abc"
}
}
```

3. Identity Representation

New API Identity Namespace:

  • `api.organization.name` → Organization display name
  • `api.organization.id` → Unique organization identifier
  • `api.organization.email` → Organization contact email
  • `api.key.id` → API key identifier (for audit)

Recipients can distinguish sender type by inspecting attributes:

  • `api.*` → System/Organization sender
  • `pbdf.`, `irma-demo.` → Human sender (Yivi)

Implementation Phases

Phase 1: Core Infrastructure (MVP) - 2-3 weeks

  • SQLite-based API key storage
  • API key generation CLI (`pg-pkg api-key create`)
  • API key management CLI (list, revoke, info)
  • Basic authentication middleware for API keys
  • `POST /v2/api/sign/key` endpoint
  • Rate limiting (simple in-memory counter)

Phase 2: Security Hardening - 1-2 weeks

  • Audit logging infrastructure
  • Advanced rate limiting (sliding window, Redis-backed)
  • Key rotation support
  • Permission scoping
  • Metrics and monitoring (Prometheus)

Phase 3: Client Support - 1-2 weeks

  • Update `pg-cli` to support API key authentication
  • WASM library support for API keys (optional)
  • Example integrations (Python, Node.js SDK)
  • Documentation and tutorials

Phase 4: Advanced Features (Future)

  • API key rotation webhooks
  • Multi-tenancy support
  • Organization management UI
  • Usage analytics dashboard
  • Integration with external IdPs (OAuth2)

Security Considerations

API Key Security

  • Storage: SHA-256 hashes only, never plaintext
  • Transmission: Always TLS/HTTPS
  • Rotation: Grace period support, automatic expiry

Rate Limiting

  • Per-API-key hourly and daily limits
  • Sliding window algorithm for accuracy

Audit Logging

  • All API key operations logged
  • Retention: 90 days minimum, 1 year recommended

Permission Model

  • Scoped permissions per API key
  • Recipient attribute whitelisting
  • Max recipients per message limits

Revocation

  • Immediate revocation support
  • In-memory cache of revoked keys
  • Optional webhook notifications

Code Structure

New Modules in `pg-pkg`

```
pg-pkg/src/api_key/
├── mod.rs # Public API key module interface
├── storage.rs # Storage abstraction (SQLite/file)
├── manager.rs # CRUD operations for API keys
├── validation.rs # Key format validation, checksum
├── rate_limit.rs # Rate limiting logic
└── audit.rs # Audit logging

pg-pkg/src/handlers/
├── api_sign_key.rs # POST /v2/api/sign/key
└── api_auth.rs # POST /v2/api/auth/verify

pg-pkg/src/middleware/
└── api_auth.rs # API key authentication middleware

pg-pkg/src/cli/
└── api_key.rs # CLI commands for API key management
```


Backwards Compatibility

Fully backwards compatible

  • Existing Yivi-based authentication works unchanged
  • Wire format remains compatible (no changes required)
  • Recipients can decrypt messages from both API-based and Yivi-based senders
  • No database migrations for existing deployments

Open Questions

  1. Multi-PKG deployments: Should API keys be scoped to specific PKG instances, or support a federated model?
  2. Key recovery: Should there be a secure key recovery mechanism for lost API keys, or force regeneration?
  3. Billing/quotas: Should usage tracking support billing/quota enforcement, or just rate limiting?
  4. Webhook notifications: Should the PKG support webhooks for key events (usage, expiry, revocation)?
  5. External IdP integration: Should API keys support being issued via OAuth2/OIDC from external identity providers?
  6. Batch operations: Should there be dedicated endpoints for bulk encryption operations?

Labels

`enhancement`, `api`, `security`, `B2C`

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions